From cfb2f7e06c406b3f3ddb506a6356382737b53746 Mon Sep 17 00:00:00 2001 From: Lucas McDonald Date: Fri, 4 Oct 2024 15:40:59 -0700 Subject: [PATCH] feat: Python MPL (#805) --- .github/actions/polymorph_codegen/action.yml | 6 + .github/workflows/daily_ci.yml | 6 + .github/workflows/library_codegen.yml | 14 + .github/workflows/library_interop_tests.yml | 44 +- .github/workflows/library_python_tests.yml | 92 + .github/workflows/manual.yml | 5 + .github/workflows/nightly_dafny.yml | 5 + .github/workflows/pull.yml | 5 + .github/workflows/push.yml | 5 + .gitignore | 5 + .releaserc.cjs | 101 + AwsCryptographicMaterialProviders/Makefile | 66 +- .../codebuild/release-python/prod-release.yml | 63 + .../codebuild/release-python/test-release.yml | 65 + .../codebuild/release-python/validate.yml | 89 + .../runtimes/python/.gitignore | 17 + .../runtimes/python/.readthedocs.yaml | 37 + .../runtimes/python/README.rst | 78 + .../runtimes/python/doc/conf.py | 72 + .../runtimes/python/doc/index.rst | 24 + .../runtimes/python/pyproject.toml | 52 + .../__init__.py | 17 + .../internaldafny/extern/StormTrackingCMC.py | 83 + .../extern/SynchronizedLocalCMC.py | 70 + .../internaldafny/extern/__init__.py | 25 + .../internaldafny/generated/dafny_src-py.dtr | 179 + .../keystore/__init__.py | 3 + .../keystore/client.py | 3 + .../keystore/config.py | 3 + .../keystore/errors.py | 3 + .../keystore/models.py | 3 + .../mpl/__init__.py | 3 + .../mpl/client.py | 3 + .../mpl/config.py | 3 + .../mpl/errors.py | 3 + .../mpl/models.py | 3 + .../mpl/references.py | 3 + .../aws_cryptography_keystore/__init__.py | 3 + .../aws_cryptography_keystore/client.py | 452 + .../aws_cryptography_keystore/config.py | 118 + .../dafnyImplInterface.py | 39 + .../dafny_protocol.py | 42 + .../dafny_to_smithy.py | 308 + .../aws_cryptography_keystore/deserialize.py | 120 + .../aws_cryptography_keystore/errors.py | 238 + .../aws_cryptography_keystore/models.py | 1044 ++ .../aws_cryptography_keystore/plugin.py | 46 + .../aws_cryptography_keystore/serialize.py | 67 + .../smithy_to_dafny.py | 564 + .../__init__.py | 3 + .../aws_sdk_to_dafny.py | 22 + .../client.py | 894 ++ .../config.py | 77 + .../dafnyImplInterface.py | 61 + .../dafny_protocol.py | 85 + .../dafny_to_aws_sdk.py | 25 + .../dafny_to_smithy.py | 1741 +++ .../deserialize.py | 375 + .../errors.py | 731 + .../models.py | 5743 ++++++++ .../plugin.py | 51 + .../references.py | 710 + .../serialize.py | 296 + .../shim.py | 548 + .../smithy_to_dafny.py | 2280 ++++ .../runtimes/python/test/__init__.py | 2 + .../python/test/internaldafny/__init__.py | 2 + .../test/internaldafny/test_dafny_wrapper.py | 20 + .../runtimes/python/tox.ini | 87 + AwsCryptographyPrimitives/Makefile | 20 +- .../codebuild/release-python/prod-release.yml | 63 + .../codebuild/release-python/test-release.yml | 65 + .../codebuild/release-python/validate.yml | 39 + .../runtimes/python/.gitignore | 16 + .../runtimes/python/pyproject.toml | 39 + .../aws_cryptography_primitives/__init__.py | 8 + .../internaldafny/extern/AESEncryption.py | 74 + .../internaldafny/extern/AesKdfCtr.py | 37 + .../internaldafny/extern/ECDH.py | 381 + .../internaldafny/extern/ExternDigest.py | 52 + .../internaldafny/extern/ExternRandom.py | 27 + .../internaldafny/extern/HMAC.py | 80 + .../internaldafny/extern/RSAEncryption.py | 130 + .../internaldafny/extern/Signature.py | 362 + .../internaldafny/extern/__init__.py | 12 + .../internaldafny/generated/dafny_src-py.dtr | 59 + .../aws_cryptography_primitives/__init__.py | 3 + .../aws_cryptography_primitives/client.py | 756 ++ .../aws_cryptography_primitives/config.py | 77 + .../dafnyImplInterface.py | 56 + .../dafny_protocol.py | 77 + .../dafny_to_smithy.py | 510 + .../deserialize.py | 263 + .../aws_cryptography_primitives/errors.py | 218 + .../aws_cryptography_primitives/models.py | 2319 ++++ .../aws_cryptography_primitives/plugin.py | 46 + .../aws_cryptography_primitives/serialize.py | 225 + .../smithy_to_dafny.py | 566 + .../runtimes/python/test/__init__.py | 2 + .../test/functional/test_ECDH_exceptions.py | 184 + .../python/test/internaldafny/__init__.py | 2 + .../python/test/internaldafny/extern/ECDH.py | 123 + .../test/internaldafny/extern/__init__.py | 5 + .../test/internaldafny/test_dafny_wrapper.py | 22 + .../runtimes/python/tox.ini | 87 + AwsCryptographyPrimitives/test/TestECDH.dfy | 14 +- ComAmazonawsDynamodb/Makefile | 18 + .../codebuild/release-python/prod-release.yml | 65 + .../codebuild/release-python/test-release.yml | 65 + .../codebuild/release-python/validate.yml | 46 + .../runtimes/python/.gitignore | 16 + .../runtimes/python/pyproject.toml | 38 + .../__init__.py | 8 + .../extern/Com_Amazonaws_Dynamodb.py | 60 + .../internaldafny/extern/__init__.py | 3 + .../internaldafny/generated/dafny_src-py.dtr | 14 + .../com_amazonaws_dynamodb/__init__.py | 3 + .../aws_sdk_to_dafny.py | 11279 ++++++++++++++++ .../dafny_to_aws_sdk.py | 6347 +++++++++ .../com_amazonaws_dynamodb/shim.py | 1177 ++ .../runtimes/python/test/__init__.py | 2 + .../python/test/internaldafny/__init__.py | 2 + .../test/internaldafny/test_dafny_wrapper.py | 19 + ComAmazonawsDynamodb/runtimes/python/tox.ini | 86 + ComAmazonawsKms/Makefile | 18 + .../codebuild/release-python/prod-release.yml | 63 + .../codebuild/release-python/test-release.yml | 65 + .../codebuild/release-python/validate.yml | 46 + ComAmazonawsKms/runtimes/python/.gitignore | 16 + .../runtimes/python/pyproject.toml | 38 + .../aws_cryptography_internal_kms/__init__.py | 8 + .../internaldafny/extern/Com_Amazonaws_Kms.py | 60 + .../internaldafny/extern/__init__.py | 3 + .../internaldafny/generated/dafny_src-py.dtr | 14 + .../com_amazonaws_kms/__init__.py | 3 + .../com_amazonaws_kms/aws_sdk_to_dafny.py | 6363 +++++++++ .../com_amazonaws_kms/dafny_to_aws_sdk.py | 3533 +++++ .../smithygenerated/com_amazonaws_kms/shim.py | 1149 ++ .../runtimes/python/test/__init__.py | 2 + .../python/test/internaldafny/__init__.py | 2 + .../test/internaldafny/test_dafny_wrapper.py | 19 + ComAmazonawsKms/runtimes/python/tox.ini | 86 + Makefile | 2 +- README.md | 4 +- SharedMakefileV2.mk | 2 + StandardLibrary/Makefile | 3 + .../codebuild/release-python/prod-release.yml | 63 + .../codebuild/release-python/test-release.yml | 63 + .../codebuild/release-python/validate.yml | 39 + StandardLibrary/runtimes/python/.gitignore | 16 + .../MANIFEST.in | 1 + .../NOTICE | 1 + .../README.md | 4 + .../pyproject.toml | 50 + .../requirements-dev.txt | 6 + .../requirements.txt | 2 + .../smithy_python/__init__.py | 15 + .../smithy_python/_private/__init__.py | 341 + .../smithy_python/_private/abnf.py | 120 + .../smithy_python/_private/api_key_auth.py | 145 + .../smithy_python/_private/auth.py | 42 + .../smithy_python/_private/http/__init__.py | 116 + .../_private/http/aiohttp_client.py | 113 + .../smithy_python/_private/http/crt.py | 296 + .../smithy_python/_private/identity.py | 41 + .../_private/retries/__init__.py | 256 + .../smithy_python/async_utils.py | 25 + .../smithy_python/exceptions.py | 32 + .../smithy_python/httputils.py | 133 + .../smithy_python/interfaces/__init__.py | 181 + .../smithy_python/interfaces/auth.py | 122 + .../smithy_python/interfaces/blobs.py | 305 + .../smithy_python/interfaces/http.py | 112 + .../smithy_python/interfaces/identity.py | 64 + .../smithy_python/interfaces/interceptor.py | 606 + .../smithy_python/interfaces/retries.py | 132 + .../smithy_python/mediatypes.py | 36 + .../smithy_python/protocolutils.py | 69 + .../smithy_python/py.typed | 1 + .../smithy_python/types.py | 5 + .../smithy_python/utils.py | 275 + .../runtimes/python/pyproject.toml | 43 + .../smithy_dafny_standard_library/__init__.py | 8 + .../internaldafny/extern/ConcurrentCall.py | 25 + .../internaldafny/extern/DafnyLibraries.py | 132 + .../internaldafny/extern/SortedSets.py | 48 + .../internaldafny/extern/Time.py | 21 + .../internaldafny/extern/UTF8.py | 133 + .../internaldafny/extern/UUID.py | 39 + .../internaldafny/extern/__init__.py | 8 + .../internaldafny/generated/dafny_src-py.dtr | 251 + .../python/test/internaldafny/__init__.py | 2 + .../test/internaldafny/test_dafny_wrapper.py | 19 + StandardLibrary/runtimes/python/tox.ini | 86 + .../Makefile | 62 + .../runtimes/python/.gitignore | 16 + .../runtimes/python/pyproject.toml | 23 + .../__init__.py | 8 + .../internaldafny/extern/__init__.py | 3 + .../internaldafny/extern/wrapped_mpl.py | 18 + .../internaldafny/generated/dafny_src-py.dtr | 104 + .../__init__.py | 3 + .../shim.py | 560 + .../__init__.py | 3 + .../aws_sdk_to_dafny.py | 22 + .../client.py | 414 + .../config.py | 81 + .../dafnyImplInterface.py | 37 + .../dafny_protocol.py | 37 + .../dafny_to_aws_sdk.py | 25 + .../dafny_to_smithy.py | 363 + .../deserialize.py | 81 + .../errors.py | 170 + .../models.py | 1330 ++ .../plugin.py | 46 + .../serialize.py | 56 + .../smithy_to_dafny.py | 608 + .../runtimes/python/test/__init__.py | 2 + .../python/test/internaldafny/__init__.py | 2 + .../extern/GetTestDirectoryExtern.py | 8 + .../test/internaldafny/extern/__init__.py | 3 + .../test/internaldafny/test_dafny_wrapper.py | 21 + .../runtimes/python/tox.ini | 28 + cfn/python/MPL-Python.yml | 405 + model/traits.smithy | 4 + smithy-dafny | 2 +- 226 files changed, 64994 insertions(+), 12 deletions(-) create mode 100644 .github/workflows/library_python_tests.yml create mode 100644 AwsCryptographicMaterialProviders/codebuild/release-python/prod-release.yml create mode 100644 AwsCryptographicMaterialProviders/codebuild/release-python/test-release.yml create mode 100644 AwsCryptographicMaterialProviders/codebuild/release-python/validate.yml create mode 100644 AwsCryptographicMaterialProviders/runtimes/python/.gitignore create mode 100644 AwsCryptographicMaterialProviders/runtimes/python/.readthedocs.yaml create mode 100644 AwsCryptographicMaterialProviders/runtimes/python/README.rst create mode 100644 AwsCryptographicMaterialProviders/runtimes/python/doc/conf.py create mode 100644 AwsCryptographicMaterialProviders/runtimes/python/doc/index.rst create mode 100644 AwsCryptographicMaterialProviders/runtimes/python/pyproject.toml create mode 100644 AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/__init__.py create mode 100644 AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/internaldafny/extern/StormTrackingCMC.py create mode 100644 AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/internaldafny/extern/SynchronizedLocalCMC.py create mode 100644 AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/internaldafny/extern/__init__.py create mode 100644 AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/internaldafny/generated/dafny_src-py.dtr create mode 100644 AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/keystore/__init__.py create mode 100644 AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/keystore/client.py create mode 100644 AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/keystore/config.py create mode 100644 AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/keystore/errors.py create mode 100644 AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/keystore/models.py create mode 100644 AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/mpl/__init__.py create mode 100644 AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/mpl/client.py create mode 100644 AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/mpl/config.py create mode 100644 AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/mpl/errors.py create mode 100644 AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/mpl/models.py create mode 100644 AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/mpl/references.py create mode 100644 AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/smithygenerated/aws_cryptography_keystore/__init__.py create mode 100644 AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/smithygenerated/aws_cryptography_keystore/client.py create mode 100644 AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/smithygenerated/aws_cryptography_keystore/config.py create mode 100644 AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/smithygenerated/aws_cryptography_keystore/dafnyImplInterface.py create mode 100644 AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/smithygenerated/aws_cryptography_keystore/dafny_protocol.py create mode 100644 AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/smithygenerated/aws_cryptography_keystore/dafny_to_smithy.py create mode 100644 AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/smithygenerated/aws_cryptography_keystore/deserialize.py create mode 100644 AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/smithygenerated/aws_cryptography_keystore/errors.py create mode 100644 AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/smithygenerated/aws_cryptography_keystore/models.py create mode 100644 AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/smithygenerated/aws_cryptography_keystore/plugin.py create mode 100644 AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/smithygenerated/aws_cryptography_keystore/serialize.py create mode 100644 AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/smithygenerated/aws_cryptography_keystore/smithy_to_dafny.py create mode 100644 AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/smithygenerated/aws_cryptography_materialproviders/__init__.py create mode 100644 AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/smithygenerated/aws_cryptography_materialproviders/aws_sdk_to_dafny.py create mode 100644 AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/smithygenerated/aws_cryptography_materialproviders/client.py create mode 100644 AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/smithygenerated/aws_cryptography_materialproviders/config.py create mode 100644 AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/smithygenerated/aws_cryptography_materialproviders/dafnyImplInterface.py create mode 100644 AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/smithygenerated/aws_cryptography_materialproviders/dafny_protocol.py create mode 100644 AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/smithygenerated/aws_cryptography_materialproviders/dafny_to_aws_sdk.py create mode 100644 AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/smithygenerated/aws_cryptography_materialproviders/dafny_to_smithy.py create mode 100644 AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/smithygenerated/aws_cryptography_materialproviders/deserialize.py create mode 100644 AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/smithygenerated/aws_cryptography_materialproviders/errors.py create mode 100644 AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/smithygenerated/aws_cryptography_materialproviders/models.py create mode 100644 AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/smithygenerated/aws_cryptography_materialproviders/plugin.py create mode 100644 AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/smithygenerated/aws_cryptography_materialproviders/references.py create mode 100644 AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/smithygenerated/aws_cryptography_materialproviders/serialize.py create mode 100644 AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/smithygenerated/aws_cryptography_materialproviders/shim.py create mode 100644 AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/smithygenerated/aws_cryptography_materialproviders/smithy_to_dafny.py create mode 100644 AwsCryptographicMaterialProviders/runtimes/python/test/__init__.py create mode 100644 AwsCryptographicMaterialProviders/runtimes/python/test/internaldafny/__init__.py create mode 100644 AwsCryptographicMaterialProviders/runtimes/python/test/internaldafny/test_dafny_wrapper.py create mode 100644 AwsCryptographicMaterialProviders/runtimes/python/tox.ini create mode 100644 AwsCryptographyPrimitives/codebuild/release-python/prod-release.yml create mode 100644 AwsCryptographyPrimitives/codebuild/release-python/test-release.yml create mode 100644 AwsCryptographyPrimitives/codebuild/release-python/validate.yml create mode 100644 AwsCryptographyPrimitives/runtimes/python/.gitignore create mode 100644 AwsCryptographyPrimitives/runtimes/python/pyproject.toml create mode 100644 AwsCryptographyPrimitives/runtimes/python/src/aws_cryptography_primitives/__init__.py create mode 100644 AwsCryptographyPrimitives/runtimes/python/src/aws_cryptography_primitives/internaldafny/extern/AESEncryption.py create mode 100644 AwsCryptographyPrimitives/runtimes/python/src/aws_cryptography_primitives/internaldafny/extern/AesKdfCtr.py create mode 100644 AwsCryptographyPrimitives/runtimes/python/src/aws_cryptography_primitives/internaldafny/extern/ECDH.py create mode 100644 AwsCryptographyPrimitives/runtimes/python/src/aws_cryptography_primitives/internaldafny/extern/ExternDigest.py create mode 100644 AwsCryptographyPrimitives/runtimes/python/src/aws_cryptography_primitives/internaldafny/extern/ExternRandom.py create mode 100644 AwsCryptographyPrimitives/runtimes/python/src/aws_cryptography_primitives/internaldafny/extern/HMAC.py create mode 100644 AwsCryptographyPrimitives/runtimes/python/src/aws_cryptography_primitives/internaldafny/extern/RSAEncryption.py create mode 100644 AwsCryptographyPrimitives/runtimes/python/src/aws_cryptography_primitives/internaldafny/extern/Signature.py create mode 100644 AwsCryptographyPrimitives/runtimes/python/src/aws_cryptography_primitives/internaldafny/extern/__init__.py create mode 100644 AwsCryptographyPrimitives/runtimes/python/src/aws_cryptography_primitives/internaldafny/generated/dafny_src-py.dtr create mode 100644 AwsCryptographyPrimitives/runtimes/python/src/aws_cryptography_primitives/smithygenerated/aws_cryptography_primitives/__init__.py create mode 100644 AwsCryptographyPrimitives/runtimes/python/src/aws_cryptography_primitives/smithygenerated/aws_cryptography_primitives/client.py create mode 100644 AwsCryptographyPrimitives/runtimes/python/src/aws_cryptography_primitives/smithygenerated/aws_cryptography_primitives/config.py create mode 100644 AwsCryptographyPrimitives/runtimes/python/src/aws_cryptography_primitives/smithygenerated/aws_cryptography_primitives/dafnyImplInterface.py create mode 100644 AwsCryptographyPrimitives/runtimes/python/src/aws_cryptography_primitives/smithygenerated/aws_cryptography_primitives/dafny_protocol.py create mode 100644 AwsCryptographyPrimitives/runtimes/python/src/aws_cryptography_primitives/smithygenerated/aws_cryptography_primitives/dafny_to_smithy.py create mode 100644 AwsCryptographyPrimitives/runtimes/python/src/aws_cryptography_primitives/smithygenerated/aws_cryptography_primitives/deserialize.py create mode 100644 AwsCryptographyPrimitives/runtimes/python/src/aws_cryptography_primitives/smithygenerated/aws_cryptography_primitives/errors.py create mode 100644 AwsCryptographyPrimitives/runtimes/python/src/aws_cryptography_primitives/smithygenerated/aws_cryptography_primitives/models.py create mode 100644 AwsCryptographyPrimitives/runtimes/python/src/aws_cryptography_primitives/smithygenerated/aws_cryptography_primitives/plugin.py create mode 100644 AwsCryptographyPrimitives/runtimes/python/src/aws_cryptography_primitives/smithygenerated/aws_cryptography_primitives/serialize.py create mode 100644 AwsCryptographyPrimitives/runtimes/python/src/aws_cryptography_primitives/smithygenerated/aws_cryptography_primitives/smithy_to_dafny.py create mode 100644 AwsCryptographyPrimitives/runtimes/python/test/__init__.py create mode 100644 AwsCryptographyPrimitives/runtimes/python/test/functional/test_ECDH_exceptions.py create mode 100644 AwsCryptographyPrimitives/runtimes/python/test/internaldafny/__init__.py create mode 100644 AwsCryptographyPrimitives/runtimes/python/test/internaldafny/extern/ECDH.py create mode 100644 AwsCryptographyPrimitives/runtimes/python/test/internaldafny/extern/__init__.py create mode 100644 AwsCryptographyPrimitives/runtimes/python/test/internaldafny/test_dafny_wrapper.py create mode 100644 AwsCryptographyPrimitives/runtimes/python/tox.ini create mode 100644 ComAmazonawsDynamodb/codebuild/release-python/prod-release.yml create mode 100644 ComAmazonawsDynamodb/codebuild/release-python/test-release.yml create mode 100644 ComAmazonawsDynamodb/codebuild/release-python/validate.yml create mode 100644 ComAmazonawsDynamodb/runtimes/python/.gitignore create mode 100644 ComAmazonawsDynamodb/runtimes/python/pyproject.toml create mode 100644 ComAmazonawsDynamodb/runtimes/python/src/aws_cryptography_internal_dynamodb/__init__.py create mode 100644 ComAmazonawsDynamodb/runtimes/python/src/aws_cryptography_internal_dynamodb/internaldafny/extern/Com_Amazonaws_Dynamodb.py create mode 100644 ComAmazonawsDynamodb/runtimes/python/src/aws_cryptography_internal_dynamodb/internaldafny/extern/__init__.py create mode 100644 ComAmazonawsDynamodb/runtimes/python/src/aws_cryptography_internal_dynamodb/internaldafny/generated/dafny_src-py.dtr create mode 100644 ComAmazonawsDynamodb/runtimes/python/src/aws_cryptography_internal_dynamodb/smithygenerated/com_amazonaws_dynamodb/__init__.py create mode 100644 ComAmazonawsDynamodb/runtimes/python/src/aws_cryptography_internal_dynamodb/smithygenerated/com_amazonaws_dynamodb/aws_sdk_to_dafny.py create mode 100644 ComAmazonawsDynamodb/runtimes/python/src/aws_cryptography_internal_dynamodb/smithygenerated/com_amazonaws_dynamodb/dafny_to_aws_sdk.py create mode 100644 ComAmazonawsDynamodb/runtimes/python/src/aws_cryptography_internal_dynamodb/smithygenerated/com_amazonaws_dynamodb/shim.py create mode 100644 ComAmazonawsDynamodb/runtimes/python/test/__init__.py create mode 100644 ComAmazonawsDynamodb/runtimes/python/test/internaldafny/__init__.py create mode 100644 ComAmazonawsDynamodb/runtimes/python/test/internaldafny/test_dafny_wrapper.py create mode 100644 ComAmazonawsDynamodb/runtimes/python/tox.ini create mode 100644 ComAmazonawsKms/codebuild/release-python/prod-release.yml create mode 100644 ComAmazonawsKms/codebuild/release-python/test-release.yml create mode 100644 ComAmazonawsKms/codebuild/release-python/validate.yml create mode 100644 ComAmazonawsKms/runtimes/python/.gitignore create mode 100644 ComAmazonawsKms/runtimes/python/pyproject.toml create mode 100644 ComAmazonawsKms/runtimes/python/src/aws_cryptography_internal_kms/__init__.py create mode 100644 ComAmazonawsKms/runtimes/python/src/aws_cryptography_internal_kms/internaldafny/extern/Com_Amazonaws_Kms.py create mode 100644 ComAmazonawsKms/runtimes/python/src/aws_cryptography_internal_kms/internaldafny/extern/__init__.py create mode 100644 ComAmazonawsKms/runtimes/python/src/aws_cryptography_internal_kms/internaldafny/generated/dafny_src-py.dtr create mode 100644 ComAmazonawsKms/runtimes/python/src/aws_cryptography_internal_kms/smithygenerated/com_amazonaws_kms/__init__.py create mode 100644 ComAmazonawsKms/runtimes/python/src/aws_cryptography_internal_kms/smithygenerated/com_amazonaws_kms/aws_sdk_to_dafny.py create mode 100644 ComAmazonawsKms/runtimes/python/src/aws_cryptography_internal_kms/smithygenerated/com_amazonaws_kms/dafny_to_aws_sdk.py create mode 100644 ComAmazonawsKms/runtimes/python/src/aws_cryptography_internal_kms/smithygenerated/com_amazonaws_kms/shim.py create mode 100644 ComAmazonawsKms/runtimes/python/test/__init__.py create mode 100644 ComAmazonawsKms/runtimes/python/test/internaldafny/__init__.py create mode 100644 ComAmazonawsKms/runtimes/python/test/internaldafny/test_dafny_wrapper.py create mode 100644 ComAmazonawsKms/runtimes/python/tox.ini create mode 100644 StandardLibrary/codebuild/release-python/prod-release.yml create mode 100644 StandardLibrary/codebuild/release-python/test-release.yml create mode 100644 StandardLibrary/codebuild/release-python/validate.yml create mode 100644 StandardLibrary/runtimes/python/.gitignore create mode 100644 StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/MANIFEST.in create mode 100644 StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/NOTICE create mode 100644 StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/README.md create mode 100644 StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/pyproject.toml create mode 100644 StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/requirements-dev.txt create mode 100644 StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/requirements.txt create mode 100644 StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/smithy_python/__init__.py create mode 100644 StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/smithy_python/_private/__init__.py create mode 100644 StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/smithy_python/_private/abnf.py create mode 100644 StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/smithy_python/_private/api_key_auth.py create mode 100644 StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/smithy_python/_private/auth.py create mode 100644 StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/smithy_python/_private/http/__init__.py create mode 100644 StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/smithy_python/_private/http/aiohttp_client.py create mode 100644 StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/smithy_python/_private/http/crt.py create mode 100644 StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/smithy_python/_private/identity.py create mode 100644 StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/smithy_python/_private/retries/__init__.py create mode 100644 StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/smithy_python/async_utils.py create mode 100644 StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/smithy_python/exceptions.py create mode 100644 StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/smithy_python/httputils.py create mode 100644 StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/smithy_python/interfaces/__init__.py create mode 100644 StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/smithy_python/interfaces/auth.py create mode 100644 StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/smithy_python/interfaces/blobs.py create mode 100644 StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/smithy_python/interfaces/http.py create mode 100644 StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/smithy_python/interfaces/identity.py create mode 100644 StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/smithy_python/interfaces/interceptor.py create mode 100644 StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/smithy_python/interfaces/retries.py create mode 100644 StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/smithy_python/mediatypes.py create mode 100644 StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/smithy_python/protocolutils.py create mode 100644 StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/smithy_python/py.typed create mode 100644 StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/smithy_python/types.py create mode 100644 StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/smithy_python/utils.py create mode 100644 StandardLibrary/runtimes/python/pyproject.toml create mode 100644 StandardLibrary/runtimes/python/src/smithy_dafny_standard_library/__init__.py create mode 100644 StandardLibrary/runtimes/python/src/smithy_dafny_standard_library/internaldafny/extern/ConcurrentCall.py create mode 100644 StandardLibrary/runtimes/python/src/smithy_dafny_standard_library/internaldafny/extern/DafnyLibraries.py create mode 100644 StandardLibrary/runtimes/python/src/smithy_dafny_standard_library/internaldafny/extern/SortedSets.py create mode 100644 StandardLibrary/runtimes/python/src/smithy_dafny_standard_library/internaldafny/extern/Time.py create mode 100644 StandardLibrary/runtimes/python/src/smithy_dafny_standard_library/internaldafny/extern/UTF8.py create mode 100644 StandardLibrary/runtimes/python/src/smithy_dafny_standard_library/internaldafny/extern/UUID.py create mode 100644 StandardLibrary/runtimes/python/src/smithy_dafny_standard_library/internaldafny/extern/__init__.py create mode 100644 StandardLibrary/runtimes/python/src/smithy_dafny_standard_library/internaldafny/generated/dafny_src-py.dtr create mode 100644 StandardLibrary/runtimes/python/test/internaldafny/__init__.py create mode 100644 StandardLibrary/runtimes/python/test/internaldafny/test_dafny_wrapper.py create mode 100644 StandardLibrary/runtimes/python/tox.ini create mode 100644 TestVectorsAwsCryptographicMaterialProviders/runtimes/python/.gitignore create mode 100644 TestVectorsAwsCryptographicMaterialProviders/runtimes/python/pyproject.toml create mode 100644 TestVectorsAwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptography_materialproviders_test_vectors/__init__.py create mode 100644 TestVectorsAwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptography_materialproviders_test_vectors/internaldafny/extern/__init__.py create mode 100644 TestVectorsAwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptography_materialproviders_test_vectors/internaldafny/extern/wrapped_mpl.py create mode 100644 TestVectorsAwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptography_materialproviders_test_vectors/internaldafny/generated/dafny_src-py.dtr create mode 100644 TestVectorsAwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptography_materialproviders_test_vectors/smithygenerated/aws_cryptography_materialproviders/__init__.py create mode 100644 TestVectorsAwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptography_materialproviders_test_vectors/smithygenerated/aws_cryptography_materialproviders/shim.py create mode 100644 TestVectorsAwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptography_materialproviders_test_vectors/smithygenerated/aws_cryptography_materialproviderstestvectorkeys/__init__.py create mode 100644 TestVectorsAwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptography_materialproviders_test_vectors/smithygenerated/aws_cryptography_materialproviderstestvectorkeys/aws_sdk_to_dafny.py create mode 100644 TestVectorsAwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptography_materialproviders_test_vectors/smithygenerated/aws_cryptography_materialproviderstestvectorkeys/client.py create mode 100644 TestVectorsAwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptography_materialproviders_test_vectors/smithygenerated/aws_cryptography_materialproviderstestvectorkeys/config.py create mode 100644 TestVectorsAwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptography_materialproviders_test_vectors/smithygenerated/aws_cryptography_materialproviderstestvectorkeys/dafnyImplInterface.py create mode 100644 TestVectorsAwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptography_materialproviders_test_vectors/smithygenerated/aws_cryptography_materialproviderstestvectorkeys/dafny_protocol.py create mode 100644 TestVectorsAwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptography_materialproviders_test_vectors/smithygenerated/aws_cryptography_materialproviderstestvectorkeys/dafny_to_aws_sdk.py create mode 100644 TestVectorsAwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptography_materialproviders_test_vectors/smithygenerated/aws_cryptography_materialproviderstestvectorkeys/dafny_to_smithy.py create mode 100644 TestVectorsAwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptography_materialproviders_test_vectors/smithygenerated/aws_cryptography_materialproviderstestvectorkeys/deserialize.py create mode 100644 TestVectorsAwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptography_materialproviders_test_vectors/smithygenerated/aws_cryptography_materialproviderstestvectorkeys/errors.py create mode 100644 TestVectorsAwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptography_materialproviders_test_vectors/smithygenerated/aws_cryptography_materialproviderstestvectorkeys/models.py create mode 100644 TestVectorsAwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptography_materialproviders_test_vectors/smithygenerated/aws_cryptography_materialproviderstestvectorkeys/plugin.py create mode 100644 TestVectorsAwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptography_materialproviders_test_vectors/smithygenerated/aws_cryptography_materialproviderstestvectorkeys/serialize.py create mode 100644 TestVectorsAwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptography_materialproviders_test_vectors/smithygenerated/aws_cryptography_materialproviderstestvectorkeys/smithy_to_dafny.py create mode 100644 TestVectorsAwsCryptographicMaterialProviders/runtimes/python/test/__init__.py create mode 100644 TestVectorsAwsCryptographicMaterialProviders/runtimes/python/test/internaldafny/__init__.py create mode 100644 TestVectorsAwsCryptographicMaterialProviders/runtimes/python/test/internaldafny/extern/GetTestDirectoryExtern.py create mode 100644 TestVectorsAwsCryptographicMaterialProviders/runtimes/python/test/internaldafny/extern/__init__.py create mode 100644 TestVectorsAwsCryptographicMaterialProviders/runtimes/python/test/internaldafny/test_dafny_wrapper.py create mode 100644 TestVectorsAwsCryptographicMaterialProviders/runtimes/python/tox.ini create mode 100644 cfn/python/MPL-Python.yml diff --git a/.github/actions/polymorph_codegen/action.yml b/.github/actions/polymorph_codegen/action.yml index ca900aae6..78e87b6d0 100644 --- a/.github/actions/polymorph_codegen/action.yml +++ b/.github/actions/polymorph_codegen/action.yml @@ -82,6 +82,12 @@ runs: run: | make polymorph_dotnet + - name: Regenerate Python code using smithy-dafny + working-directory: ./${{ inputs.library }} + shell: bash + run: | + make polymorph_python + - name: Check regenerated code against commited code # Composite action inputs seem to not actually support booleans properly for some reason if: inputs.diff-generated-code == 'true' diff --git a/.github/workflows/daily_ci.yml b/.github/workflows/daily_ci.yml index 1b9eb7f91..1b7aea948 100644 --- a/.github/workflows/daily_ci.yml +++ b/.github/workflows/daily_ci.yml @@ -43,6 +43,12 @@ jobs: uses: ./.github/workflows/library_net_tests.yml with: dafny: ${{needs.getVersion.outputs.version}} + daily-ci-python: + needs: getVersion + if: github.event_name != 'schedule' || github.repository_owner == 'aws' + uses: ./.github/workflows/library_python_tests.yml + with: + dafny: ${{needs.getVersion.outputs.version}} daily-interop-test: needs: getVersion if: github.event_name != 'schedule' || github.repository_owner == 'aws' diff --git a/.github/workflows/library_codegen.yml b/.github/workflows/library_codegen.yml index 2c984d57d..7ddeef657 100644 --- a/.github/workflows/library_codegen.yml +++ b/.github/workflows/library_codegen.yml @@ -25,6 +25,10 @@ jobs: # Note dotnet is only used for formatting generated code # in this workflow dotnet-version: ["6.0.x"] + # Note python is only used for formatting generated code + # in this workflow. + # The workflow installs black and docformatter and runs them on generated code. + python-version: [3.11] os: [ubuntu-latest] runs-on: ${{ matrix.os }} defaults: @@ -66,6 +70,16 @@ jobs: - name: Install Smithy-Dafny codegen dependencies uses: ./.github/actions/install_smithy_dafny_codegen_dependencies + - name: Setup Python, black, and docformatter for code formatting + uses: actions/setup-python@v4 + with: + python-version: ${{ matrix.python-version }} + architecture: x64 + - run: | + python -m pip install --upgrade pip + python -m pip install --upgrade black + python -m pip install --upgrade docformatter + - uses: ./.github/actions/polymorph_codegen with: dafny: ${{ env.DAFNY_VERSION }} diff --git a/.github/workflows/library_interop_tests.yml b/.github/workflows/library_interop_tests.yml index 02c510614..5ea08760d 100644 --- a/.github/workflows/library_interop_tests.yml +++ b/.github/workflows/library_interop_tests.yml @@ -25,7 +25,7 @@ jobs: ubuntu-latest, macos-12, ] - language: [java, net] + language: [java, net, python] # https://taskei.amazon.dev/tasks/CrypTool-5284 dotnet-version: ["6.0.x"] runs-on: ${{ matrix.os }} @@ -57,6 +57,16 @@ jobs: distribution: "corretto" java-version: 17 + - name: Setup Python for running tests + uses: actions/setup-python@v4 + with: + python-version: 3.11 + architecture: x64 + - run: | + python -m pip install --upgrade pip + pip install --upgrade tox + pip install poetry + - name: Setup Dafny uses: dafny-lang/setup-dafny-action@v1.6.1 with: @@ -89,6 +99,15 @@ jobs: CORES=$(node -e 'console.log(os.cpus().length)') make transpile_net + - name: Build ${{ matrix.library }} implementation in Python + if: matrix.language == 'python' + 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 transpile_python + - name: Setup gradle if: matrix.language == 'java' uses: gradle/gradle-build-action@v2 @@ -128,8 +147,8 @@ jobs: ubuntu-latest, macos-12, ] - encrypting_language: [java, net] - decrypting_language: [java, net] + encrypting_language: [java, net, python] + decrypting_language: [java, net, python] dotnet-version: ["6.0.x"] runs-on: ${{ matrix.os }} permissions: @@ -167,6 +186,16 @@ jobs: distribution: "corretto" java-version: 17 + - name: Setup Python for running tests + uses: actions/setup-python@v4 + with: + python-version: 3.11 + architecture: x64 + - run: | + python -m pip install --upgrade pip + pip install --upgrade tox + pip install poetry + - name: Setup Dafny uses: dafny-lang/setup-dafny-action@v1.6.1 with: @@ -199,6 +228,15 @@ jobs: CORES=$(node -e 'console.log(os.cpus().length)') make transpile_net + - name: Build ${{ matrix.library }} implementation in Python + if: matrix.decrypting_language == 'python' + 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 transpile_python + - name: Download Encrypt Manifest Artifact uses: actions/download-artifact@v4 with: diff --git a/.github/workflows/library_python_tests.yml b/.github/workflows/library_python_tests.yml new file mode 100644 index 000000000..d862576bd --- /dev/null +++ b/.github/workflows/library_python_tests.yml @@ -0,0 +1,92 @@ +# This workflow performs tests in Python. +name: Library Python 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: + testPython: + strategy: + fail-fast: false + matrix: + library: + [ + StandardLibrary, + AwsCryptographyPrimitives, + ComAmazonawsKms, + ComAmazonawsDynamodb, + AwsCryptographicMaterialProviders, + TestVectorsAwsCryptographicMaterialProviders, + ] + python-version: ["3.11"] + os: [ + # TODO fix Dafny-generated tests on Windows; + # the sys.path workaround for generated Dafny doesn't work on Windows. + # Note: only tests use the sys.path workaround, not source code. + # Windows source code is tested downstream (ex. ESDK-Python CI). + # windows-latest, + ubuntu-latest, + macos-12, + ] + runs-on: ${{ matrix.os }} + defaults: + run: + shell: bash + permissions: + id-token: write + contents: read + steps: + - name: Support longpaths on Git checkout + run: | + git config --global core.longpaths true + + - name: Configure AWS Credentials + 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: PythonTests + + - uses: actions/checkout@v4 + # The specification submodule is private so we don't have access, but we don't need + # it to verify the Dafny code. Instead we manually pull the submodules we DO need. + - 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 Python ${{ matrix.python-version }} for running tests + uses: actions/setup-python@v4 + with: + python-version: ${{ matrix.python-version }} + architecture: x64 + - run: | + python -m pip install --upgrade pip + pip install --upgrade tox + pip install poetry + + - name: Build ${{ matrix.library }} implementation + 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 transpile_python CORES=$CORES + + - name: Test ${{ matrix.library }} + working-directory: ./${{ matrix.library }} + shell: bash + run: | + make test_python diff --git a/.github/workflows/manual.yml b/.github/workflows/manual.yml index 6370e370d..872df8748 100644 --- a/.github/workflows/manual.yml +++ b/.github/workflows/manual.yml @@ -37,6 +37,11 @@ jobs: with: dafny: ${{ inputs.dafny }} regenerate-code: ${{ inputs.regenerate-code }} + manual-ci-python: + uses: ./.github/workflows/library_python_tests.yml + with: + dafny: ${{needs.getVersion.outputs.version}} + regenerate-code: ${{ inputs.regenerate-code }} manual-interop-test: uses: ./.github/workflows/library_interop_tests.yml with: diff --git a/.github/workflows/nightly_dafny.yml b/.github/workflows/nightly_dafny.yml index fb2a89df5..8c7eeafbc 100644 --- a/.github/workflows/nightly_dafny.yml +++ b/.github/workflows/nightly_dafny.yml @@ -37,6 +37,11 @@ jobs: with: dafny: "nightly-latest" regenerate-code: true + dafny-nightly-python: + needs: getVersion + uses: ./.github/workflows/library_python_tests.yml + with: + dafny: ${{needs.getVersion.outputs.version}} cut-issue-on-failure: runs-on: ubuntu-latest diff --git a/.github/workflows/pull.yml b/.github/workflows/pull.yml index 389ac8dda..5756acd1d 100644 --- a/.github/workflows/pull.yml +++ b/.github/workflows/pull.yml @@ -34,6 +34,11 @@ jobs: uses: ./.github/workflows/library_net_tests.yml with: dafny: ${{needs.getVersion.outputs.version}} + pr-ci-python: + needs: getVersion + uses: ./.github/workflows/library_python_tests.yml + with: + dafny: ${{needs.getVersion.outputs.version}} pr-interop-test: needs: getVersion uses: ./.github/workflows/library_interop_tests.yml diff --git a/.github/workflows/push.yml b/.github/workflows/push.yml index 2bd230bae..18f45b044 100644 --- a/.github/workflows/push.yml +++ b/.github/workflows/push.yml @@ -36,6 +36,11 @@ jobs: uses: ./.github/workflows/library_net_tests.yml with: dafny: ${{needs.getVersion.outputs.version}} + push-ci-python: + needs: getVersion + uses: ./.github/workflows/library_python_tests.yml + with: + dafny: ${{needs.getVersion.outputs.version}} pr-interop-test: needs: getVersion uses: ./.github/workflows/library_interop_tests.yml diff --git a/.gitignore b/.gitignore index 4c4877bfc..bbd423f5c 100644 --- a/.gitignore +++ b/.gitignore @@ -7,6 +7,11 @@ test/**/Output/* /package-lock.json /node_modules +# Python docs build Artifacts +build +doc/build +AwsCryptographicMaterialProviders/runtimes/python/doc/generated/* + # Duvet output specification_compliance_report.html diff --git a/.releaserc.cjs b/.releaserc.cjs index 4d94b40ab..769b8406a 100644 --- a/.releaserc.cjs +++ b/.releaserc.cjs @@ -51,6 +51,30 @@ const Runtimes = { assemblyInfo: "StandardLibrary/runtimes/net/AssemblyInfo.cs", }, }, + // Any change to the size of the `dependencies` list + // must be accounted for in `CheckDependencyReplacementResults`. + python: { + "AwsCryptographicMaterialProviders/runtimes/python/pyproject.toml": { + dependencies: [ + "AwsCryptographyPrimitives", + "ComAmazonawsKms", + "ComAmazonawsDynamodb", + "StandardLibrary", + ], + }, + "AwsCryptographyPrimitives/runtimes/python/pyproject.toml": { + dependencies: ["StandardLibrary"], + }, + "ComAmazonawsKms/runtimes/python/pyproject.toml": { + dependencies: ["StandardLibrary"], + }, + "ComAmazonawsDynamodb/runtimes/python/pyproject.toml": { + dependencies: ["StandardLibrary"], + }, + "StandardLibrary/runtimes/python/pyproject.toml": { + dependencies: [], + }, + }, }; /** @@ -120,9 +144,39 @@ module.exports = { countMatches: true, }), ), + + // Update the version in pyproject.toml for all Python projects + // Does not update the dependencies + { + files: Object.keys(Runtimes.python), + from: 'version = ".*"', + to: 'version = "${nextRelease.version}"', + results: Object.keys(Runtimes.python).map(CheckResults), + countMatches: true, + }, + + // Now update the local filesystem dependencies to PyPI dependencies + // pinned to the minor MPL version + { + files: Object.keys(Runtimes.python), + from: "{path =.*", + to: '"~${nextRelease.version}"', + results: Object.keys(Runtimes.python).map( + CheckDependencyReplacementResults, + ), + countMatches: true, + }, ], }, ], + [ + // Re-transpile Python code to update .dtr files as part of the release commit + "@semantic-release/exec", + { + prepareCmd: + "make -C TestVectorsAwsCryptographicMaterialProviders transpile_python", + }, + ], // Commit and push changes the changelog and versions bumps [ "@semantic-release/git", @@ -131,6 +185,7 @@ module.exports = { "CHANGELOG.md", ...Object.values(Runtimes).flatMap((r) => Object.keys(r)), ...Object.values(Runtimes.net).flatMap((r) => r.assemblyInfo), + "**/runtimes/python/**/*.dtr", ], message: "chore(release): ${nextRelease.version} [skip ci]\n\n${nextRelease.notes}", @@ -147,3 +202,49 @@ function CheckResults(file) { numReplacements: 1, }; } + +// For dependency replacement. +// If the runtime defines dependencies, +// assert the expected number of dependencies were replaced. +function CheckDependencyReplacementResults(file) { + if (file.includes("AwsCryptographicMaterialProviders")) { + return { + file, + hasChanged: true, + numMatches: 4, + numReplacements: 4, + }; + } else if (file.includes("StandardLibrary")) { + return { + file, + hasChanged: false, + numMatches: 0, + numReplacements: 0, + }; + } else if (file.includes("AwsCryptographyPrimitives")) { + return { + file, + hasChanged: true, + numMatches: 1, + numReplacements: 1, + }; + } else if (file.includes("ComAmazonawsKms")) { + return { + file, + hasChanged: true, + numMatches: 1, + numReplacements: 1, + }; + } else if (file.includes("ComAmazonawsDynamodb")) { + return { + file, + hasChanged: true, + numMatches: 1, + numReplacements: 1, + }; + } else { + throw new Error( + `No known dependency replacement result specification for file ${file}`, + ); + } +} diff --git a/AwsCryptographicMaterialProviders/Makefile b/AwsCryptographicMaterialProviders/Makefile index cdedf1dc8..9377b9cd3 100644 --- a/AwsCryptographicMaterialProviders/Makefile +++ b/AwsCryptographicMaterialProviders/Makefile @@ -3,11 +3,13 @@ CORES=2 +ENABLE_EXTERN_PROCESSING=1 + include ../SharedMakefileV2.mk PROJECT_SERVICES := \ - AwsCryptographicMaterialProviders \ AwsCryptographyKeyStore \ + AwsCryptographicMaterialProviders \ SERVICE_NAMESPACE_AwsCryptographicMaterialProviders=aws.cryptography.materialProviders SERVICE_NAMESPACE_AwsCryptographyKeyStore=aws.cryptography.keyStore @@ -44,3 +46,65 @@ SERVICE_DEPS_AwsCryptographyKeyStore := \ ComAmazonawsDynamodb \ AwsCryptographicMaterialProviders/dafny/AwsCryptographicMaterialProviders \ +# 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" + +MPL_CORE_INDEX_FILE_PATH=dafny/AwsCryptographicMaterialProviders/src/Index.dfy +MPL_CORE_INDEX_FILE_WITH_EXTERN_STRING="module {:extern \"software.amazon.cryptography.materialproviders.internaldafny\" } MaterialProviders refines AbstractAwsCryptographyMaterialProvidersService" +MPL_CORE_INDEX_FILE_WITHOUT_EXTERN_STRING="module MaterialProviders refines AbstractAwsCryptographyMaterialProvidersService" + +KEYSTORE_TYPES_FILE_PATH=dafny/AwsCryptographyKeyStore/Model/AwsCryptographyKeyStoreTypes.dfy +KEYSTORE_TYPES_FILE_WITH_EXTERN_STRING="module {:extern \"software.amazon.cryptography.keystore.internaldafny.types\" } AwsCryptographyKeyStoreTypes" +KEYSTORE_TYPES_FILE_WITHOUT_EXTERN_STRING="module AwsCryptographyKeyStoreTypes" + +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" + +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 {" + +STORM_TRACKING_CMC_FILE_PATH=dafny/AwsCryptographicMaterialProviders/src/CMCs/StormTrackingCMC.dfy +STORM_TRACKING_CMC_WITH_EXTERN_STRING="module {:options \"\/functionSyntax:4\" } {:extern \"software.amazon.cryptography.internaldafny.StormTrackingCMC\" } StormTrackingCMC {" +STORM_TRACKING_CMC_WITHOUT_EXTERN_STRING="module {:options \"\/functionSyntax:4\" } StormTrackingCMC {" + +_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) + +_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=$(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) + +_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=$(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) + +# Python + +PYTHON_MODULE_NAME=aws_cryptographic_materialproviders + +TRANSLATION_RECORD_PYTHON := \ + --translation-record ../StandardLibrary/runtimes/python/src/smithy_dafny_standard_library/internaldafny/generated/dafny_src-py.dtr \ + --translation-record ../ComAmazonawsKms/runtimes/python/src/aws_cryptography_internal_kms/internaldafny/generated/dafny_src-py.dtr \ + --translation-record ../ComAmazonawsDynamodb/runtimes/python/src/aws_cryptography_internal_dynamodb/internaldafny/generated/dafny_src-py.dtr \ + --translation-record ../AwsCryptographyPrimitives/runtimes/python/src/aws_cryptography_primitives/internaldafny/generated/dafny_src-py.dtr + +PYTHON_DEPENDENCY_MODULE_NAMES := \ + --dependency-library-name=aws.cryptography.primitives=aws_cryptography_primitives \ + --dependency-library-name=com.amazonaws.kms=aws_cryptography_internal_kms \ + --dependency-library-name=com.amazonaws.dynamodb=aws_cryptography_internal_dynamodb \ + --dependency-library-name=aws.cryptography.materialProviders=aws_cryptographic_materialproviders \ + --dependency-library-name=aws.cryptography.keyStore=aws_cryptographic_materialproviders \ \ No newline at end of file diff --git a/AwsCryptographicMaterialProviders/codebuild/release-python/prod-release.yml b/AwsCryptographicMaterialProviders/codebuild/release-python/prod-release.yml new file mode 100644 index 000000000..f38fb12cf --- /dev/null +++ b/AwsCryptographicMaterialProviders/codebuild/release-python/prod-release.yml @@ -0,0 +1,63 @@ +version: 0.2 + +env: + variables: + BRANCH: "main" + secrets-manager: + TWINE_USERNAME: PyPiAPIToken:username + TWINE_PASSWORD: PyPiAPIToken:password + +phases: + install: + commands: + - pip install "tox < 4.0" + - pip install --upgrade pip + runtime-versions: + python: latest + pre_build: + commands: + # Get Dafny + - export dafnyVersion=$(grep '^dafnyVersion=' project.properties | cut -d '=' -f 2) + - cd .. + - curl https://github.com/dafny-lang/dafny/releases/download/v$dafnyVersion/dafny-$dafnyVersion-x64-ubuntu-20.04.zip -L -o dafny.zip + - unzip -qq dafny.zip && rm dafny.zip + - export PATH="$PWD/dafny:$PATH" + # Switch back to the main directory + - cd aws-cryptographic-material-providers-library + # Assert that project version is the expected released version + - git checkout $COMMIT_ID + - FOUND_VERSION=$(sed -n 's/version = "\(.*\)"/\1/p' AwsCryptographicMaterialProviders/runtimes/python/pyproject.toml) + - | + if expr ${FOUND_VERSION} != ${VERSION}; then + echo "pyproject.toml version (${FOUND_VERSION}) does not match expected version (${VERSION}), stopping" + exit 1; + fi + - cd AwsCryptographicMaterialProviders + # Build Dafny test source code + - make transpile_only_test_python + build: + commands: + - cd runtimes/python/ + # Install poetry + # https://python-poetry.org/docs/#installing-manually + - pip install poetry + # Install project dependencies with release dependencies + - poetry install --with release + # Build whl/sdist, upload to PyPI + # TODO: When ready to prod release, uncomment this line + # tox -e release + +batch: + fast-fail: true + build-graph: + - identifier: release_to_prod + env: + image: aws/codebuild/standard:7.0 + - identifier: validate_prod_release + depend-on: + - release_to_prod + buildspec: AwsCryptographicMaterialProviders/codebuild/release-python/validate.yml + env: + variables: + PIP_INDEX_URL: https://pypi.python.org/simple/ + image: aws/codebuild/standard:7.0 diff --git a/AwsCryptographicMaterialProviders/codebuild/release-python/test-release.yml b/AwsCryptographicMaterialProviders/codebuild/release-python/test-release.yml new file mode 100644 index 000000000..67ca5b517 --- /dev/null +++ b/AwsCryptographicMaterialProviders/codebuild/release-python/test-release.yml @@ -0,0 +1,65 @@ +version: 0.2 + +env: + variables: + BRANCH: "main" + secrets-manager: + TWINE_USERNAME: TestPyPiAPIToken:username + TWINE_PASSWORD: TestPyPiAPIToken:password + +phases: + install: + commands: + - pip install "tox < 4.0" + - pip install --upgrade pip + runtime-versions: + python: latest + pre_build: + commands: + # Get Dafny + - export dafnyVersion=$(grep '^dafnyVersion=' project.properties | cut -d '=' -f 2) + - cd .. + - curl https://github.com/dafny-lang/dafny/releases/download/v$dafnyVersion/dafny-$dafnyVersion-x64-ubuntu-20.04.zip -L -o dafny.zip + - unzip -qq dafny.zip && rm dafny.zip + - export PATH="$PWD/dafny:$PATH" + # Switch back to the main directory + - cd aws-cryptographic-material-providers-library + # Assert that project version is the expected released version + - git checkout $COMMIT_ID + - FOUND_VERSION=$(sed -n 's/version = "\(.*\)"/\1/p' AwsCryptographicMaterialProviders/runtimes/python/pyproject.toml) + - | + if expr ${FOUND_VERSION} != ${VERSION}; then + echo "pyproject.toml version (${FOUND_VERSION}) does not match expected version (${VERSION}), stopping" + exit 1; + fi + - cd AwsCryptographicMaterialProviders + # Build Dafny test source code + - make transpile_only_test_python + build: + commands: + - cd runtimes/python/ + # Install poetry + # https://python-poetry.org/docs/#installing-manually + - pip install poetry + # Add test PyPI as a supplemental repo for installing previously published test packages + - poetry source add --priority=supplemental test https://test.pypi.org/simple/ + # Install project dependencies with release dependencies + - poetry install --with release + # Build whl/sdist, upload to test PyPI + - tox -e test-release + +batch: + fast-fail: true + build-graph: + - identifier: release_to_staging + env: + image: aws/codebuild/standard:7.0 + - identifier: validate_staging_release + depend-on: + - release_to_staging + buildspec: AwsCryptographicMaterialProviders/codebuild/release-python/validate.yml + env: + variables: + PIP_INDEX_URL: https://test.pypi.org/simple/ + PIP_EXTRA_INDEX_URL: https://pypi.python.org/simple/ + image: aws/codebuild/standard:7.0 diff --git a/AwsCryptographicMaterialProviders/codebuild/release-python/validate.yml b/AwsCryptographicMaterialProviders/codebuild/release-python/validate.yml new file mode 100644 index 000000000..37c85036e --- /dev/null +++ b/AwsCryptographicMaterialProviders/codebuild/release-python/validate.yml @@ -0,0 +1,89 @@ +version: 0.2 + +# Validate that the released artifact is usable +# by installing it from PyPI +# then running tests from source against the published artifact. + +# For the MPL package, which has the ESDK as a downstream dependency, +# also validate that the released artifact is usable by the ESDK +# by downloading the ESDK from source +# and running tests with the newly published MPL artifact. + +phases: + install: + commands: + - pip install "tox < 4.0" + runtime-versions: + python: latest + pre_build: + commands: + # Get Dafny + - export dafnyVersion=$(grep '^dafnyVersion=' project.properties | cut -d '=' -f 2) + - cd .. + - curl https://github.com/dafny-lang/dafny/releases/download/v$dafnyVersion/dafny-$dafnyVersion-x64-ubuntu-20.04.zip -L -o dafny.zip + - unzip -qq dafny.zip && rm dafny.zip + - export PATH="$PWD/dafny:$PATH" + # Switch back to the main directory + - cd aws-cryptographic-material-providers-library + # Install test dependencies + - pyenv install --skip-existing 3.11 + - pyenv local 3.11 + - pip install "tox < 4.0" + - pip install pytest + # Install the published artifact from PyPI. + # The tests will use the installed package, not the local code. + # The actual test code must be from local, since we don't publish tests. + - pip install aws-cryptographic-materialproviders==$VERSION + # Install ESDK-Python, override its requirements to force use of the just-published MPL version + - git clone -b mpl-reviewed https://github.com/aws/aws-encryption-sdk-python.git + - cd aws-encryption-sdk-python + - sed -i "s/aws-cryptographic-materialproviders.*/aws-cryptographic-materialproviders==$VERSION/" requirements_mpl.txt + - cd .. + # Get CI Creds to be able to call KMS and DDB + - TMP_ROLE=$(aws sts assume-role --role-arn "arn:aws:iam::370957321024:role/GitHub-CI-MPL-Dafny-Role-us-west-2" --role-session-name "MPL-Python-Release") + - export TMP_ROLE + - export AWS_ACCESS_KEY_ID=$(echo "${TMP_ROLE}" | jq -r '.Credentials.AccessKeyId') + - export AWS_SECRET_ACCESS_KEY=$(echo "${TMP_ROLE}" | jq -r '.Credentials.SecretAccessKey') + - export AWS_SESSION_TOKEN=$(echo "${TMP_ROLE}" | jq -r '.Credentials.SessionToken') + - aws sts get-caller-identity + build: + commands: + - NUM_RETRIES=3 + # First, run tests with the published package + - cd AwsCryptographicMaterialProviders + - make transpile_python + - cd runtimes/python + - python -m pytest test/ -s -v + # Then, run ESDK local tests with the new MPL artifact installed + - cd ../../../aws-encryption-sdk-python + - | + while [ $NUM_RETRIES -gt 0 ] + do + tox -e py311-local-mpl + if [ $? -eq 0 ]; then + break + fi + NUM_RETRIES=$((NUM_RETRIES-1)) + if [ $NUM_RETRIES -eq 0 ]; then + echo "All validation attempts failed, stopping" + exit 1; + else + echo "Validation failed, retrying in 60 seconds; will retry $NUM_RETRIES more times" && sleep 60 + fi + done + # Then, MPL-only local tests with the MPL installed + - | + while [ $NUM_RETRIES -gt 0 ] + do + tox -e py311-mpllocal-mpl + if [ $? -eq 0 ]; then + break + fi + NUM_RETRIES=$((NUM_RETRIES-1)) + if [ $NUM_RETRIES -eq 0 ]; then + echo "All validation attempts failed, stopping" + exit 1; + else + echo "Validation failed, retrying in 60 seconds; will retry $NUM_RETRIES more times" && sleep 60 + fi + done diff --git a/AwsCryptographicMaterialProviders/runtimes/python/.gitignore b/AwsCryptographicMaterialProviders/runtimes/python/.gitignore new file mode 100644 index 000000000..61d5202d8 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/python/.gitignore @@ -0,0 +1,17 @@ +# Python build artifacts +__pycache__ +**/__pycache__ +*.pyc +src/**.egg-info/ +build +poetry.lock +**/poetry.lock +dist + +# Dafny-generated Python +**/internaldafny/generated/*.py + +# Python test artifacts +.tox +.pytest_cache + diff --git a/AwsCryptographicMaterialProviders/runtimes/python/.readthedocs.yaml b/AwsCryptographicMaterialProviders/runtimes/python/.readthedocs.yaml new file mode 100644 index 000000000..87bbc4df5 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/python/.readthedocs.yaml @@ -0,0 +1,37 @@ +# .readthedocs.yaml +# Read the Docs configuration file +# See https://docs.readthedocs.io/en/stable/config-file/v2.html for details + +# Required +version: 2 + +# Set the OS, Python version and other tools you might need +build: + os: ubuntu-22.04 + tools: + python: "3.11" + jobs: + post_create_environment: + # Install poetry + # https://python-poetry.org/docs/#installing-manually + - pip install poetry + # Get Dafny. + # readthedocs executes each command in a new shell process, so exported variables aren't persisted between commands. + # Any command that relies on exported variables needs to be executed in one command. + - export dafnyVersion=$(grep '^dafnyVersion=' project.properties | cut -d '=' -f 2) && curl https://github.com/dafny-lang/dafny/releases/download/v$dafnyVersion/dafny-$dafnyVersion-x64-ubuntu-20.04.zip -L -o dafny.zip + - unzip -qq dafny.zip && rm dafny.zip + - export PATH="$PWD/dafny:$PATH" && make transpile_python -C AwsCryptographicMaterialProviders + post_install: + # Install project with 'docs' dependency group + # https://python-poetry.org/docs/managing-dependencies/#dependency-groups + # VIRTUAL_ENV needs to be set manually for now. + # See https://github.com/readthedocs/readthedocs.org/pull/11152/ + - VIRTUAL_ENV=$READTHEDOCS_VIRTUALENV_PATH poetry install --directory AwsCryptographicMaterialProviders/runtimes/python --with docs + +# Build documentation in the doc/ directory with Sphinx +sphinx: + configuration: AwsCryptographicMaterialProviders/runtimes/python/doc/conf.py + +submodules: + include: all + recursive: true diff --git a/AwsCryptographicMaterialProviders/runtimes/python/README.rst b/AwsCryptographicMaterialProviders/runtimes/python/README.rst new file mode 100644 index 000000000..db96f71de --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/python/README.rst @@ -0,0 +1,78 @@ +#################################################### +aws-cryptographic-materials-providers-library-python +#################################################### + +.. image:: https://github.com/aws/aws-cryptographic-material-providers-library/actions/workflows/push.yml/badge.svg + :target: https://github.com/aws/aws-cryptographic-material-providers-library/actions/workflows/push.yml + :alt: MPL-python-tests + +.. image:: https://img.shields.io/badge/code_style-black-000000.svg + :target: https://github.com/ambv/black + :alt: Code style: black + +.. image:: https://readthedocs.org/projects/aws-cryptographic-material-providers-library/badge/ + :target: https://aws-cryptographic-material-providers-library.readthedocs.io/en/latest/ + :alt: Documentation Status + +These are the docs for the AWS Cryptographic Materials Providers Library for Python. + +The latest full documentation can be found at `Read the Docs`_. + +Find us on `GitHub`_. + +Security +******** + +If you discover a potential security issue in this project +we ask that you notify AWS/Amazon Security via our +`vulnerability reporting page`_. +Please **do not** create a public GitHub issue. + +*************** +Getting Started +*************** +Required Prerequisites +====================== + +* Python 3.11+ +* cryptography >= 41.0.0 +* boto3 >= 1.28.0 + +Installation +============ + +.. note:: + + If you have not already installed `cryptography`_, you might need to install additional prerequisites as + detailed in the `cryptography installation guide`_ for your operating system. + + .. code:: + + $ pip install aws-cryptographic-material-providers + + +Concepts +======== +The AWS Cryptographic Materials Providers Library (MPL) is available in multiple languages. +The concepts in the Python implementation of the MPL are the same as in other languages. +For more information on concepts in the MPL, see the `README`_ for all languages. + +************* +Thread safety +************* + +The ``MaterialProviders`` client and all provided ``CryptoMaterialsManagers`` (CMMs) are thread safe. +But keyrings that call AWS Key Management Service (KMS) and CMMs that use keyrings that call KMS MUST not be shared between threads, for reasons outlined in `the boto3 docs`_. + +(Keyrings that call KMS are identified by the string ``Kms`` in their name. ex. ``AwsKmsKeyring``, ``AwsKmsMrkDiscoveryMultiKeyring``, etc.) + +Finally, while the provided implementations of ``ICryptographicMaterialsCache`` are thread-safe, +there is currently no thread-safe keyring implementation that supports using a cache. + +.. _cryptography: https://cryptography.io/en/latest/ +.. _cryptography installation guide: https://cryptography.io/en/latest/installation/ +.. _Read the Docs: https://aws-cryptographic-material-providers-library.readthedocs.io/en/latest/ +.. _GitHub: https://github.com/aws/aws-cryptographic-material-providers-library +.. _vulnerability reporting page : http://aws.amazon.com/security/vulnerability-reporting/ +.. _the boto3 docs: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/resources.html#multithreading-or-multiprocessing-with-resources +.. _README: https://github.com/aws/aws-cryptographic-material-providers-library/blob/main/README.md \ No newline at end of file diff --git a/AwsCryptographicMaterialProviders/runtimes/python/doc/conf.py b/AwsCryptographicMaterialProviders/runtimes/python/doc/conf.py new file mode 100644 index 000000000..41372f070 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/python/doc/conf.py @@ -0,0 +1,72 @@ +# -*- coding: utf-8 -*- +import os +import re +from datetime import datetime +import toml + +VERSION_RE = re.compile(r"""__version__ = ['"]([0-9.]+)['"]""") +HERE = os.path.abspath(os.path.dirname(__file__)) + + +def get_release(): + with open('../pyproject.toml', 'r') as toml_file: + data = toml.load(toml_file) + return data['tool']['poetry']['version'] + +def get_version(): + """Reads the version (MAJOR.MINOR) from this module.""" + release = get_release() + split_version = release.split(".") + if len(split_version) == 3: + return ".".join(split_version[:2]) + return release + +project = u"aws-cryptographic-materialproviders" +version = get_version() +release = get_release() + +# Add any Sphinx extension module names here, as strings. They can be extensions +# coming with Sphinx (named 'sphinx.ext.*') or your custom ones. +extensions = [ + "sphinx.ext.autodoc", + "sphinx.ext.doctest", + "sphinx.ext.intersphinx", + "sphinx.ext.todo", + "sphinx.ext.coverage", + "sphinx.ext.autosummary", + "sphinx.ext.napoleon", +] +napoleon_include_special_with_doc = False + +# Add any paths that contain templates here, relative to this directory. +templates_path = ["_templates"] + +source_suffix = ".rst" # The suffix of source filenames. +root_doc = "index" # The master toctree document. + +copyright = u"%s, Amazon" % datetime.now().year + +# List of directories, relative to source directory, that shouldn't be searched +# for source files. +exclude_trees = ["_build"] + +pygments_style = "sphinx" + +autoclass_content = "both" +autodoc_default_options = { + "show-inheritance": True, + "undoc-members": True, + 'special-members': '__init__', + "members": True +} +autodoc_member_order = "bysource" + +html_theme = "sphinx_rtd_theme" +html_static_path = ["_static"] +htmlhelp_basename = "%sdoc" % project + +# Example configuration for intersphinx: refer to the Python standard library. +intersphinx_mapping = {"http://docs.python.org/": None} + +# autosummary +autosummary_generate = True diff --git a/AwsCryptographicMaterialProviders/runtimes/python/doc/index.rst b/AwsCryptographicMaterialProviders/runtimes/python/doc/index.rst new file mode 100644 index 000000000..762a7e8c9 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/python/doc/index.rst @@ -0,0 +1,24 @@ +.. include:: ../README.rst + +.. include:: ../../../../README.md + :parser: myst_parser.docutils_ + +******* +Modules +******* + +.. autosummary:: + :toctree: generated + + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_keystore.client + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_keystore.config + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_keystore.errors + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_keystore.models + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.client + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.config + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.errors + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.references + +.. include:: ../../../../CHANGELOG.md + :parser: myst_parser.docutils_ \ No newline at end of file diff --git a/AwsCryptographicMaterialProviders/runtimes/python/pyproject.toml b/AwsCryptographicMaterialProviders/runtimes/python/pyproject.toml new file mode 100644 index 000000000..eb7ccf04c --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/python/pyproject.toml @@ -0,0 +1,52 @@ +[tool.poetry] +name = "aws-cryptographic-materialproviders" +version = "0.1.1" +description = "AWS Cryptographic Material Providers Library for Python" +authors = ["AWS Crypto Tools "] +packages = [ + { include = "aws_cryptographic_materialproviders", from = "src" }, +] +# Include generated internaldafny files in package distributions, +# even though they are not included in version control +include = ["**/internaldafny/generated/*.py"] +readme = "README.rst" + +[tool.poetry.dependencies] +python = "^3.11.0" +aws-cryptography-internal-standard-library = {path = "../../../StandardLibrary/runtimes/python"} +aws-cryptography-internal-kms = {path = "../../../ComAmazonawsKms/runtimes/python"} +aws-cryptography-internal-dynamodb = {path = "../../../ComAmazonawsDynamodb/runtimes/python"} +aws-cryptography-internal-primitives = {path = "../../../AwsCryptographyPrimitives/runtimes/python"} + +# Package testing + +[tool.poetry.group.test] +optional = true + +[tool.poetry.group.test.dependencies] +pytest = "^7.4.0" + +# Package release + +[tool.poetry.group.release] +optional = true + +[tool.poetry.group.release.dependencies] +poetry = "1.8.3" +twine = "5.1.1" +wheel = "0.38.4" + +# Package documentation + +[tool.poetry.group.docs] +optional = true + +[tool.poetry.group.docs.dependencies] +toml = "^0.10.2" +myst-parser = "^4" +sphinx = "^7" +sphinx_rtd_theme = "^2" + +[build-system] +requires = ["poetry-core"] +build-backend = "poetry.core.masonry.api" diff --git a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/__init__.py b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/__init__.py new file mode 100644 index 000000000..90cb5ca0d --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/__init__.py @@ -0,0 +1,17 @@ +# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 + +# Initialize generated Dafny +from .internaldafny.generated import module_ + +# Initialize externs +from .internaldafny import extern + +# Export user-friendly access paths +import aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders as mpl +import aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_keystore as keystore + +__all__ = [ + mpl, + keystore +] diff --git a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/internaldafny/extern/StormTrackingCMC.py b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/internaldafny/extern/StormTrackingCMC.py new file mode 100644 index 000000000..3d36b96a8 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/internaldafny/extern/StormTrackingCMC.py @@ -0,0 +1,83 @@ +import time +import aws_cryptographic_materialproviders.internaldafny.generated.StormTrackingCMC +import smithy_dafny_standard_library.internaldafny.generated.Wrappers as Wrappers +import aws_cryptographic_materialproviders.internaldafny.generated.AwsCryptographyMaterialProvidersTypes +from . import Lock + +class StormTrackingCMC: + + def __init__(self, wrapped): + self.wrapped = wrapped + self.lock = Lock() + + def PutCacheEntry(self, input): + self.lock.Lock__() + val = self.wrapped.PutCacheEntry(input) + self.lock.Unlock() + return val + + def UpdateUsageMetadata(self, input): + self.lock.Lock__() + val = self.wrapped.UpdateUsageMetadata(input) + self.lock.Unlock() + return val + + # NOT locked, as some sleeping might be involved + def GetCacheEntry(self, input): + return self.GetCacheEntry_k(input) + + def DeleteCacheEntry(self, input): + self.lock.Lock__() + val = self.wrapped.DeleteCacheEntry(input) + self.lock.Unlock() + return val + + def PutCacheEntry_k(self, input): + self.lock.Lock__() + val = self.wrapped.PutCacheEntry(input) + self.lock.Unlock() + return val + + def UpdateUsageMetadata_k(self, input): + self.lock.Lock__() + val = self.wrapped.UpdateUsageMetadata(input) + self.lock.Unlock() + return val + + # This is the synchronization for GetCacheEntry and GetCacheEntry_k + def GetFromCacheInner(self, input): + self.lock.Lock__() + val = self.wrapped.GetFromCache(input) + self.lock.Unlock() + return val + + # NOT locked, because we sleep. Calls GetFromCache which IS synchronized. + def GetCacheEntry_k(self, input): + while True: + result = self.GetFromCacheInner(input) + if result.is_Failure: + return Wrappers.Result_Failure(result.error) + elif result.value.is_Full: + return Wrappers.Result_Success(result.value.data) + elif result.value.is_EmptyFetch: + return Wrappers.Result_Failure( + aws_cryptographic_materialproviders.internaldafny.generated.AwsCryptographyMaterialProvidersTypes.Error_EntryDoesNotExist( + "Entry does not exist" + ) + ) + else: + try: + time.sleep(self.wrapped.sleepMilli) + except: + pass + + def DeleteCacheEntry_k(self, input): + self.lock.Lock__() + val = self.wrapped.DeleteCacheEntry(input) + self.lock.Unlock() + return val + + def __str__(self): + return "StormTracker.StormTrackerCMC" + +aws_cryptographic_materialproviders.internaldafny.generated.StormTrackingCMC.StormTrackingCMC = StormTrackingCMC \ No newline at end of file diff --git a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/internaldafny/extern/SynchronizedLocalCMC.py b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/internaldafny/extern/SynchronizedLocalCMC.py new file mode 100644 index 000000000..8b7eca684 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/internaldafny/extern/SynchronizedLocalCMC.py @@ -0,0 +1,70 @@ +import aws_cryptographic_materialproviders.internaldafny.generated.StormTrackingCMC +import aws_cryptographic_materialproviders.internaldafny.generated.SynchronizedLocalCMC +import smithy_dafny_standard_library.internaldafny.generated.Wrappers as Wrappers +import aws_cryptographic_materialproviders.internaldafny.generated.AwsCryptographyMaterialProvidersTypes +from . import Lock + +class SynchronizedLocalCMC: + + def __init__(self, wrapped): + self.wrapped = wrapped + self.lock = Lock() + + def PutCacheEntry(self, input): + self.lock.Lock__() + val = self.wrapped.PutCacheEntry(input) + self.lock.Unlock() + return val + + def UpdateUsageMetadata(self, input): + self.lock.Lock__() + val = self.wrapped.UpdateUsageMetadata(input) + self.lock.Unlock() + return val + + def GetCacheEntry(self, input): + self.lock.Lock__() + val = self.wrapped.GetCacheEntry(input) + self.lock.Unlock() + return val + + def DeleteCacheEntry(self, input): + self.lock.Lock__() + val = self.wrapped.DeleteCacheEntry(input) + self.lock.Unlock() + return val + + def PutCacheEntry_k(self, input): + self.lock.Lock__() + val = self.wrapped.PutCacheEntry(input) + self.lock.Unlock() + return val + + def UpdateUsageMetadata_k(self, input): + self.lock.Lock__() + val = self.wrapped.UpdateUsageMetadata(input) + self.lock.Unlock() + return val + + def GetFromCacheInner(self, input): + self.lock.Lock__() + val = self.wrapped.GetFromCache(input) + self.lock.Unlock() + return val + + def GetCacheEntry_k(self, input): + self.lock.Lock__() + val = self.wrapped.GetCacheEntry(input) + self.lock.Unlock() + return val + + def DeleteCacheEntry_k(self, input): + self.lock.Lock__() + val = self.wrapped.DeleteCacheEntry(input) + self.lock.Unlock() + return val + + def __str__(self): + return "LocalCMC.SynchronizedLocalCMC" + +aws_cryptographic_materialproviders.internaldafny.generated.SynchronizedLocalCMC.SynchronizedLocalCMC = SynchronizedLocalCMC \ No newline at end of file diff --git a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/internaldafny/extern/__init__.py b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/internaldafny/extern/__init__.py new file mode 100644 index 000000000..501c51def --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/internaldafny/extern/__init__.py @@ -0,0 +1,25 @@ +# This is copy-pasted from DafnyStandardLibraries: +# https://github.com/dafny-lang/dafny/blob/f01af4a4e86a038ed4ea9f81464b2c9bca1955e4/Source/DafnyStandardLibraries/src/Std_Concurrent.py +import threading + +# Module: Std_Concurrent + +class Lock: + def ctor__(self): + pass + + def __init__(self) -> None: + self.lock = threading.Lock() + + def Lock__(self): + self.lock.acquire() + + def Unlock(self): + self.lock.release() + +# externs depend on the Lock definition; +# import them after defining Lock +from . import ( + StormTrackingCMC, + SynchronizedLocalCMC, +) \ No newline at end of file diff --git a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/internaldafny/generated/dafny_src-py.dtr b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/internaldafny/generated/dafny_src-py.dtr new file mode 100644 index 000000000..0639ba4cf --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/internaldafny/generated/dafny_src-py.dtr @@ -0,0 +1,179 @@ +file_format_version = "1.0" +dafny_version = "4.8.0.0" +[options_by_module.AwsCryptographyKeyStoreTypes] +legacy-module-names = false +python-module-name = "aws_cryptographic_materialproviders.internaldafny.generated" +[options_by_module.AbstractAwsCryptographyKeyStoreOperations] +legacy-module-names = false +python-module-name = "aws_cryptographic_materialproviders.internaldafny.generated" +[options_by_module.AbstractAwsCryptographyKeyStoreService] +legacy-module-names = false +python-module-name = "aws_cryptographic_materialproviders.internaldafny.generated" +[options_by_module.AwsCryptographyMaterialProvidersTypes] +legacy-module-names = false +python-module-name = "aws_cryptographic_materialproviders.internaldafny.generated" +[options_by_module.AwsArnParsing] +legacy-module-names = false +python-module-name = "aws_cryptographic_materialproviders.internaldafny.generated" +[options_by_module.AwsKmsMrkMatchForDecrypt] +legacy-module-names = false +python-module-name = "aws_cryptographic_materialproviders.internaldafny.generated" +[options_by_module.AwsKmsUtils] +legacy-module-names = false +python-module-name = "aws_cryptographic_materialproviders.internaldafny.generated" +[options_by_module.KeyStoreErrorMessages] +legacy-module-names = false +python-module-name = "aws_cryptographic_materialproviders.internaldafny.generated" +[options_by_module.KmsArn] +legacy-module-names = false +python-module-name = "aws_cryptographic_materialproviders.internaldafny.generated" +[options_by_module.Structure] +legacy-module-names = false +python-module-name = "aws_cryptographic_materialproviders.internaldafny.generated" +[options_by_module.KMSKeystoreOperations] +legacy-module-names = false +python-module-name = "aws_cryptographic_materialproviders.internaldafny.generated" +[options_by_module.DDBKeystoreOperations] +legacy-module-names = false +python-module-name = "aws_cryptographic_materialproviders.internaldafny.generated" +[options_by_module.CreateKeys] +legacy-module-names = false +python-module-name = "aws_cryptographic_materialproviders.internaldafny.generated" +[options_by_module.CreateKeyStoreTable] +legacy-module-names = false +python-module-name = "aws_cryptographic_materialproviders.internaldafny.generated" +[options_by_module.GetKeys] +legacy-module-names = false +python-module-name = "aws_cryptographic_materialproviders.internaldafny.generated" +[options_by_module.AwsCryptographyKeyStoreOperations] +legacy-module-names = false +python-module-name = "aws_cryptographic_materialproviders.internaldafny.generated" +[options_by_module.KeyStore] +legacy-module-names = false +python-module-name = "aws_cryptographic_materialproviders.internaldafny.generated" +[options_by_module.AbstractAwsCryptographyMaterialProvidersOperations] +legacy-module-names = false +python-module-name = "aws_cryptographic_materialproviders.internaldafny.generated" +[options_by_module.AbstractAwsCryptographyMaterialProvidersService] +legacy-module-names = false +python-module-name = "aws_cryptographic_materialproviders.internaldafny.generated" +[options_by_module.AlgorithmSuites] +legacy-module-names = false +python-module-name = "aws_cryptographic_materialproviders.internaldafny.generated" +[options_by_module.Materials] +legacy-module-names = false +python-module-name = "aws_cryptographic_materialproviders.internaldafny.generated" +[options_by_module.Keyring] +legacy-module-names = false +python-module-name = "aws_cryptographic_materialproviders.internaldafny.generated" +[options_by_module.MultiKeyring] +legacy-module-names = false +python-module-name = "aws_cryptographic_materialproviders.internaldafny.generated" +[options_by_module.AwsKmsMrkAreUnique] +legacy-module-names = false +python-module-name = "aws_cryptographic_materialproviders.internaldafny.generated" +[options_by_module.Constants] +legacy-module-names = false +python-module-name = "aws_cryptographic_materialproviders.internaldafny.generated" +[options_by_module.MaterialWrapping] +legacy-module-names = false +python-module-name = "aws_cryptographic_materialproviders.internaldafny.generated" +[options_by_module.CanonicalEncryptionContext] +legacy-module-names = false +python-module-name = "aws_cryptographic_materialproviders.internaldafny.generated" +[options_by_module.IntermediateKeyWrapping] +legacy-module-names = false +python-module-name = "aws_cryptographic_materialproviders.internaldafny.generated" +[options_by_module.EdkWrapping] +legacy-module-names = false +python-module-name = "aws_cryptographic_materialproviders.internaldafny.generated" +[options_by_module.ErrorMessages] +legacy-module-names = false +python-module-name = "aws_cryptographic_materialproviders.internaldafny.generated" +[options_by_module.AwsKmsKeyring] +legacy-module-names = false +python-module-name = "aws_cryptographic_materialproviders.internaldafny.generated" +[options_by_module.StrictMultiKeyring] +legacy-module-names = false +python-module-name = "aws_cryptographic_materialproviders.internaldafny.generated" +[options_by_module.AwsKmsDiscoveryKeyring] +legacy-module-names = false +python-module-name = "aws_cryptographic_materialproviders.internaldafny.generated" +[options_by_module.DiscoveryMultiKeyring] +legacy-module-names = false +python-module-name = "aws_cryptographic_materialproviders.internaldafny.generated" +[options_by_module.AwsKmsMrkDiscoveryKeyring] +legacy-module-names = false +python-module-name = "aws_cryptographic_materialproviders.internaldafny.generated" +[options_by_module.MrkAwareDiscoveryMultiKeyring] +legacy-module-names = false +python-module-name = "aws_cryptographic_materialproviders.internaldafny.generated" +[options_by_module.AwsKmsMrkKeyring] +legacy-module-names = false +python-module-name = "aws_cryptographic_materialproviders.internaldafny.generated" +[options_by_module.MrkAwareStrictMultiKeyring] +legacy-module-names = false +python-module-name = "aws_cryptographic_materialproviders.internaldafny.generated" +[options_by_module.LocalCMC] +legacy-module-names = false +python-module-name = "aws_cryptographic_materialproviders.internaldafny.generated" +[options_by_module.SynchronizedLocalCMC] +legacy-module-names = false +python-module-name = "aws_cryptographic_materialproviders.internaldafny.generated" +[options_by_module.StormTracker] +legacy-module-names = false +python-module-name = "aws_cryptographic_materialproviders.internaldafny.generated" +[options_by_module.StormTrackingCMC] +legacy-module-names = false +python-module-name = "aws_cryptographic_materialproviders.internaldafny.generated" +[options_by_module.CacheConstants] +legacy-module-names = false +python-module-name = "aws_cryptographic_materialproviders.internaldafny.generated" +[options_by_module.AwsKmsHierarchicalKeyring] +legacy-module-names = false +python-module-name = "aws_cryptographic_materialproviders.internaldafny.generated" +[options_by_module.AwsKmsRsaKeyring] +legacy-module-names = false +python-module-name = "aws_cryptographic_materialproviders.internaldafny.generated" +[options_by_module.EcdhEdkWrapping] +legacy-module-names = false +python-module-name = "aws_cryptographic_materialproviders.internaldafny.generated" +[options_by_module.RawECDHKeyring] +legacy-module-names = false +python-module-name = "aws_cryptographic_materialproviders.internaldafny.generated" +[options_by_module.AwsKmsEcdhKeyring] +legacy-module-names = false +python-module-name = "aws_cryptographic_materialproviders.internaldafny.generated" +[options_by_module.RawAESKeyring] +legacy-module-names = false +python-module-name = "aws_cryptographic_materialproviders.internaldafny.generated" +[options_by_module.RawRSAKeyring] +legacy-module-names = false +python-module-name = "aws_cryptographic_materialproviders.internaldafny.generated" +[options_by_module.CMM] +legacy-module-names = false +python-module-name = "aws_cryptographic_materialproviders.internaldafny.generated" +[options_by_module.Defaults] +legacy-module-names = false +python-module-name = "aws_cryptographic_materialproviders.internaldafny.generated" +[options_by_module.Commitment] +legacy-module-names = false +python-module-name = "aws_cryptographic_materialproviders.internaldafny.generated" +[options_by_module.DefaultCMM] +legacy-module-names = false +python-module-name = "aws_cryptographic_materialproviders.internaldafny.generated" +[options_by_module.DefaultClientSupplier] +legacy-module-names = false +python-module-name = "aws_cryptographic_materialproviders.internaldafny.generated" +[options_by_module.Utils] +legacy-module-names = false +python-module-name = "aws_cryptographic_materialproviders.internaldafny.generated" +[options_by_module.RequiredEncryptionContextCMM] +legacy-module-names = false +python-module-name = "aws_cryptographic_materialproviders.internaldafny.generated" +[options_by_module.AwsCryptographyMaterialProvidersOperations] +legacy-module-names = false +python-module-name = "aws_cryptographic_materialproviders.internaldafny.generated" +[options_by_module.MaterialProviders] +legacy-module-names = false +python-module-name = "aws_cryptographic_materialproviders.internaldafny.generated" diff --git a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/keystore/__init__.py b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/keystore/__init__.py new file mode 100644 index 000000000..a939b1849 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/keystore/__init__.py @@ -0,0 +1,3 @@ +# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 +from .client import KeyStore diff --git a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/keystore/client.py b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/keystore/client.py new file mode 100644 index 000000000..132e93507 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/keystore/client.py @@ -0,0 +1,3 @@ +# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 +from aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_keystore.client import * diff --git a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/keystore/config.py b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/keystore/config.py new file mode 100644 index 000000000..3925445fe --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/keystore/config.py @@ -0,0 +1,3 @@ +# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 +from aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_keystore.config import * diff --git a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/keystore/errors.py b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/keystore/errors.py new file mode 100644 index 000000000..494095b1a --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/keystore/errors.py @@ -0,0 +1,3 @@ +# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 +from aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_keystore.errors import * diff --git a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/keystore/models.py b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/keystore/models.py new file mode 100644 index 000000000..af8dc0e01 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/keystore/models.py @@ -0,0 +1,3 @@ +# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 +from aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_keystore.models import * diff --git a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/mpl/__init__.py b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/mpl/__init__.py new file mode 100644 index 000000000..16c57b9eb --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/mpl/__init__.py @@ -0,0 +1,3 @@ +# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 +from .client import AwsCryptographicMaterialProviders diff --git a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/mpl/client.py b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/mpl/client.py new file mode 100644 index 000000000..1b396c435 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/mpl/client.py @@ -0,0 +1,3 @@ +# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 +from aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.client import * diff --git a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/mpl/config.py b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/mpl/config.py new file mode 100644 index 000000000..4d0b3109c --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/mpl/config.py @@ -0,0 +1,3 @@ +# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 +from aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.config import * diff --git a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/mpl/errors.py b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/mpl/errors.py new file mode 100644 index 000000000..90c40e051 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/mpl/errors.py @@ -0,0 +1,3 @@ +# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 +from aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.errors import * diff --git a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/mpl/models.py b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/mpl/models.py new file mode 100644 index 000000000..4545350cc --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/mpl/models.py @@ -0,0 +1,3 @@ +# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 +from aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models import * diff --git a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/mpl/references.py b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/mpl/references.py new file mode 100644 index 000000000..9d03ff462 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/mpl/references.py @@ -0,0 +1,3 @@ +# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 +from aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.references import * diff --git a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/smithygenerated/aws_cryptography_keystore/__init__.py b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/smithygenerated/aws_cryptography_keystore/__init__.py new file mode 100644 index 000000000..09be6133b --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/smithygenerated/aws_cryptography_keystore/__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_materialproviders/smithygenerated/aws_cryptography_keystore/client.py b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/smithygenerated/aws_cryptography_keystore/client.py new file mode 100644 index 000000000..477e66639 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/smithygenerated/aws_cryptography_keystore/client.py @@ -0,0 +1,452 @@ +# 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_materialproviders.internaldafny.generated.AwsCryptographyKeyStoreTypes import ( + IKeyStoreClient, +) +from typing import Callable, TypeVar, cast + +from .config import Config, KeyStoreConfig +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_create_key, + _deserialize_create_key_store, + _deserialize_get_active_branch_key, + _deserialize_get_beacon_key, + _deserialize_get_branch_key_version, + _deserialize_get_key_store_info, + _deserialize_version_key, +) +from .errors import ServiceError +from .models import ( + CreateKeyInput, + CreateKeyOutput, + CreateKeyStoreInput, + CreateKeyStoreOutput, + GetActiveBranchKeyInput, + GetActiveBranchKeyOutput, + GetBeaconKeyInput, + GetBeaconKeyOutput, + GetBranchKeyVersionInput, + GetBranchKeyVersionOutput, + GetKeyStoreInfoOutput, + Unit, + VersionKeyInput, + VersionKeyOutput, +) +from .serialize import ( + _serialize_create_key, + _serialize_create_key_store, + _serialize_get_active_branch_key, + _serialize_get_beacon_key, + _serialize_get_branch_key_version, + _serialize_get_key_store_info, + _serialize_version_key, +) + + +Input = TypeVar("Input") +Output = TypeVar("Output") + + +class KeyStore: + """Client for KeyStore. + + :param config: Configuration for the client. + """ + + def __init__( + self, + config: KeyStoreConfig | None = None, + dafny_client: IKeyStoreClient | 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 get_key_store_info(self, input: Unit) -> GetKeyStoreInfoOutput: + """Returns the configuration information for a Key Store. + + :param input: The operation's input. + """ + return self._execute_operation( + input=input, + plugins=[], + serialize=_serialize_get_key_store_info, + deserialize=_deserialize_get_key_store_info, + config=self._config, + operation_name="GetKeyStoreInfo", + ) + + def create_key_store(self, input: CreateKeyStoreInput) -> CreateKeyStoreOutput: + """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. + + :param input: The operation's input. + """ + return self._execute_operation( + input=input, + plugins=[], + serialize=_serialize_create_key_store, + deserialize=_deserialize_create_key_store, + config=self._config, + operation_name="CreateKeyStore", + ) + + 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 in the Key + Store, and set the previously ACTIVE version to DECRYPT_ONLY. + + :param input: Inputs for versioning a Branch Key. + """ + return self._execute_operation( + input=input, + plugins=[], + serialize=_serialize_version_key, + deserialize=_deserialize_version_key, + config=self._config, + operation_name="VersionKey", + ) + + def get_active_branch_key( + self, input: GetActiveBranchKeyInput + ) -> GetActiveBranchKeyOutput: + """Get the ACTIVE version for a particular Branch Key from the Key + Store. + + :param input: Inputs for getting a Branch Key's ACTIVE version. + """ + return self._execute_operation( + input=input, + plugins=[], + serialize=_serialize_get_active_branch_key, + deserialize=_deserialize_get_active_branch_key, + config=self._config, + operation_name="GetActiveBranchKey", + ) + + def get_branch_key_version( + self, input: GetBranchKeyVersionInput + ) -> GetBranchKeyVersionOutput: + """Get a particular version of a Branch Key from the Key Store. + + :param input: Inputs for getting a version of a Branch Key. + """ + return self._execute_operation( + input=input, + plugins=[], + serialize=_serialize_get_branch_key_version, + deserialize=_deserialize_get_branch_key_version, + config=self._config, + operation_name="GetBranchKeyVersion", + ) + + def get_beacon_key(self, input: GetBeaconKeyInput) -> GetBeaconKeyOutput: + """Get a Beacon Key from the Key Store. + + :param input: Inputs for getting a Beacon Key + """ + return self._execute_operation( + input=input, + plugins=[], + serialize=_serialize_get_beacon_key, + deserialize=_deserialize_get_beacon_key, + config=self._config, + operation_name="GetBeaconKey", + ) + + 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_materialproviders/smithygenerated/aws_cryptography_keystore/config.py b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/smithygenerated/aws_cryptography_keystore/config.py new file mode 100644 index 000000000..9ee65fce6 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/smithygenerated/aws_cryptography_keystore/config.py @@ -0,0 +1,118 @@ +# 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_materialproviders.internaldafny.generated.AwsCryptographyKeyStoreTypes import ( + KeyStoreConfig_KeyStoreConfig as DafnyKeyStoreConfig, +) +import aws_cryptographic_materialproviders.internaldafny.generated.module_ +import aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_keystore.dafny_to_smithy +import aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_keystore.smithy_to_dafny +from dataclasses import dataclass +from typing import Any, Callable, Optional, TypeAlias + +from .dafnyImplInterface import DafnyImplInterface +from botocore.client import BaseClient +from smithy_python._private.retries import SimpleRetryStrategy +from smithy_python.interfaces.retries import RetryStrategy + +from .models import KMSConfiguration + + +_ServiceInterceptor = Any + + +@dataclass(init=False) +class Config: + """Configuration for KeyStore.""" + + 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 KeyStoreConfig(Config): + """Smithy-modelled localService Config shape for this localService.""" + + ddb_table_name: str + kms_configuration: KMSConfiguration + logical_key_store_name: str + id: Optional[str] + grant_tokens: Optional[list[str]] + ddb_client: Optional[BaseClient] + kms_client: Optional[BaseClient] + + def __init__( + self, + ddb_table_name: str, + kms_configuration: KMSConfiguration, + logical_key_store_name: str, + id: Optional[str] = None, + grant_tokens: Optional[list[str]] = 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 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 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. + :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. + """ + super().__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.ddb_client = ddb_client + self.kms_client = kms_client + + +def dafny_config_to_smithy_config(dafny_config) -> KeyStoreConfig: + """Converts the provided Dafny shape for this localService's config into + the corresponding Smithy-modelled shape.""" + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_KeyStoreConfig( + dafny_config + ) + + +def smithy_config_to_dafny_config(smithy_config) -> DafnyKeyStoreConfig: + """Converts the provided Smithy-modelled shape for this localService's + config into the corresponding Dafny shape.""" + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_KeyStoreConfig( + smithy_config + ) diff --git a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/smithygenerated/aws_cryptography_keystore/dafnyImplInterface.py b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/smithygenerated/aws_cryptography_keystore/dafnyImplInterface.py new file mode 100644 index 000000000..aab1c7b6c --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/smithygenerated/aws_cryptography_keystore/dafnyImplInterface.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_materialproviders.internaldafny.generated.KeyStore import ( + KeyStoreClient, +) +from .dafny_protocol import DafnyRequest + + +class DafnyImplInterface: + impl: KeyStoreClient | 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 = { + "GetKeyStoreInfo": self.impl.GetKeyStoreInfo, + "CreateKeyStore": self.impl.CreateKeyStore, + "CreateKey": self.impl.CreateKey, + "VersionKey": self.impl.VersionKey, + "GetActiveBranchKey": self.impl.GetActiveBranchKey, + "GetBranchKeyVersion": self.impl.GetBranchKeyVersion, + "GetBeaconKey": self.impl.GetBeaconKey, + } + + # 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_materialproviders/smithygenerated/aws_cryptography_keystore/dafny_protocol.py b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/smithygenerated/aws_cryptography_keystore/dafny_protocol.py new file mode 100644 index 000000000..dda2b999f --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/smithygenerated/aws_cryptography_keystore/dafny_protocol.py @@ -0,0 +1,42 @@ +# 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_materialproviders.internaldafny.generated.AwsCryptographyKeyStoreTypes import ( + CreateKeyInput_CreateKeyInput as DafnyCreateKeyInput, + CreateKeyStoreInput_CreateKeyStoreInput as DafnyCreateKeyStoreInput, + GetActiveBranchKeyInput_GetActiveBranchKeyInput as DafnyGetActiveBranchKeyInput, + GetBeaconKeyInput_GetBeaconKeyInput as DafnyGetBeaconKeyInput, + GetBranchKeyVersionInput_GetBranchKeyVersionInput as DafnyGetBranchKeyVersionInput, + VersionKeyInput_VersionKeyInput as DafnyVersionKeyInput, +) +import aws_cryptographic_materialproviders.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[ + DafnyGetActiveBranchKeyInput, + DafnyVersionKeyInput, + DafnyGetBranchKeyVersionInput, + DafnyGetBeaconKeyInput, + None, + DafnyCreateKeyInput, + DafnyCreateKeyStoreInput, + ] + + 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_materialproviders/smithygenerated/aws_cryptography_keystore/dafny_to_smithy.py b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/smithygenerated/aws_cryptography_keystore/dafny_to_smithy.py new file mode 100644 index 000000000..f0e72c0a1 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/smithygenerated/aws_cryptography_keystore/dafny_to_smithy.py @@ -0,0 +1,308 @@ +# 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_materialproviders.internaldafny.generated.AwsCryptographyKeyStoreTypes import ( + KMSConfiguration_discovery, + KMSConfiguration_kmsKeyArn, + KMSConfiguration_kmsMRKeyArn, + KMSConfiguration_mrDiscovery, +) +import aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_keystore.dafny_to_smithy +import aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_keystore.models + + +def smithy_api_Unit(): + return ( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_keystore.models.Unit() + ) + + +def aws_cryptography_keystore_CreateKeyStoreInput(dafny_input): + return ( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_keystore.models.CreateKeyStoreInput() + ) + + +def aws_cryptography_keystore_CreateKeyInput(dafny_input): + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_keystore.models.CreateKeyInput( + branch_key_identifier=( + ( + b"".join( + ord(c).to_bytes(2, "big") + for c in dafny_input.branchKeyIdentifier.value + ).decode("utf-16-be") + ) + if (dafny_input.branchKeyIdentifier.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 + ), + ) + + +def aws_cryptography_keystore_VersionKeyInput(dafny_input): + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_keystore.models.VersionKeyInput( + branch_key_identifier=b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.branchKeyIdentifier + ).decode("utf-16-be"), + ) + + +def aws_cryptography_keystore_GetActiveBranchKeyInput(dafny_input): + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_keystore.models.GetActiveBranchKeyInput( + branch_key_identifier=b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.branchKeyIdentifier + ).decode("utf-16-be"), + ) + + +def aws_cryptography_keystore_GetBranchKeyVersionInput(dafny_input): + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_keystore.models.GetBranchKeyVersionInput( + branch_key_identifier=b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.branchKeyIdentifier + ).decode("utf-16-be"), + branch_key_version=b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.branchKeyVersion + ).decode("utf-16-be"), + ) + + +def aws_cryptography_keystore_GetBeaconKeyInput(dafny_input): + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_keystore.models.GetBeaconKeyInput( + branch_key_identifier=b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.branchKeyIdentifier + ).decode("utf-16-be"), + ) + + +def aws_cryptography_keystore_KMSConfiguration(dafny_input): + # Convert KMSConfiguration + if isinstance(dafny_input, KMSConfiguration_kmsKeyArn): + KMSConfiguration_union_value = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_keystore.models.KMSConfigurationKmsKeyArn( + b"".join(ord(c).to_bytes(2, "big") for c in dafny_input.kmsKeyArn).decode( + "utf-16-be" + ) + ) + elif isinstance(dafny_input, KMSConfiguration_kmsMRKeyArn): + KMSConfiguration_union_value = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_keystore.models.KMSConfigurationKmsMRKeyArn( + b"".join(ord(c).to_bytes(2, "big") for c in dafny_input.kmsMRKeyArn).decode( + "utf-16-be" + ) + ) + elif isinstance(dafny_input, KMSConfiguration_discovery): + KMSConfiguration_union_value = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_keystore.models.KMSConfigurationDiscovery( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_Discovery( + dafny_input.discovery + ) + ) + elif isinstance(dafny_input, KMSConfiguration_mrDiscovery): + KMSConfiguration_union_value = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_keystore.models.KMSConfigurationMrDiscovery( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_MRDiscovery( + dafny_input.mrDiscovery + ) + ) + else: + raise ValueError("No recognized union value in union type: " + str(dafny_input)) + + return KMSConfiguration_union_value + + +def aws_cryptography_keystore_Discovery(dafny_input): + return ( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_keystore.models.Discovery() + ) + + +def aws_cryptography_keystore_MRDiscovery(dafny_input): + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_keystore.models.MRDiscovery( + region=b"".join(ord(c).to_bytes(2, "big") for c in dafny_input.region).decode( + "utf-16-be" + ), + ) + + +def aws_cryptography_keystore_GetKeyStoreInfoOutput(dafny_input): + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_keystore.models.GetKeyStoreInfoOutput( + key_store_id=b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.keyStoreId + ).decode("utf-16-be"), + key_store_name=b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.keyStoreName + ).decode("utf-16-be"), + logical_key_store_name=b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.logicalKeyStoreName + ).decode("utf-16-be"), + 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 + ], + kms_configuration=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_KMSConfiguration( + dafny_input.kmsConfiguration + ), + ) + + +def aws_cryptography_keystore_CreateKeyStoreOutput(dafny_input): + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_keystore.models.CreateKeyStoreOutput( + table_arn=b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.tableArn + ).decode("utf-16-be"), + ) + + +def aws_cryptography_keystore_CreateKeyOutput(dafny_input): + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_keystore.models.CreateKeyOutput( + branch_key_identifier=b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.branchKeyIdentifier + ).decode("utf-16-be"), + ) + + +def aws_cryptography_keystore_VersionKeyOutput(dafny_input): + return ( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_keystore.models.VersionKeyOutput() + ) + + +def aws_cryptography_keystore_BranchKeyMaterials(dafny_input): + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_keystore.models.BranchKeyMaterials( + branch_key_identifier=b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.branchKeyIdentifier + ).decode("utf-16-be"), + branch_key_version=bytes(dafny_input.branchKeyVersion.Elements).decode("utf-8"), + encryption_context={ + bytes(key.Elements).decode("utf-8"): bytes(value.Elements).decode("utf-8") + for (key, value) in dafny_input.encryptionContext.items + }, + branch_key=bytes(dafny_input.branchKey), + ) + + +def aws_cryptography_keystore_GetActiveBranchKeyOutput(dafny_input): + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_keystore.models.GetActiveBranchKeyOutput( + branch_key_materials=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_BranchKeyMaterials( + dafny_input.branchKeyMaterials + ), + ) + + +def aws_cryptography_keystore_GetBranchKeyVersionOutput(dafny_input): + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_keystore.models.GetBranchKeyVersionOutput( + branch_key_materials=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_BranchKeyMaterials( + dafny_input.branchKeyMaterials + ), + ) + + +def aws_cryptography_keystore_BeaconKeyMaterials(dafny_input): + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_keystore.models.BeaconKeyMaterials( + beacon_key_identifier=b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.beaconKeyIdentifier + ).decode("utf-16-be"), + encryption_context={ + bytes(key.Elements).decode("utf-8"): bytes(value.Elements).decode("utf-8") + for (key, value) in dafny_input.encryptionContext.items + }, + beacon_key=( + (bytes(dafny_input.beaconKey.value)) + if (dafny_input.beaconKey.is_Some) + else None + ), + hmac_keys=( + ( + { + b"".join(ord(c).to_bytes(2, "big") for c in key).decode( + "utf-16-be" + ): bytes(value) + for (key, value) in dafny_input.hmacKeys.value.items + } + ) + if (dafny_input.hmacKeys.is_Some) + else None + ), + ) + + +def aws_cryptography_keystore_GetBeaconKeyOutput(dafny_input): + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_keystore.models.GetBeaconKeyOutput( + beacon_key_materials=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_BeaconKeyMaterials( + dafny_input.beaconKeyMaterials + ), + ) + + +def aws_cryptography_keystore_DdbClientReference(dafny_input): + return dafny_input._impl + + +def aws_cryptography_keystore_KmsClientReference(dafny_input): + return dafny_input._impl + + +def aws_cryptography_keystore_KeyStoreConfig(dafny_input): + # Deferred import of .config to avoid circular dependency + import aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_keystore.config + + return aws_cryptographic_materialproviders.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_materialproviders.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"), + id=( + ( + b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.id.value + ).decode("utf-16-be") + ) + if (dafny_input.id.is_Some) + else None + ), + 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 + ), + ddb_client=( + ( + aws_cryptographic_materialproviders.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 + ), + kms_client=( + ( + aws_cryptographic_materialproviders.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 + ), + ) diff --git a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/smithygenerated/aws_cryptography_keystore/deserialize.py b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/smithygenerated/aws_cryptography_keystore/deserialize.py new file mode 100644 index 000000000..51a73e7cc --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/smithygenerated/aws_cryptography_keystore/deserialize.py @@ -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. + +import _dafny +from aws_cryptographic_materialproviders.internaldafny.generated.AwsCryptographyKeyStoreTypes import ( + CreateKeyOutput_CreateKeyOutput as DafnyCreateKeyOutput, + CreateKeyStoreOutput_CreateKeyStoreOutput as DafnyCreateKeyStoreOutput, + Error, + Error_KeyStoreException, + GetActiveBranchKeyOutput_GetActiveBranchKeyOutput as DafnyGetActiveBranchKeyOutput, + GetBeaconKeyOutput_GetBeaconKeyOutput as DafnyGetBeaconKeyOutput, + GetBranchKeyVersionOutput_GetBranchKeyVersionOutput as DafnyGetBranchKeyVersionOutput, + GetKeyStoreInfoOutput_GetKeyStoreInfoOutput as DafnyGetKeyStoreInfoOutput, + VersionKeyOutput_VersionKeyOutput as DafnyVersionKeyOutput, +) +import aws_cryptographic_materialproviders.internaldafny.generated.module_ +import aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_keystore.dafny_to_smithy +from typing import Any + +from .dafny_protocol import DafnyResponse +from .errors import ( + CollectionOfErrors, + ComAmazonawsDynamodb, + ComAmazonawsKms, + KeyStoreException, + OpaqueError, + ServiceError, +) +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 .config import Config + + +def _deserialize_get_key_store_info(input: DafnyResponse, config: Config): + + if input.IsFailure(): + return _deserialize_error(input.error) + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_GetKeyStoreInfoOutput( + input.value + ) + + +def _deserialize_create_key_store(input: DafnyResponse, config: Config): + + if input.IsFailure(): + return _deserialize_error(input.error) + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_CreateKeyStoreOutput( + input.value + ) + + +def _deserialize_create_key(input: DafnyResponse, config: Config): + + if input.IsFailure(): + return _deserialize_error(input.error) + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_CreateKeyOutput( + input.value + ) + + +def _deserialize_version_key(input: DafnyResponse, config: Config): + + if input.IsFailure(): + return _deserialize_error(input.error) + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_VersionKeyOutput( + input.value + ) + + +def _deserialize_get_active_branch_key(input: DafnyResponse, config: Config): + + if input.IsFailure(): + return _deserialize_error(input.error) + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_GetActiveBranchKeyOutput( + input.value + ) + + +def _deserialize_get_branch_key_version(input: DafnyResponse, config: Config): + + if input.IsFailure(): + return _deserialize_error(input.error) + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_GetBranchKeyVersionOutput( + input.value + ) + + +def _deserialize_get_beacon_key(input: DafnyResponse, config: Config): + + if input.IsFailure(): + return _deserialize_error(input.error) + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_GetBeaconKeyOutput( + input.value + ) + + +def _deserialize_error(error: Error) -> ServiceError: + if error.is_Opaque: + return OpaqueError(obj=error.obj) + 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_KeyStoreException: + return KeyStoreException(message=_dafny.string_of(error.message)) + 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_materialproviders/smithygenerated/aws_cryptography_keystore/errors.py b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/smithygenerated/aws_cryptography_keystore/errors.py new file mode 100644 index 000000000..ba94e2279 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/smithygenerated/aws_cryptography_keystore/errors.py @@ -0,0 +1,238 @@ +# 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_materialproviders.internaldafny.generated +import aws_cryptographic_materialproviders.internaldafny.generated.AwsCryptographyKeyStoreTypes +import aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_keystore.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 KeyStoreException(ApiError[Literal["KeyStoreException"]]): + code: Literal["KeyStoreException"] = "KeyStoreException" + message: str + + def __init__( + self, + *, + message: str, + ): + super().__init__(message) + + def as_dict(self) -> Dict[str, Any]: + """Converts the KeyStoreException 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.""" + kwargs: Dict[str, Any] = { + "message": d["message"], + } + + return KeyStoreException(**kwargs) + + def __repr__(self) -> str: + 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, KeyStoreException): + 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 + + +class ComAmazonawsDynamodb(ApiError[Literal["ComAmazonawsDynamodb"]]): + ComAmazonawsDynamodb: Any + + +class ComAmazonawsKms(ApiError[Literal["ComAmazonawsKms"]]): + ComAmazonawsKms: 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) + + +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_materialproviders.smithygenerated.aws_cryptography_keystore.errors.KeyStoreException, + ): + return aws_cryptographic_materialproviders.internaldafny.generated.AwsCryptographyKeyStoreTypes.Error_KeyStoreException( + message=_dafny.Seq(e.message) + ) + + if isinstance(e, ComAmazonawsDynamodb): + return aws_cryptographic_materialproviders.internaldafny.generated.AwsCryptographyKeyStoreTypes.Error_ComAmazonawsDynamodb( + com_amazonaws_dynamodb_sdk_error_to_dafny_error(e.message) + ) + + if isinstance(e, ComAmazonawsKms): + return aws_cryptographic_materialproviders.internaldafny.generated.AwsCryptographyKeyStoreTypes.Error_ComAmazonawsKms( + com_amazonaws_kms_sdk_error_to_dafny_error(e.message) + ) + + if isinstance(e, CollectionOfErrors): + return aws_cryptographic_materialproviders.internaldafny.generated.AwsCryptographyKeyStoreTypes.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_materialproviders.internaldafny.generated.AwsCryptographyKeyStoreTypes.Error_Opaque( + obj=e.obj + ) + + else: + return aws_cryptographic_materialproviders.internaldafny.generated.AwsCryptographyKeyStoreTypes.Error_Opaque( + obj=e + ) diff --git a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/smithygenerated/aws_cryptography_keystore/models.py b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/smithygenerated/aws_cryptography_keystore/models.py new file mode 100644 index 000000000..aa4095773 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/smithygenerated/aws_cryptography_keystore/models.py @@ -0,0 +1,1044 @@ +# 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, Optional, Union + + +class BeaconKeyMaterials: + beacon_key_identifier: str + encryption_context: dict[str, str] + beacon_key: Optional[bytes | bytearray] + hmac_keys: Optional[dict[str, bytes | bytearray]] + + def __init__( + self, + *, + beacon_key_identifier: str, + encryption_context: dict[str, str], + beacon_key: Optional[bytes | bytearray] = None, + hmac_keys: Optional[dict[str, bytes | bytearray]] = None, + ): + self.beacon_key_identifier = beacon_key_identifier + self.encryption_context = encryption_context + self.beacon_key = beacon_key + self.hmac_keys = hmac_keys + + def as_dict(self) -> Dict[str, Any]: + """Converts the BeaconKeyMaterials to a dictionary.""" + d: Dict[str, Any] = { + "beacon_key_identifier": self.beacon_key_identifier, + "encryption_context": self.encryption_context, + } + + if self.beacon_key is not None: + d["beacon_key"] = self.beacon_key + + if self.hmac_keys is not None: + d["hmac_keys"] = self.hmac_keys + + return d + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "BeaconKeyMaterials": + """Creates a BeaconKeyMaterials from a dictionary.""" + kwargs: Dict[str, Any] = { + "beacon_key_identifier": d["beacon_key_identifier"], + "encryption_context": d["encryption_context"], + } + + if "beacon_key" in d: + kwargs["beacon_key"] = d["beacon_key"] + + if "hmac_keys" in d: + kwargs["hmac_keys"] = d["hmac_keys"] + + return BeaconKeyMaterials(**kwargs) + + def __repr__(self) -> str: + result = "BeaconKeyMaterials(" + if self.beacon_key_identifier is not None: + result += f"beacon_key_identifier={repr(self.beacon_key_identifier)}, " + + if self.encryption_context is not None: + result += f"encryption_context={repr(self.encryption_context)}, " + + if self.beacon_key is not None: + result += f"beacon_key={repr(self.beacon_key)}, " + + if self.hmac_keys is not None: + result += f"hmac_keys={repr(self.hmac_keys)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, BeaconKeyMaterials): + return False + attributes: list[str] = [ + "beacon_key_identifier", + "encryption_context", + "beacon_key", + "hmac_keys", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class BranchKeyMaterials: + branch_key_identifier: str + branch_key_version: str + encryption_context: dict[str, str] + branch_key: bytes | bytearray + + def __init__( + self, + *, + branch_key_identifier: str, + branch_key_version: str, + encryption_context: dict[str, str], + branch_key: bytes | bytearray, + ): + self.branch_key_identifier = branch_key_identifier + self.branch_key_version = branch_key_version + self.encryption_context = encryption_context + self.branch_key = branch_key + + def as_dict(self) -> Dict[str, Any]: + """Converts the BranchKeyMaterials to a dictionary.""" + return { + "branch_key_identifier": self.branch_key_identifier, + "branch_key_version": self.branch_key_version, + "encryption_context": self.encryption_context, + "branch_key": self.branch_key, + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "BranchKeyMaterials": + """Creates a BranchKeyMaterials from a dictionary.""" + kwargs: Dict[str, Any] = { + "branch_key_identifier": d["branch_key_identifier"], + "branch_key_version": d["branch_key_version"], + "encryption_context": d["encryption_context"], + "branch_key": d["branch_key"], + } + + return BranchKeyMaterials(**kwargs) + + def __repr__(self) -> str: + result = "BranchKeyMaterials(" + if self.branch_key_identifier is not None: + result += f"branch_key_identifier={repr(self.branch_key_identifier)}, " + + if self.branch_key_version is not None: + result += f"branch_key_version={repr(self.branch_key_version)}, " + + if self.encryption_context is not None: + result += f"encryption_context={repr(self.encryption_context)}, " + + if self.branch_key is not None: + result += f"branch_key={repr(self.branch_key)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, BranchKeyMaterials): + return False + attributes: list[str] = [ + "branch_key_identifier", + "branch_key_version", + "encryption_context", + "branch_key", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class CreateKeyInput: + branch_key_identifier: Optional[str] + encryption_context: Optional[dict[str, str]] + + def __init__( + self, + *, + branch_key_identifier: Optional[str] = None, + encryption_context: Optional[dict[str, str]] = None, + ): + """ + :param branch_key_identifier: The identifier for the created Branch Key. + :param encryption_context: Custom encryption context for the Branch Key. + Required if branchKeyIdentifier is set. + """ + self.branch_key_identifier = branch_key_identifier + self.encryption_context = encryption_context + + def as_dict(self) -> Dict[str, Any]: + """Converts the CreateKeyInput to a dictionary.""" + d: Dict[str, Any] = {} + + if self.branch_key_identifier is not None: + d["branch_key_identifier"] = self.branch_key_identifier + + if self.encryption_context is not None: + d["encryption_context"] = self.encryption_context + + return d + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "CreateKeyInput": + """Creates a CreateKeyInput from a dictionary.""" + kwargs: Dict[str, Any] = {} + + if "branch_key_identifier" in d: + kwargs["branch_key_identifier"] = d["branch_key_identifier"] + + if "encryption_context" in d: + kwargs["encryption_context"] = d["encryption_context"] + + return CreateKeyInput(**kwargs) + + def __repr__(self) -> str: + result = "CreateKeyInput(" + if self.branch_key_identifier is not None: + result += f"branch_key_identifier={repr(self.branch_key_identifier)}, " + + if self.encryption_context is not None: + result += f"encryption_context={repr(self.encryption_context)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, CreateKeyInput): + return False + attributes: list[str] = [ + "branch_key_identifier", + "encryption_context", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class CreateKeyOutput: + branch_key_identifier: str + + def __init__( + self, + *, + branch_key_identifier: str, + ): + """Outputs for Branch Key creation. + + :param branch_key_identifier: A identifier for the created + Branch Key. + """ + self.branch_key_identifier = branch_key_identifier + + def as_dict(self) -> Dict[str, Any]: + """Converts the CreateKeyOutput to a dictionary.""" + return { + "branch_key_identifier": self.branch_key_identifier, + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "CreateKeyOutput": + """Creates a CreateKeyOutput from a dictionary.""" + kwargs: Dict[str, Any] = { + "branch_key_identifier": d["branch_key_identifier"], + } + + return CreateKeyOutput(**kwargs) + + def __repr__(self) -> str: + result = "CreateKeyOutput(" + if self.branch_key_identifier is not None: + result += f"branch_key_identifier={repr(self.branch_key_identifier)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, CreateKeyOutput): + return False + attributes: list[str] = [ + "branch_key_identifier", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class CreateKeyStoreInput: + def as_dict(self) -> Dict[str, Any]: + """Converts the CreateKeyStoreInput to a dictionary.""" + return {} + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "CreateKeyStoreInput": + """Creates a CreateKeyStoreInput from a dictionary.""" + return CreateKeyStoreInput() + + def __repr__(self) -> str: + result = "CreateKeyStoreInput(" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + return isinstance(other, CreateKeyStoreInput) + + +class CreateKeyStoreOutput: + table_arn: str + + def __init__( + self, + *, + table_arn: str, + ): + """Outputs for Key Store DynamoDB table creation. + + :param table_arn: The ARN of the DynamoDB table that backs this + Key Store. + """ + self.table_arn = table_arn + + def as_dict(self) -> Dict[str, Any]: + """Converts the CreateKeyStoreOutput to a dictionary.""" + return { + "table_arn": self.table_arn, + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "CreateKeyStoreOutput": + """Creates a CreateKeyStoreOutput from a dictionary.""" + kwargs: Dict[str, Any] = { + "table_arn": d["table_arn"], + } + + return CreateKeyStoreOutput(**kwargs) + + def __repr__(self) -> str: + result = "CreateKeyStoreOutput(" + if self.table_arn is not None: + result += f"table_arn={repr(self.table_arn)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, CreateKeyStoreOutput): + return False + attributes: list[str] = [ + "table_arn", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class Discovery: + def as_dict(self) -> Dict[str, Any]: + """Converts the Discovery to a dictionary.""" + return {} + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "Discovery": + """Creates a Discovery from a dictionary.""" + return Discovery() + + def __repr__(self) -> str: + result = "Discovery(" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + return isinstance(other, Discovery) + + +class GetActiveBranchKeyInput: + branch_key_identifier: str + + def __init__( + self, + *, + branch_key_identifier: str, + ): + """Inputs for getting a Branch Key's ACTIVE version. + + :param branch_key_identifier: The identifier for the Branch Key + to get the ACTIVE version for. + """ + self.branch_key_identifier = branch_key_identifier + + def as_dict(self) -> Dict[str, Any]: + """Converts the GetActiveBranchKeyInput to a dictionary.""" + return { + "branch_key_identifier": self.branch_key_identifier, + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "GetActiveBranchKeyInput": + """Creates a GetActiveBranchKeyInput from a dictionary.""" + kwargs: Dict[str, Any] = { + "branch_key_identifier": d["branch_key_identifier"], + } + + return GetActiveBranchKeyInput(**kwargs) + + def __repr__(self) -> str: + result = "GetActiveBranchKeyInput(" + if self.branch_key_identifier is not None: + result += f"branch_key_identifier={repr(self.branch_key_identifier)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, GetActiveBranchKeyInput): + return False + attributes: list[str] = [ + "branch_key_identifier", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class GetActiveBranchKeyOutput: + branch_key_materials: BranchKeyMaterials + + def __init__( + self, + *, + branch_key_materials: BranchKeyMaterials, + ): + """Outputs for getting a Branch Key's ACTIVE version. + + :param branch_key_materials: The materials for the Branch Key. + """ + self.branch_key_materials = branch_key_materials + + def as_dict(self) -> Dict[str, Any]: + """Converts the GetActiveBranchKeyOutput to a dictionary.""" + return { + "branch_key_materials": self.branch_key_materials.as_dict(), + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "GetActiveBranchKeyOutput": + """Creates a GetActiveBranchKeyOutput from a dictionary.""" + kwargs: Dict[str, Any] = { + "branch_key_materials": BranchKeyMaterials.from_dict( + d["branch_key_materials"] + ), + } + + return GetActiveBranchKeyOutput(**kwargs) + + def __repr__(self) -> str: + result = "GetActiveBranchKeyOutput(" + if self.branch_key_materials is not None: + result += f"branch_key_materials={repr(self.branch_key_materials)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, GetActiveBranchKeyOutput): + return False + attributes: list[str] = [ + "branch_key_materials", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class GetBeaconKeyInput: + branch_key_identifier: str + + def __init__( + self, + *, + branch_key_identifier: str, + ): + """Inputs for getting a Beacon Key. + + :param branch_key_identifier: The identifier of the Branch Key + the Beacon Key is associated with. + """ + self.branch_key_identifier = branch_key_identifier + + def as_dict(self) -> Dict[str, Any]: + """Converts the GetBeaconKeyInput to a dictionary.""" + return { + "branch_key_identifier": self.branch_key_identifier, + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "GetBeaconKeyInput": + """Creates a GetBeaconKeyInput from a dictionary.""" + kwargs: Dict[str, Any] = { + "branch_key_identifier": d["branch_key_identifier"], + } + + return GetBeaconKeyInput(**kwargs) + + def __repr__(self) -> str: + result = "GetBeaconKeyInput(" + if self.branch_key_identifier is not None: + result += f"branch_key_identifier={repr(self.branch_key_identifier)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, GetBeaconKeyInput): + return False + attributes: list[str] = [ + "branch_key_identifier", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class GetBeaconKeyOutput: + beacon_key_materials: BeaconKeyMaterials + + def __init__( + self, + *, + beacon_key_materials: BeaconKeyMaterials, + ): + """Outputs for getting a Beacon Key. + + :param beacon_key_materials: The materials for the Beacon Key. + """ + self.beacon_key_materials = beacon_key_materials + + def as_dict(self) -> Dict[str, Any]: + """Converts the GetBeaconKeyOutput to a dictionary.""" + return { + "beacon_key_materials": self.beacon_key_materials.as_dict(), + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "GetBeaconKeyOutput": + """Creates a GetBeaconKeyOutput from a dictionary.""" + kwargs: Dict[str, Any] = { + "beacon_key_materials": BeaconKeyMaterials.from_dict( + d["beacon_key_materials"] + ), + } + + return GetBeaconKeyOutput(**kwargs) + + def __repr__(self) -> str: + result = "GetBeaconKeyOutput(" + if self.beacon_key_materials is not None: + result += f"beacon_key_materials={repr(self.beacon_key_materials)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, GetBeaconKeyOutput): + return False + attributes: list[str] = [ + "beacon_key_materials", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class GetBranchKeyVersionInput: + branch_key_identifier: str + branch_key_version: str + + def __init__( + self, + *, + branch_key_identifier: str, + branch_key_version: str, + ): + """Inputs for getting a version of a Branch Key. + + :param branch_key_identifier: The identifier for the Branch Key + to get a particular version for. + :param branch_key_version: The version to get. + """ + self.branch_key_identifier = branch_key_identifier + self.branch_key_version = branch_key_version + + def as_dict(self) -> Dict[str, Any]: + """Converts the GetBranchKeyVersionInput to a dictionary.""" + return { + "branch_key_identifier": self.branch_key_identifier, + "branch_key_version": self.branch_key_version, + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "GetBranchKeyVersionInput": + """Creates a GetBranchKeyVersionInput from a dictionary.""" + kwargs: Dict[str, Any] = { + "branch_key_identifier": d["branch_key_identifier"], + "branch_key_version": d["branch_key_version"], + } + + return GetBranchKeyVersionInput(**kwargs) + + def __repr__(self) -> str: + result = "GetBranchKeyVersionInput(" + if self.branch_key_identifier is not None: + result += f"branch_key_identifier={repr(self.branch_key_identifier)}, " + + if self.branch_key_version is not None: + result += f"branch_key_version={repr(self.branch_key_version)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, GetBranchKeyVersionInput): + return False + attributes: list[str] = [ + "branch_key_identifier", + "branch_key_version", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class GetBranchKeyVersionOutput: + branch_key_materials: BranchKeyMaterials + + def __init__( + self, + *, + branch_key_materials: BranchKeyMaterials, + ): + """Outputs for getting a version of a Branch Key. + + :param branch_key_materials: The materials for the Branch Key. + """ + self.branch_key_materials = branch_key_materials + + def as_dict(self) -> Dict[str, Any]: + """Converts the GetBranchKeyVersionOutput to a dictionary.""" + return { + "branch_key_materials": self.branch_key_materials.as_dict(), + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "GetBranchKeyVersionOutput": + """Creates a GetBranchKeyVersionOutput from a dictionary.""" + kwargs: Dict[str, Any] = { + "branch_key_materials": BranchKeyMaterials.from_dict( + d["branch_key_materials"] + ), + } + + return GetBranchKeyVersionOutput(**kwargs) + + def __repr__(self) -> str: + result = "GetBranchKeyVersionOutput(" + if self.branch_key_materials is not None: + result += f"branch_key_materials={repr(self.branch_key_materials)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, GetBranchKeyVersionOutput): + return False + attributes: list[str] = [ + "branch_key_materials", + ] + 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 + + +class KMSConfigurationKmsMRKeyArn: + """If an MRK ARN is provided, and the Key Store table 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 mrkKmsKeyArn behaves exactly + as kmsKeyArn. + """ + + 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 {"kmsMRKeyArn": self.value} + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "KMSConfigurationKmsMRKeyArn": + if len(d) != 1: + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + + return KMSConfigurationKmsMRKeyArn(d["kmsMRKeyArn"]) + + def __repr__(self) -> str: + return f"KMSConfigurationKmsMRKeyArn(value=repr(self.value))" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, KMSConfigurationKmsMRKeyArn): + return False + return self.value == other.value + + +class KMSConfigurationDiscovery: + """The Key Store can use the KMS Key ARNs already persisted in the Backing + Table. + + The VersionKey and CreateKey Operations are NOT supported and will + fail with a runtime exception. There is no Multi-Region logic with + this configuration; if a Multi-Region Key is encountered, and the + region in the ARN is not the region of the KMS Client, requests will + Fail with KMS Exceptions. + """ + + def __init__(self, value: Discovery): + self.value = value + + def as_dict(self) -> Dict[str, Any]: + return {"discovery": self.value.as_dict()} + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "KMSConfigurationDiscovery": + if len(d) != 1: + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + + return KMSConfigurationDiscovery(Discovery.from_dict(d["discovery"])) + + def __repr__(self) -> str: + return f"KMSConfigurationDiscovery(value=repr(self.value))" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, KMSConfigurationDiscovery): + return False + return self.value == other.value + + +class KMSConfigurationMrDiscovery: + """The Key Store can use the KMS Key ARNs already persisted in the Backing + Table. + + The VersionKey and CreateKey Operations are NOT supported and will + fail with a runtime exception. If a Multi-Region Key is encountered, + the region in the ARN is changed to the configured region. + """ + + def __init__(self, value: MRDiscovery): + self.value = value + + def as_dict(self) -> Dict[str, Any]: + return {"mrDiscovery": self.value.as_dict()} + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "KMSConfigurationMrDiscovery": + if len(d) != 1: + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + + return KMSConfigurationMrDiscovery(MRDiscovery.from_dict(d["mrDiscovery"])) + + def __repr__(self) -> str: + return f"KMSConfigurationMrDiscovery(value=repr(self.value))" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, KMSConfigurationMrDiscovery): + return False + return self.value == other.value + + +class KMSConfigurationUnknown: + """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]) -> "KMSConfigurationUnknown": + if len(d) != 1: + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + return KMSConfigurationUnknown(d["SDK_UNKNOWN_MEMBER"]["name"]) + + def __repr__(self) -> str: + return f"KMSConfigurationUnknown(tag={self.tag})" + + +# Configures Key Store's KMS Key ARN restrictions. +KMSConfiguration = Union[ + KMSConfigurationKmsKeyArn, + KMSConfigurationKmsMRKeyArn, + KMSConfigurationDiscovery, + KMSConfigurationMrDiscovery, + KMSConfigurationUnknown, +] + + +def _kms_configuration_from_dict(d: Dict[str, Any]) -> KMSConfiguration: + if "kmsKeyArn" in d: + return KMSConfigurationKmsKeyArn.from_dict(d) + + if "kmsMRKeyArn" in d: + return KMSConfigurationKmsMRKeyArn.from_dict(d) + + if "discovery" in d: + return KMSConfigurationDiscovery.from_dict(d) + + if "mrDiscovery" in d: + return KMSConfigurationMrDiscovery.from_dict(d) + + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + + +class GetKeyStoreInfoOutput: + key_store_id: str + key_store_name: str + logical_key_store_name: str + grant_tokens: list[str] + kms_configuration: KMSConfiguration + + def __init__( + self, + *, + key_store_id: str, + key_store_name: str, + logical_key_store_name: str, + grant_tokens: list[str], + kms_configuration: KMSConfiguration, + ): + """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 logical_key_store_name: The logical name for this Key + Store, which is cryptographically bound to the keys it + holds. + :param grant_tokens: The AWS KMS grant tokens that are used when + this Key Store calls to AWS KMS. + :param kms_configuration: Configures Key Store's KMS Key ARN + 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 + self.kms_configuration = kms_configuration + + def as_dict(self) -> Dict[str, Any]: + """Converts the GetKeyStoreInfoOutput to a dictionary.""" + return { + "key_store_id": self.key_store_id, + "key_store_name": self.key_store_name, + "logical_key_store_name": self.logical_key_store_name, + "grant_tokens": self.grant_tokens, + "kms_configuration": self.kms_configuration.as_dict(), + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "GetKeyStoreInfoOutput": + """Creates a GetKeyStoreInfoOutput from a dictionary.""" + kwargs: Dict[str, Any] = { + "key_store_id": d["key_store_id"], + "key_store_name": d["key_store_name"], + "logical_key_store_name": d["logical_key_store_name"], + "grant_tokens": d["grant_tokens"], + "kms_configuration": _kms_configuration_from_dict(d["kms_configuration"]), + } + + return GetKeyStoreInfoOutput(**kwargs) + + def __repr__(self) -> str: + result = "GetKeyStoreInfoOutput(" + if self.key_store_id is not None: + result += f"key_store_id={repr(self.key_store_id)}, " + + if self.key_store_name is not None: + result += f"key_store_name={repr(self.key_store_name)}, " + + if self.logical_key_store_name is not None: + result += f"logical_key_store_name={repr(self.logical_key_store_name)}, " + + if self.grant_tokens is not None: + result += f"grant_tokens={repr(self.grant_tokens)}, " + + if self.kms_configuration is not None: + result += f"kms_configuration={repr(self.kms_configuration)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, GetKeyStoreInfoOutput): + return False + attributes: list[str] = [ + "key_store_id", + "key_store_name", + "logical_key_store_name", + "grant_tokens", + "kms_configuration", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class VersionKeyInput: + branch_key_identifier: str + + def __init__( + self, + *, + branch_key_identifier: str, + ): + """Inputs for versioning a Branch Key. + + :param branch_key_identifier: The identifier for the Branch Key + to be versioned. + """ + self.branch_key_identifier = branch_key_identifier + + def as_dict(self) -> Dict[str, Any]: + """Converts the VersionKeyInput to a dictionary.""" + return { + "branch_key_identifier": self.branch_key_identifier, + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "VersionKeyInput": + """Creates a VersionKeyInput from a dictionary.""" + kwargs: Dict[str, Any] = { + "branch_key_identifier": d["branch_key_identifier"], + } + + return VersionKeyInput(**kwargs) + + def __repr__(self) -> str: + result = "VersionKeyInput(" + if self.branch_key_identifier is not None: + result += f"branch_key_identifier={repr(self.branch_key_identifier)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, VersionKeyInput): + return False + attributes: list[str] = [ + "branch_key_identifier", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class VersionKeyOutput: + """Outputs for versioning a Branch Key.""" + + 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) + + +class Unit: + pass diff --git a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/smithygenerated/aws_cryptography_keystore/plugin.py b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/smithygenerated/aws_cryptography_keystore/plugin.py new file mode 100644 index 000000000..bf0948d70 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/smithygenerated/aws_cryptography_keystore/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, KeyStoreConfig +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, KeyStoreConfig): + from aws_cryptographic_materialproviders.internaldafny.generated.KeyStore import ( + default__, + ) + + config.dafnyImplInterface.impl = default__.KeyStore( + 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_materialproviders/smithygenerated/aws_cryptography_keystore/serialize.py b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/smithygenerated/aws_cryptography_keystore/serialize.py new file mode 100644 index 000000000..b459e2cd3 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/smithygenerated/aws_cryptography_keystore/serialize.py @@ -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. + +import aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_keystore.smithy_to_dafny + +from .dafny_protocol import DafnyRequest + +from .config import Config + + +def _serialize_get_key_store_info(input, config: Config) -> DafnyRequest: + return DafnyRequest(operation_name="GetKeyStoreInfo", dafny_operation_input=None) + + +def _serialize_create_key_store(input, config: Config) -> DafnyRequest: + return DafnyRequest( + operation_name="CreateKeyStore", + dafny_operation_input=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_CreateKeyStoreInput( + input + ), + ) + + +def _serialize_create_key(input, config: Config) -> DafnyRequest: + return DafnyRequest( + operation_name="CreateKey", + dafny_operation_input=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_CreateKeyInput( + input + ), + ) + + +def _serialize_version_key(input, config: Config) -> DafnyRequest: + return DafnyRequest( + operation_name="VersionKey", + dafny_operation_input=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_VersionKeyInput( + input + ), + ) + + +def _serialize_get_active_branch_key(input, config: Config) -> DafnyRequest: + return DafnyRequest( + operation_name="GetActiveBranchKey", + dafny_operation_input=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_GetActiveBranchKeyInput( + input + ), + ) + + +def _serialize_get_branch_key_version(input, config: Config) -> DafnyRequest: + return DafnyRequest( + operation_name="GetBranchKeyVersion", + dafny_operation_input=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_GetBranchKeyVersionInput( + input + ), + ) + + +def _serialize_get_beacon_key(input, config: Config) -> DafnyRequest: + return DafnyRequest( + operation_name="GetBeaconKey", + dafny_operation_input=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_GetBeaconKeyInput( + input + ), + ) diff --git a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/smithygenerated/aws_cryptography_keystore/smithy_to_dafny.py b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/smithygenerated/aws_cryptography_keystore/smithy_to_dafny.py new file mode 100644 index 000000000..7bac3cc5f --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/smithygenerated/aws_cryptography_keystore/smithy_to_dafny.py @@ -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. + +from _dafny import Map, Seq +from aws_cryptographic_materialproviders.internaldafny.generated.AwsCryptographyKeyStoreTypes import ( + BeaconKeyMaterials_BeaconKeyMaterials as DafnyBeaconKeyMaterials, + BranchKeyMaterials_BranchKeyMaterials as DafnyBranchKeyMaterials, + CreateKeyInput_CreateKeyInput as DafnyCreateKeyInput, + CreateKeyOutput_CreateKeyOutput as DafnyCreateKeyOutput, + CreateKeyStoreInput_CreateKeyStoreInput as DafnyCreateKeyStoreInput, + CreateKeyStoreOutput_CreateKeyStoreOutput as DafnyCreateKeyStoreOutput, + Discovery_Discovery as DafnyDiscovery, + GetActiveBranchKeyInput_GetActiveBranchKeyInput as DafnyGetActiveBranchKeyInput, + GetActiveBranchKeyOutput_GetActiveBranchKeyOutput as DafnyGetActiveBranchKeyOutput, + GetBeaconKeyInput_GetBeaconKeyInput as DafnyGetBeaconKeyInput, + GetBeaconKeyOutput_GetBeaconKeyOutput as DafnyGetBeaconKeyOutput, + GetBranchKeyVersionInput_GetBranchKeyVersionInput as DafnyGetBranchKeyVersionInput, + GetBranchKeyVersionOutput_GetBranchKeyVersionOutput as DafnyGetBranchKeyVersionOutput, + GetKeyStoreInfoOutput_GetKeyStoreInfoOutput as DafnyGetKeyStoreInfoOutput, + KMSConfiguration_discovery, + KMSConfiguration_kmsKeyArn, + KMSConfiguration_kmsMRKeyArn, + KMSConfiguration_mrDiscovery, + KeyStoreConfig_KeyStoreConfig as DafnyKeyStoreConfig, + MRDiscovery_MRDiscovery as DafnyMRDiscovery, + VersionKeyInput_VersionKeyInput as DafnyVersionKeyInput, + VersionKeyOutput_VersionKeyOutput as DafnyVersionKeyOutput, +) +import aws_cryptographic_materialproviders.internaldafny.generated.module_ +import aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_keystore.models +import aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_keystore.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 smithy_api_Unit(native_input): + return None + + +def aws_cryptography_keystore_CreateKeyStoreInput(native_input): + return DafnyCreateKeyStoreInput() + + +def aws_cryptography_keystore_CreateKeyInput(native_input): + return DafnyCreateKeyInput( + branchKeyIdentifier=( + ( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[ + iter( + native_input.branch_key_identifier.encode( + "utf-16-be" + ) + ) + ] + * 2 + ) + ] + ) + ) + ) + ) + if (native_input.branch_key_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()) + ), + ) + + +def aws_cryptography_keystore_VersionKeyInput(native_input): + return DafnyVersionKeyInput( + branchKeyIdentifier=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input.branch_key_identifier.encode("utf-16-be"))] + * 2 + ) + ] + ) + ), + ) + + +def aws_cryptography_keystore_GetActiveBranchKeyInput(native_input): + return DafnyGetActiveBranchKeyInput( + branchKeyIdentifier=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input.branch_key_identifier.encode("utf-16-be"))] + * 2 + ) + ] + ) + ), + ) + + +def aws_cryptography_keystore_GetBranchKeyVersionInput(native_input): + return DafnyGetBranchKeyVersionInput( + branchKeyIdentifier=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input.branch_key_identifier.encode("utf-16-be"))] + * 2 + ) + ] + ) + ), + branchKeyVersion=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input.branch_key_version.encode("utf-16-be"))] * 2 + ) + ] + ) + ), + ) + + +def aws_cryptography_keystore_GetBeaconKeyInput(native_input): + return DafnyGetBeaconKeyInput( + branchKeyIdentifier=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input.branch_key_identifier.encode("utf-16-be"))] + * 2 + ) + ] + ) + ), + ) + + +def aws_cryptography_keystore_GetKeyStoreInfoOutput(native_input): + return DafnyGetKeyStoreInfoOutput( + keyStoreId=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input.key_store_id.encode("utf-16-be"))] * 2 + ) + ] + ) + ), + keyStoreName=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input.key_store_name.encode("utf-16-be"))] * 2 + ) + ] + ) + ), + 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 + ) + ] + ) + ), + grantTokens=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 + ] + ), + kmsConfiguration=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_KMSConfiguration( + native_input.kms_configuration + ), + ) + + +def aws_cryptography_keystore_KMSConfiguration(native_input): + if isinstance( + native_input, + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_keystore.models.KMSConfigurationKmsKeyArn, + ): + KMSConfiguration_union_value = KMSConfiguration_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_materialproviders.smithygenerated.aws_cryptography_keystore.models.KMSConfigurationKmsMRKeyArn, + ): + KMSConfiguration_union_value = KMSConfiguration_kmsMRKeyArn( + 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_materialproviders.smithygenerated.aws_cryptography_keystore.models.KMSConfigurationDiscovery, + ): + KMSConfiguration_union_value = KMSConfiguration_discovery( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_Discovery( + native_input.value + ) + ) + elif isinstance( + native_input, + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_keystore.models.KMSConfigurationMrDiscovery, + ): + KMSConfiguration_union_value = KMSConfiguration_mrDiscovery( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_MRDiscovery( + native_input.value + ) + ) + else: + raise ValueError( + "No recognized union value in union type: " + str(native_input) + ) + + return KMSConfiguration_union_value + + +def aws_cryptography_keystore_Discovery(native_input): + return DafnyDiscovery() + + +def aws_cryptography_keystore_MRDiscovery(native_input): + return DafnyMRDiscovery( + region=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input.region.encode("utf-16-be"))] * 2 + ) + ] + ) + ), + ) + + +def aws_cryptography_keystore_CreateKeyStoreOutput(native_input): + return DafnyCreateKeyStoreOutput( + tableArn=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input.table_arn.encode("utf-16-be"))] * 2 + ) + ] + ) + ), + ) + + +def aws_cryptography_keystore_CreateKeyOutput(native_input): + return DafnyCreateKeyOutput( + branchKeyIdentifier=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input.branch_key_identifier.encode("utf-16-be"))] + * 2 + ) + ] + ) + ), + ) + + +def aws_cryptography_keystore_VersionKeyOutput(native_input): + return DafnyVersionKeyOutput() + + +def aws_cryptography_keystore_GetActiveBranchKeyOutput(native_input): + return DafnyGetActiveBranchKeyOutput( + branchKeyMaterials=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_BranchKeyMaterials( + native_input.branch_key_materials + ), + ) + + +def aws_cryptography_keystore_BranchKeyMaterials(native_input): + return DafnyBranchKeyMaterials( + branchKeyIdentifier=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input.branch_key_identifier.encode("utf-16-be"))] + * 2 + ) + ] + ) + ), + branchKeyVersion=Seq(native_input.branch_key_version.encode("utf-8")), + encryptionContext=Map( + { + Seq(key.encode("utf-8")): Seq(value.encode("utf-8")) + for (key, value) in native_input.encryption_context.items() + } + ), + branchKey=Seq(native_input.branch_key), + ) + + +def aws_cryptography_keystore_GetBranchKeyVersionOutput(native_input): + return DafnyGetBranchKeyVersionOutput( + branchKeyMaterials=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_BranchKeyMaterials( + native_input.branch_key_materials + ), + ) + + +def aws_cryptography_keystore_GetBeaconKeyOutput(native_input): + return DafnyGetBeaconKeyOutput( + beaconKeyMaterials=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_BeaconKeyMaterials( + native_input.beacon_key_materials + ), + ) + + +def aws_cryptography_keystore_BeaconKeyMaterials(native_input): + return DafnyBeaconKeyMaterials( + beaconKeyIdentifier=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input.beacon_key_identifier.encode("utf-16-be"))] + * 2 + ) + ] + ) + ), + encryptionContext=Map( + { + Seq(key.encode("utf-8")): Seq(value.encode("utf-8")) + for (key, value) in native_input.encryption_context.items() + } + ), + beaconKey=( + (Option_Some(Seq(native_input.beacon_key))) + if (native_input.beacon_key is not None) + else (Option_None()) + ), + hmacKeys=( + ( + Option_Some( + Map( + { + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(key.encode("utf-16-be"))] * 2 + ) + ] + ) + ): Seq(value) + for (key, value) in native_input.hmac_keys.items() + } + ) + ) + ) + if (native_input.hmac_keys is not None) + else (Option_None()) + ), + ) + + +def aws_cryptography_keystore_KeyStoreConfig(native_input): + return DafnyKeyStoreConfig( + ddbTableName=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input.ddb_table_name.encode("utf-16-be"))] * 2 + ) + ] + ) + ), + kmsConfiguration=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_KMSConfiguration( + native_input.kms_configuration + ), + 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 + ) + ] + ) + ), + id=( + ( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input.id.encode("utf-16-be"))] * 2 + ) + ] + ) + ) + ) + ) + if (native_input.id is not None) + else (Option_None()) + ), + 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()) + ), + ddbClient=( + ( + Option_Some( + aws_cryptographic_materialproviders.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_materialproviders.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_DdbClientReference( + native_input.ddb_client + ) + is not None + ) + ) + else (Option_None()) + ), + kmsClient=( + ( + Option_Some( + aws_cryptographic_materialproviders.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_materialproviders.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_KmsClientReference( + native_input.kms_client + ) + is not None + ) + ) + else (Option_None()) + ), + ) + + +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_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/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/smithygenerated/aws_cryptography_materialproviders/__init__.py b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/smithygenerated/aws_cryptography_materialproviders/__init__.py new file mode 100644 index 000000000..09be6133b --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/smithygenerated/aws_cryptography_materialproviders/__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_materialproviders/smithygenerated/aws_cryptography_materialproviders/aws_sdk_to_dafny.py b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/smithygenerated/aws_cryptography_materialproviders/aws_sdk_to_dafny.py new file mode 100644 index 000000000..c7e077cb5 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/smithygenerated/aws_cryptography_materialproviders/aws_sdk_to_dafny.py @@ -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. + +from aws_cryptography_internal_kms.internaldafny.generated.ComAmazonawsKmsTypes import ( + EncryptionAlgorithmSpec_RSAES__OAEP__SHA__1, + EncryptionAlgorithmSpec_RSAES__OAEP__SHA__256, + EncryptionAlgorithmSpec_SYMMETRIC__DEFAULT, +) +import aws_cryptography_internal_kms.internaldafny.generated.module_ + + +def com_amazonaws_kms_EncryptionAlgorithmSpec(native_input): + # Convert EncryptionAlgorithmSpec + if native_input == "SYMMETRIC_DEFAULT": + return EncryptionAlgorithmSpec_SYMMETRIC__DEFAULT() + elif native_input == "RSAES_OAEP_SHA_1": + return EncryptionAlgorithmSpec_RSAES__OAEP__SHA__1() + elif native_input == "RSAES_OAEP_SHA_256": + return EncryptionAlgorithmSpec_RSAES__OAEP__SHA__256() + else: + raise ValueError("No recognized enum value in enum type: " + native_input) diff --git a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/smithygenerated/aws_cryptography_materialproviders/client.py b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/smithygenerated/aws_cryptography_materialproviders/client.py new file mode 100644 index 000000000..2051bbac1 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/smithygenerated/aws_cryptography_materialproviders/client.py @@ -0,0 +1,894 @@ +# 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_materialproviders.internaldafny.generated.AwsCryptographyMaterialProvidersTypes import ( + IAwsCryptographicMaterialProvidersClient, +) +import aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.references +from typing import Callable, TypeVar, cast + +from .config import Config, MaterialProvidersConfig +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_create_aws_kms_discovery_keyring, + _deserialize_create_aws_kms_discovery_multi_keyring, + _deserialize_create_aws_kms_ecdh_keyring, + _deserialize_create_aws_kms_hierarchical_keyring, + _deserialize_create_aws_kms_keyring, + _deserialize_create_aws_kms_mrk_discovery_keyring, + _deserialize_create_aws_kms_mrk_discovery_multi_keyring, + _deserialize_create_aws_kms_mrk_keyring, + _deserialize_create_aws_kms_mrk_multi_keyring, + _deserialize_create_aws_kms_multi_keyring, + _deserialize_create_aws_kms_rsa_keyring, + _deserialize_create_cryptographic_materials_cache, + _deserialize_create_default_client_supplier, + _deserialize_create_default_cryptographic_materials_manager, + _deserialize_create_multi_keyring, + _deserialize_create_raw_aes_keyring, + _deserialize_create_raw_ecdh_keyring, + _deserialize_create_raw_rsa_keyring, + _deserialize_create_required_encryption_context_cmm, + _deserialize_decryption_materials_with_plaintext_data_key, + _deserialize_encryption_materials_has_plaintext_data_key, + _deserialize_get_algorithm_suite_info, + _deserialize_initialize_decryption_materials, + _deserialize_initialize_encryption_materials, + _deserialize_valid_algorithm_suite_info, + _deserialize_valid_decryption_materials_transition, + _deserialize_valid_encryption_materials_transition, + _deserialize_validate_commitment_policy_on_decrypt, + _deserialize_validate_commitment_policy_on_encrypt, +) +from .errors import ServiceError +from .models import ( + AlgorithmSuiteInfo, + CreateAwsKmsDiscoveryKeyringInput, + CreateAwsKmsDiscoveryMultiKeyringInput, + CreateAwsKmsEcdhKeyringInput, + CreateAwsKmsHierarchicalKeyringInput, + CreateAwsKmsKeyringInput, + CreateAwsKmsMrkDiscoveryKeyringInput, + CreateAwsKmsMrkDiscoveryMultiKeyringInput, + CreateAwsKmsMrkKeyringInput, + CreateAwsKmsMrkMultiKeyringInput, + CreateAwsKmsMultiKeyringInput, + CreateAwsKmsRsaKeyringInput, + CreateCryptographicMaterialsCacheInput, + CreateDefaultClientSupplierInput, + CreateDefaultCryptographicMaterialsManagerInput, + CreateMultiKeyringInput, + CreateRawAesKeyringInput, + CreateRawEcdhKeyringInput, + CreateRawRsaKeyringInput, + CreateRequiredEncryptionContextCMMInput, + DecryptionMaterials, + EncryptionMaterials, + InitializeDecryptionMaterialsInput, + InitializeEncryptionMaterialsInput, + Unit, + ValidDecryptionMaterialsTransitionInput, + ValidEncryptionMaterialsTransitionInput, + ValidateCommitmentPolicyOnDecryptInput, + ValidateCommitmentPolicyOnEncryptInput, +) +from .serialize import ( + _serialize_create_aws_kms_discovery_keyring, + _serialize_create_aws_kms_discovery_multi_keyring, + _serialize_create_aws_kms_ecdh_keyring, + _serialize_create_aws_kms_hierarchical_keyring, + _serialize_create_aws_kms_keyring, + _serialize_create_aws_kms_mrk_discovery_keyring, + _serialize_create_aws_kms_mrk_discovery_multi_keyring, + _serialize_create_aws_kms_mrk_keyring, + _serialize_create_aws_kms_mrk_multi_keyring, + _serialize_create_aws_kms_multi_keyring, + _serialize_create_aws_kms_rsa_keyring, + _serialize_create_cryptographic_materials_cache, + _serialize_create_default_client_supplier, + _serialize_create_default_cryptographic_materials_manager, + _serialize_create_multi_keyring, + _serialize_create_raw_aes_keyring, + _serialize_create_raw_ecdh_keyring, + _serialize_create_raw_rsa_keyring, + _serialize_create_required_encryption_context_cmm, + _serialize_decryption_materials_with_plaintext_data_key, + _serialize_encryption_materials_has_plaintext_data_key, + _serialize_get_algorithm_suite_info, + _serialize_initialize_decryption_materials, + _serialize_initialize_encryption_materials, + _serialize_valid_algorithm_suite_info, + _serialize_valid_decryption_materials_transition, + _serialize_valid_encryption_materials_transition, + _serialize_validate_commitment_policy_on_decrypt, + _serialize_validate_commitment_policy_on_encrypt, +) + + +Input = TypeVar("Input") +Output = TypeVar("Output") + + +class AwsCryptographicMaterialProviders: + """Client for AwsCryptographicMaterialProviders. + + :param config: Configuration for the client. + """ + + def __init__( + self, + config: MaterialProvidersConfig | None = None, + dafny_client: IAwsCryptographicMaterialProvidersClient | 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_aws_kms_keyring( + self, input: CreateAwsKmsKeyringInput + ) -> "aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.references.Keyring": + """Creates an AWS KMS Keyring, which wraps and unwraps data keys using + single symmetric AWS KMS Key. + + :param input: Inputs for for creating a AWS KMS Keyring. + """ + return self._execute_operation( + input=input, + plugins=[], + serialize=_serialize_create_aws_kms_keyring, + deserialize=_deserialize_create_aws_kms_keyring, + config=self._config, + operation_name="CreateAwsKmsKeyring", + ) + + def create_aws_kms_discovery_keyring( + self, input: CreateAwsKmsDiscoveryKeyringInput + ) -> "aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.references.Keyring": + """Creates an AWS KMS Discovery Keyring, which supports unwrapping data + keys wrapped by a symmetric AWS KMS Key for a single region. + + :param input: Inputs for for creating a AWS KMS Discovery + Keyring. + """ + return self._execute_operation( + input=input, + plugins=[], + serialize=_serialize_create_aws_kms_discovery_keyring, + deserialize=_deserialize_create_aws_kms_discovery_keyring, + config=self._config, + operation_name="CreateAwsKmsDiscoveryKeyring", + ) + + def create_aws_kms_multi_keyring( + self, input: CreateAwsKmsMultiKeyringInput + ) -> "aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.references.Keyring": + """Creates an AWS KMS Multi-Keyring, which wraps and unwraps data keys + using one or more symmetric AWS KMS Keys. + + :param input: Inputs for for creating a AWS KMS Multi-Keyring. + """ + return self._execute_operation( + input=input, + plugins=[], + serialize=_serialize_create_aws_kms_multi_keyring, + deserialize=_deserialize_create_aws_kms_multi_keyring, + config=self._config, + operation_name="CreateAwsKmsMultiKeyring", + ) + + def create_aws_kms_discovery_multi_keyring( + self, input: CreateAwsKmsDiscoveryMultiKeyringInput + ) -> "aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.references.Keyring": + """Creates an AWS KMS Discovery Multi-Keyring, which supports + unwrapping data keys wrapped by a symmetric AWS KMS Key, for multiple + regions. + + :param input: Inputs for for creating an AWS KMS Discovery + Multi-Keyring. + """ + return self._execute_operation( + input=input, + plugins=[], + serialize=_serialize_create_aws_kms_discovery_multi_keyring, + deserialize=_deserialize_create_aws_kms_discovery_multi_keyring, + config=self._config, + operation_name="CreateAwsKmsDiscoveryMultiKeyring", + ) + + def create_aws_kms_mrk_keyring( + self, input: CreateAwsKmsMrkKeyringInput + ) -> "aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.references.Keyring": + """Creates an AWS KMS MRK Keyring, which wraps and unwraps data keys + using single symmetric AWS KMS Key or AWS KMS Multi-Region Key. + + :param input: Inputs for for creating an AWS KMS MRK Keyring. + """ + return self._execute_operation( + input=input, + plugins=[], + serialize=_serialize_create_aws_kms_mrk_keyring, + deserialize=_deserialize_create_aws_kms_mrk_keyring, + config=self._config, + operation_name="CreateAwsKmsMrkKeyring", + ) + + def create_aws_kms_mrk_multi_keyring( + self, input: CreateAwsKmsMrkMultiKeyringInput + ) -> "aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.references.Keyring": + """Creates an AWS KMS MRK Multi-Keyring, which wraps and unwraps data + keys using one or more symmetric AWS KMS Keys or AWS KMS Multi-Region + Keys. + + :param input: Inputs for for creating a AWS KMS MRK Multi- + Keyring. + """ + return self._execute_operation( + input=input, + plugins=[], + serialize=_serialize_create_aws_kms_mrk_multi_keyring, + deserialize=_deserialize_create_aws_kms_mrk_multi_keyring, + config=self._config, + operation_name="CreateAwsKmsMrkMultiKeyring", + ) + + def create_aws_kms_mrk_discovery_keyring( + self, input: CreateAwsKmsMrkDiscoveryKeyringInput + ) -> "aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.references.Keyring": + """Creates an AWS KMS MRK Discovery Keyring, which supports unwrapping + data keys wrapped by a symmetric AWS KMS Key or AWS KMS Multi-Region + Key in a particular region. + + :param input: Inputs for for creating a AWS KMS MRK Discovery + Keyring. + """ + return self._execute_operation( + input=input, + plugins=[], + serialize=_serialize_create_aws_kms_mrk_discovery_keyring, + deserialize=_deserialize_create_aws_kms_mrk_discovery_keyring, + config=self._config, + operation_name="CreateAwsKmsMrkDiscoveryKeyring", + ) + + def create_aws_kms_mrk_discovery_multi_keyring( + self, input: CreateAwsKmsMrkDiscoveryMultiKeyringInput + ) -> "aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.references.Keyring": + """Creates an AWS KMS MRK Discovery Multi-Keyring that supports + unwrapping data keys wrapped by a symmetric AWS KMS Key or AWS KMS + Multi-Region Key, for a single region. + + :param input: Inputs for for creating a AWS KMS MRK Discovery + Multi-Keyring. + """ + return self._execute_operation( + input=input, + plugins=[], + serialize=_serialize_create_aws_kms_mrk_discovery_multi_keyring, + deserialize=_deserialize_create_aws_kms_mrk_discovery_multi_keyring, + config=self._config, + operation_name="CreateAwsKmsMrkDiscoveryMultiKeyring", + ) + + def create_aws_kms_hierarchical_keyring( + self, input: CreateAwsKmsHierarchicalKeyringInput + ) -> "aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.references.Keyring": + """Creates a Hierarchical Keyring, which supports wrapping and + unwrapping data keys using Branch Keys persisted in DynamoDB and + protected by a symmetric AWS KMS Key or AWS KMS Multi-Region Key. + + :param input: Inputs for creating a Hierarchical Keyring. + """ + return self._execute_operation( + input=input, + plugins=[], + serialize=_serialize_create_aws_kms_hierarchical_keyring, + deserialize=_deserialize_create_aws_kms_hierarchical_keyring, + config=self._config, + operation_name="CreateAwsKmsHierarchicalKeyring", + ) + + def create_aws_kms_rsa_keyring( + self, input: CreateAwsKmsRsaKeyringInput + ) -> "aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.references.Keyring": + """Creates an AWS KMS RSA Keyring, which wraps and unwraps data keys + using a single asymmetric AWS KMS Key for RSA. + + :param input: Inputs for creating a AWS KMS RSA Keyring. + """ + return self._execute_operation( + input=input, + plugins=[], + serialize=_serialize_create_aws_kms_rsa_keyring, + deserialize=_deserialize_create_aws_kms_rsa_keyring, + config=self._config, + operation_name="CreateAwsKmsRsaKeyring", + ) + + def create_aws_kms_ecdh_keyring( + self, input: CreateAwsKmsEcdhKeyringInput + ) -> "aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.references.Keyring": + """Creates an AWS KMS ECDH Keyring, which wraps and unwraps data keys + by deriving a shared data key from the established shared secret + between parties through the ECDH protocol. + + :param input: Inputs for creating an AWS KMS ECDH Keyring. + """ + return self._execute_operation( + input=input, + plugins=[], + serialize=_serialize_create_aws_kms_ecdh_keyring, + deserialize=_deserialize_create_aws_kms_ecdh_keyring, + config=self._config, + operation_name="CreateAwsKmsEcdhKeyring", + ) + + def create_multi_keyring( + self, input: CreateMultiKeyringInput + ) -> "aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.references.Keyring": + """Creates a Multi-Keyring comprised of one or more other Keyrings. + + :param input: Inputs for creating a Multi-Keyring. + """ + return self._execute_operation( + input=input, + plugins=[], + serialize=_serialize_create_multi_keyring, + deserialize=_deserialize_create_multi_keyring, + config=self._config, + operation_name="CreateMultiKeyring", + ) + + def create_raw_aes_keyring( + self, input: CreateRawAesKeyringInput + ) -> "aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.references.Keyring": + """Creates a Raw AES Keyring, which wraps and unwraps data keys locally + using AES_GCM. + + :param input: Inputs for creating a Raw AES Keyring. + """ + return self._execute_operation( + input=input, + plugins=[], + serialize=_serialize_create_raw_aes_keyring, + deserialize=_deserialize_create_raw_aes_keyring, + config=self._config, + operation_name="CreateRawAesKeyring", + ) + + def create_raw_rsa_keyring( + self, input: CreateRawRsaKeyringInput + ) -> "aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.references.Keyring": + """Creates a Raw RSA Keyring, which wraps and unwraps data keys locally + using RSA. + + :param input: Inputs for creating a Raw RAW Keyring. + """ + return self._execute_operation( + input=input, + plugins=[], + serialize=_serialize_create_raw_rsa_keyring, + deserialize=_deserialize_create_raw_rsa_keyring, + config=self._config, + operation_name="CreateRawRsaKeyring", + ) + + def create_raw_ecdh_keyring( + self, input: CreateRawEcdhKeyringInput + ) -> "aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.references.Keyring": + """Creates a Raw ECDH Keyring, which wraps and unwraps data keys by + deriving a shared data key from the established shared secret between + parties through the ECDH protocol. + + :param input: Inputs for creating a raw ECDH Keyring. + """ + return self._execute_operation( + input=input, + plugins=[], + serialize=_serialize_create_raw_ecdh_keyring, + deserialize=_deserialize_create_raw_ecdh_keyring, + config=self._config, + operation_name="CreateRawEcdhKeyring", + ) + + def create_default_cryptographic_materials_manager( + self, input: CreateDefaultCryptographicMaterialsManagerInput + ) -> "aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.references.CryptographicMaterialsManager": + """Creates a Default Cryptographic Materials Manager. + + :param input: Inputs for creating a Default Cryptographic + Materials Manager. + """ + return self._execute_operation( + input=input, + plugins=[], + serialize=_serialize_create_default_cryptographic_materials_manager, + deserialize=_deserialize_create_default_cryptographic_materials_manager, + config=self._config, + operation_name="CreateDefaultCryptographicMaterialsManager", + ) + + def create_required_encryption_context_cmm( + self, input: CreateRequiredEncryptionContextCMMInput + ) -> "aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.references.CryptographicMaterialsManager": + """Creates an Required Encryption Context Cryptographic Materials + Manager. + + :param input: Inputs for creating an Required Encryption Context + Cryptographic Materials Manager. + """ + return self._execute_operation( + input=input, + plugins=[], + serialize=_serialize_create_required_encryption_context_cmm, + deserialize=_deserialize_create_required_encryption_context_cmm, + config=self._config, + operation_name="CreateRequiredEncryptionContextCMM", + ) + + def create_cryptographic_materials_cache( + self, input: CreateCryptographicMaterialsCacheInput + ) -> "aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.references.CryptographicMaterialsCache": + """Invokes the CreateCryptographicMaterialsCache operation. + + :param input: The operation's input. + """ + return self._execute_operation( + input=input, + plugins=[], + serialize=_serialize_create_cryptographic_materials_cache, + deserialize=_deserialize_create_cryptographic_materials_cache, + config=self._config, + operation_name="CreateCryptographicMaterialsCache", + ) + + def create_default_client_supplier( + self, input: CreateDefaultClientSupplierInput + ) -> "aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.references.ClientSupplier": + """Invokes the CreateDefaultClientSupplier operation. + + :param input: The operation's input. + """ + return self._execute_operation( + input=input, + plugins=[], + serialize=_serialize_create_default_client_supplier, + deserialize=_deserialize_create_default_client_supplier, + config=self._config, + operation_name="CreateDefaultClientSupplier", + ) + + def initialize_encryption_materials( + self, input: InitializeEncryptionMaterialsInput + ) -> EncryptionMaterials: + """Invokes the InitializeEncryptionMaterials operation. + + :param input: The operation's input. + """ + return self._execute_operation( + input=input, + plugins=[], + serialize=_serialize_initialize_encryption_materials, + deserialize=_deserialize_initialize_encryption_materials, + config=self._config, + operation_name="InitializeEncryptionMaterials", + ) + + def initialize_decryption_materials( + self, input: InitializeDecryptionMaterialsInput + ) -> DecryptionMaterials: + """Invokes the InitializeDecryptionMaterials operation. + + :param input: The operation's input. + """ + return self._execute_operation( + input=input, + plugins=[], + serialize=_serialize_initialize_decryption_materials, + deserialize=_deserialize_initialize_decryption_materials, + config=self._config, + operation_name="InitializeDecryptionMaterials", + ) + + def valid_encryption_materials_transition( + self, input: ValidEncryptionMaterialsTransitionInput + ) -> Unit: + """Invokes the ValidEncryptionMaterialsTransition operation. + + :param input: The operation's input. + """ + return self._execute_operation( + input=input, + plugins=[], + serialize=_serialize_valid_encryption_materials_transition, + deserialize=_deserialize_valid_encryption_materials_transition, + config=self._config, + operation_name="ValidEncryptionMaterialsTransition", + ) + + def valid_decryption_materials_transition( + self, input: ValidDecryptionMaterialsTransitionInput + ) -> Unit: + """Invokes the ValidDecryptionMaterialsTransition operation. + + :param input: The operation's input. + """ + return self._execute_operation( + input=input, + plugins=[], + serialize=_serialize_valid_decryption_materials_transition, + deserialize=_deserialize_valid_decryption_materials_transition, + config=self._config, + operation_name="ValidDecryptionMaterialsTransition", + ) + + def encryption_materials_has_plaintext_data_key( + self, input: EncryptionMaterials + ) -> Unit: + """Invokes the EncryptionMaterialsHasPlaintextDataKey operation. + + :param input: The operation's input. + """ + return self._execute_operation( + input=input, + plugins=[], + serialize=_serialize_encryption_materials_has_plaintext_data_key, + deserialize=_deserialize_encryption_materials_has_plaintext_data_key, + config=self._config, + operation_name="EncryptionMaterialsHasPlaintextDataKey", + ) + + def decryption_materials_with_plaintext_data_key( + self, input: DecryptionMaterials + ) -> Unit: + """Invokes the DecryptionMaterialsWithPlaintextDataKey operation. + + :param input: The operation's input. + """ + return self._execute_operation( + input=input, + plugins=[], + serialize=_serialize_decryption_materials_with_plaintext_data_key, + deserialize=_deserialize_decryption_materials_with_plaintext_data_key, + config=self._config, + operation_name="DecryptionMaterialsWithPlaintextDataKey", + ) + + def get_algorithm_suite_info(self, input: bytes | bytearray) -> AlgorithmSuiteInfo: + """Invokes the GetAlgorithmSuiteInfo operation. + + :param input: The operation's input. + """ + return self._execute_operation( + input=input, + plugins=[], + serialize=_serialize_get_algorithm_suite_info, + deserialize=_deserialize_get_algorithm_suite_info, + config=self._config, + operation_name="GetAlgorithmSuiteInfo", + ) + + def valid_algorithm_suite_info(self, input: AlgorithmSuiteInfo) -> Unit: + """Invokes the ValidAlgorithmSuiteInfo operation. + + :param input: The operation's input. + """ + return self._execute_operation( + input=input, + plugins=[], + serialize=_serialize_valid_algorithm_suite_info, + deserialize=_deserialize_valid_algorithm_suite_info, + config=self._config, + operation_name="ValidAlgorithmSuiteInfo", + ) + + def validate_commitment_policy_on_encrypt( + self, input: ValidateCommitmentPolicyOnEncryptInput + ) -> Unit: + """Invokes the ValidateCommitmentPolicyOnEncrypt operation. + + :param input: The operation's input. + """ + return self._execute_operation( + input=input, + plugins=[], + serialize=_serialize_validate_commitment_policy_on_encrypt, + deserialize=_deserialize_validate_commitment_policy_on_encrypt, + config=self._config, + operation_name="ValidateCommitmentPolicyOnEncrypt", + ) + + def validate_commitment_policy_on_decrypt( + self, input: ValidateCommitmentPolicyOnDecryptInput + ) -> Unit: + """Invokes the ValidateCommitmentPolicyOnDecrypt operation. + + :param input: The operation's input. + """ + return self._execute_operation( + input=input, + plugins=[], + serialize=_serialize_validate_commitment_policy_on_decrypt, + deserialize=_deserialize_validate_commitment_policy_on_decrypt, + config=self._config, + operation_name="ValidateCommitmentPolicyOnDecrypt", + ) + + 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_materialproviders/smithygenerated/aws_cryptography_materialproviders/config.py b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/smithygenerated/aws_cryptography_materialproviders/config.py new file mode 100644 index 000000000..25102483f --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/smithygenerated/aws_cryptography_materialproviders/config.py @@ -0,0 +1,77 @@ +# 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_materialproviders.internaldafny.generated.AwsCryptographyMaterialProvidersTypes import ( + MaterialProvidersConfig_MaterialProvidersConfig as DafnyMaterialProvidersConfig, +) +import aws_cryptographic_materialproviders.internaldafny.generated.module_ +import aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy +import aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny +from dataclasses import dataclass +from typing import Any, Callable, TypeAlias + +from .dafnyImplInterface import DafnyImplInterface +from smithy_python._private.retries import SimpleRetryStrategy +from smithy_python.interfaces.retries import RetryStrategy + + +_ServiceInterceptor = Any + + +@dataclass(init=False) +class Config: + """Configuration for AwsCryptographicMaterialProviders.""" + + 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 MaterialProvidersConfig(Config): + """Smithy-modelled localService Config shape for this localService.""" + + def __init__( + self, + ): + """Constructor for MaterialProvidersConfig.""" + super().__init__() + + +def dafny_config_to_smithy_config(dafny_config) -> MaterialProvidersConfig: + """Converts the provided Dafny shape for this localService's config into + the corresponding Smithy-modelled shape.""" + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_MaterialProvidersConfig( + dafny_config + ) + + +def smithy_config_to_dafny_config(smithy_config) -> DafnyMaterialProvidersConfig: + """Converts the provided Smithy-modelled shape for this localService's + config into the corresponding Dafny shape.""" + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_MaterialProvidersConfig( + smithy_config + ) diff --git a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/smithygenerated/aws_cryptography_materialproviders/dafnyImplInterface.py b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/smithygenerated/aws_cryptography_materialproviders/dafnyImplInterface.py new file mode 100644 index 000000000..3e67708bb --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/smithygenerated/aws_cryptography_materialproviders/dafnyImplInterface.py @@ -0,0 +1,61 @@ +# 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_materialproviders.internaldafny.generated.MaterialProviders import ( + MaterialProvidersClient, +) +from .dafny_protocol import DafnyRequest + + +class DafnyImplInterface: + impl: MaterialProvidersClient | 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 = { + "CreateAwsKmsKeyring": self.impl.CreateAwsKmsKeyring, + "CreateAwsKmsDiscoveryKeyring": self.impl.CreateAwsKmsDiscoveryKeyring, + "CreateAwsKmsMultiKeyring": self.impl.CreateAwsKmsMultiKeyring, + "CreateAwsKmsDiscoveryMultiKeyring": self.impl.CreateAwsKmsDiscoveryMultiKeyring, + "CreateAwsKmsMrkKeyring": self.impl.CreateAwsKmsMrkKeyring, + "CreateAwsKmsMrkMultiKeyring": self.impl.CreateAwsKmsMrkMultiKeyring, + "CreateAwsKmsMrkDiscoveryKeyring": self.impl.CreateAwsKmsMrkDiscoveryKeyring, + "CreateAwsKmsMrkDiscoveryMultiKeyring": self.impl.CreateAwsKmsMrkDiscoveryMultiKeyring, + "CreateAwsKmsHierarchicalKeyring": self.impl.CreateAwsKmsHierarchicalKeyring, + "CreateAwsKmsRsaKeyring": self.impl.CreateAwsKmsRsaKeyring, + "CreateAwsKmsEcdhKeyring": self.impl.CreateAwsKmsEcdhKeyring, + "CreateMultiKeyring": self.impl.CreateMultiKeyring, + "CreateRawAesKeyring": self.impl.CreateRawAesKeyring, + "CreateRawRsaKeyring": self.impl.CreateRawRsaKeyring, + "CreateRawEcdhKeyring": self.impl.CreateRawEcdhKeyring, + "CreateDefaultCryptographicMaterialsManager": self.impl.CreateDefaultCryptographicMaterialsManager, + "CreateRequiredEncryptionContextCMM": self.impl.CreateRequiredEncryptionContextCMM, + "CreateCryptographicMaterialsCache": self.impl.CreateCryptographicMaterialsCache, + "CreateDefaultClientSupplier": self.impl.CreateDefaultClientSupplier, + "InitializeEncryptionMaterials": self.impl.InitializeEncryptionMaterials, + "InitializeDecryptionMaterials": self.impl.InitializeDecryptionMaterials, + "ValidEncryptionMaterialsTransition": self.impl.ValidEncryptionMaterialsTransition, + "ValidDecryptionMaterialsTransition": self.impl.ValidDecryptionMaterialsTransition, + "EncryptionMaterialsHasPlaintextDataKey": self.impl.EncryptionMaterialsHasPlaintextDataKey, + "DecryptionMaterialsWithPlaintextDataKey": self.impl.DecryptionMaterialsWithPlaintextDataKey, + "GetAlgorithmSuiteInfo": self.impl.GetAlgorithmSuiteInfo, + "ValidAlgorithmSuiteInfo": self.impl.ValidAlgorithmSuiteInfo, + "ValidateCommitmentPolicyOnEncrypt": self.impl.ValidateCommitmentPolicyOnEncrypt, + "ValidateCommitmentPolicyOnDecrypt": self.impl.ValidateCommitmentPolicyOnDecrypt, + } + + # 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_materialproviders/smithygenerated/aws_cryptography_materialproviders/dafny_protocol.py b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/smithygenerated/aws_cryptography_materialproviders/dafny_protocol.py new file mode 100644 index 000000000..8e929e044 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/smithygenerated/aws_cryptography_materialproviders/dafny_protocol.py @@ -0,0 +1,85 @@ +# 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_materialproviders.internaldafny.generated.AwsCryptographyMaterialProvidersTypes import ( + AlgorithmSuiteInfo_AlgorithmSuiteInfo as DafnyAlgorithmSuiteInfo, + CreateAwsKmsDiscoveryKeyringInput_CreateAwsKmsDiscoveryKeyringInput as DafnyCreateAwsKmsDiscoveryKeyringInput, + CreateAwsKmsDiscoveryMultiKeyringInput_CreateAwsKmsDiscoveryMultiKeyringInput as DafnyCreateAwsKmsDiscoveryMultiKeyringInput, + CreateAwsKmsEcdhKeyringInput_CreateAwsKmsEcdhKeyringInput as DafnyCreateAwsKmsEcdhKeyringInput, + CreateAwsKmsHierarchicalKeyringInput_CreateAwsKmsHierarchicalKeyringInput as DafnyCreateAwsKmsHierarchicalKeyringInput, + CreateAwsKmsKeyringInput_CreateAwsKmsKeyringInput as DafnyCreateAwsKmsKeyringInput, + CreateAwsKmsMrkDiscoveryKeyringInput_CreateAwsKmsMrkDiscoveryKeyringInput as DafnyCreateAwsKmsMrkDiscoveryKeyringInput, + CreateAwsKmsMrkDiscoveryMultiKeyringInput_CreateAwsKmsMrkDiscoveryMultiKeyringInput as DafnyCreateAwsKmsMrkDiscoveryMultiKeyringInput, + CreateAwsKmsMrkKeyringInput_CreateAwsKmsMrkKeyringInput as DafnyCreateAwsKmsMrkKeyringInput, + CreateAwsKmsMrkMultiKeyringInput_CreateAwsKmsMrkMultiKeyringInput as DafnyCreateAwsKmsMrkMultiKeyringInput, + CreateAwsKmsMultiKeyringInput_CreateAwsKmsMultiKeyringInput as DafnyCreateAwsKmsMultiKeyringInput, + CreateAwsKmsRsaKeyringInput_CreateAwsKmsRsaKeyringInput as DafnyCreateAwsKmsRsaKeyringInput, + CreateCryptographicMaterialsCacheInput_CreateCryptographicMaterialsCacheInput as DafnyCreateCryptographicMaterialsCacheInput, + CreateDefaultClientSupplierInput_CreateDefaultClientSupplierInput as DafnyCreateDefaultClientSupplierInput, + CreateDefaultCryptographicMaterialsManagerInput_CreateDefaultCryptographicMaterialsManagerInput as DafnyCreateDefaultCryptographicMaterialsManagerInput, + CreateMultiKeyringInput_CreateMultiKeyringInput as DafnyCreateMultiKeyringInput, + CreateRawAesKeyringInput_CreateRawAesKeyringInput as DafnyCreateRawAesKeyringInput, + CreateRawEcdhKeyringInput_CreateRawEcdhKeyringInput as DafnyCreateRawEcdhKeyringInput, + CreateRawRsaKeyringInput_CreateRawRsaKeyringInput as DafnyCreateRawRsaKeyringInput, + CreateRequiredEncryptionContextCMMInput_CreateRequiredEncryptionContextCMMInput as DafnyCreateRequiredEncryptionContextCMMInput, + DecryptionMaterials_DecryptionMaterials as DafnyDecryptionMaterials, + EncryptionMaterials_EncryptionMaterials as DafnyEncryptionMaterials, + InitializeDecryptionMaterialsInput_InitializeDecryptionMaterialsInput as DafnyInitializeDecryptionMaterialsInput, + InitializeEncryptionMaterialsInput_InitializeEncryptionMaterialsInput as DafnyInitializeEncryptionMaterialsInput, + ValidDecryptionMaterialsTransitionInput_ValidDecryptionMaterialsTransitionInput as DafnyValidDecryptionMaterialsTransitionInput, + ValidEncryptionMaterialsTransitionInput_ValidEncryptionMaterialsTransitionInput as DafnyValidEncryptionMaterialsTransitionInput, + ValidateCommitmentPolicyOnDecryptInput_ValidateCommitmentPolicyOnDecryptInput as DafnyValidateCommitmentPolicyOnDecryptInput, + ValidateCommitmentPolicyOnEncryptInput_ValidateCommitmentPolicyOnEncryptInput as DafnyValidateCommitmentPolicyOnEncryptInput, +) +import aws_cryptographic_materialproviders.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[ + DafnyValidEncryptionMaterialsTransitionInput, + DafnyAlgorithmSuiteInfo, + DafnyCreateRawEcdhKeyringInput, + DafnyCreateDefaultClientSupplierInput, + DafnyCreateRequiredEncryptionContextCMMInput, + DafnyCreateAwsKmsKeyringInput, + DafnyCreateAwsKmsMrkMultiKeyringInput, + DafnyInitializeEncryptionMaterialsInput, + DafnyEncryptionMaterials, + DafnyCreateAwsKmsDiscoveryKeyringInput, + DafnyInitializeDecryptionMaterialsInput, + DafnyValidateCommitmentPolicyOnDecryptInput, + DafnyCreateAwsKmsDiscoveryMultiKeyringInput, + DafnyCreateAwsKmsMrkDiscoveryMultiKeyringInput, + DafnyCreateAwsKmsRsaKeyringInput, + DafnyValidDecryptionMaterialsTransitionInput, + DafnyCreateDefaultCryptographicMaterialsManagerInput, + DafnyCreateRawRsaKeyringInput, + DafnyValidateCommitmentPolicyOnEncryptInput, + DafnyCreateAwsKmsEcdhKeyringInput, + DafnyCreateAwsKmsMrkKeyringInput, + DafnyCreateAwsKmsHierarchicalKeyringInput, + DafnyCreateAwsKmsMrkDiscoveryKeyringInput, + DafnyCreateAwsKmsMultiKeyringInput, + DafnyCreateRawAesKeyringInput, + DafnyCreateCryptographicMaterialsCacheInput, + DafnyCreateMultiKeyringInput, + DafnyDecryptionMaterials, + ] + + 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_materialproviders/smithygenerated/aws_cryptography_materialproviders/dafny_to_aws_sdk.py b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/smithygenerated/aws_cryptography_materialproviders/dafny_to_aws_sdk.py new file mode 100644 index 000000000..4bdc4dd35 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/smithygenerated/aws_cryptography_materialproviders/dafny_to_aws_sdk.py @@ -0,0 +1,25 @@ +# 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_cryptography_internal_kms.internaldafny.generated.ComAmazonawsKmsTypes import ( + EncryptionAlgorithmSpec_RSAES__OAEP__SHA__1, + EncryptionAlgorithmSpec_RSAES__OAEP__SHA__256, + EncryptionAlgorithmSpec_SYMMETRIC__DEFAULT, +) +import aws_cryptography_internal_kms.internaldafny.generated.module_ + + +def com_amazonaws_kms_EncryptionAlgorithmSpec(dafny_input): + # Convert EncryptionAlgorithmSpec + if isinstance(dafny_input, EncryptionAlgorithmSpec_SYMMETRIC__DEFAULT): + return "SYMMETRIC_DEFAULT" + + elif isinstance(dafny_input, EncryptionAlgorithmSpec_RSAES__OAEP__SHA__1): + return "RSAES_OAEP_SHA_1" + + elif isinstance(dafny_input, EncryptionAlgorithmSpec_RSAES__OAEP__SHA__256): + return "RSAES_OAEP_SHA_256" + + else: + raise ValueError("No recognized enum value in enum type: " + dafny_input) diff --git a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/smithygenerated/aws_cryptography_materialproviders/dafny_to_smithy.py b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/smithygenerated/aws_cryptography_materialproviders/dafny_to_smithy.py new file mode 100644 index 000000000..e1f638d23 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/smithygenerated/aws_cryptography_materialproviders/dafny_to_smithy.py @@ -0,0 +1,1741 @@ +# 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_materialproviders.internaldafny.generated.AwsCryptographyMaterialProvidersTypes import ( + AesWrappingAlg_ALG__AES128__GCM__IV12__TAG16, + AesWrappingAlg_ALG__AES192__GCM__IV12__TAG16, + AesWrappingAlg_ALG__AES256__GCM__IV12__TAG16, + AlgorithmSuiteId_DBE, + AlgorithmSuiteId_ESDK, + CacheType_Default, + CacheType_MultiThreaded, + CacheType_No, + CacheType_Shared, + CacheType_SingleThreaded, + CacheType_StormTracking, + CommitmentPolicy_DBE, + CommitmentPolicy_ESDK, + DBEAlgorithmSuiteId_ALG__AES__256__GCM__HKDF__SHA512__COMMIT__KEY__ECDSA__P384__SYMSIG__HMAC__SHA384, + DBEAlgorithmSuiteId_ALG__AES__256__GCM__HKDF__SHA512__COMMIT__KEY__SYMSIG__HMAC__SHA384, + DBECommitmentPolicy_REQUIRE__ENCRYPT__REQUIRE__DECRYPT, + DerivationAlgorithm_HKDF, + DerivationAlgorithm_IDENTITY, + DerivationAlgorithm_None, + ESDKAlgorithmSuiteId_ALG__AES__128__GCM__IV12__TAG16__HKDF__SHA256, + ESDKAlgorithmSuiteId_ALG__AES__128__GCM__IV12__TAG16__HKDF__SHA256__ECDSA__P256, + ESDKAlgorithmSuiteId_ALG__AES__128__GCM__IV12__TAG16__NO__KDF, + ESDKAlgorithmSuiteId_ALG__AES__192__GCM__IV12__TAG16__HKDF__SHA256, + ESDKAlgorithmSuiteId_ALG__AES__192__GCM__IV12__TAG16__HKDF__SHA384__ECDSA__P384, + ESDKAlgorithmSuiteId_ALG__AES__192__GCM__IV12__TAG16__NO__KDF, + ESDKAlgorithmSuiteId_ALG__AES__256__GCM__HKDF__SHA512__COMMIT__KEY, + ESDKAlgorithmSuiteId_ALG__AES__256__GCM__HKDF__SHA512__COMMIT__KEY__ECDSA__P384, + ESDKAlgorithmSuiteId_ALG__AES__256__GCM__IV12__TAG16__HKDF__SHA256, + ESDKAlgorithmSuiteId_ALG__AES__256__GCM__IV12__TAG16__HKDF__SHA384__ECDSA__P384, + ESDKAlgorithmSuiteId_ALG__AES__256__GCM__IV12__TAG16__NO__KDF, + ESDKCommitmentPolicy_FORBID__ENCRYPT__ALLOW__DECRYPT, + ESDKCommitmentPolicy_REQUIRE__ENCRYPT__ALLOW__DECRYPT, + ESDKCommitmentPolicy_REQUIRE__ENCRYPT__REQUIRE__DECRYPT, + EdkWrappingAlgorithm_DIRECT__KEY__WRAPPING, + EdkWrappingAlgorithm_IntermediateKeyWrapping, + Encrypt_AES__GCM, + KmsEcdhStaticConfigurations_KmsPrivateKeyToStaticPublicKey, + KmsEcdhStaticConfigurations_KmsPublicKeyDiscovery, + Materials_BeaconKey, + Materials_BranchKey, + Materials_Decryption, + Materials_Encryption, + PaddingScheme_OAEP__SHA1__MGF1, + PaddingScheme_OAEP__SHA256__MGF1, + PaddingScheme_OAEP__SHA384__MGF1, + PaddingScheme_OAEP__SHA512__MGF1, + PaddingScheme_PKCS1, + RawEcdhStaticConfigurations_EphemeralPrivateKeyToStaticPublicKey, + RawEcdhStaticConfigurations_PublicKeyDiscovery, + RawEcdhStaticConfigurations_RawPrivateKeyToStaticPublicKey, + SignatureAlgorithm_ECDSA, + SignatureAlgorithm_None, + SymmetricSignatureAlgorithm_HMAC, + SymmetricSignatureAlgorithm_None, +) +import aws_cryptographic_materialproviders.internaldafny.generated.module_ +import aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_keystore.dafny_to_smithy +import aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy +import aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models +import aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk +import aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.dafny_to_smithy + + +def aws_cryptography_materialproviders_GetBranchKeyIdInput(dafny_input): + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.GetBranchKeyIdInput( + encryption_context={ + bytes(key.Elements).decode("utf-8"): bytes(value.Elements).decode("utf-8") + for (key, value) in dafny_input.encryptionContext.items + }, + ) + + +def aws_cryptography_materialproviders_GetBranchKeyIdOutput(dafny_input): + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.GetBranchKeyIdOutput( + branch_key_id=b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.branchKeyId + ).decode("utf-16-be"), + ) + + +def aws_cryptography_materialproviders_GetClientInput(dafny_input): + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.GetClientInput( + region=b"".join(ord(c).to_bytes(2, "big") for c in dafny_input.region).decode( + "utf-16-be" + ), + ) + + +def aws_cryptography_materialproviders_KmsClientReference(dafny_input): + return dafny_input._impl + + +def aws_cryptography_materialproviders_GetClientOutput(dafny_input): + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_KmsClientReference( + dafny_input + ) + + +def aws_cryptography_materialproviders_Materials(dafny_input): + # Convert Materials + if isinstance(dafny_input, Materials_Encryption): + Materials_union_value = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.MaterialsEncryption( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_EncryptionMaterials( + dafny_input.Encryption + ) + ) + elif isinstance(dafny_input, Materials_Decryption): + Materials_union_value = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.MaterialsDecryption( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_DecryptionMaterials( + dafny_input.Decryption + ) + ) + elif isinstance(dafny_input, Materials_BranchKey): + Materials_union_value = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.MaterialsBranchKey( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_BranchKeyMaterials( + dafny_input.BranchKey + ) + ) + elif isinstance(dafny_input, Materials_BeaconKey): + Materials_union_value = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.MaterialsBeaconKey( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_keystore.dafny_to_smithy.aws_cryptography_keystore_BeaconKeyMaterials( + dafny_input.BeaconKey + ) + ) + else: + raise ValueError("No recognized union value in union type: " + str(dafny_input)) + + return Materials_union_value + + +def aws_cryptography_materialproviders_EncryptionMaterials(dafny_input): + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.EncryptionMaterials( + algorithm_suite=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_AlgorithmSuiteInfo( + dafny_input.algorithmSuite + ), + encryption_context={ + bytes(key.Elements).decode("utf-8"): bytes(value.Elements).decode("utf-8") + for (key, value) in dafny_input.encryptionContext.items + }, + encrypted_data_keys=[ + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_EncryptedDataKey( + list_element + ) + for list_element in dafny_input.encryptedDataKeys + ], + required_encryption_context_keys=[ + bytes(list_element.Elements).decode("utf-8") + for list_element in dafny_input.requiredEncryptionContextKeys + ], + plaintext_data_key=( + (bytes(dafny_input.plaintextDataKey.value)) + if (dafny_input.plaintextDataKey.is_Some) + else None + ), + signing_key=( + (bytes(dafny_input.signingKey.value)) + if (dafny_input.signingKey.is_Some) + else None + ), + symmetric_signing_keys=( + ( + [ + bytes(list_element) + for list_element in dafny_input.symmetricSigningKeys.value + ] + ) + if (dafny_input.symmetricSigningKeys.is_Some) + else None + ), + ) + + +def aws_cryptography_materialproviders_DecryptionMaterials(dafny_input): + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.DecryptionMaterials( + algorithm_suite=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_AlgorithmSuiteInfo( + dafny_input.algorithmSuite + ), + encryption_context={ + bytes(key.Elements).decode("utf-8"): bytes(value.Elements).decode("utf-8") + for (key, value) in dafny_input.encryptionContext.items + }, + required_encryption_context_keys=[ + bytes(list_element.Elements).decode("utf-8") + for list_element in dafny_input.requiredEncryptionContextKeys + ], + plaintext_data_key=( + (bytes(dafny_input.plaintextDataKey.value)) + if (dafny_input.plaintextDataKey.is_Some) + else None + ), + verification_key=( + (bytes(dafny_input.verificationKey.value)) + if (dafny_input.verificationKey.is_Some) + else None + ), + symmetric_signing_key=( + (bytes(dafny_input.symmetricSigningKey.value)) + if (dafny_input.symmetricSigningKey.is_Some) + else None + ), + ) + + +def aws_cryptography_materialproviders_AlgorithmSuiteInfo(dafny_input): + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.AlgorithmSuiteInfo( + id=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_AlgorithmSuiteId( + dafny_input.id + ), + binary_id=bytes(dafny_input.binaryId), + message_version=dafny_input.messageVersion, + encrypt=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_Encrypt( + dafny_input.encrypt + ), + kdf=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_DerivationAlgorithm( + dafny_input.kdf + ), + commitment=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_DerivationAlgorithm( + dafny_input.commitment + ), + signature=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_SignatureAlgorithm( + dafny_input.signature + ), + symmetric_signature=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_SymmetricSignatureAlgorithm( + dafny_input.symmetricSignature + ), + edk_wrapping=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_EdkWrappingAlgorithm( + dafny_input.edkWrapping + ), + ) + + +def aws_cryptography_materialproviders_EncryptedDataKey(dafny_input): + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.EncryptedDataKey( + key_provider_id=bytes(dafny_input.keyProviderId.Elements).decode("utf-8"), + key_provider_info=bytes(dafny_input.keyProviderInfo), + ciphertext=bytes(dafny_input.ciphertext), + ) + + +def aws_cryptography_materialproviders_AlgorithmSuiteId(dafny_input): + # Convert AlgorithmSuiteId + if isinstance(dafny_input, AlgorithmSuiteId_ESDK): + AlgorithmSuiteId_union_value = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.AlgorithmSuiteIdESDK( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_ESDKAlgorithmSuiteId( + dafny_input.ESDK + ) + ) + elif isinstance(dafny_input, AlgorithmSuiteId_DBE): + AlgorithmSuiteId_union_value = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.AlgorithmSuiteIdDBE( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_DBEAlgorithmSuiteId( + dafny_input.DBE + ) + ) + else: + raise ValueError("No recognized union value in union type: " + str(dafny_input)) + + return AlgorithmSuiteId_union_value + + +def aws_cryptography_materialproviders_Encrypt(dafny_input): + # Convert Encrypt + if isinstance(dafny_input, Encrypt_AES__GCM): + Encrypt_union_value = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.EncryptAES_GCM( + aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.dafny_to_smithy.aws_cryptography_primitives_AES_GCM( + dafny_input.AES__GCM + ) + ) + else: + raise ValueError("No recognized union value in union type: " + str(dafny_input)) + + return Encrypt_union_value + + +def aws_cryptography_materialproviders_DerivationAlgorithm(dafny_input): + # Convert DerivationAlgorithm + if isinstance(dafny_input, DerivationAlgorithm_HKDF): + DerivationAlgorithm_union_value = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.DerivationAlgorithmHKDF( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_HKDF( + dafny_input.HKDF + ) + ) + elif isinstance(dafny_input, DerivationAlgorithm_IDENTITY): + DerivationAlgorithm_union_value = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.DerivationAlgorithmIDENTITY( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_IDENTITY( + dafny_input.IDENTITY + ) + ) + elif isinstance(dafny_input, DerivationAlgorithm_None): + DerivationAlgorithm_union_value = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.DerivationAlgorithmNone( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_None( + dafny_input.None_ + ) + ) + else: + raise ValueError("No recognized union value in union type: " + str(dafny_input)) + + return DerivationAlgorithm_union_value + + +def aws_cryptography_materialproviders_SignatureAlgorithm(dafny_input): + # Convert SignatureAlgorithm + if isinstance(dafny_input, SignatureAlgorithm_ECDSA): + SignatureAlgorithm_union_value = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.SignatureAlgorithmECDSA( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_ECDSA( + dafny_input.ECDSA + ) + ) + elif isinstance(dafny_input, SignatureAlgorithm_None): + SignatureAlgorithm_union_value = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.SignatureAlgorithmNone( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_None( + dafny_input.None_ + ) + ) + else: + raise ValueError("No recognized union value in union type: " + str(dafny_input)) + + return SignatureAlgorithm_union_value + + +def aws_cryptography_materialproviders_SymmetricSignatureAlgorithm(dafny_input): + # Convert SymmetricSignatureAlgorithm + if isinstance(dafny_input, SymmetricSignatureAlgorithm_HMAC): + SymmetricSignatureAlgorithm_union_value = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.SymmetricSignatureAlgorithmHMAC( + aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.dafny_to_smithy.aws_cryptography_primitives_DigestAlgorithm( + dafny_input.HMAC + ) + ) + elif isinstance(dafny_input, SymmetricSignatureAlgorithm_None): + SymmetricSignatureAlgorithm_union_value = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.SymmetricSignatureAlgorithmNone( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_None( + dafny_input.None_ + ) + ) + else: + raise ValueError("No recognized union value in union type: " + str(dafny_input)) + + return SymmetricSignatureAlgorithm_union_value + + +def aws_cryptography_materialproviders_EdkWrappingAlgorithm(dafny_input): + # Convert EdkWrappingAlgorithm + if isinstance(dafny_input, EdkWrappingAlgorithm_DIRECT__KEY__WRAPPING): + EdkWrappingAlgorithm_union_value = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.EdkWrappingAlgorithmDIRECT_KEY_WRAPPING( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_DIRECT_KEY_WRAPPING( + dafny_input.DIRECT__KEY__WRAPPING + ) + ) + elif isinstance(dafny_input, EdkWrappingAlgorithm_IntermediateKeyWrapping): + EdkWrappingAlgorithm_union_value = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.EdkWrappingAlgorithmIntermediateKeyWrapping( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_IntermediateKeyWrapping( + dafny_input.IntermediateKeyWrapping + ) + ) + else: + raise ValueError("No recognized union value in union type: " + str(dafny_input)) + + return EdkWrappingAlgorithm_union_value + + +def aws_cryptography_materialproviders_ESDKAlgorithmSuiteId(dafny_input): + if isinstance( + dafny_input, ESDKAlgorithmSuiteId_ALG__AES__128__GCM__IV12__TAG16__NO__KDF + ): + return "0x0014" + + elif isinstance( + dafny_input, ESDKAlgorithmSuiteId_ALG__AES__192__GCM__IV12__TAG16__NO__KDF + ): + return "0x0046" + + elif isinstance( + dafny_input, ESDKAlgorithmSuiteId_ALG__AES__256__GCM__IV12__TAG16__NO__KDF + ): + return "0x0078" + + elif isinstance( + dafny_input, ESDKAlgorithmSuiteId_ALG__AES__128__GCM__IV12__TAG16__HKDF__SHA256 + ): + return "0x0114" + + elif isinstance( + dafny_input, ESDKAlgorithmSuiteId_ALG__AES__192__GCM__IV12__TAG16__HKDF__SHA256 + ): + return "0x0146" + + elif isinstance( + dafny_input, ESDKAlgorithmSuiteId_ALG__AES__256__GCM__IV12__TAG16__HKDF__SHA256 + ): + return "0x0178" + + elif isinstance( + dafny_input, + ESDKAlgorithmSuiteId_ALG__AES__128__GCM__IV12__TAG16__HKDF__SHA256__ECDSA__P256, + ): + return "0x0214" + + elif isinstance( + dafny_input, + ESDKAlgorithmSuiteId_ALG__AES__192__GCM__IV12__TAG16__HKDF__SHA384__ECDSA__P384, + ): + return "0x0346" + + elif isinstance( + dafny_input, + ESDKAlgorithmSuiteId_ALG__AES__256__GCM__IV12__TAG16__HKDF__SHA384__ECDSA__P384, + ): + return "0x0378" + + elif isinstance( + dafny_input, ESDKAlgorithmSuiteId_ALG__AES__256__GCM__HKDF__SHA512__COMMIT__KEY + ): + return "0x0478" + + elif isinstance( + dafny_input, + ESDKAlgorithmSuiteId_ALG__AES__256__GCM__HKDF__SHA512__COMMIT__KEY__ECDSA__P384, + ): + return "0x0578" + + else: + raise ValueError(f"No recognized enum value in enum type: {dafny_input=}") + + +def aws_cryptography_materialproviders_DBEAlgorithmSuiteId(dafny_input): + if isinstance( + dafny_input, + DBEAlgorithmSuiteId_ALG__AES__256__GCM__HKDF__SHA512__COMMIT__KEY__SYMSIG__HMAC__SHA384, + ): + return "0x6700" + + elif isinstance( + dafny_input, + DBEAlgorithmSuiteId_ALG__AES__256__GCM__HKDF__SHA512__COMMIT__KEY__ECDSA__P384__SYMSIG__HMAC__SHA384, + ): + return "0x6701" + + else: + raise ValueError(f"No recognized enum value in enum type: {dafny_input=}") + + +def aws_cryptography_materialproviders_HKDF(dafny_input): + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.HKDF( + hmac=aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.dafny_to_smithy.aws_cryptography_primitives_DigestAlgorithm( + dafny_input.hmac + ), + salt_length=dafny_input.saltLength, + input_key_length=dafny_input.inputKeyLength, + output_key_length=dafny_input.outputKeyLength, + ) + + +def aws_cryptography_materialproviders_IDENTITY(dafny_input): + return ( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.IDENTITY() + ) + + +def aws_cryptography_materialproviders_None(dafny_input): + return ( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.None_() + ) + + +def aws_cryptography_materialproviders_ECDSA(dafny_input): + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.ECDSA( + curve=aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.dafny_to_smithy.aws_cryptography_primitives_ECDSASignatureAlgorithm( + dafny_input.curve + ), + ) + + +def aws_cryptography_materialproviders_DIRECT_KEY_WRAPPING(dafny_input): + return ( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.DIRECT_KEY_WRAPPING() + ) + + +def aws_cryptography_materialproviders_IntermediateKeyWrapping(dafny_input): + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.IntermediateKeyWrapping( + key_encryption_key_kdf=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_DerivationAlgorithm( + dafny_input.keyEncryptionKeyKdf + ), + mac_key_kdf=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_DerivationAlgorithm( + dafny_input.macKeyKdf + ), + pdk_encrypt_algorithm=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_Encrypt( + dafny_input.pdkEncryptAlgorithm + ), + ) + + +def aws_cryptography_materialproviders_PutCacheEntryInput(dafny_input): + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.PutCacheEntryInput( + identifier=bytes(dafny_input.identifier), + materials=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_Materials( + dafny_input.materials + ), + creation_time=dafny_input.creationTime, + expiry_time=dafny_input.expiryTime, + messages_used=( + (dafny_input.messagesUsed.value) + if (dafny_input.messagesUsed.is_Some) + else None + ), + bytes_used=( + (dafny_input.bytesUsed.value) if (dafny_input.bytesUsed.is_Some) else None + ), + ) + + +def smithy_api_Unit(): + return ( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.Unit() + ) + + +def aws_cryptography_materialproviders_GetCacheEntryInput(dafny_input): + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.GetCacheEntryInput( + identifier=bytes(dafny_input.identifier), + bytes_used=( + (dafny_input.bytesUsed.value) if (dafny_input.bytesUsed.is_Some) else None + ), + ) + + +def aws_cryptography_materialproviders_GetCacheEntryOutput(dafny_input): + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.GetCacheEntryOutput( + materials=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_Materials( + dafny_input.materials + ), + creation_time=dafny_input.creationTime, + expiry_time=dafny_input.expiryTime, + messages_used=dafny_input.messagesUsed, + bytes_used=dafny_input.bytesUsed, + ) + + +def aws_cryptography_materialproviders_UpdateUsageMetadataInput(dafny_input): + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.UpdateUsageMetadataInput( + identifier=bytes(dafny_input.identifier), + bytes_used=dafny_input.bytesUsed, + ) + + +def aws_cryptography_materialproviders_DeleteCacheEntryInput(dafny_input): + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.DeleteCacheEntryInput( + identifier=bytes(dafny_input.identifier), + ) + + +def aws_cryptography_materialproviders_CommitmentPolicy(dafny_input): + # Convert CommitmentPolicy + if isinstance(dafny_input, CommitmentPolicy_ESDK): + CommitmentPolicy_union_value = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.CommitmentPolicyESDK( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_ESDKCommitmentPolicy( + dafny_input.ESDK + ) + ) + elif isinstance(dafny_input, CommitmentPolicy_DBE): + CommitmentPolicy_union_value = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.CommitmentPolicyDBE( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_DBECommitmentPolicy( + dafny_input.DBE + ) + ) + else: + raise ValueError("No recognized union value in union type: " + str(dafny_input)) + + return CommitmentPolicy_union_value + + +def aws_cryptography_materialproviders_ESDKCommitmentPolicy(dafny_input): + if isinstance(dafny_input, ESDKCommitmentPolicy_FORBID__ENCRYPT__ALLOW__DECRYPT): + return "FORBID_ENCRYPT_ALLOW_DECRYPT" + + elif isinstance(dafny_input, ESDKCommitmentPolicy_REQUIRE__ENCRYPT__ALLOW__DECRYPT): + return "REQUIRE_ENCRYPT_ALLOW_DECRYPT" + + elif isinstance( + dafny_input, ESDKCommitmentPolicy_REQUIRE__ENCRYPT__REQUIRE__DECRYPT + ): + return "REQUIRE_ENCRYPT_REQUIRE_DECRYPT" + + else: + raise ValueError(f"No recognized enum value in enum type: {dafny_input=}") + + +def aws_cryptography_materialproviders_DBECommitmentPolicy(dafny_input): + if isinstance(dafny_input, DBECommitmentPolicy_REQUIRE__ENCRYPT__REQUIRE__DECRYPT): + return "REQUIRE_ENCRYPT_REQUIRE_DECRYPT" + + else: + raise ValueError(f"No recognized enum value in enum type: {dafny_input=}") + + +def aws_cryptography_materialproviders_GetEncryptionMaterialsInput(dafny_input): + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.GetEncryptionMaterialsInput( + encryption_context={ + bytes(key.Elements).decode("utf-8"): bytes(value.Elements).decode("utf-8") + for (key, value) in dafny_input.encryptionContext.items + }, + commitment_policy=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_CommitmentPolicy( + dafny_input.commitmentPolicy + ), + algorithm_suite_id=( + ( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_AlgorithmSuiteId( + dafny_input.algorithmSuiteId.value + ) + ) + if (dafny_input.algorithmSuiteId.is_Some) + else None + ), + max_plaintext_length=( + (dafny_input.maxPlaintextLength.value) + if (dafny_input.maxPlaintextLength.is_Some) + else None + ), + required_encryption_context_keys=( + ( + [ + bytes(list_element.Elements).decode("utf-8") + for list_element in dafny_input.requiredEncryptionContextKeys.value + ] + ) + if (dafny_input.requiredEncryptionContextKeys.is_Some) + else None + ), + ) + + +def aws_cryptography_materialproviders_GetEncryptionMaterialsOutput(dafny_input): + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.GetEncryptionMaterialsOutput( + encryption_materials=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_EncryptionMaterials( + dafny_input.encryptionMaterials + ), + ) + + +def aws_cryptography_materialproviders_DecryptMaterialsInput(dafny_input): + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.DecryptMaterialsInput( + algorithm_suite_id=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_AlgorithmSuiteId( + dafny_input.algorithmSuiteId + ), + commitment_policy=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_CommitmentPolicy( + dafny_input.commitmentPolicy + ), + encrypted_data_keys=[ + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_EncryptedDataKey( + list_element + ) + for list_element in dafny_input.encryptedDataKeys + ], + encryption_context={ + bytes(key.Elements).decode("utf-8"): bytes(value.Elements).decode("utf-8") + for (key, value) in dafny_input.encryptionContext.items + }, + reproduced_encryption_context=( + ( + { + bytes(key.Elements) + .decode("utf-8"): bytes(value.Elements) + .decode("utf-8") + for ( + key, + value, + ) in dafny_input.reproducedEncryptionContext.value.items + } + ) + if (dafny_input.reproducedEncryptionContext.is_Some) + else None + ), + ) + + +def aws_cryptography_materialproviders_DecryptMaterialsOutput(dafny_input): + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.DecryptMaterialsOutput( + decryption_materials=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_DecryptionMaterials( + dafny_input.decryptionMaterials + ), + ) + + +def aws_cryptography_materialproviders_OnEncryptInput(dafny_input): + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.OnEncryptInput( + materials=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_EncryptionMaterials( + dafny_input.materials + ), + ) + + +def aws_cryptography_materialproviders_OnEncryptOutput(dafny_input): + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.OnEncryptOutput( + materials=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_EncryptionMaterials( + dafny_input.materials + ), + ) + + +def aws_cryptography_materialproviders_OnDecryptInput(dafny_input): + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.OnDecryptInput( + materials=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_DecryptionMaterials( + dafny_input.materials + ), + encrypted_data_keys=[ + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_EncryptedDataKey( + list_element + ) + for list_element in dafny_input.encryptedDataKeys + ], + ) + + +def aws_cryptography_materialproviders_OnDecryptOutput(dafny_input): + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.OnDecryptOutput( + materials=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_DecryptionMaterials( + dafny_input.materials + ), + ) + + +def aws_cryptography_materialproviders_CreateAwsKmsKeyringInput(dafny_input): + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.CreateAwsKmsKeyringInput( + kms_key_id=b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.kmsKeyId + ).decode("utf-16-be"), + kms_client=( + ( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_KmsClientReference( + dafny_input.kmsClient + ) + ) + if (dafny_input.kmsClient is not None) + else None + ), + 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 + ), + ) + + +def aws_cryptography_materialproviders_DiscoveryFilter(dafny_input): + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.DiscoveryFilter( + account_ids=[ + b"".join(ord(c).to_bytes(2, "big") for c in list_element).decode( + "utf-16-be" + ) + for list_element in dafny_input.accountIds + ], + partition=b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.partition + ).decode("utf-16-be"), + ) + + +def aws_cryptography_materialproviders_CreateAwsKmsDiscoveryKeyringInput(dafny_input): + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.CreateAwsKmsDiscoveryKeyringInput( + kms_client=( + ( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_KmsClientReference( + dafny_input.kmsClient + ) + ) + if (dafny_input.kmsClient is not None) + else None + ), + discovery_filter=( + ( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_DiscoveryFilter( + dafny_input.discoveryFilter.value + ) + ) + if (dafny_input.discoveryFilter.is_Some) + else None + ), + 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 + ), + ) + + +def aws_cryptography_materialproviders_ClientSupplierReference(dafny_input): + if hasattr(dafny_input, "_native_impl"): + return dafny_input._native_impl + + else: + from aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.references import ( + ClientSupplier, + ) + + return ClientSupplier(_impl=dafny_input) + + +def aws_cryptography_materialproviders_CreateAwsKmsMultiKeyringInput(dafny_input): + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.CreateAwsKmsMultiKeyringInput( + generator=( + ( + b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.generator.value + ).decode("utf-16-be") + ) + if (dafny_input.generator.is_Some) + else None + ), + kms_key_ids=( + ( + [ + b"".join(ord(c).to_bytes(2, "big") for c in list_element).decode( + "utf-16-be" + ) + for list_element in dafny_input.kmsKeyIds.value + ] + ) + if (dafny_input.kmsKeyIds.is_Some) + else None + ), + client_supplier=( + ( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_ClientSupplierReference( + dafny_input.clientSupplier.UnwrapOr(None) + ) + ) + if (dafny_input.clientSupplier.UnwrapOr(None) is not None) + else None + ), + 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 + ), + ) + + +def aws_cryptography_materialproviders_CreateAwsKmsDiscoveryMultiKeyringInput( + dafny_input, +): + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.CreateAwsKmsDiscoveryMultiKeyringInput( + regions=[ + b"".join(ord(c).to_bytes(2, "big") for c in list_element).decode( + "utf-16-be" + ) + for list_element in dafny_input.regions + ], + discovery_filter=( + ( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_DiscoveryFilter( + dafny_input.discoveryFilter.value + ) + ) + if (dafny_input.discoveryFilter.is_Some) + else None + ), + client_supplier=( + ( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_ClientSupplierReference( + dafny_input.clientSupplier.UnwrapOr(None) + ) + ) + if (dafny_input.clientSupplier.UnwrapOr(None) is not None) + else None + ), + 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 + ), + ) + + +def aws_cryptography_materialproviders_CreateAwsKmsMrkKeyringInput(dafny_input): + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.CreateAwsKmsMrkKeyringInput( + kms_key_id=b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.kmsKeyId + ).decode("utf-16-be"), + kms_client=( + ( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_KmsClientReference( + dafny_input.kmsClient + ) + ) + if (dafny_input.kmsClient is not None) + else None + ), + 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 + ), + ) + + +def aws_cryptography_materialproviders_CreateAwsKmsMrkMultiKeyringInput(dafny_input): + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.CreateAwsKmsMrkMultiKeyringInput( + generator=( + ( + b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.generator.value + ).decode("utf-16-be") + ) + if (dafny_input.generator.is_Some) + else None + ), + kms_key_ids=( + ( + [ + b"".join(ord(c).to_bytes(2, "big") for c in list_element).decode( + "utf-16-be" + ) + for list_element in dafny_input.kmsKeyIds.value + ] + ) + if (dafny_input.kmsKeyIds.is_Some) + else None + ), + client_supplier=( + ( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_ClientSupplierReference( + dafny_input.clientSupplier.UnwrapOr(None) + ) + ) + if (dafny_input.clientSupplier.UnwrapOr(None) is not None) + else None + ), + 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 + ), + ) + + +def aws_cryptography_materialproviders_CreateAwsKmsMrkDiscoveryKeyringInput( + dafny_input, +): + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.CreateAwsKmsMrkDiscoveryKeyringInput( + kms_client=( + ( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_KmsClientReference( + dafny_input.kmsClient + ) + ) + if (dafny_input.kmsClient is not None) + else None + ), + discovery_filter=( + ( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_DiscoveryFilter( + dafny_input.discoveryFilter.value + ) + ) + if (dafny_input.discoveryFilter.is_Some) + else None + ), + 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 + ), + region=b"".join(ord(c).to_bytes(2, "big") for c in dafny_input.region).decode( + "utf-16-be" + ), + ) + + +def aws_cryptography_materialproviders_CreateAwsKmsMrkDiscoveryMultiKeyringInput( + dafny_input, +): + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.CreateAwsKmsMrkDiscoveryMultiKeyringInput( + regions=[ + b"".join(ord(c).to_bytes(2, "big") for c in list_element).decode( + "utf-16-be" + ) + for list_element in dafny_input.regions + ], + discovery_filter=( + ( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_DiscoveryFilter( + dafny_input.discoveryFilter.value + ) + ) + if (dafny_input.discoveryFilter.is_Some) + else None + ), + client_supplier=( + ( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_ClientSupplierReference( + dafny_input.clientSupplier.UnwrapOr(None) + ) + ) + if (dafny_input.clientSupplier.UnwrapOr(None) is not None) + else None + ), + 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 + ), + ) + + +def aws_cryptography_materialproviders_BranchKeyIdSupplierReference(dafny_input): + if hasattr(dafny_input, "_native_impl"): + return dafny_input._native_impl + + else: + from aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.references import ( + BranchKeyIdSupplier, + ) + + return BranchKeyIdSupplier(_impl=dafny_input) + + +def aws_cryptography_materialproviders_KeyStoreReference(dafny_input): + from aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_keystore.client import ( + KeyStore, + ) + + return KeyStore(config=None, dafny_client=dafny_input) + + +def aws_cryptography_materialproviders_CacheType(dafny_input): + # Convert CacheType + if isinstance(dafny_input, CacheType_Default): + CacheType_union_value = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.CacheTypeDefault( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_DefaultCache( + dafny_input.Default + ) + ) + elif isinstance(dafny_input, CacheType_No): + CacheType_union_value = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.CacheTypeNo( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_NoCache( + dafny_input.No + ) + ) + elif isinstance(dafny_input, CacheType_SingleThreaded): + CacheType_union_value = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.CacheTypeSingleThreaded( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_SingleThreadedCache( + dafny_input.SingleThreaded + ) + ) + elif isinstance(dafny_input, CacheType_MultiThreaded): + CacheType_union_value = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.CacheTypeMultiThreaded( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_MultiThreadedCache( + dafny_input.MultiThreaded + ) + ) + elif isinstance(dafny_input, CacheType_StormTracking): + CacheType_union_value = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.CacheTypeStormTracking( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_StormTrackingCache( + dafny_input.StormTracking + ) + ) + elif isinstance(dafny_input, CacheType_Shared): + CacheType_union_value = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.CacheTypeShared( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_CryptographicMaterialsCacheReference( + dafny_input.Shared + ) + ) + else: + raise ValueError("No recognized union value in union type: " + str(dafny_input)) + + return CacheType_union_value + + +def aws_cryptography_materialproviders_DefaultCache(dafny_input): + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.DefaultCache( + entry_capacity=dafny_input.entryCapacity, + ) + + +def aws_cryptography_materialproviders_NoCache(dafny_input): + return ( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.NoCache() + ) + + +def aws_cryptography_materialproviders_SingleThreadedCache(dafny_input): + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.SingleThreadedCache( + entry_capacity=dafny_input.entryCapacity, + entry_pruning_tail_size=( + (dafny_input.entryPruningTailSize.value) + if (dafny_input.entryPruningTailSize.is_Some) + else None + ), + ) + + +def aws_cryptography_materialproviders_MultiThreadedCache(dafny_input): + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.MultiThreadedCache( + entry_capacity=dafny_input.entryCapacity, + entry_pruning_tail_size=( + (dafny_input.entryPruningTailSize.value) + if (dafny_input.entryPruningTailSize.is_Some) + else None + ), + ) + + +def aws_cryptography_materialproviders_StormTrackingCache(dafny_input): + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.StormTrackingCache( + entry_capacity=dafny_input.entryCapacity, + entry_pruning_tail_size=( + (dafny_input.entryPruningTailSize.value) + if (dafny_input.entryPruningTailSize.is_Some) + else None + ), + grace_period=dafny_input.gracePeriod, + grace_interval=dafny_input.graceInterval, + fan_out=dafny_input.fanOut, + in_flight_ttl=dafny_input.inFlightTTL, + sleep_milli=dafny_input.sleepMilli, + ) + + +def aws_cryptography_materialproviders_CryptographicMaterialsCacheReference( + dafny_input, +): + if hasattr(dafny_input, "_native_impl"): + return dafny_input._native_impl + + else: + from aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.references import ( + CryptographicMaterialsCache, + ) + + return CryptographicMaterialsCache(_impl=dafny_input) + + +def aws_cryptography_materialproviders_CreateAwsKmsHierarchicalKeyringInput( + dafny_input, +): + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.CreateAwsKmsHierarchicalKeyringInput( + branch_key_id=( + ( + b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.branchKeyId.value + ).decode("utf-16-be") + ) + if (dafny_input.branchKeyId.is_Some) + else None + ), + branch_key_id_supplier=( + ( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_BranchKeyIdSupplierReference( + dafny_input.branchKeyIdSupplier.UnwrapOr(None) + ) + ) + if (dafny_input.branchKeyIdSupplier.UnwrapOr(None) is not None) + else None + ), + key_store=( + ( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_KeyStoreReference( + dafny_input.keyStore + ) + ) + if (dafny_input.keyStore is not None) + else None + ), + ttl_seconds=dafny_input.ttlSeconds, + cache=( + ( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_CacheType( + dafny_input.cache.value + ) + ) + if (dafny_input.cache.is_Some) + else None + ), + partition_id=( + ( + b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.partitionId.value + ).decode("utf-16-be") + ) + if (dafny_input.partitionId.is_Some) + else None + ), + ) + + +def aws_cryptography_materialproviders_CreateAwsKmsRsaKeyringInput(dafny_input): + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.CreateAwsKmsRsaKeyringInput( + public_key=( + (bytes(dafny_input.publicKey.value)) + if (dafny_input.publicKey.is_Some) + else None + ), + kms_key_id=b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.kmsKeyId + ).decode("utf-16-be"), + encryption_algorithm=aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_EncryptionAlgorithmSpec( + dafny_input.encryptionAlgorithm + ), + kms_client=( + ( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_KmsClientReference( + dafny_input.kmsClient.UnwrapOr(None) + ) + ) + if (dafny_input.kmsClient.UnwrapOr(None) is not None) + else None + ), + 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 + ), + ) + + +def aws_cryptography_materialproviders_KmsEcdhStaticConfigurations(dafny_input): + # Convert KmsEcdhStaticConfigurations + if isinstance(dafny_input, KmsEcdhStaticConfigurations_KmsPublicKeyDiscovery): + KmsEcdhStaticConfigurations_union_value = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.KmsEcdhStaticConfigurationsKmsPublicKeyDiscovery( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_KmsPublicKeyDiscoveryInput( + dafny_input.KmsPublicKeyDiscovery + ) + ) + elif isinstance( + dafny_input, KmsEcdhStaticConfigurations_KmsPrivateKeyToStaticPublicKey + ): + KmsEcdhStaticConfigurations_union_value = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.KmsEcdhStaticConfigurationsKmsPrivateKeyToStaticPublicKey( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_KmsPrivateKeyToStaticPublicKeyInput( + dafny_input.KmsPrivateKeyToStaticPublicKey + ) + ) + else: + raise ValueError("No recognized union value in union type: " + str(dafny_input)) + + return KmsEcdhStaticConfigurations_union_value + + +def aws_cryptography_materialproviders_KmsPublicKeyDiscoveryInput(dafny_input): + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.KmsPublicKeyDiscoveryInput( + recipient_kms_identifier=b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.recipientKmsIdentifier + ).decode("utf-16-be"), + ) + + +def aws_cryptography_materialproviders_KmsPrivateKeyToStaticPublicKeyInput(dafny_input): + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.KmsPrivateKeyToStaticPublicKeyInput( + sender_kms_identifier=b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.senderKmsIdentifier + ).decode("utf-16-be"), + sender_public_key=( + (bytes(dafny_input.senderPublicKey.value)) + if (dafny_input.senderPublicKey.is_Some) + else None + ), + recipient_public_key=bytes(dafny_input.recipientPublicKey), + ) + + +def aws_cryptography_materialproviders_CreateAwsKmsEcdhKeyringInput(dafny_input): + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.CreateAwsKmsEcdhKeyringInput( + key_agreement_scheme=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_KmsEcdhStaticConfigurations( + dafny_input.KeyAgreementScheme + ), + curve_spec=aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.dafny_to_smithy.aws_cryptography_primitives_ECDHCurveSpec( + dafny_input.curveSpec + ), + kms_client=( + ( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_KmsClientReference( + dafny_input.kmsClient + ) + ) + if (dafny_input.kmsClient is not None) + else None + ), + 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 + ), + ) + + +def aws_cryptography_materialproviders_KeyringReference(dafny_input): + if hasattr(dafny_input, "_native_impl"): + return dafny_input._native_impl + + else: + from aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.references import ( + Keyring, + ) + + return Keyring(_impl=dafny_input) + + +def aws_cryptography_materialproviders_CreateMultiKeyringInput(dafny_input): + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.CreateMultiKeyringInput( + generator=( + ( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_KeyringReference( + dafny_input.generator.UnwrapOr(None) + ) + ) + if (dafny_input.generator.UnwrapOr(None) is not None) + else None + ), + child_keyrings=[ + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_KeyringReference( + list_element + ) + for list_element in dafny_input.childKeyrings + ], + ) + + +def aws_cryptography_materialproviders_AesWrappingAlg(dafny_input): + if isinstance(dafny_input, AesWrappingAlg_ALG__AES128__GCM__IV12__TAG16): + return "ALG_AES128_GCM_IV12_TAG16" + + elif isinstance(dafny_input, AesWrappingAlg_ALG__AES192__GCM__IV12__TAG16): + return "ALG_AES192_GCM_IV12_TAG16" + + elif isinstance(dafny_input, AesWrappingAlg_ALG__AES256__GCM__IV12__TAG16): + return "ALG_AES256_GCM_IV12_TAG16" + + else: + raise ValueError(f"No recognized enum value in enum type: {dafny_input=}") + + +def aws_cryptography_materialproviders_CreateRawAesKeyringInput(dafny_input): + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.CreateRawAesKeyringInput( + key_namespace=b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.keyNamespace + ).decode("utf-16-be"), + key_name=b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.keyName + ).decode("utf-16-be"), + wrapping_key=bytes(dafny_input.wrappingKey), + wrapping_alg=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_AesWrappingAlg( + dafny_input.wrappingAlg + ), + ) + + +def aws_cryptography_materialproviders_PaddingScheme(dafny_input): + if isinstance(dafny_input, PaddingScheme_PKCS1): + return "PKCS1" + + elif isinstance(dafny_input, PaddingScheme_OAEP__SHA1__MGF1): + return "OAEP_SHA1_MGF1" + + elif isinstance(dafny_input, PaddingScheme_OAEP__SHA256__MGF1): + return "OAEP_SHA256_MGF1" + + elif isinstance(dafny_input, PaddingScheme_OAEP__SHA384__MGF1): + return "OAEP_SHA384_MGF1" + + elif isinstance(dafny_input, PaddingScheme_OAEP__SHA512__MGF1): + return "OAEP_SHA512_MGF1" + + else: + raise ValueError(f"No recognized enum value in enum type: {dafny_input=}") + + +def aws_cryptography_materialproviders_CreateRawRsaKeyringInput(dafny_input): + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.CreateRawRsaKeyringInput( + key_namespace=b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.keyNamespace + ).decode("utf-16-be"), + key_name=b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.keyName + ).decode("utf-16-be"), + padding_scheme=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_PaddingScheme( + dafny_input.paddingScheme + ), + public_key=( + (bytes(dafny_input.publicKey.value)) + if (dafny_input.publicKey.is_Some) + else None + ), + private_key=( + (bytes(dafny_input.privateKey.value)) + if (dafny_input.privateKey.is_Some) + else None + ), + ) + + +def aws_cryptography_materialproviders_RawEcdhStaticConfigurations(dafny_input): + # Convert RawEcdhStaticConfigurations + if isinstance(dafny_input, RawEcdhStaticConfigurations_PublicKeyDiscovery): + RawEcdhStaticConfigurations_union_value = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.RawEcdhStaticConfigurationsPublicKeyDiscovery( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_PublicKeyDiscoveryInput( + dafny_input.PublicKeyDiscovery + ) + ) + elif isinstance( + dafny_input, RawEcdhStaticConfigurations_RawPrivateKeyToStaticPublicKey + ): + RawEcdhStaticConfigurations_union_value = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.RawEcdhStaticConfigurationsRawPrivateKeyToStaticPublicKey( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_RawPrivateKeyToStaticPublicKeyInput( + dafny_input.RawPrivateKeyToStaticPublicKey + ) + ) + elif isinstance( + dafny_input, RawEcdhStaticConfigurations_EphemeralPrivateKeyToStaticPublicKey + ): + RawEcdhStaticConfigurations_union_value = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.RawEcdhStaticConfigurationsEphemeralPrivateKeyToStaticPublicKey( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_EphemeralPrivateKeyToStaticPublicKeyInput( + dafny_input.EphemeralPrivateKeyToStaticPublicKey + ) + ) + else: + raise ValueError("No recognized union value in union type: " + str(dafny_input)) + + return RawEcdhStaticConfigurations_union_value + + +def aws_cryptography_materialproviders_PublicKeyDiscoveryInput(dafny_input): + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.PublicKeyDiscoveryInput( + recipient_static_private_key=bytes(dafny_input.recipientStaticPrivateKey), + ) + + +def aws_cryptography_materialproviders_RawPrivateKeyToStaticPublicKeyInput(dafny_input): + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.RawPrivateKeyToStaticPublicKeyInput( + sender_static_private_key=bytes(dafny_input.senderStaticPrivateKey), + recipient_public_key=bytes(dafny_input.recipientPublicKey), + ) + + +def aws_cryptography_materialproviders_EphemeralPrivateKeyToStaticPublicKeyInput( + dafny_input, +): + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.EphemeralPrivateKeyToStaticPublicKeyInput( + recipient_public_key=bytes(dafny_input.recipientPublicKey), + ) + + +def aws_cryptography_materialproviders_CreateRawEcdhKeyringInput(dafny_input): + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.CreateRawEcdhKeyringInput( + key_agreement_scheme=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_RawEcdhStaticConfigurations( + dafny_input.KeyAgreementScheme + ), + curve_spec=aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.dafny_to_smithy.aws_cryptography_primitives_ECDHCurveSpec( + dafny_input.curveSpec + ), + ) + + +def aws_cryptography_materialproviders_CreateDefaultCryptographicMaterialsManagerInput( + dafny_input, +): + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.CreateDefaultCryptographicMaterialsManagerInput( + keyring=( + ( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_KeyringReference( + dafny_input.keyring + ) + ) + if (dafny_input.keyring is not None) + else None + ), + ) + + +def aws_cryptography_materialproviders_CryptographicMaterialsManagerReference( + dafny_input, +): + if hasattr(dafny_input, "_native_impl"): + return dafny_input._native_impl + + else: + from aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.references import ( + CryptographicMaterialsManager, + ) + + return CryptographicMaterialsManager(_impl=dafny_input) + + +def aws_cryptography_materialproviders_CreateRequiredEncryptionContextCMMInput( + dafny_input, +): + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.CreateRequiredEncryptionContextCMMInput( + underlying_cmm=( + ( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_CryptographicMaterialsManagerReference( + dafny_input.underlyingCMM.UnwrapOr(None) + ) + ) + if (dafny_input.underlyingCMM.UnwrapOr(None) is not None) + else None + ), + keyring=( + ( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_KeyringReference( + dafny_input.keyring.UnwrapOr(None) + ) + ) + if (dafny_input.keyring.UnwrapOr(None) is not None) + else None + ), + required_encryption_context_keys=[ + bytes(list_element.Elements).decode("utf-8") + for list_element in dafny_input.requiredEncryptionContextKeys + ], + ) + + +def aws_cryptography_materialproviders_CreateCryptographicMaterialsCacheInput( + dafny_input, +): + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.CreateCryptographicMaterialsCacheInput( + cache=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_CacheType( + dafny_input.cache + ), + ) + + +def aws_cryptography_materialproviders_CreateDefaultClientSupplierInput(dafny_input): + return ( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.CreateDefaultClientSupplierInput() + ) + + +def aws_cryptography_materialproviders_InitializeEncryptionMaterialsInput(dafny_input): + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.InitializeEncryptionMaterialsInput( + algorithm_suite_id=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_AlgorithmSuiteId( + dafny_input.algorithmSuiteId + ), + encryption_context={ + bytes(key.Elements).decode("utf-8"): bytes(value.Elements).decode("utf-8") + for (key, value) in dafny_input.encryptionContext.items + }, + required_encryption_context_keys=[ + bytes(list_element.Elements).decode("utf-8") + for list_element in dafny_input.requiredEncryptionContextKeys + ], + signing_key=( + (bytes(dafny_input.signingKey.value)) + if (dafny_input.signingKey.is_Some) + else None + ), + verification_key=( + (bytes(dafny_input.verificationKey.value)) + if (dafny_input.verificationKey.is_Some) + else None + ), + ) + + +def aws_cryptography_materialproviders_InitializeDecryptionMaterialsInput(dafny_input): + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.InitializeDecryptionMaterialsInput( + algorithm_suite_id=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_AlgorithmSuiteId( + dafny_input.algorithmSuiteId + ), + encryption_context={ + bytes(key.Elements).decode("utf-8"): bytes(value.Elements).decode("utf-8") + for (key, value) in dafny_input.encryptionContext.items + }, + required_encryption_context_keys=[ + bytes(list_element.Elements).decode("utf-8") + for list_element in dafny_input.requiredEncryptionContextKeys + ], + ) + + +def aws_cryptography_materialproviders_ValidEncryptionMaterialsTransitionInput( + dafny_input, +): + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.ValidEncryptionMaterialsTransitionInput( + start=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_EncryptionMaterials( + dafny_input.start + ), + stop=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_EncryptionMaterials( + dafny_input.stop + ), + ) + + +def aws_cryptography_materialproviders_ValidDecryptionMaterialsTransitionInput( + dafny_input, +): + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.ValidDecryptionMaterialsTransitionInput( + start=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_DecryptionMaterials( + dafny_input.start + ), + stop=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_DecryptionMaterials( + dafny_input.stop + ), + ) + + +def aws_cryptography_materialproviders_GetAlgorithmSuiteInfoInput(dafny_input): + return bytes(dafny_input) + + +def aws_cryptography_materialproviders_ValidateCommitmentPolicyOnEncryptInput( + dafny_input, +): + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.ValidateCommitmentPolicyOnEncryptInput( + algorithm=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_AlgorithmSuiteId( + dafny_input.algorithm + ), + commitment_policy=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_CommitmentPolicy( + dafny_input.commitmentPolicy + ), + ) + + +def aws_cryptography_materialproviders_ValidateCommitmentPolicyOnDecryptInput( + dafny_input, +): + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.ValidateCommitmentPolicyOnDecryptInput( + algorithm=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_AlgorithmSuiteId( + dafny_input.algorithm + ), + commitment_policy=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_CommitmentPolicy( + dafny_input.commitmentPolicy + ), + ) + + +def aws_cryptography_materialproviders_CreateKeyringOutput(dafny_input): + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_KeyringReference( + dafny_input + ) + + +def aws_cryptography_materialproviders_CreateCryptographicMaterialsManagerOutput( + dafny_input, +): + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_CryptographicMaterialsManagerReference( + dafny_input + ) + + +def aws_cryptography_materialproviders_CreateRequiredEncryptionContextCMMOutput( + dafny_input, +): + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_CryptographicMaterialsManagerReference( + dafny_input + ) + + +def aws_cryptography_materialproviders_CreateCryptographicMaterialsCacheOutput( + dafny_input, +): + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_CryptographicMaterialsCacheReference( + dafny_input + ) + + +def aws_cryptography_materialproviders_CreateDefaultClientSupplierOutput(dafny_input): + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_ClientSupplierReference( + dafny_input + ) + + +def aws_cryptography_materialproviders_MaterialProvidersConfig(dafny_input): + # Deferred import of .config to avoid circular dependency + import aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.config + + return ( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.config.MaterialProvidersConfig() + ) diff --git a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/smithygenerated/aws_cryptography_materialproviders/deserialize.py b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/smithygenerated/aws_cryptography_materialproviders/deserialize.py new file mode 100644 index 000000000..f525335db --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/smithygenerated/aws_cryptography_materialproviders/deserialize.py @@ -0,0 +1,375 @@ +# 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_materialproviders.internaldafny.generated.AwsCryptographyMaterialProvidersTypes import ( + DecryptionMaterials_DecryptionMaterials as DafnyDecryptionMaterials, + EncryptionMaterials_EncryptionMaterials as DafnyEncryptionMaterials, + Error, + Error_AwsCryptographicMaterialProvidersException, + Error_EntryAlreadyExists, + Error_EntryDoesNotExist, + Error_InvalidAlgorithmSuiteInfo, + Error_InvalidAlgorithmSuiteInfoOnDecrypt, + Error_InvalidAlgorithmSuiteInfoOnEncrypt, + Error_InvalidDecryptionMaterials, + Error_InvalidDecryptionMaterialsTransition, + Error_InvalidEncryptionMaterials, + Error_InvalidEncryptionMaterialsTransition, +) +import aws_cryptographic_materialproviders.internaldafny.generated.module_ +import aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy +from typing import Any + +from .dafny_protocol import DafnyResponse +from .errors import ( + AwsCryptographicMaterialProvidersException, + AwsCryptographicPrimitives, + CollectionOfErrors, + ComAmazonawsDynamodb, + ComAmazonawsKms, + EntryAlreadyExists, + EntryDoesNotExist, + InvalidAlgorithmSuiteInfo, + InvalidAlgorithmSuiteInfoOnDecrypt, + InvalidAlgorithmSuiteInfoOnEncrypt, + InvalidDecryptionMaterials, + InvalidDecryptionMaterialsTransition, + InvalidEncryptionMaterials, + InvalidEncryptionMaterialsTransition, + KeyStore, + OpaqueError, + ServiceError, +) +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_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, +) +from .config import Config + + +def _deserialize_create_aws_kms_keyring(input: DafnyResponse, config: Config): + + if input.IsFailure(): + return _deserialize_error(input.error) + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_CreateKeyringOutput( + input.value + ) + + +def _deserialize_create_aws_kms_discovery_keyring(input: DafnyResponse, config: Config): + + if input.IsFailure(): + return _deserialize_error(input.error) + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_CreateKeyringOutput( + input.value + ) + + +def _deserialize_create_aws_kms_multi_keyring(input: DafnyResponse, config: Config): + + if input.IsFailure(): + return _deserialize_error(input.error) + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_CreateKeyringOutput( + input.value + ) + + +def _deserialize_create_aws_kms_discovery_multi_keyring( + input: DafnyResponse, config: Config +): + + if input.IsFailure(): + return _deserialize_error(input.error) + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_CreateKeyringOutput( + input.value + ) + + +def _deserialize_create_aws_kms_mrk_keyring(input: DafnyResponse, config: Config): + + if input.IsFailure(): + return _deserialize_error(input.error) + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_CreateKeyringOutput( + input.value + ) + + +def _deserialize_create_aws_kms_mrk_multi_keyring(input: DafnyResponse, config: Config): + + if input.IsFailure(): + return _deserialize_error(input.error) + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_CreateKeyringOutput( + input.value + ) + + +def _deserialize_create_aws_kms_mrk_discovery_keyring( + input: DafnyResponse, config: Config +): + + if input.IsFailure(): + return _deserialize_error(input.error) + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_CreateKeyringOutput( + input.value + ) + + +def _deserialize_create_aws_kms_mrk_discovery_multi_keyring( + input: DafnyResponse, config: Config +): + + if input.IsFailure(): + return _deserialize_error(input.error) + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_CreateKeyringOutput( + input.value + ) + + +def _deserialize_create_aws_kms_hierarchical_keyring( + input: DafnyResponse, config: Config +): + + if input.IsFailure(): + return _deserialize_error(input.error) + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_CreateKeyringOutput( + input.value + ) + + +def _deserialize_create_aws_kms_rsa_keyring(input: DafnyResponse, config: Config): + + if input.IsFailure(): + return _deserialize_error(input.error) + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_CreateKeyringOutput( + input.value + ) + + +def _deserialize_create_aws_kms_ecdh_keyring(input: DafnyResponse, config: Config): + + if input.IsFailure(): + return _deserialize_error(input.error) + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_CreateKeyringOutput( + input.value + ) + + +def _deserialize_create_multi_keyring(input: DafnyResponse, config: Config): + + if input.IsFailure(): + return _deserialize_error(input.error) + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_CreateKeyringOutput( + input.value + ) + + +def _deserialize_create_raw_aes_keyring(input: DafnyResponse, config: Config): + + if input.IsFailure(): + return _deserialize_error(input.error) + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_CreateKeyringOutput( + input.value + ) + + +def _deserialize_create_raw_rsa_keyring(input: DafnyResponse, config: Config): + + if input.IsFailure(): + return _deserialize_error(input.error) + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_CreateKeyringOutput( + input.value + ) + + +def _deserialize_create_raw_ecdh_keyring(input: DafnyResponse, config: Config): + + if input.IsFailure(): + return _deserialize_error(input.error) + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_CreateKeyringOutput( + input.value + ) + + +def _deserialize_create_default_cryptographic_materials_manager( + input: DafnyResponse, config: Config +): + + if input.IsFailure(): + return _deserialize_error(input.error) + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_CreateCryptographicMaterialsManagerOutput( + input.value + ) + + +def _deserialize_create_required_encryption_context_cmm( + input: DafnyResponse, config: Config +): + + if input.IsFailure(): + return _deserialize_error(input.error) + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_CreateRequiredEncryptionContextCMMOutput( + input.value + ) + + +def _deserialize_create_cryptographic_materials_cache( + input: DafnyResponse, config: Config +): + + if input.IsFailure(): + return _deserialize_error(input.error) + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_CreateCryptographicMaterialsCacheOutput( + input.value + ) + + +def _deserialize_create_default_client_supplier(input: DafnyResponse, config: Config): + + if input.IsFailure(): + return _deserialize_error(input.error) + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_CreateDefaultClientSupplierOutput( + input.value + ) + + +def _deserialize_initialize_encryption_materials(input: DafnyResponse, config: Config): + + if input.IsFailure(): + return _deserialize_error(input.error) + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_EncryptionMaterials( + input.value + ) + + +def _deserialize_initialize_decryption_materials(input: DafnyResponse, config: Config): + + if input.IsFailure(): + return _deserialize_error(input.error) + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_DecryptionMaterials( + input.value + ) + + +def _deserialize_valid_encryption_materials_transition( + input: DafnyResponse, config: Config +): + + return None + + +def _deserialize_valid_decryption_materials_transition( + input: DafnyResponse, config: Config +): + + return None + + +def _deserialize_encryption_materials_has_plaintext_data_key( + input: DafnyResponse, config: Config +): + + return None + + +def _deserialize_decryption_materials_with_plaintext_data_key( + input: DafnyResponse, config: Config +): + + return None + + +def _deserialize_get_algorithm_suite_info(input: DafnyResponse, config: Config): + + if input.IsFailure(): + return _deserialize_error(input.error) + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_AlgorithmSuiteInfo( + input.value + ) + + +def _deserialize_valid_algorithm_suite_info(input: DafnyResponse, config: Config): + + return None + + +def _deserialize_validate_commitment_policy_on_encrypt( + input: DafnyResponse, config: Config +): + + return None + + +def _deserialize_validate_commitment_policy_on_decrypt( + input: DafnyResponse, config: Config +): + + return None + + +def _deserialize_error(error: Error) -> ServiceError: + if error.is_Opaque: + return OpaqueError(obj=error.obj) + 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_AwsCryptographicMaterialProvidersException: + return AwsCryptographicMaterialProvidersException( + message=_dafny.string_of(error.message) + ) + elif error.is_EntryAlreadyExists: + return EntryAlreadyExists(message=_dafny.string_of(error.message)) + elif error.is_EntryDoesNotExist: + return EntryDoesNotExist(message=_dafny.string_of(error.message)) + elif error.is_InvalidAlgorithmSuiteInfo: + return InvalidAlgorithmSuiteInfo(message=_dafny.string_of(error.message)) + elif error.is_InvalidAlgorithmSuiteInfoOnDecrypt: + return InvalidAlgorithmSuiteInfoOnDecrypt( + message=_dafny.string_of(error.message) + ) + elif error.is_InvalidAlgorithmSuiteInfoOnEncrypt: + return InvalidAlgorithmSuiteInfoOnEncrypt( + message=_dafny.string_of(error.message) + ) + elif error.is_InvalidDecryptionMaterials: + return InvalidDecryptionMaterials(message=_dafny.string_of(error.message)) + elif error.is_InvalidDecryptionMaterialsTransition: + return InvalidDecryptionMaterialsTransition( + message=_dafny.string_of(error.message) + ) + elif error.is_InvalidEncryptionMaterials: + return InvalidEncryptionMaterials(message=_dafny.string_of(error.message)) + elif error.is_InvalidEncryptionMaterialsTransition: + return InvalidEncryptionMaterialsTransition( + 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) + ) + 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_materialproviders/smithygenerated/aws_cryptography_materialproviders/errors.py b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/smithygenerated/aws_cryptography_materialproviders/errors.py new file mode 100644 index 000000000..1edcd6387 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/smithygenerated/aws_cryptography_materialproviders/errors.py @@ -0,0 +1,731 @@ +# 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_materialproviders.internaldafny.generated +import aws_cryptographic_materialproviders.internaldafny.generated.AwsCryptographyMaterialProvidersTypes +from aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_keystore.errors import ( + _smithy_error_to_dafny_error as aws_cryptography_keystore_smithy_error_to_dafny_error, +) +import aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.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 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 + + +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 AwsCryptographicMaterialProvidersException( + ApiError[Literal["AwsCryptographicMaterialProvidersException"]] +): + code: Literal["AwsCryptographicMaterialProvidersException"] = ( + "AwsCryptographicMaterialProvidersException" + ) + message: str + + def __init__( + self, + *, + message: str, + ): + super().__init__(message) + + def as_dict(self) -> Dict[str, Any]: + """Converts the AwsCryptographicMaterialProvidersException to a + dictionary.""" + return { + "message": self.message, + "code": self.code, + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "AwsCryptographicMaterialProvidersException": + """Creates a AwsCryptographicMaterialProvidersException from a + dictionary.""" + kwargs: Dict[str, Any] = { + "message": d["message"], + } + + return AwsCryptographicMaterialProvidersException(**kwargs) + + def __repr__(self) -> str: + result = "AwsCryptographicMaterialProvidersException(" + if self.message is not None: + result += f"message={repr(self.message)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, AwsCryptographicMaterialProvidersException): + return False + attributes: list[str] = [ + "message", + "message", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class InvalidDecryptionMaterials(ApiError[Literal["InvalidDecryptionMaterials"]]): + code: Literal["InvalidDecryptionMaterials"] = "InvalidDecryptionMaterials" + message: str + + def __init__( + self, + *, + message: str, + ): + super().__init__(message) + + def as_dict(self) -> Dict[str, Any]: + """Converts the InvalidDecryptionMaterials to a dictionary.""" + return { + "message": self.message, + "code": self.code, + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "InvalidDecryptionMaterials": + """Creates a InvalidDecryptionMaterials from a dictionary.""" + kwargs: Dict[str, Any] = { + "message": d["message"], + } + + return InvalidDecryptionMaterials(**kwargs) + + def __repr__(self) -> str: + result = "InvalidDecryptionMaterials(" + if self.message is not None: + result += f"message={repr(self.message)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, InvalidDecryptionMaterials): + return False + attributes: list[str] = [ + "message", + "message", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class InvalidEncryptionMaterials(ApiError[Literal["InvalidEncryptionMaterials"]]): + code: Literal["InvalidEncryptionMaterials"] = "InvalidEncryptionMaterials" + message: str + + def __init__( + self, + *, + message: str, + ): + super().__init__(message) + + def as_dict(self) -> Dict[str, Any]: + """Converts the InvalidEncryptionMaterials to a dictionary.""" + return { + "message": self.message, + "code": self.code, + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "InvalidEncryptionMaterials": + """Creates a InvalidEncryptionMaterials from a dictionary.""" + kwargs: Dict[str, Any] = { + "message": d["message"], + } + + return InvalidEncryptionMaterials(**kwargs) + + def __repr__(self) -> str: + result = "InvalidEncryptionMaterials(" + if self.message is not None: + result += f"message={repr(self.message)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, InvalidEncryptionMaterials): + return False + attributes: list[str] = [ + "message", + "message", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class InvalidAlgorithmSuiteInfo(ApiError[Literal["InvalidAlgorithmSuiteInfo"]]): + code: Literal["InvalidAlgorithmSuiteInfo"] = "InvalidAlgorithmSuiteInfo" + message: str + + def __init__( + self, + *, + message: str, + ): + super().__init__(message) + + def as_dict(self) -> Dict[str, Any]: + """Converts the InvalidAlgorithmSuiteInfo to a dictionary.""" + return { + "message": self.message, + "code": self.code, + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "InvalidAlgorithmSuiteInfo": + """Creates a InvalidAlgorithmSuiteInfo from a dictionary.""" + kwargs: Dict[str, Any] = { + "message": d["message"], + } + + return InvalidAlgorithmSuiteInfo(**kwargs) + + def __repr__(self) -> str: + result = "InvalidAlgorithmSuiteInfo(" + if self.message is not None: + result += f"message={repr(self.message)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, InvalidAlgorithmSuiteInfo): + return False + attributes: list[str] = [ + "message", + "message", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class InvalidAlgorithmSuiteInfoOnDecrypt( + ApiError[Literal["InvalidAlgorithmSuiteInfoOnDecrypt"]] +): + code: Literal["InvalidAlgorithmSuiteInfoOnDecrypt"] = ( + "InvalidAlgorithmSuiteInfoOnDecrypt" + ) + message: str + + def __init__( + self, + *, + message: str, + ): + super().__init__(message) + + def as_dict(self) -> Dict[str, Any]: + """Converts the InvalidAlgorithmSuiteInfoOnDecrypt to a dictionary.""" + return { + "message": self.message, + "code": self.code, + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "InvalidAlgorithmSuiteInfoOnDecrypt": + """Creates a InvalidAlgorithmSuiteInfoOnDecrypt from a dictionary.""" + kwargs: Dict[str, Any] = { + "message": d["message"], + } + + return InvalidAlgorithmSuiteInfoOnDecrypt(**kwargs) + + def __repr__(self) -> str: + result = "InvalidAlgorithmSuiteInfoOnDecrypt(" + if self.message is not None: + result += f"message={repr(self.message)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, InvalidAlgorithmSuiteInfoOnDecrypt): + return False + attributes: list[str] = [ + "message", + "message", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class InvalidAlgorithmSuiteInfoOnEncrypt( + ApiError[Literal["InvalidAlgorithmSuiteInfoOnEncrypt"]] +): + code: Literal["InvalidAlgorithmSuiteInfoOnEncrypt"] = ( + "InvalidAlgorithmSuiteInfoOnEncrypt" + ) + message: str + + def __init__( + self, + *, + message: str, + ): + super().__init__(message) + + def as_dict(self) -> Dict[str, Any]: + """Converts the InvalidAlgorithmSuiteInfoOnEncrypt to a dictionary.""" + return { + "message": self.message, + "code": self.code, + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "InvalidAlgorithmSuiteInfoOnEncrypt": + """Creates a InvalidAlgorithmSuiteInfoOnEncrypt from a dictionary.""" + kwargs: Dict[str, Any] = { + "message": d["message"], + } + + return InvalidAlgorithmSuiteInfoOnEncrypt(**kwargs) + + def __repr__(self) -> str: + result = "InvalidAlgorithmSuiteInfoOnEncrypt(" + if self.message is not None: + result += f"message={repr(self.message)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, InvalidAlgorithmSuiteInfoOnEncrypt): + return False + attributes: list[str] = [ + "message", + "message", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class InvalidDecryptionMaterialsTransition( + ApiError[Literal["InvalidDecryptionMaterialsTransition"]] +): + code: Literal["InvalidDecryptionMaterialsTransition"] = ( + "InvalidDecryptionMaterialsTransition" + ) + message: str + + def __init__( + self, + *, + message: str, + ): + super().__init__(message) + + def as_dict(self) -> Dict[str, Any]: + """Converts the InvalidDecryptionMaterialsTransition to a + dictionary.""" + return { + "message": self.message, + "code": self.code, + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "InvalidDecryptionMaterialsTransition": + """Creates a InvalidDecryptionMaterialsTransition from a dictionary.""" + kwargs: Dict[str, Any] = { + "message": d["message"], + } + + return InvalidDecryptionMaterialsTransition(**kwargs) + + def __repr__(self) -> str: + result = "InvalidDecryptionMaterialsTransition(" + if self.message is not None: + result += f"message={repr(self.message)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, InvalidDecryptionMaterialsTransition): + return False + attributes: list[str] = [ + "message", + "message", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class InvalidEncryptionMaterialsTransition( + ApiError[Literal["InvalidEncryptionMaterialsTransition"]] +): + code: Literal["InvalidEncryptionMaterialsTransition"] = ( + "InvalidEncryptionMaterialsTransition" + ) + message: str + + def __init__( + self, + *, + message: str, + ): + super().__init__(message) + + def as_dict(self) -> Dict[str, Any]: + """Converts the InvalidEncryptionMaterialsTransition to a + dictionary.""" + return { + "message": self.message, + "code": self.code, + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "InvalidEncryptionMaterialsTransition": + """Creates a InvalidEncryptionMaterialsTransition from a dictionary.""" + kwargs: Dict[str, Any] = { + "message": d["message"], + } + + return InvalidEncryptionMaterialsTransition(**kwargs) + + def __repr__(self) -> str: + result = "InvalidEncryptionMaterialsTransition(" + if self.message is not None: + result += f"message={repr(self.message)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, InvalidEncryptionMaterialsTransition): + return False + attributes: list[str] = [ + "message", + "message", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class AwsCryptographicMaterialProvidersException( + ApiError[Literal["AwsCryptographicMaterialProvidersException"]] +): + code: Literal["AwsCryptographicMaterialProvidersException"] = ( + "AwsCryptographicMaterialProvidersException" + ) + message: str + + +class EntryAlreadyExists(ApiError[Literal["EntryAlreadyExists"]]): + code: Literal["EntryAlreadyExists"] = "EntryAlreadyExists" + message: str + + +class EntryDoesNotExist(ApiError[Literal["EntryDoesNotExist"]]): + code: Literal["EntryDoesNotExist"] = "EntryDoesNotExist" + message: str + + +class InvalidAlgorithmSuiteInfo(ApiError[Literal["InvalidAlgorithmSuiteInfo"]]): + code: Literal["InvalidAlgorithmSuiteInfo"] = "InvalidAlgorithmSuiteInfo" + message: str + + +class InvalidAlgorithmSuiteInfoOnDecrypt( + ApiError[Literal["InvalidAlgorithmSuiteInfoOnDecrypt"]] +): + code: Literal["InvalidAlgorithmSuiteInfoOnDecrypt"] = ( + "InvalidAlgorithmSuiteInfoOnDecrypt" + ) + message: str + + +class InvalidAlgorithmSuiteInfoOnEncrypt( + ApiError[Literal["InvalidAlgorithmSuiteInfoOnEncrypt"]] +): + code: Literal["InvalidAlgorithmSuiteInfoOnEncrypt"] = ( + "InvalidAlgorithmSuiteInfoOnEncrypt" + ) + message: str + + +class InvalidDecryptionMaterials(ApiError[Literal["InvalidDecryptionMaterials"]]): + code: Literal["InvalidDecryptionMaterials"] = "InvalidDecryptionMaterials" + message: str + + +class InvalidDecryptionMaterialsTransition( + ApiError[Literal["InvalidDecryptionMaterialsTransition"]] +): + code: Literal["InvalidDecryptionMaterialsTransition"] = ( + "InvalidDecryptionMaterialsTransition" + ) + message: str + + +class InvalidEncryptionMaterials(ApiError[Literal["InvalidEncryptionMaterials"]]): + code: Literal["InvalidEncryptionMaterials"] = "InvalidEncryptionMaterials" + message: str + + +class InvalidEncryptionMaterialsTransition( + ApiError[Literal["InvalidEncryptionMaterialsTransition"]] +): + code: Literal["InvalidEncryptionMaterialsTransition"] = ( + "InvalidEncryptionMaterialsTransition" + ) + message: str + + +class AwsCryptographicPrimitives(ApiError[Literal["AwsCryptographicPrimitives"]]): + AwsCryptographicPrimitives: Any + + +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) + + +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_materialproviders.smithygenerated.aws_cryptography_materialproviders.errors.AwsCryptographicMaterialProvidersException, + ): + return aws_cryptographic_materialproviders.internaldafny.generated.AwsCryptographyMaterialProvidersTypes.Error_AwsCryptographicMaterialProvidersException( + message=_dafny.Seq(e.message) + ) + + if isinstance( + e, + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.errors.EntryAlreadyExists, + ): + return aws_cryptographic_materialproviders.internaldafny.generated.AwsCryptographyMaterialProvidersTypes.Error_EntryAlreadyExists( + message=_dafny.Seq(e.message) + ) + + if isinstance( + e, + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.errors.EntryDoesNotExist, + ): + return aws_cryptographic_materialproviders.internaldafny.generated.AwsCryptographyMaterialProvidersTypes.Error_EntryDoesNotExist( + message=_dafny.Seq(e.message) + ) + + if isinstance( + e, + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.errors.InvalidAlgorithmSuiteInfo, + ): + return aws_cryptographic_materialproviders.internaldafny.generated.AwsCryptographyMaterialProvidersTypes.Error_InvalidAlgorithmSuiteInfo( + message=_dafny.Seq(e.message) + ) + + if isinstance( + e, + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.errors.InvalidAlgorithmSuiteInfoOnDecrypt, + ): + return aws_cryptographic_materialproviders.internaldafny.generated.AwsCryptographyMaterialProvidersTypes.Error_InvalidAlgorithmSuiteInfoOnDecrypt( + message=_dafny.Seq(e.message) + ) + + if isinstance( + e, + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.errors.InvalidAlgorithmSuiteInfoOnEncrypt, + ): + return aws_cryptographic_materialproviders.internaldafny.generated.AwsCryptographyMaterialProvidersTypes.Error_InvalidAlgorithmSuiteInfoOnEncrypt( + message=_dafny.Seq(e.message) + ) + + if isinstance( + e, + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.errors.InvalidDecryptionMaterials, + ): + return aws_cryptographic_materialproviders.internaldafny.generated.AwsCryptographyMaterialProvidersTypes.Error_InvalidDecryptionMaterials( + message=_dafny.Seq(e.message) + ) + + if isinstance( + e, + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.errors.InvalidDecryptionMaterialsTransition, + ): + return aws_cryptographic_materialproviders.internaldafny.generated.AwsCryptographyMaterialProvidersTypes.Error_InvalidDecryptionMaterialsTransition( + message=_dafny.Seq(e.message) + ) + + if isinstance( + e, + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.errors.InvalidEncryptionMaterials, + ): + return aws_cryptographic_materialproviders.internaldafny.generated.AwsCryptographyMaterialProvidersTypes.Error_InvalidEncryptionMaterials( + message=_dafny.Seq(e.message) + ) + + if isinstance( + e, + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.errors.InvalidEncryptionMaterialsTransition, + ): + return aws_cryptographic_materialproviders.internaldafny.generated.AwsCryptographyMaterialProvidersTypes.Error_InvalidEncryptionMaterialsTransition( + message=_dafny.Seq(e.message) + ) + + if isinstance(e, AwsCryptographicPrimitives): + return aws_cryptographic_materialproviders.internaldafny.generated.AwsCryptographyMaterialProvidersTypes.Error_AwsCryptographyPrimitives( + aws_cryptography_primitives_smithy_error_to_dafny_error(e.message) + ) + + if isinstance(e, ComAmazonawsDynamodb): + return aws_cryptographic_materialproviders.internaldafny.generated.AwsCryptographyMaterialProvidersTypes.Error_ComAmazonawsDynamodb( + com_amazonaws_dynamodb_sdk_error_to_dafny_error(e.message) + ) + + if isinstance(e, ComAmazonawsKms): + return aws_cryptographic_materialproviders.internaldafny.generated.AwsCryptographyMaterialProvidersTypes.Error_ComAmazonawsKms( + com_amazonaws_kms_sdk_error_to_dafny_error(e.message) + ) + + if isinstance(e, KeyStore): + return aws_cryptographic_materialproviders.internaldafny.generated.AwsCryptographyMaterialProvidersTypes.Error_AwsCryptographyKeyStore( + aws_cryptography_keystore_smithy_error_to_dafny_error(e.message) + ) + + if isinstance(e, CollectionOfErrors): + return aws_cryptographic_materialproviders.internaldafny.generated.AwsCryptographyMaterialProvidersTypes.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_materialproviders.internaldafny.generated.AwsCryptographyMaterialProvidersTypes.Error_Opaque( + obj=e.obj + ) + + else: + return aws_cryptographic_materialproviders.internaldafny.generated.AwsCryptographyMaterialProvidersTypes.Error_Opaque( + obj=e + ) diff --git a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/smithygenerated/aws_cryptography_materialproviders/models.py b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/smithygenerated/aws_cryptography_materialproviders/models.py new file mode 100644 index 000000000..e760525a5 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/smithygenerated/aws_cryptography_materialproviders/models.py @@ -0,0 +1,5743 @@ +# 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_materialproviders.smithygenerated.aws_cryptography_keystore.client +import aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.references +import botocore.client +from typing import Any, Dict, List, Optional, Union + +from aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.models import ( + AES_GCM, +) + +from ..aws_cryptography_keystore.models import BeaconKeyMaterials, BranchKeyMaterials + + +class AesWrappingAlg: + ALG_AES128_GCM_IV12_TAG16 = "ALG_AES128_GCM_IV12_TAG16" + + ALG_AES192_GCM_IV12_TAG16 = "ALG_AES192_GCM_IV12_TAG16" + + ALG_AES256_GCM_IV12_TAG16 = "ALG_AES256_GCM_IV12_TAG16" + + # This set contains every possible value known at the time this was generated. New + # values may be added in the future. + values = frozenset( + { + "ALG_AES128_GCM_IV12_TAG16", + "ALG_AES192_GCM_IV12_TAG16", + "ALG_AES256_GCM_IV12_TAG16", + } + ) + + +class DBEAlgorithmSuiteId: + ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY_SYMSIG_HMAC_SHA384 = "0x6700" + + ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY_ECDSA_P384_SYMSIG_HMAC_SHA384 = "0x6701" + + # This set contains every possible value known at the time this was generated. New + # values may be added in the future. + values = frozenset({"0x6700", "0x6701"}) + + +class ESDKAlgorithmSuiteId: + ALG_AES_128_GCM_IV12_TAG16_NO_KDF = "0x0014" + + ALG_AES_192_GCM_IV12_TAG16_NO_KDF = "0x0046" + + ALG_AES_256_GCM_IV12_TAG16_NO_KDF = "0x0078" + + ALG_AES_128_GCM_IV12_TAG16_HKDF_SHA256 = "0x0114" + + ALG_AES_192_GCM_IV12_TAG16_HKDF_SHA256 = "0x0146" + + ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256 = "0x0178" + + ALG_AES_128_GCM_IV12_TAG16_HKDF_SHA256_ECDSA_P256 = "0x0214" + + ALG_AES_192_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384 = "0x0346" + + ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384 = "0x0378" + + ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY = "0x0478" + + ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY_ECDSA_P384 = "0x0578" + + # This set contains every possible value known at the time this was generated. New + # values may be added in the future. + values = frozenset( + { + "0x0014", + "0x0046", + "0x0078", + "0x0114", + "0x0146", + "0x0178", + "0x0214", + "0x0346", + "0x0378", + "0x0478", + "0x0578", + } + ) + + +class AlgorithmSuiteIdESDK: + def __init__(self, value: str): + self.value = value + + def as_dict(self) -> Dict[str, Any]: + return {"ESDK": self.value} + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "AlgorithmSuiteIdESDK": + if len(d) != 1: + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + + return AlgorithmSuiteIdESDK(d["ESDK"]) + + def __repr__(self) -> str: + return f"AlgorithmSuiteIdESDK(value=repr(self.value))" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, AlgorithmSuiteIdESDK): + return False + return self.value == other.value + + +class AlgorithmSuiteIdDBE: + def __init__(self, value: str): + self.value = value + + def as_dict(self) -> Dict[str, Any]: + return {"DBE": self.value} + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "AlgorithmSuiteIdDBE": + if len(d) != 1: + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + + return AlgorithmSuiteIdDBE(d["DBE"]) + + def __repr__(self) -> str: + return f"AlgorithmSuiteIdDBE(value=repr(self.value))" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, AlgorithmSuiteIdDBE): + return False + return self.value == other.value + + +class AlgorithmSuiteIdUnknown: + """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]) -> "AlgorithmSuiteIdUnknown": + if len(d) != 1: + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + return AlgorithmSuiteIdUnknown(d["SDK_UNKNOWN_MEMBER"]["name"]) + + def __repr__(self) -> str: + return f"AlgorithmSuiteIdUnknown(tag={self.tag})" + + +AlgorithmSuiteId = Union[ + AlgorithmSuiteIdESDK, AlgorithmSuiteIdDBE, AlgorithmSuiteIdUnknown +] + + +def _algorithm_suite_id_from_dict(d: Dict[str, Any]) -> AlgorithmSuiteId: + if "ESDK" in d: + return AlgorithmSuiteIdESDK.from_dict(d) + + if "DBE" in d: + return AlgorithmSuiteIdDBE.from_dict(d) + + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + + +class HKDF: + hmac: str + salt_length: int + input_key_length: int + output_key_length: int + + def __init__( + self, + *, + hmac: str, + salt_length: int = 0, + input_key_length: int = 0, + output_key_length: int = 0, + ): + self.hmac = hmac + if (salt_length is not None) and (salt_length < 0): + raise ValueError("salt_length must be greater than or equal to 0") + + self.salt_length = salt_length + if (input_key_length is not None) and (input_key_length < 1): + raise ValueError("input_key_length must be greater than or equal to 1") + + if (input_key_length is not None) and (input_key_length > 32): + raise ValueError("input_key_length must be less than or equal to 32") + + self.input_key_length = input_key_length + if (output_key_length is not None) and (output_key_length < 1): + raise ValueError("output_key_length must be greater than or equal to 1") + + if (output_key_length is not None) and (output_key_length > 32): + raise ValueError("output_key_length must be less than or equal to 32") + + self.output_key_length = output_key_length + + def as_dict(self) -> Dict[str, Any]: + """Converts the HKDF to a dictionary.""" + d: Dict[str, Any] = { + "hmac": self.hmac, + } + + if self.salt_length is not None: + d["salt_length"] = self.salt_length + + if self.input_key_length is not None: + d["input_key_length"] = self.input_key_length + + if self.output_key_length is not None: + d["output_key_length"] = self.output_key_length + + return d + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "HKDF": + """Creates a HKDF from a dictionary.""" + kwargs: Dict[str, Any] = { + "hmac": d["hmac"], + } + + if "salt_length" in d: + kwargs["salt_length"] = d["salt_length"] + + if "input_key_length" in d: + kwargs["input_key_length"] = d["input_key_length"] + + if "output_key_length" in d: + kwargs["output_key_length"] = d["output_key_length"] + + return HKDF(**kwargs) + + def __repr__(self) -> str: + result = "HKDF(" + if self.hmac is not None: + result += f"hmac={repr(self.hmac)}, " + + if self.salt_length is not None: + result += f"salt_length={repr(self.salt_length)}, " + + if self.input_key_length is not None: + result += f"input_key_length={repr(self.input_key_length)}, " + + if self.output_key_length is not None: + result += f"output_key_length={repr(self.output_key_length)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, HKDF): + return False + attributes: list[str] = [ + "hmac", + "salt_length", + "input_key_length", + "output_key_length", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class IDENTITY: + def as_dict(self) -> Dict[str, Any]: + """Converts the IDENTITY to a dictionary.""" + return {} + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "IDENTITY": + """Creates a IDENTITY from a dictionary.""" + return IDENTITY() + + def __repr__(self) -> str: + result = "IDENTITY(" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + return isinstance(other, IDENTITY) + + +class None_: + def as_dict(self) -> Dict[str, Any]: + """Converts the None_ to a dictionary.""" + return {} + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "None_": + """Creates a None_ from a dictionary.""" + return None_() + + def __repr__(self) -> str: + result = "None_(" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + return isinstance(other, None_) + + +class DerivationAlgorithmHKDF: + def __init__(self, value: HKDF): + self.value = value + + def as_dict(self) -> Dict[str, Any]: + return {"HKDF": self.value.as_dict()} + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "DerivationAlgorithmHKDF": + if len(d) != 1: + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + + return DerivationAlgorithmHKDF(HKDF.from_dict(d["HKDF"])) + + def __repr__(self) -> str: + return f"DerivationAlgorithmHKDF(value=repr(self.value))" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, DerivationAlgorithmHKDF): + return False + return self.value == other.value + + +class DerivationAlgorithmIDENTITY: + def __init__(self, value: IDENTITY): + self.value = value + + def as_dict(self) -> Dict[str, Any]: + return {"IDENTITY": self.value.as_dict()} + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "DerivationAlgorithmIDENTITY": + if len(d) != 1: + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + + return DerivationAlgorithmIDENTITY(IDENTITY.from_dict(d["IDENTITY"])) + + def __repr__(self) -> str: + return f"DerivationAlgorithmIDENTITY(value=repr(self.value))" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, DerivationAlgorithmIDENTITY): + return False + return self.value == other.value + + +class DerivationAlgorithmNone: + def __init__(self, value: None_): + self.value = value + + def as_dict(self) -> Dict[str, Any]: + return {"None": self.value.as_dict()} + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "DerivationAlgorithmNone": + if len(d) != 1: + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + + return DerivationAlgorithmNone(None_.from_dict(d["None"])) + + def __repr__(self) -> str: + return f"DerivationAlgorithmNone(value=repr(self.value))" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, DerivationAlgorithmNone): + return False + return self.value == other.value + + +class DerivationAlgorithmUnknown: + """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]) -> "DerivationAlgorithmUnknown": + if len(d) != 1: + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + return DerivationAlgorithmUnknown(d["SDK_UNKNOWN_MEMBER"]["name"]) + + def __repr__(self) -> str: + return f"DerivationAlgorithmUnknown(tag={self.tag})" + + +DerivationAlgorithm = Union[ + DerivationAlgorithmHKDF, + DerivationAlgorithmIDENTITY, + DerivationAlgorithmNone, + DerivationAlgorithmUnknown, +] + + +def _derivation_algorithm_from_dict(d: Dict[str, Any]) -> DerivationAlgorithm: + if "HKDF" in d: + return DerivationAlgorithmHKDF.from_dict(d) + + if "IDENTITY" in d: + return DerivationAlgorithmIDENTITY.from_dict(d) + + if "None" in d: + return DerivationAlgorithmNone.from_dict(d) + + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + + +class DIRECT_KEY_WRAPPING: + def as_dict(self) -> Dict[str, Any]: + """Converts the DIRECT_KEY_WRAPPING to a dictionary.""" + return {} + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "DIRECT_KEY_WRAPPING": + """Creates a DIRECT_KEY_WRAPPING from a dictionary.""" + return DIRECT_KEY_WRAPPING() + + def __repr__(self) -> str: + result = "DIRECT_KEY_WRAPPING(" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + return isinstance(other, DIRECT_KEY_WRAPPING) + + +class EncryptAES_GCM: + def __init__(self, value: AES_GCM): + self.value = value + + def as_dict(self) -> Dict[str, Any]: + return {"AES_GCM": self.value.as_dict()} + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "EncryptAES_GCM": + if len(d) != 1: + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + + return EncryptAES_GCM(AES_GCM.from_dict(d["AES_GCM"])) + + def __repr__(self) -> str: + return f"EncryptAES_GCM(value=repr(self.value))" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, EncryptAES_GCM): + return False + return self.value == other.value + + +class EncryptUnknown: + """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]) -> "EncryptUnknown": + if len(d) != 1: + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + return EncryptUnknown(d["SDK_UNKNOWN_MEMBER"]["name"]) + + def __repr__(self) -> str: + return f"EncryptUnknown(tag={self.tag})" + + +Encrypt = Union[EncryptAES_GCM, EncryptUnknown] + + +def _encrypt_from_dict(d: Dict[str, Any]) -> Encrypt: + if "AES_GCM" in d: + return EncryptAES_GCM.from_dict(d) + + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + + +class IntermediateKeyWrapping: + key_encryption_key_kdf: DerivationAlgorithm + mac_key_kdf: DerivationAlgorithm + pdk_encrypt_algorithm: Encrypt + + def __init__( + self, + *, + key_encryption_key_kdf: DerivationAlgorithm, + mac_key_kdf: DerivationAlgorithm, + pdk_encrypt_algorithm: Encrypt, + ): + self.key_encryption_key_kdf = key_encryption_key_kdf + self.mac_key_kdf = mac_key_kdf + self.pdk_encrypt_algorithm = pdk_encrypt_algorithm + + def as_dict(self) -> Dict[str, Any]: + """Converts the IntermediateKeyWrapping to a dictionary.""" + return { + "key_encryption_key_kdf": self.key_encryption_key_kdf.as_dict(), + "mac_key_kdf": self.mac_key_kdf.as_dict(), + "pdk_encrypt_algorithm": self.pdk_encrypt_algorithm.as_dict(), + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "IntermediateKeyWrapping": + """Creates a IntermediateKeyWrapping from a dictionary.""" + kwargs: Dict[str, Any] = { + "key_encryption_key_kdf": _derivation_algorithm_from_dict( + d["key_encryption_key_kdf"] + ), + "mac_key_kdf": _derivation_algorithm_from_dict(d["mac_key_kdf"]), + "pdk_encrypt_algorithm": _encrypt_from_dict(d["pdk_encrypt_algorithm"]), + } + + return IntermediateKeyWrapping(**kwargs) + + def __repr__(self) -> str: + result = "IntermediateKeyWrapping(" + if self.key_encryption_key_kdf is not None: + result += f"key_encryption_key_kdf={repr(self.key_encryption_key_kdf)}, " + + if self.mac_key_kdf is not None: + result += f"mac_key_kdf={repr(self.mac_key_kdf)}, " + + if self.pdk_encrypt_algorithm is not None: + result += f"pdk_encrypt_algorithm={repr(self.pdk_encrypt_algorithm)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, IntermediateKeyWrapping): + return False + attributes: list[str] = [ + "key_encryption_key_kdf", + "mac_key_kdf", + "pdk_encrypt_algorithm", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class EdkWrappingAlgorithmDIRECT_KEY_WRAPPING: + def __init__(self, value: DIRECT_KEY_WRAPPING): + self.value = value + + def as_dict(self) -> Dict[str, Any]: + return {"DIRECT_KEY_WRAPPING": self.value.as_dict()} + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "EdkWrappingAlgorithmDIRECT_KEY_WRAPPING": + if len(d) != 1: + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + + return EdkWrappingAlgorithmDIRECT_KEY_WRAPPING( + DIRECT_KEY_WRAPPING.from_dict(d["DIRECT_KEY_WRAPPING"]) + ) + + def __repr__(self) -> str: + return f"EdkWrappingAlgorithmDIRECT_KEY_WRAPPING(value=repr(self.value))" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, EdkWrappingAlgorithmDIRECT_KEY_WRAPPING): + return False + return self.value == other.value + + +class EdkWrappingAlgorithmIntermediateKeyWrapping: + def __init__(self, value: IntermediateKeyWrapping): + self.value = value + + def as_dict(self) -> Dict[str, Any]: + return {"IntermediateKeyWrapping": self.value.as_dict()} + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "EdkWrappingAlgorithmIntermediateKeyWrapping": + if len(d) != 1: + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + + return EdkWrappingAlgorithmIntermediateKeyWrapping( + IntermediateKeyWrapping.from_dict(d["IntermediateKeyWrapping"]) + ) + + def __repr__(self) -> str: + return f"EdkWrappingAlgorithmIntermediateKeyWrapping(value=repr(self.value))" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, EdkWrappingAlgorithmIntermediateKeyWrapping): + return False + return self.value == other.value + + +class EdkWrappingAlgorithmUnknown: + """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]) -> "EdkWrappingAlgorithmUnknown": + if len(d) != 1: + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + return EdkWrappingAlgorithmUnknown(d["SDK_UNKNOWN_MEMBER"]["name"]) + + def __repr__(self) -> str: + return f"EdkWrappingAlgorithmUnknown(tag={self.tag})" + + +EdkWrappingAlgorithm = Union[ + EdkWrappingAlgorithmDIRECT_KEY_WRAPPING, + EdkWrappingAlgorithmIntermediateKeyWrapping, + EdkWrappingAlgorithmUnknown, +] + + +def _edk_wrapping_algorithm_from_dict(d: Dict[str, Any]) -> EdkWrappingAlgorithm: + if "DIRECT_KEY_WRAPPING" in d: + return EdkWrappingAlgorithmDIRECT_KEY_WRAPPING.from_dict(d) + + if "IntermediateKeyWrapping" in d: + return EdkWrappingAlgorithmIntermediateKeyWrapping.from_dict(d) + + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + + +class ECDSA: + curve: str + + def __init__( + self, + *, + curve: str, + ): + self.curve = curve + + def as_dict(self) -> Dict[str, Any]: + """Converts the ECDSA to a dictionary.""" + return { + "curve": self.curve, + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "ECDSA": + """Creates a ECDSA from a dictionary.""" + kwargs: Dict[str, Any] = { + "curve": d["curve"], + } + + return ECDSA(**kwargs) + + def __repr__(self) -> str: + result = "ECDSA(" + if self.curve is not None: + result += f"curve={repr(self.curve)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, ECDSA): + return False + attributes: list[str] = [ + "curve", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class SignatureAlgorithmECDSA: + def __init__(self, value: ECDSA): + self.value = value + + def as_dict(self) -> Dict[str, Any]: + return {"ECDSA": self.value.as_dict()} + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "SignatureAlgorithmECDSA": + if len(d) != 1: + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + + return SignatureAlgorithmECDSA(ECDSA.from_dict(d["ECDSA"])) + + def __repr__(self) -> str: + return f"SignatureAlgorithmECDSA(value=repr(self.value))" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, SignatureAlgorithmECDSA): + return False + return self.value == other.value + + +class SignatureAlgorithmNone: + def __init__(self, value: None_): + self.value = value + + def as_dict(self) -> Dict[str, Any]: + return {"None": self.value.as_dict()} + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "SignatureAlgorithmNone": + if len(d) != 1: + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + + return SignatureAlgorithmNone(None_.from_dict(d["None"])) + + def __repr__(self) -> str: + return f"SignatureAlgorithmNone(value=repr(self.value))" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, SignatureAlgorithmNone): + return False + return self.value == other.value + + +class SignatureAlgorithmUnknown: + """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]) -> "SignatureAlgorithmUnknown": + if len(d) != 1: + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + return SignatureAlgorithmUnknown(d["SDK_UNKNOWN_MEMBER"]["name"]) + + def __repr__(self) -> str: + return f"SignatureAlgorithmUnknown(tag={self.tag})" + + +SignatureAlgorithm = Union[ + SignatureAlgorithmECDSA, SignatureAlgorithmNone, SignatureAlgorithmUnknown +] + + +def _signature_algorithm_from_dict(d: Dict[str, Any]) -> SignatureAlgorithm: + if "ECDSA" in d: + return SignatureAlgorithmECDSA.from_dict(d) + + if "None" in d: + return SignatureAlgorithmNone.from_dict(d) + + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + + +class SymmetricSignatureAlgorithmHMAC: + def __init__(self, value: str): + self.value = value + + def as_dict(self) -> Dict[str, Any]: + return {"HMAC": self.value} + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "SymmetricSignatureAlgorithmHMAC": + if len(d) != 1: + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + + return SymmetricSignatureAlgorithmHMAC(d["HMAC"]) + + def __repr__(self) -> str: + return f"SymmetricSignatureAlgorithmHMAC(value=repr(self.value))" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, SymmetricSignatureAlgorithmHMAC): + return False + return self.value == other.value + + +class SymmetricSignatureAlgorithmNone: + def __init__(self, value: None_): + self.value = value + + def as_dict(self) -> Dict[str, Any]: + return {"None": self.value.as_dict()} + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "SymmetricSignatureAlgorithmNone": + if len(d) != 1: + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + + return SymmetricSignatureAlgorithmNone(None_.from_dict(d["None"])) + + def __repr__(self) -> str: + return f"SymmetricSignatureAlgorithmNone(value=repr(self.value))" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, SymmetricSignatureAlgorithmNone): + return False + return self.value == other.value + + +class SymmetricSignatureAlgorithmUnknown: + """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]) -> "SymmetricSignatureAlgorithmUnknown": + if len(d) != 1: + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + return SymmetricSignatureAlgorithmUnknown(d["SDK_UNKNOWN_MEMBER"]["name"]) + + def __repr__(self) -> str: + return f"SymmetricSignatureAlgorithmUnknown(tag={self.tag})" + + +SymmetricSignatureAlgorithm = Union[ + SymmetricSignatureAlgorithmHMAC, + SymmetricSignatureAlgorithmNone, + SymmetricSignatureAlgorithmUnknown, +] + + +def _symmetric_signature_algorithm_from_dict( + d: Dict[str, Any] +) -> SymmetricSignatureAlgorithm: + if "HMAC" in d: + return SymmetricSignatureAlgorithmHMAC.from_dict(d) + + if "None" in d: + return SymmetricSignatureAlgorithmNone.from_dict(d) + + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + + +class AlgorithmSuiteInfo: + id: AlgorithmSuiteId + binary_id: bytes | bytearray + message_version: int + encrypt: Encrypt + kdf: DerivationAlgorithm + commitment: DerivationAlgorithm + signature: SignatureAlgorithm + symmetric_signature: SymmetricSignatureAlgorithm + edk_wrapping: EdkWrappingAlgorithm + + def __init__( + self, + *, + id: AlgorithmSuiteId, + binary_id: bytes | bytearray, + message_version: int, + encrypt: Encrypt, + kdf: DerivationAlgorithm, + commitment: DerivationAlgorithm, + signature: SignatureAlgorithm, + symmetric_signature: SymmetricSignatureAlgorithm, + edk_wrapping: EdkWrappingAlgorithm, + ): + self.id = id + self.binary_id = binary_id + self.message_version = message_version + self.encrypt = encrypt + self.kdf = kdf + self.commitment = commitment + self.signature = signature + self.symmetric_signature = symmetric_signature + self.edk_wrapping = edk_wrapping + + def as_dict(self) -> Dict[str, Any]: + """Converts the AlgorithmSuiteInfo to a dictionary.""" + return { + "id": self.id.as_dict(), + "binary_id": self.binary_id, + "message_version": self.message_version, + "encrypt": self.encrypt.as_dict(), + "kdf": self.kdf.as_dict(), + "commitment": self.commitment.as_dict(), + "signature": self.signature.as_dict(), + "symmetric_signature": self.symmetric_signature.as_dict(), + "edk_wrapping": self.edk_wrapping.as_dict(), + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "AlgorithmSuiteInfo": + """Creates a AlgorithmSuiteInfo from a dictionary.""" + kwargs: Dict[str, Any] = { + "id": _algorithm_suite_id_from_dict(d["id"]), + "binary_id": d["binary_id"], + "message_version": d["message_version"], + "encrypt": _encrypt_from_dict(d["encrypt"]), + "kdf": _derivation_algorithm_from_dict(d["kdf"]), + "commitment": _derivation_algorithm_from_dict(d["commitment"]), + "signature": _signature_algorithm_from_dict(d["signature"]), + "symmetric_signature": _symmetric_signature_algorithm_from_dict( + d["symmetric_signature"] + ), + "edk_wrapping": _edk_wrapping_algorithm_from_dict(d["edk_wrapping"]), + } + + return AlgorithmSuiteInfo(**kwargs) + + def __repr__(self) -> str: + result = "AlgorithmSuiteInfo(" + if self.id is not None: + result += f"id={repr(self.id)}, " + + if self.binary_id is not None: + result += f"binary_id={repr(self.binary_id)}, " + + if self.message_version is not None: + result += f"message_version={repr(self.message_version)}, " + + if self.encrypt is not None: + result += f"encrypt={repr(self.encrypt)}, " + + if self.kdf is not None: + result += f"kdf={repr(self.kdf)}, " + + if self.commitment is not None: + result += f"commitment={repr(self.commitment)}, " + + if self.signature is not None: + result += f"signature={repr(self.signature)}, " + + if self.symmetric_signature is not None: + result += f"symmetric_signature={repr(self.symmetric_signature)}, " + + if self.edk_wrapping is not None: + result += f"edk_wrapping={repr(self.edk_wrapping)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, AlgorithmSuiteInfo): + return False + attributes: list[str] = [ + "id", + "binary_id", + "message_version", + "encrypt", + "kdf", + "commitment", + "signature", + "symmetric_signature", + "edk_wrapping", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class GetBranchKeyIdInput: + encryption_context: dict[str, str] + + def __init__( + self, + *, + encryption_context: dict[str, str], + ): + """Inputs for determining the Branch Key which should be used to wrap + or unwrap the data key for this encryption or decryption. + + :param encryption_context: The Encryption Context used with this + encryption or decryption. + """ + self.encryption_context = encryption_context + + def as_dict(self) -> Dict[str, Any]: + """Converts the GetBranchKeyIdInput to a dictionary.""" + return { + "encryption_context": self.encryption_context, + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "GetBranchKeyIdInput": + """Creates a GetBranchKeyIdInput from a dictionary.""" + kwargs: Dict[str, Any] = { + "encryption_context": d["encryption_context"], + } + + return GetBranchKeyIdInput(**kwargs) + + def __repr__(self) -> str: + result = "GetBranchKeyIdInput(" + if self.encryption_context is not None: + result += f"encryption_context={repr(self.encryption_context)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, GetBranchKeyIdInput): + return False + attributes: list[str] = [ + "encryption_context", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class GetBranchKeyIdOutput: + branch_key_id: str + + def __init__( + self, + *, + branch_key_id: str, + ): + """Outputs for the Branch Key responsible for wrapping or unwrapping + the data key in this encryption or decryption. + + :param branch_key_id: The identifier of the Branch Key that + should be responsible for wrapping or unwrapping the data + key in this encryption or decryption. + """ + self.branch_key_id = branch_key_id + + def as_dict(self) -> Dict[str, Any]: + """Converts the GetBranchKeyIdOutput to a dictionary.""" + return { + "branch_key_id": self.branch_key_id, + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "GetBranchKeyIdOutput": + """Creates a GetBranchKeyIdOutput from a dictionary.""" + kwargs: Dict[str, Any] = { + "branch_key_id": d["branch_key_id"], + } + + return GetBranchKeyIdOutput(**kwargs) + + def __repr__(self) -> str: + result = "GetBranchKeyIdOutput(" + if self.branch_key_id is not None: + result += f"branch_key_id={repr(self.branch_key_id)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, GetBranchKeyIdOutput): + return False + attributes: list[str] = [ + "branch_key_id", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class GetClientInput: + region: str + + def __init__( + self, + *, + region: str, + ): + """Inputs for getting a AWS KMS Client. + + :param region: The region the client should be created in. + """ + self.region = region + + def as_dict(self) -> Dict[str, Any]: + """Converts the GetClientInput to a dictionary.""" + return { + "region": self.region, + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "GetClientInput": + """Creates a GetClientInput from a dictionary.""" + kwargs: Dict[str, Any] = { + "region": d["region"], + } + + return GetClientInput(**kwargs) + + def __repr__(self) -> str: + result = "GetClientInput(" + if self.region is not None: + result += f"region={repr(self.region)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, GetClientInput): + return False + attributes: list[str] = [ + "region", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class DiscoveryFilter: + account_ids: list[str] + partition: str + + def __init__( + self, + *, + account_ids: list[str], + partition: str, + ): + """A filter which defines what AWS partition and AWS accounts a KMS Key + may be in for a Keyring to be allowed to attempt to decrypt it. + + :param account_ids: A list of allowed AWS account IDs. + :param partition: The AWS partition which is allowed. + """ + self.account_ids = account_ids + self.partition = partition + + def as_dict(self) -> Dict[str, Any]: + """Converts the DiscoveryFilter to a dictionary.""" + return { + "account_ids": self.account_ids, + "partition": self.partition, + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "DiscoveryFilter": + """Creates a DiscoveryFilter from a dictionary.""" + kwargs: Dict[str, Any] = { + "account_ids": d["account_ids"], + "partition": d["partition"], + } + + return DiscoveryFilter(**kwargs) + + def __repr__(self) -> str: + result = "DiscoveryFilter(" + if self.account_ids is not None: + result += f"account_ids={repr(self.account_ids)}, " + + if self.partition is not None: + result += f"partition={repr(self.partition)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, DiscoveryFilter): + return False + attributes: list[str] = [ + "account_ids", + "partition", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class CreateAwsKmsDiscoveryKeyringInput: + kms_client: "botocore.client.BaseClient" + discovery_filter: Optional[DiscoveryFilter] + grant_tokens: Optional[list[str]] + + def __init__( + self, + *, + kms_client: "botocore.client.BaseClient", + discovery_filter: Optional[DiscoveryFilter] = None, + grant_tokens: Optional[list[str]] = None, + ): + """Inputs for for creating a AWS KMS Discovery Keyring. + + :param kms_client: The KMS Client this Keyring will use to call + KMS. + :param discovery_filter: A filter which restricts which KMS Keys + this Keyring may attempt to decrypt with by AWS partition + and account. + :param grant_tokens: A list of grant tokens to be used when + calling KMS. + """ + self.kms_client = kms_client + self.discovery_filter = discovery_filter + self.grant_tokens = grant_tokens + + def as_dict(self) -> Dict[str, Any]: + """Converts the CreateAwsKmsDiscoveryKeyringInput to a dictionary.""" + d: Dict[str, Any] = { + "kms_client": self.kms_client, + } + + if self.discovery_filter is not None: + d["discovery_filter"] = self.discovery_filter.as_dict() + + if self.grant_tokens is not None: + d["grant_tokens"] = self.grant_tokens + + return d + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "CreateAwsKmsDiscoveryKeyringInput": + """Creates a CreateAwsKmsDiscoveryKeyringInput from a dictionary.""" + from botocore.client import BaseClient + + kwargs: Dict[str, Any] = { + "kms_client": d["kms_client"], + } + + if "discovery_filter" in d: + kwargs["discovery_filter"] = DiscoveryFilter.from_dict( + d["discovery_filter"] + ) + + if "grant_tokens" in d: + kwargs["grant_tokens"] = d["grant_tokens"] + + return CreateAwsKmsDiscoveryKeyringInput(**kwargs) + + def __repr__(self) -> str: + result = "CreateAwsKmsDiscoveryKeyringInput(" + if self.kms_client is not None: + result += f"kms_client={repr(self.kms_client)}, " + + if self.discovery_filter is not None: + result += f"discovery_filter={repr(self.discovery_filter)}, " + + if self.grant_tokens is not None: + result += f"grant_tokens={repr(self.grant_tokens)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, CreateAwsKmsDiscoveryKeyringInput): + return False + attributes: list[str] = [ + "kms_client", + "discovery_filter", + "grant_tokens", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class CreateAwsKmsDiscoveryMultiKeyringInput: + regions: list[str] + discovery_filter: Optional[DiscoveryFilter] + client_supplier: Optional[ + "aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.references.ClientSupplier" + ] + grant_tokens: Optional[list[str]] + + def __init__( + self, + *, + regions: list[str], + discovery_filter: Optional[DiscoveryFilter] = None, + client_supplier: Optional[ + "aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.references.ClientSupplier" + ] = None, + grant_tokens: Optional[list[str]] = None, + ): + """Inputs for for creating an AWS KMS Discovery Multi-Keyring. + + :param regions: The list of regions this Keyring will creates + KMS clients for. + :param discovery_filter: A filter which restricts which KMS Keys + this Keyring may attempt to decrypt with by AWS partition + and account. + :param client_supplier: The Client Supplier which will be used + to get KMS Clients for use with this Keyring. If not + specified on input, a Default Client Supplier is created + which creates a KMS Client for each region in the 'regions' + input. + :param grant_tokens: A list of grant tokens to be used when + calling KMS. + """ + self.regions = regions + self.discovery_filter = discovery_filter + self.client_supplier = client_supplier + self.grant_tokens = grant_tokens + + def as_dict(self) -> Dict[str, Any]: + """Converts the CreateAwsKmsDiscoveryMultiKeyringInput to a + dictionary.""" + d: Dict[str, Any] = { + "regions": self.regions, + } + + if self.discovery_filter is not None: + d["discovery_filter"] = self.discovery_filter.as_dict() + + if self.client_supplier is not None: + d["client_supplier"] = self.client_supplier.as_dict() + + if self.grant_tokens is not None: + d["grant_tokens"] = self.grant_tokens + + return d + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "CreateAwsKmsDiscoveryMultiKeyringInput": + """Creates a CreateAwsKmsDiscoveryMultiKeyringInput from a + dictionary.""" + from aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.references import ( + ClientSupplier, + ) + + kwargs: Dict[str, Any] = { + "regions": d["regions"], + } + + if "discovery_filter" in d: + kwargs["discovery_filter"] = DiscoveryFilter.from_dict( + d["discovery_filter"] + ) + + if "client_supplier" in d: + kwargs["client_supplier"] = ClientSupplier.from_dict(d["client_supplier"]) + + if "grant_tokens" in d: + kwargs["grant_tokens"] = d["grant_tokens"] + + return CreateAwsKmsDiscoveryMultiKeyringInput(**kwargs) + + def __repr__(self) -> str: + result = "CreateAwsKmsDiscoveryMultiKeyringInput(" + if self.regions is not None: + result += f"regions={repr(self.regions)}, " + + if self.discovery_filter is not None: + result += f"discovery_filter={repr(self.discovery_filter)}, " + + if self.client_supplier is not None: + result += f"client_supplier={repr(self.client_supplier)}, " + + if self.grant_tokens is not None: + result += f"grant_tokens={repr(self.grant_tokens)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, CreateAwsKmsDiscoveryMultiKeyringInput): + return False + attributes: list[str] = [ + "regions", + "discovery_filter", + "client_supplier", + "grant_tokens", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class KmsPrivateKeyToStaticPublicKeyInput: + sender_kms_identifier: str + sender_public_key: Optional[bytes | bytearray] + recipient_public_key: bytes | bytearray + + def __init__( + self, + *, + sender_kms_identifier: str, + recipient_public_key: bytes | bytearray, + sender_public_key: Optional[bytes | bytearray] = None, + ): + """Inputs for creating a KmsPrivateKeyToStaticPublicKey Configuration. + + :param sender_kms_identifier: AWS KMS Key Identifier belonging + to the sender. + :param recipient_public_key: Recipient Public Key. This MUST be + a raw public ECC key in DER format. + :param sender_public_key: Sender Public Key. This is the raw + public ECC key in DER format that belongs to the + senderKmsIdentifier. + """ + self.sender_kms_identifier = sender_kms_identifier + self.recipient_public_key = recipient_public_key + self.sender_public_key = sender_public_key + + def as_dict(self) -> Dict[str, Any]: + """Converts the KmsPrivateKeyToStaticPublicKeyInput to a dictionary.""" + d: Dict[str, Any] = { + "sender_kms_identifier": self.sender_kms_identifier, + "recipient_public_key": self.recipient_public_key, + } + + if self.sender_public_key is not None: + d["sender_public_key"] = self.sender_public_key + + return d + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "KmsPrivateKeyToStaticPublicKeyInput": + """Creates a KmsPrivateKeyToStaticPublicKeyInput from a dictionary.""" + kwargs: Dict[str, Any] = { + "sender_kms_identifier": d["sender_kms_identifier"], + "recipient_public_key": d["recipient_public_key"], + } + + if "sender_public_key" in d: + kwargs["sender_public_key"] = d["sender_public_key"] + + return KmsPrivateKeyToStaticPublicKeyInput(**kwargs) + + def __repr__(self) -> str: + result = "KmsPrivateKeyToStaticPublicKeyInput(" + if self.sender_kms_identifier is not None: + result += f"sender_kms_identifier={repr(self.sender_kms_identifier)}, " + + if self.sender_public_key is not None: + result += f"sender_public_key={repr(self.sender_public_key)}, " + + if self.recipient_public_key is not None: + result += f"recipient_public_key={repr(self.recipient_public_key)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, KmsPrivateKeyToStaticPublicKeyInput): + return False + attributes: list[str] = [ + "sender_kms_identifier", + "sender_public_key", + "recipient_public_key", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class KmsPublicKeyDiscoveryInput: + recipient_kms_identifier: str + + def __init__( + self, + *, + recipient_kms_identifier: str, + ): + """Inputs for creating a KmsPublicKeyDiscovery Configuration. This is a + DECRYPT ONLY configuration. + + :param recipient_kms_identifier: AWS KMS key identifier + belonging to the recipient. + """ + self.recipient_kms_identifier = recipient_kms_identifier + + def as_dict(self) -> Dict[str, Any]: + """Converts the KmsPublicKeyDiscoveryInput to a dictionary.""" + return { + "recipient_kms_identifier": self.recipient_kms_identifier, + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "KmsPublicKeyDiscoveryInput": + """Creates a KmsPublicKeyDiscoveryInput from a dictionary.""" + kwargs: Dict[str, Any] = { + "recipient_kms_identifier": d["recipient_kms_identifier"], + } + + return KmsPublicKeyDiscoveryInput(**kwargs) + + def __repr__(self) -> str: + result = "KmsPublicKeyDiscoveryInput(" + if self.recipient_kms_identifier is not None: + result += f"recipient_kms_identifier={repr(self.recipient_kms_identifier)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, KmsPublicKeyDiscoveryInput): + return False + attributes: list[str] = [ + "recipient_kms_identifier", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class KmsEcdhStaticConfigurationsKmsPublicKeyDiscovery: + """Inputs for creating a KmsPublicKeyDiscovery Configuration. + + This is a DECRYPT ONLY configuration. + """ + + def __init__(self, value: KmsPublicKeyDiscoveryInput): + self.value = value + + def as_dict(self) -> Dict[str, Any]: + return {"KmsPublicKeyDiscovery": self.value.as_dict()} + + @staticmethod + def from_dict( + d: Dict[str, Any] + ) -> "KmsEcdhStaticConfigurationsKmsPublicKeyDiscovery": + if len(d) != 1: + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + + return KmsEcdhStaticConfigurationsKmsPublicKeyDiscovery( + KmsPublicKeyDiscoveryInput.from_dict(d["KmsPublicKeyDiscovery"]) + ) + + def __repr__(self) -> str: + return ( + f"KmsEcdhStaticConfigurationsKmsPublicKeyDiscovery(value=repr(self.value))" + ) + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, KmsEcdhStaticConfigurationsKmsPublicKeyDiscovery): + return False + return self.value == other.value + + +class KmsEcdhStaticConfigurationsKmsPrivateKeyToStaticPublicKey: + """Inputs for creating a KmsPrivateKeyToStaticPublicKey Configuration.""" + + def __init__(self, value: KmsPrivateKeyToStaticPublicKeyInput): + self.value = value + + def as_dict(self) -> Dict[str, Any]: + return {"KmsPrivateKeyToStaticPublicKey": self.value.as_dict()} + + @staticmethod + def from_dict( + d: Dict[str, Any] + ) -> "KmsEcdhStaticConfigurationsKmsPrivateKeyToStaticPublicKey": + if len(d) != 1: + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + + return KmsEcdhStaticConfigurationsKmsPrivateKeyToStaticPublicKey( + KmsPrivateKeyToStaticPublicKeyInput.from_dict( + d["KmsPrivateKeyToStaticPublicKey"] + ) + ) + + def __repr__(self) -> str: + return f"KmsEcdhStaticConfigurationsKmsPrivateKeyToStaticPublicKey(value=repr(self.value))" + + def __eq__(self, other: Any) -> bool: + if not isinstance( + other, KmsEcdhStaticConfigurationsKmsPrivateKeyToStaticPublicKey + ): + return False + return self.value == other.value + + +class KmsEcdhStaticConfigurationsUnknown: + """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]) -> "KmsEcdhStaticConfigurationsUnknown": + if len(d) != 1: + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + return KmsEcdhStaticConfigurationsUnknown(d["SDK_UNKNOWN_MEMBER"]["name"]) + + def __repr__(self) -> str: + return f"KmsEcdhStaticConfigurationsUnknown(tag={self.tag})" + + +# Allowed configurations when using KmsEcdhStaticConfigurations. +KmsEcdhStaticConfigurations = Union[ + KmsEcdhStaticConfigurationsKmsPublicKeyDiscovery, + KmsEcdhStaticConfigurationsKmsPrivateKeyToStaticPublicKey, + KmsEcdhStaticConfigurationsUnknown, +] + + +def _kms_ecdh_static_configurations_from_dict( + d: Dict[str, Any] +) -> KmsEcdhStaticConfigurations: + if "KmsPublicKeyDiscovery" in d: + return KmsEcdhStaticConfigurationsKmsPublicKeyDiscovery.from_dict(d) + + if "KmsPrivateKeyToStaticPublicKey" in d: + return KmsEcdhStaticConfigurationsKmsPrivateKeyToStaticPublicKey.from_dict(d) + + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + + +class CreateAwsKmsEcdhKeyringInput: + key_agreement_scheme: KmsEcdhStaticConfigurations + curve_spec: str + kms_client: "botocore.client.BaseClient" + grant_tokens: Optional[list[str]] + + def __init__( + self, + *, + key_agreement_scheme: KmsEcdhStaticConfigurations, + curve_spec: str, + kms_client: "botocore.client.BaseClient", + grant_tokens: Optional[list[str]] = None, + ): + """Inputs for creating an AWS KMS ECDH Keyring. + + :param key_agreement_scheme: The Key Agreement Scheme + configuration that is responsible for how the shared secret + is calculated. + :param curve_spec: The named curve that corresponds to the curve + on which the sender's private and recipient's public key + lie. + :param kms_client: The KMS Client this Keyring will use to call + KMS. + :param grant_tokens: A list of grant tokens to be used when + calling KMS. + """ + self.key_agreement_scheme = key_agreement_scheme + self.curve_spec = curve_spec + self.kms_client = kms_client + self.grant_tokens = grant_tokens + + def as_dict(self) -> Dict[str, Any]: + """Converts the CreateAwsKmsEcdhKeyringInput to a dictionary.""" + d: Dict[str, Any] = { + "key_agreement_scheme": self.key_agreement_scheme.as_dict(), + "curve_spec": self.curve_spec, + "kms_client": self.kms_client, + } + + if self.grant_tokens is not None: + d["grant_tokens"] = self.grant_tokens + + return d + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "CreateAwsKmsEcdhKeyringInput": + """Creates a CreateAwsKmsEcdhKeyringInput from a dictionary.""" + from botocore.client import BaseClient + + kwargs: Dict[str, Any] = { + "key_agreement_scheme": _kms_ecdh_static_configurations_from_dict( + d["key_agreement_scheme"] + ), + "curve_spec": d["curve_spec"], + "kms_client": d["kms_client"], + } + + if "grant_tokens" in d: + kwargs["grant_tokens"] = d["grant_tokens"] + + return CreateAwsKmsEcdhKeyringInput(**kwargs) + + def __repr__(self) -> str: + result = "CreateAwsKmsEcdhKeyringInput(" + if self.key_agreement_scheme is not None: + result += f"key_agreement_scheme={repr(self.key_agreement_scheme)}, " + + if self.curve_spec is not None: + result += f"curve_spec={repr(self.curve_spec)}, " + + if self.kms_client is not None: + result += f"kms_client={repr(self.kms_client)}, " + + if self.grant_tokens is not None: + result += f"grant_tokens={repr(self.grant_tokens)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, CreateAwsKmsEcdhKeyringInput): + return False + attributes: list[str] = [ + "key_agreement_scheme", + "curve_spec", + "kms_client", + "grant_tokens", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class DefaultCache: + entry_capacity: int + + def __init__( + self, + *, + entry_capacity: int = 0, + ): + """The best choice for most situations. Probably a StormTrackingCache. + + :param entry_capacity: Maximum number of entries cached. + """ + if (entry_capacity is not None) and (entry_capacity < 1): + raise ValueError("entry_capacity must be greater than or equal to 1") + + self.entry_capacity = entry_capacity + + def as_dict(self) -> Dict[str, Any]: + """Converts the DefaultCache to a dictionary.""" + d: Dict[str, Any] = {} + + if self.entry_capacity is not None: + d["entry_capacity"] = self.entry_capacity + + return d + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "DefaultCache": + """Creates a DefaultCache from a dictionary.""" + kwargs: Dict[str, Any] = {} + + if "entry_capacity" in d: + kwargs["entry_capacity"] = d["entry_capacity"] + + return DefaultCache(**kwargs) + + def __repr__(self) -> str: + result = "DefaultCache(" + if self.entry_capacity is not None: + result += f"entry_capacity={repr(self.entry_capacity)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, DefaultCache): + return False + attributes: list[str] = [ + "entry_capacity", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class MultiThreadedCache: + entry_capacity: int + entry_pruning_tail_size: int + + def __init__( + self, + *, + entry_capacity: int = 0, + entry_pruning_tail_size: int = 0, + ): + """A cache that is safe for use in a multi threaded environment, but no + extra functionality. + + :param entry_capacity: Maximum number of entries cached. + :param entry_pruning_tail_size: Number of entries to prune at a + time. + """ + if (entry_capacity is not None) and (entry_capacity < 1): + raise ValueError("entry_capacity must be greater than or equal to 1") + + self.entry_capacity = entry_capacity + if (entry_pruning_tail_size is not None) and (entry_pruning_tail_size < 1): + raise ValueError( + "entry_pruning_tail_size must be greater than or equal to 1" + ) + + self.entry_pruning_tail_size = entry_pruning_tail_size + + def as_dict(self) -> Dict[str, Any]: + """Converts the MultiThreadedCache to a dictionary.""" + d: Dict[str, Any] = {} + + if self.entry_capacity is not None: + d["entry_capacity"] = self.entry_capacity + + if self.entry_pruning_tail_size is not None: + d["entry_pruning_tail_size"] = self.entry_pruning_tail_size + + return d + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "MultiThreadedCache": + """Creates a MultiThreadedCache from a dictionary.""" + kwargs: Dict[str, Any] = {} + + if "entry_capacity" in d: + kwargs["entry_capacity"] = d["entry_capacity"] + + if "entry_pruning_tail_size" in d: + kwargs["entry_pruning_tail_size"] = d["entry_pruning_tail_size"] + + return MultiThreadedCache(**kwargs) + + def __repr__(self) -> str: + result = "MultiThreadedCache(" + if self.entry_capacity is not None: + result += f"entry_capacity={repr(self.entry_capacity)}, " + + if self.entry_pruning_tail_size is not None: + result += f"entry_pruning_tail_size={repr(self.entry_pruning_tail_size)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, MultiThreadedCache): + return False + attributes: list[str] = [ + "entry_capacity", + "entry_pruning_tail_size", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class NoCache: + """Nothing should ever be cached.""" + + def as_dict(self) -> Dict[str, Any]: + """Converts the NoCache to a dictionary.""" + return {} + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "NoCache": + """Creates a NoCache from a dictionary.""" + return NoCache() + + def __repr__(self) -> str: + result = "NoCache(" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + return isinstance(other, NoCache) + + +class SingleThreadedCache: + entry_capacity: int + entry_pruning_tail_size: int + + def __init__( + self, + *, + entry_capacity: int = 0, + entry_pruning_tail_size: int = 0, + ): + """A cache that is NOT safe for use in a multi threaded environment. + + :param entry_capacity: Maximum number of entries cached. + :param entry_pruning_tail_size: Number of entries to prune at a + time. + """ + if (entry_capacity is not None) and (entry_capacity < 1): + raise ValueError("entry_capacity must be greater than or equal to 1") + + self.entry_capacity = entry_capacity + if (entry_pruning_tail_size is not None) and (entry_pruning_tail_size < 1): + raise ValueError( + "entry_pruning_tail_size must be greater than or equal to 1" + ) + + self.entry_pruning_tail_size = entry_pruning_tail_size + + def as_dict(self) -> Dict[str, Any]: + """Converts the SingleThreadedCache to a dictionary.""" + d: Dict[str, Any] = {} + + if self.entry_capacity is not None: + d["entry_capacity"] = self.entry_capacity + + if self.entry_pruning_tail_size is not None: + d["entry_pruning_tail_size"] = self.entry_pruning_tail_size + + return d + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "SingleThreadedCache": + """Creates a SingleThreadedCache from a dictionary.""" + kwargs: Dict[str, Any] = {} + + if "entry_capacity" in d: + kwargs["entry_capacity"] = d["entry_capacity"] + + if "entry_pruning_tail_size" in d: + kwargs["entry_pruning_tail_size"] = d["entry_pruning_tail_size"] + + return SingleThreadedCache(**kwargs) + + def __repr__(self) -> str: + result = "SingleThreadedCache(" + if self.entry_capacity is not None: + result += f"entry_capacity={repr(self.entry_capacity)}, " + + if self.entry_pruning_tail_size is not None: + result += f"entry_pruning_tail_size={repr(self.entry_pruning_tail_size)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, SingleThreadedCache): + return False + attributes: list[str] = [ + "entry_capacity", + "entry_pruning_tail_size", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class StormTrackingCache: + entry_capacity: int + entry_pruning_tail_size: int + grace_period: int + grace_interval: int + fan_out: int + in_flight_ttl: int + sleep_milli: int + + def __init__( + self, + *, + entry_capacity: int = 0, + entry_pruning_tail_size: int = 0, + grace_period: int = 0, + grace_interval: int = 0, + fan_out: int = 0, + in_flight_ttl: int = 0, + sleep_milli: int = 0, + ): + """A cache that is safe for use in a multi threaded environment, and + tries to prevent redundant or overly parallel backend calls. + + :param entry_capacity: Maximum number of entries cached. + :param entry_pruning_tail_size: Number of entries to prune at a + time. + :param grace_period: How many seconds before expiration should + an attempt be made to refresh the materials. If zero, use a + simple cache with no storm tracking. + :param grace_interval: How many seconds between attempts to + refresh the materials. + :param fan_out: How many simultaneous attempts to refresh the + materials. + :param in_flight_ttl: How many seconds until an attempt to + refresh the materials should be forgotten. + :param sleep_milli: How many milliseconds should a thread sleep + if fanOut is exceeded. + """ + if (entry_capacity is not None) and (entry_capacity < 1): + raise ValueError("entry_capacity must be greater than or equal to 1") + + self.entry_capacity = entry_capacity + if (entry_pruning_tail_size is not None) and (entry_pruning_tail_size < 1): + raise ValueError( + "entry_pruning_tail_size must be greater than or equal to 1" + ) + + self.entry_pruning_tail_size = entry_pruning_tail_size + if (grace_period is not None) and (grace_period < 1): + raise ValueError("grace_period must be greater than or equal to 1") + + self.grace_period = grace_period + if (grace_interval is not None) and (grace_interval < 1): + raise ValueError("grace_interval must be greater than or equal to 1") + + self.grace_interval = grace_interval + if (fan_out is not None) and (fan_out < 1): + raise ValueError("fan_out must be greater than or equal to 1") + + self.fan_out = fan_out + if (in_flight_ttl is not None) and (in_flight_ttl < 1): + raise ValueError("in_flight_ttl must be greater than or equal to 1") + + self.in_flight_ttl = in_flight_ttl + if (sleep_milli is not None) and (sleep_milli < 1): + raise ValueError("sleep_milli must be greater than or equal to 1") + + self.sleep_milli = sleep_milli + + def as_dict(self) -> Dict[str, Any]: + """Converts the StormTrackingCache to a dictionary.""" + d: Dict[str, Any] = {} + + if self.entry_capacity is not None: + d["entry_capacity"] = self.entry_capacity + + if self.entry_pruning_tail_size is not None: + d["entry_pruning_tail_size"] = self.entry_pruning_tail_size + + if self.grace_period is not None: + d["grace_period"] = self.grace_period + + if self.grace_interval is not None: + d["grace_interval"] = self.grace_interval + + if self.fan_out is not None: + d["fan_out"] = self.fan_out + + if self.in_flight_ttl is not None: + d["in_flight_ttl"] = self.in_flight_ttl + + if self.sleep_milli is not None: + d["sleep_milli"] = self.sleep_milli + + return d + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "StormTrackingCache": + """Creates a StormTrackingCache from a dictionary.""" + kwargs: Dict[str, Any] = {} + + if "entry_capacity" in d: + kwargs["entry_capacity"] = d["entry_capacity"] + + if "entry_pruning_tail_size" in d: + kwargs["entry_pruning_tail_size"] = d["entry_pruning_tail_size"] + + if "grace_period" in d: + kwargs["grace_period"] = d["grace_period"] + + if "grace_interval" in d: + kwargs["grace_interval"] = d["grace_interval"] + + if "fan_out" in d: + kwargs["fan_out"] = d["fan_out"] + + if "in_flight_ttl" in d: + kwargs["in_flight_ttl"] = d["in_flight_ttl"] + + if "sleep_milli" in d: + kwargs["sleep_milli"] = d["sleep_milli"] + + return StormTrackingCache(**kwargs) + + def __repr__(self) -> str: + result = "StormTrackingCache(" + if self.entry_capacity is not None: + result += f"entry_capacity={repr(self.entry_capacity)}, " + + if self.entry_pruning_tail_size is not None: + result += f"entry_pruning_tail_size={repr(self.entry_pruning_tail_size)}, " + + if self.grace_period is not None: + result += f"grace_period={repr(self.grace_period)}, " + + if self.grace_interval is not None: + result += f"grace_interval={repr(self.grace_interval)}, " + + if self.fan_out is not None: + result += f"fan_out={repr(self.fan_out)}, " + + if self.in_flight_ttl is not None: + result += f"in_flight_ttl={repr(self.in_flight_ttl)}, " + + if self.sleep_milli is not None: + result += f"sleep_milli={repr(self.sleep_milli)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, StormTrackingCache): + return False + attributes: list[str] = [ + "entry_capacity", + "entry_pruning_tail_size", + "grace_period", + "grace_interval", + "fan_out", + "in_flight_ttl", + "sleep_milli", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class CacheTypeDefault: + """The best choice for most situations. + + Probably a StormTrackingCache. + """ + + def __init__(self, value: DefaultCache): + self.value = value + + def as_dict(self) -> Dict[str, Any]: + return {"Default": self.value.as_dict()} + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "CacheTypeDefault": + if len(d) != 1: + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + + return CacheTypeDefault(DefaultCache.from_dict(d["Default"])) + + def __repr__(self) -> str: + return f"CacheTypeDefault(value=repr(self.value))" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, CacheTypeDefault): + return False + return self.value == other.value + + +class CacheTypeNo: + """Nothing should ever be cached.""" + + def __init__(self, value: NoCache): + self.value = value + + def as_dict(self) -> Dict[str, Any]: + return {"No": self.value.as_dict()} + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "CacheTypeNo": + if len(d) != 1: + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + + return CacheTypeNo(NoCache.from_dict(d["No"])) + + def __repr__(self) -> str: + return f"CacheTypeNo(value=repr(self.value))" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, CacheTypeNo): + return False + return self.value == other.value + + +class CacheTypeSingleThreaded: + """A cache that is NOT safe for use in a multi threaded environment.""" + + def __init__(self, value: SingleThreadedCache): + self.value = value + + def as_dict(self) -> Dict[str, Any]: + return {"SingleThreaded": self.value.as_dict()} + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "CacheTypeSingleThreaded": + if len(d) != 1: + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + + return CacheTypeSingleThreaded( + SingleThreadedCache.from_dict(d["SingleThreaded"]) + ) + + def __repr__(self) -> str: + return f"CacheTypeSingleThreaded(value=repr(self.value))" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, CacheTypeSingleThreaded): + return False + return self.value == other.value + + +class CacheTypeMultiThreaded: + """A cache that is safe for use in a multi threaded environment, but no + extra functionality.""" + + def __init__(self, value: MultiThreadedCache): + self.value = value + + def as_dict(self) -> Dict[str, Any]: + return {"MultiThreaded": self.value.as_dict()} + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "CacheTypeMultiThreaded": + if len(d) != 1: + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + + return CacheTypeMultiThreaded(MultiThreadedCache.from_dict(d["MultiThreaded"])) + + def __repr__(self) -> str: + return f"CacheTypeMultiThreaded(value=repr(self.value))" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, CacheTypeMultiThreaded): + return False + return self.value == other.value + + +class CacheTypeStormTracking: + """A cache that is safe for use in a multi threaded environment, and tries + to prevent redundant or overly parallel backend calls.""" + + def __init__(self, value: StormTrackingCache): + self.value = value + + def as_dict(self) -> Dict[str, Any]: + return {"StormTracking": self.value.as_dict()} + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "CacheTypeStormTracking": + if len(d) != 1: + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + + return CacheTypeStormTracking(StormTrackingCache.from_dict(d["StormTracking"])) + + def __repr__(self) -> str: + return f"CacheTypeStormTracking(value=repr(self.value))" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, CacheTypeStormTracking): + return False + return self.value == other.value + + +class CacheTypeShared: + """Shared cache across multiple Hierarchical Keyrings. + + For this cache type, the user should provide an already constructed + CryptographicMaterialsCache to the Hierarchical Keyring at + initialization. + """ + + def __init__( + self, + value: "aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.references.CryptographicMaterialsCache", + ): + self.value = value + + def as_dict(self) -> Dict[str, Any]: + return {"Shared": self.value.as_dict()} + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "CacheTypeShared": + from aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.references import ( + CryptographicMaterialsCache, + ) + + if len(d) != 1: + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + + return CacheTypeShared(CryptographicMaterialsCache.from_dict(d["Shared"])) + + def __repr__(self) -> str: + return f"CacheTypeShared(value=repr(self.value))" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, CacheTypeShared): + return False + return self.value == other.value + + +class CacheTypeUnknown: + """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]) -> "CacheTypeUnknown": + if len(d) != 1: + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + return CacheTypeUnknown(d["SDK_UNKNOWN_MEMBER"]["name"]) + + def __repr__(self) -> str: + return f"CacheTypeUnknown(tag={self.tag})" + + +CacheType = Union[ + CacheTypeDefault, + CacheTypeNo, + CacheTypeSingleThreaded, + CacheTypeMultiThreaded, + CacheTypeStormTracking, + CacheTypeShared, + CacheTypeUnknown, +] + + +def _cache_type_from_dict(d: Dict[str, Any]) -> CacheType: + if "Default" in d: + return CacheTypeDefault.from_dict(d) + + if "No" in d: + return CacheTypeNo.from_dict(d) + + if "SingleThreaded" in d: + return CacheTypeSingleThreaded.from_dict(d) + + if "MultiThreaded" in d: + return CacheTypeMultiThreaded.from_dict(d) + + if "StormTracking" in d: + return CacheTypeStormTracking.from_dict(d) + + if "Shared" in d: + return CacheTypeShared.from_dict(d) + + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + + +class CreateAwsKmsHierarchicalKeyringInput: + branch_key_id: Optional[str] + branch_key_id_supplier: Optional[ + "aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.references.BranchKeyIdSupplier" + ] + key_store: "aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_keystore.client.KeyStore" + ttl_seconds: int + cache: Optional[CacheType] + partition_id: Optional[str] + + def __init__( + self, + *, + key_store: "aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_keystore.client.KeyStore", + branch_key_id: Optional[str] = None, + branch_key_id_supplier: Optional[ + "aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.references.BranchKeyIdSupplier" + ] = None, + ttl_seconds: int = 0, + cache: Optional[CacheType] = None, + partition_id: Optional[str] = None, + ): + """Inputs for creating a Hierarchical Keyring. + + :param key_store: The Key Store which contains the Branch Key(s) + responsible for wrapping and unwrapping data keys. + :param branch_key_id: The identifier for the single Branch Key + responsible for wrapping and unwrapping the data key. Either + a Branch Key ID or Branch Key Supplier must be specified. + :param branch_key_id_supplier: A Branch Key Supplier which + determines what Branch Key to use to wrap and unwrap the + data key. Either a Branch Key ID or Branch Key Supplier must + be specified. + :param ttl_seconds: How many seconds the Branch Key material is + allowed to be reused within the local cache before it is re- + retrieved from Amazon DynamoDB and re-authenticated with AWS + KMS. + :param cache: Sets the type of cache for this Hierarchical + Keyring. By providing an already initialized 'Shared' cache, + users can determine the scope of the cache. That is, if the + cache is shared across other Cryptographic Material + Providers, for instance other Hierarchical Keyrings or + Caching Cryptographic Materials Managers (Caching CMMs). If + any other type of cache in the CacheType union is provided, + the Hierarchical Keyring will initialize a cache of that + type, to be used with only this Hierarchical Keyring. If not + set, a DefaultCache is initialized to be used with only this + Hierarchical Keyring with entryCapacity = 1000. + :param partition_id: Partition ID to distinguish Cryptographic + Material Providers (i.e: Keyrings) writing to a cache. If + the Partition ID is the same for two Hierarchical Keyrings + (or another Material Provider), they can share the same + cache entries in the cache. + """ + self.key_store = key_store + self.branch_key_id = branch_key_id + self.branch_key_id_supplier = branch_key_id_supplier + if (ttl_seconds is not None) and (ttl_seconds < 0): + raise ValueError("ttl_seconds must be greater than or equal to 0") + + self.ttl_seconds = ttl_seconds + self.cache = cache + self.partition_id = partition_id + + def as_dict(self) -> Dict[str, Any]: + """Converts the CreateAwsKmsHierarchicalKeyringInput to a + dictionary.""" + d: Dict[str, Any] = { + "key_store": self.key_store.as_dict(), + } + + if self.branch_key_id is not None: + d["branch_key_id"] = self.branch_key_id + + if self.branch_key_id_supplier is not None: + d["branch_key_id_supplier"] = self.branch_key_id_supplier.as_dict() + + if self.ttl_seconds is not None: + d["ttl_seconds"] = self.ttl_seconds + + if self.cache is not None: + d["cache"] = self.cache.as_dict() + + if self.partition_id is not None: + d["partition_id"] = self.partition_id + + return d + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "CreateAwsKmsHierarchicalKeyringInput": + """Creates a CreateAwsKmsHierarchicalKeyringInput from a dictionary.""" + from aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.references import ( + BranchKeyIdSupplier, + ) + from aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_keystore.client import ( + KeyStore, + ) + + kwargs: Dict[str, Any] = { + "key_store": KeyStore.from_dict(d["key_store"]), + } + + if "branch_key_id" in d: + kwargs["branch_key_id"] = d["branch_key_id"] + + if "branch_key_id_supplier" in d: + kwargs["branch_key_id_supplier"] = BranchKeyIdSupplier.from_dict( + d["branch_key_id_supplier"] + ) + + if "ttl_seconds" in d: + kwargs["ttl_seconds"] = d["ttl_seconds"] + + if "cache" in d: + kwargs["cache"] = (_cache_type_from_dict(d["cache"]),) + + if "partition_id" in d: + kwargs["partition_id"] = d["partition_id"] + + return CreateAwsKmsHierarchicalKeyringInput(**kwargs) + + def __repr__(self) -> str: + result = "CreateAwsKmsHierarchicalKeyringInput(" + if self.branch_key_id is not None: + result += f"branch_key_id={repr(self.branch_key_id)}, " + + if self.branch_key_id_supplier is not None: + result += f"branch_key_id_supplier={repr(self.branch_key_id_supplier)}, " + + if self.key_store is not None: + result += f"key_store={repr(self.key_store)}, " + + if self.ttl_seconds is not None: + result += f"ttl_seconds={repr(self.ttl_seconds)}, " + + if self.cache is not None: + result += f"cache={repr(self.cache)}, " + + if self.partition_id is not None: + result += f"partition_id={repr(self.partition_id)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, CreateAwsKmsHierarchicalKeyringInput): + return False + attributes: list[str] = [ + "branch_key_id", + "branch_key_id_supplier", + "key_store", + "ttl_seconds", + "cache", + "partition_id", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class CreateAwsKmsKeyringInput: + kms_key_id: str + kms_client: "botocore.client.BaseClient" + grant_tokens: Optional[list[str]] + + def __init__( + self, + *, + kms_key_id: str, + kms_client: "botocore.client.BaseClient", + grant_tokens: Optional[list[str]] = None, + ): + """Inputs for for creating a AWS KMS Keyring. + + :param kms_key_id: The identifier for the symmetric AWS KMS Key + responsible for wrapping and unwrapping data keys. This + should not be a AWS KMS Multi-Region Key. + :param kms_client: The KMS Client this Keyring will use to call + KMS. + :param grant_tokens: A list of grant tokens to be used when + calling KMS. + """ + self.kms_key_id = kms_key_id + self.kms_client = kms_client + self.grant_tokens = grant_tokens + + def as_dict(self) -> Dict[str, Any]: + """Converts the CreateAwsKmsKeyringInput to a dictionary.""" + d: Dict[str, Any] = { + "kms_key_id": self.kms_key_id, + "kms_client": self.kms_client, + } + + if self.grant_tokens is not None: + d["grant_tokens"] = self.grant_tokens + + return d + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "CreateAwsKmsKeyringInput": + """Creates a CreateAwsKmsKeyringInput from a dictionary.""" + from botocore.client import BaseClient + + kwargs: Dict[str, Any] = { + "kms_key_id": d["kms_key_id"], + "kms_client": d["kms_client"], + } + + if "grant_tokens" in d: + kwargs["grant_tokens"] = d["grant_tokens"] + + return CreateAwsKmsKeyringInput(**kwargs) + + def __repr__(self) -> str: + result = "CreateAwsKmsKeyringInput(" + if self.kms_key_id is not None: + result += f"kms_key_id={repr(self.kms_key_id)}, " + + if self.kms_client is not None: + result += f"kms_client={repr(self.kms_client)}, " + + if self.grant_tokens is not None: + result += f"grant_tokens={repr(self.grant_tokens)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, CreateAwsKmsKeyringInput): + return False + attributes: list[str] = [ + "kms_key_id", + "kms_client", + "grant_tokens", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class CreateAwsKmsMrkDiscoveryKeyringInput: + kms_client: "botocore.client.BaseClient" + discovery_filter: Optional[DiscoveryFilter] + grant_tokens: Optional[list[str]] + region: str + + def __init__( + self, + *, + kms_client: "botocore.client.BaseClient", + region: str, + discovery_filter: Optional[DiscoveryFilter] = None, + grant_tokens: Optional[list[str]] = None, + ): + """Inputs for for creating a AWS KMS MRK Discovery Keyring. + + :param kms_client: The KMS Client this Keyring will use to call + KMS. + :param region: The region the input 'kmsClient' is in. + :param discovery_filter: A filter which restricts which KMS Keys + this Keyring may attempt to decrypt with by AWS partition + and account. + :param grant_tokens: A list of grant tokens to be used when + calling KMS. + """ + self.kms_client = kms_client + self.region = region + self.discovery_filter = discovery_filter + self.grant_tokens = grant_tokens + + def as_dict(self) -> Dict[str, Any]: + """Converts the CreateAwsKmsMrkDiscoveryKeyringInput to a + dictionary.""" + d: Dict[str, Any] = { + "kms_client": self.kms_client, + "region": self.region, + } + + if self.discovery_filter is not None: + d["discovery_filter"] = self.discovery_filter.as_dict() + + if self.grant_tokens is not None: + d["grant_tokens"] = self.grant_tokens + + return d + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "CreateAwsKmsMrkDiscoveryKeyringInput": + """Creates a CreateAwsKmsMrkDiscoveryKeyringInput from a dictionary.""" + from botocore.client import BaseClient + + kwargs: Dict[str, Any] = { + "kms_client": d["kms_client"], + "region": d["region"], + } + + if "discovery_filter" in d: + kwargs["discovery_filter"] = DiscoveryFilter.from_dict( + d["discovery_filter"] + ) + + if "grant_tokens" in d: + kwargs["grant_tokens"] = d["grant_tokens"] + + return CreateAwsKmsMrkDiscoveryKeyringInput(**kwargs) + + def __repr__(self) -> str: + result = "CreateAwsKmsMrkDiscoveryKeyringInput(" + if self.kms_client is not None: + result += f"kms_client={repr(self.kms_client)}, " + + if self.discovery_filter is not None: + result += f"discovery_filter={repr(self.discovery_filter)}, " + + if self.grant_tokens is not None: + result += f"grant_tokens={repr(self.grant_tokens)}, " + + if self.region is not None: + result += f"region={repr(self.region)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, CreateAwsKmsMrkDiscoveryKeyringInput): + return False + attributes: list[str] = [ + "kms_client", + "discovery_filter", + "grant_tokens", + "region", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class CreateAwsKmsMrkDiscoveryMultiKeyringInput: + regions: list[str] + discovery_filter: Optional[DiscoveryFilter] + client_supplier: Optional[ + "aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.references.ClientSupplier" + ] + grant_tokens: Optional[list[str]] + + def __init__( + self, + *, + regions: list[str], + discovery_filter: Optional[DiscoveryFilter] = None, + client_supplier: Optional[ + "aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.references.ClientSupplier" + ] = None, + grant_tokens: Optional[list[str]] = None, + ): + """Inputs for for creating a AWS KMS MRK Discovery Multi-Keyring. + + :param regions: The list of regions this Keyring will creates + KMS clients for. + :param discovery_filter: A filter which restricts which KMS Keys + this Keyring may attempt to decrypt with by AWS partition + and account. + :param client_supplier: The Client Supplier which will be used + to get KMS Clients for use with this Keyring. If not + specified on input, a Default Client Supplier is created + which creates a KMS Client for each region in the 'regions' + input. + :param grant_tokens: A list of grant tokens to be used when + calling KMS. + """ + self.regions = regions + self.discovery_filter = discovery_filter + self.client_supplier = client_supplier + self.grant_tokens = grant_tokens + + def as_dict(self) -> Dict[str, Any]: + """Converts the CreateAwsKmsMrkDiscoveryMultiKeyringInput to a + dictionary.""" + d: Dict[str, Any] = { + "regions": self.regions, + } + + if self.discovery_filter is not None: + d["discovery_filter"] = self.discovery_filter.as_dict() + + if self.client_supplier is not None: + d["client_supplier"] = self.client_supplier.as_dict() + + if self.grant_tokens is not None: + d["grant_tokens"] = self.grant_tokens + + return d + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "CreateAwsKmsMrkDiscoveryMultiKeyringInput": + """Creates a CreateAwsKmsMrkDiscoveryMultiKeyringInput from a + dictionary.""" + from aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.references import ( + ClientSupplier, + ) + + kwargs: Dict[str, Any] = { + "regions": d["regions"], + } + + if "discovery_filter" in d: + kwargs["discovery_filter"] = DiscoveryFilter.from_dict( + d["discovery_filter"] + ) + + if "client_supplier" in d: + kwargs["client_supplier"] = ClientSupplier.from_dict(d["client_supplier"]) + + if "grant_tokens" in d: + kwargs["grant_tokens"] = d["grant_tokens"] + + return CreateAwsKmsMrkDiscoveryMultiKeyringInput(**kwargs) + + def __repr__(self) -> str: + result = "CreateAwsKmsMrkDiscoveryMultiKeyringInput(" + if self.regions is not None: + result += f"regions={repr(self.regions)}, " + + if self.discovery_filter is not None: + result += f"discovery_filter={repr(self.discovery_filter)}, " + + if self.client_supplier is not None: + result += f"client_supplier={repr(self.client_supplier)}, " + + if self.grant_tokens is not None: + result += f"grant_tokens={repr(self.grant_tokens)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, CreateAwsKmsMrkDiscoveryMultiKeyringInput): + return False + attributes: list[str] = [ + "regions", + "discovery_filter", + "client_supplier", + "grant_tokens", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class CreateAwsKmsMrkKeyringInput: + kms_key_id: str + kms_client: "botocore.client.BaseClient" + grant_tokens: Optional[list[str]] + + def __init__( + self, + *, + kms_key_id: str, + kms_client: "botocore.client.BaseClient", + grant_tokens: Optional[list[str]] = None, + ): + """Inputs for for creating an AWS KMS MRK Keyring. + + :param kms_key_id: The identifier for the symmetric AWS KMS Key + or AWS KMS Multi-Region Key responsible for wrapping and + unwrapping data keys. + :param kms_client: The KMS Client this Keyring will use to call + KMS. + :param grant_tokens: A list of grant tokens to be used when + calling KMS. + """ + self.kms_key_id = kms_key_id + self.kms_client = kms_client + self.grant_tokens = grant_tokens + + def as_dict(self) -> Dict[str, Any]: + """Converts the CreateAwsKmsMrkKeyringInput to a dictionary.""" + d: Dict[str, Any] = { + "kms_key_id": self.kms_key_id, + "kms_client": self.kms_client, + } + + if self.grant_tokens is not None: + d["grant_tokens"] = self.grant_tokens + + return d + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "CreateAwsKmsMrkKeyringInput": + """Creates a CreateAwsKmsMrkKeyringInput from a dictionary.""" + from botocore.client import BaseClient + + kwargs: Dict[str, Any] = { + "kms_key_id": d["kms_key_id"], + "kms_client": d["kms_client"], + } + + if "grant_tokens" in d: + kwargs["grant_tokens"] = d["grant_tokens"] + + return CreateAwsKmsMrkKeyringInput(**kwargs) + + def __repr__(self) -> str: + result = "CreateAwsKmsMrkKeyringInput(" + if self.kms_key_id is not None: + result += f"kms_key_id={repr(self.kms_key_id)}, " + + if self.kms_client is not None: + result += f"kms_client={repr(self.kms_client)}, " + + if self.grant_tokens is not None: + result += f"grant_tokens={repr(self.grant_tokens)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, CreateAwsKmsMrkKeyringInput): + return False + attributes: list[str] = [ + "kms_key_id", + "kms_client", + "grant_tokens", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class CreateAwsKmsMrkMultiKeyringInput: + generator: Optional[str] + kms_key_ids: Optional[list[str]] + client_supplier: Optional[ + "aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.references.ClientSupplier" + ] + grant_tokens: Optional[list[str]] + + def __init__( + self, + *, + generator: Optional[str] = None, + kms_key_ids: Optional[list[str]] = None, + client_supplier: Optional[ + "aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.references.ClientSupplier" + ] = None, + grant_tokens: Optional[list[str]] = None, + ): + """Inputs for for creating a AWS KMS MRK Multi-Keyring. + + :param generator: A symmetric AWS KMS Key or AWS KMS Multi- + Region Key responsible for wrapping and unwrapping data + keys. KMS.GenerateDataKey may be called with this key if the + data key has not already been generated by another Keyring. + :param kms_key_ids: A list of identifiers for the symmetric AWS + KMS Keys and/or AWS KMS Multi-Region Keys (other than the + generator) responsible for wrapping and unwrapping data + keys. + :param client_supplier: The Client Supplier which will be used + to get KMS Clients for use with this Keyring. The Client + Supplier will create a client for each region specified in + the generator and kmsKeyIds ARNs. If not specified on input, + the Default Client Supplier is used. + :param grant_tokens: A list of grant tokens to be used when + calling KMS. + """ + self.generator = generator + self.kms_key_ids = kms_key_ids + self.client_supplier = client_supplier + self.grant_tokens = grant_tokens + + def as_dict(self) -> Dict[str, Any]: + """Converts the CreateAwsKmsMrkMultiKeyringInput to a dictionary.""" + d: Dict[str, Any] = {} + + if self.generator is not None: + d["generator"] = self.generator + + if self.kms_key_ids is not None: + d["kms_key_ids"] = self.kms_key_ids + + if self.client_supplier is not None: + d["client_supplier"] = self.client_supplier.as_dict() + + if self.grant_tokens is not None: + d["grant_tokens"] = self.grant_tokens + + return d + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "CreateAwsKmsMrkMultiKeyringInput": + """Creates a CreateAwsKmsMrkMultiKeyringInput from a dictionary.""" + from aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.references import ( + ClientSupplier, + ) + + kwargs: Dict[str, Any] = {} + + if "generator" in d: + kwargs["generator"] = d["generator"] + + if "kms_key_ids" in d: + kwargs["kms_key_ids"] = d["kms_key_ids"] + + if "client_supplier" in d: + kwargs["client_supplier"] = ClientSupplier.from_dict(d["client_supplier"]) + + if "grant_tokens" in d: + kwargs["grant_tokens"] = d["grant_tokens"] + + return CreateAwsKmsMrkMultiKeyringInput(**kwargs) + + def __repr__(self) -> str: + result = "CreateAwsKmsMrkMultiKeyringInput(" + if self.generator is not None: + result += f"generator={repr(self.generator)}, " + + if self.kms_key_ids is not None: + result += f"kms_key_ids={repr(self.kms_key_ids)}, " + + if self.client_supplier is not None: + result += f"client_supplier={repr(self.client_supplier)}, " + + if self.grant_tokens is not None: + result += f"grant_tokens={repr(self.grant_tokens)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, CreateAwsKmsMrkMultiKeyringInput): + return False + attributes: list[str] = [ + "generator", + "kms_key_ids", + "client_supplier", + "grant_tokens", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class CreateAwsKmsMultiKeyringInput: + generator: Optional[str] + kms_key_ids: Optional[list[str]] + client_supplier: Optional[ + "aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.references.ClientSupplier" + ] + grant_tokens: Optional[list[str]] + + def __init__( + self, + *, + generator: Optional[str] = None, + kms_key_ids: Optional[list[str]] = None, + client_supplier: Optional[ + "aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.references.ClientSupplier" + ] = None, + grant_tokens: Optional[list[str]] = None, + ): + """Inputs for for creating a AWS KMS Multi-Keyring. + + :param generator: A identifier for a symmetric AWS KMS Key + responsible for wrapping and unwrapping data keys. + KMS.GenerateDataKey may be called with this key if the data + key has not already been generated by another Keyring. This + should not be a AWS KMS Multi-Region Key. + :param kms_key_ids: A list of identifiers for the symmetric AWS + KMS Keys (other than the generator) responsible for wrapping + and unwrapping data keys. This list should not contain AWS + KMS Multi-Region Keys. + :param client_supplier: The Client Supplier which will be used + to get KMS Clients for use with this Keyring. The Client + Supplier will create a client for each region specified in + the generator and kmsKeyIds ARNs. If not specified on input, + the Default Client Supplier is used. + :param grant_tokens: A list of grant tokens to be used when + calling KMS. + """ + self.generator = generator + self.kms_key_ids = kms_key_ids + self.client_supplier = client_supplier + self.grant_tokens = grant_tokens + + def as_dict(self) -> Dict[str, Any]: + """Converts the CreateAwsKmsMultiKeyringInput to a dictionary.""" + d: Dict[str, Any] = {} + + if self.generator is not None: + d["generator"] = self.generator + + if self.kms_key_ids is not None: + d["kms_key_ids"] = self.kms_key_ids + + if self.client_supplier is not None: + d["client_supplier"] = self.client_supplier.as_dict() + + if self.grant_tokens is not None: + d["grant_tokens"] = self.grant_tokens + + return d + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "CreateAwsKmsMultiKeyringInput": + """Creates a CreateAwsKmsMultiKeyringInput from a dictionary.""" + from aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.references import ( + ClientSupplier, + ) + + kwargs: Dict[str, Any] = {} + + if "generator" in d: + kwargs["generator"] = d["generator"] + + if "kms_key_ids" in d: + kwargs["kms_key_ids"] = d["kms_key_ids"] + + if "client_supplier" in d: + kwargs["client_supplier"] = ClientSupplier.from_dict(d["client_supplier"]) + + if "grant_tokens" in d: + kwargs["grant_tokens"] = d["grant_tokens"] + + return CreateAwsKmsMultiKeyringInput(**kwargs) + + def __repr__(self) -> str: + result = "CreateAwsKmsMultiKeyringInput(" + if self.generator is not None: + result += f"generator={repr(self.generator)}, " + + if self.kms_key_ids is not None: + result += f"kms_key_ids={repr(self.kms_key_ids)}, " + + if self.client_supplier is not None: + result += f"client_supplier={repr(self.client_supplier)}, " + + if self.grant_tokens is not None: + result += f"grant_tokens={repr(self.grant_tokens)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, CreateAwsKmsMultiKeyringInput): + return False + attributes: list[str] = [ + "generator", + "kms_key_ids", + "client_supplier", + "grant_tokens", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class CreateAwsKmsRsaKeyringInput: + public_key: Optional[bytes | bytearray] + kms_key_id: str + encryption_algorithm: str + kms_client: Optional["botocore.client.BaseClient"] + grant_tokens: Optional[list[str]] + + def __init__( + self, + *, + kms_key_id: str, + encryption_algorithm: str, + public_key: Optional[bytes | bytearray] = None, + kms_client: Optional["botocore.client.BaseClient"] = None, + grant_tokens: Optional[list[str]] = None, + ): + """Inputs for creating a AWS KMS RSA Keyring. + + :param kms_key_id: The ARN for the asymmetric AWS KMS Key for + RSA responsible for wrapping and unwrapping data keys. + :param encryption_algorithm: The RSA algorithm used to wrap and + unwrap data keys. + :param public_key: The public RSA Key responsible for wrapping + data keys, as a UTF8 encoded, PEM encoded X.509 + SubjectPublicKeyInfo structure. This should be the public + key as exported from KMS. If not specified, this Keyring + cannot be used on encrypt. + :param kms_client: The KMS Client this Keyring will use to call + KMS. + :param grant_tokens: A list of grant tokens to be used when + calling KMS. + """ + self.kms_key_id = kms_key_id + self.encryption_algorithm = encryption_algorithm + self.public_key = public_key + self.kms_client = kms_client + self.grant_tokens = grant_tokens + + def as_dict(self) -> Dict[str, Any]: + """Converts the CreateAwsKmsRsaKeyringInput to a dictionary.""" + d: Dict[str, Any] = { + "kms_key_id": self.kms_key_id, + "encryption_algorithm": self.encryption_algorithm, + } + + if self.public_key is not None: + d["public_key"] = self.public_key + + if self.kms_client is not None: + d["kms_client"] = self.kms_client + + if self.grant_tokens is not None: + d["grant_tokens"] = self.grant_tokens + + return d + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "CreateAwsKmsRsaKeyringInput": + """Creates a CreateAwsKmsRsaKeyringInput from a dictionary.""" + from botocore.client import BaseClient + + kwargs: Dict[str, Any] = { + "kms_key_id": d["kms_key_id"], + "encryption_algorithm": d["encryption_algorithm"], + } + + if "public_key" in d: + kwargs["public_key"] = d["public_key"] + + if "kms_client" in d: + kwargs["kms_client"] = d["kms_client"] + + if "grant_tokens" in d: + kwargs["grant_tokens"] = d["grant_tokens"] + + return CreateAwsKmsRsaKeyringInput(**kwargs) + + def __repr__(self) -> str: + result = "CreateAwsKmsRsaKeyringInput(" + if self.public_key is not None: + result += f"public_key={repr(self.public_key)}, " + + if self.kms_key_id is not None: + result += f"kms_key_id={repr(self.kms_key_id)}, " + + if self.encryption_algorithm is not None: + result += f"encryption_algorithm={repr(self.encryption_algorithm)}, " + + if self.kms_client is not None: + result += f"kms_client={repr(self.kms_client)}, " + + if self.grant_tokens is not None: + result += f"grant_tokens={repr(self.grant_tokens)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, CreateAwsKmsRsaKeyringInput): + return False + attributes: list[str] = [ + "public_key", + "kms_key_id", + "encryption_algorithm", + "kms_client", + "grant_tokens", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class CreateCryptographicMaterialsCacheInput: + cache: CacheType + + def __init__( + self, + *, + cache: CacheType, + ): + """ + :param cache: Which type of local cache to use. + """ + self.cache = cache + + def as_dict(self) -> Dict[str, Any]: + """Converts the CreateCryptographicMaterialsCacheInput to a + dictionary.""" + return { + "cache": self.cache.as_dict(), + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "CreateCryptographicMaterialsCacheInput": + """Creates a CreateCryptographicMaterialsCacheInput from a + dictionary.""" + kwargs: Dict[str, Any] = { + "cache": _cache_type_from_dict(d["cache"]), + } + + return CreateCryptographicMaterialsCacheInput(**kwargs) + + def __repr__(self) -> str: + result = "CreateCryptographicMaterialsCacheInput(" + if self.cache is not None: + result += f"cache={repr(self.cache)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, CreateCryptographicMaterialsCacheInput): + return False + attributes: list[str] = [ + "cache", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class CreateDefaultClientSupplierInput: + def as_dict(self) -> Dict[str, Any]: + """Converts the CreateDefaultClientSupplierInput to a dictionary.""" + return {} + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "CreateDefaultClientSupplierInput": + """Creates a CreateDefaultClientSupplierInput from a dictionary.""" + return CreateDefaultClientSupplierInput() + + def __repr__(self) -> str: + result = "CreateDefaultClientSupplierInput(" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + return isinstance(other, CreateDefaultClientSupplierInput) + + +class CreateDefaultCryptographicMaterialsManagerInput: + keyring: "aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.references.Keyring" + + def __init__( + self, + *, + keyring: "aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.references.Keyring", + ): + """Inputs for creating a Default Cryptographic Materials Manager. + + :param keyring: The Keyring that the created Default + Cryprographic Materials Manager will use to wrap data keys. + """ + self.keyring = keyring + + def as_dict(self) -> Dict[str, Any]: + """Converts the CreateDefaultCryptographicMaterialsManagerInput to a + dictionary.""" + return { + "keyring": self.keyring.as_dict(), + } + + @staticmethod + def from_dict( + d: Dict[str, Any] + ) -> "CreateDefaultCryptographicMaterialsManagerInput": + """Creates a CreateDefaultCryptographicMaterialsManagerInput from a + dictionary.""" + from aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.references import ( + Keyring, + ) + + kwargs: Dict[str, Any] = { + "keyring": Keyring.from_dict(d["keyring"]), + } + + return CreateDefaultCryptographicMaterialsManagerInput(**kwargs) + + def __repr__(self) -> str: + result = "CreateDefaultCryptographicMaterialsManagerInput(" + if self.keyring is not None: + result += f"keyring={repr(self.keyring)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, CreateDefaultCryptographicMaterialsManagerInput): + return False + attributes: list[str] = [ + "keyring", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class CreateMultiKeyringInput: + generator: Optional[ + "aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.references.Keyring" + ] + child_keyrings: list[ + "aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.references.Keyring" + ] + + def __init__( + self, + *, + child_keyrings: list[ + "aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.references.Keyring" + ], + generator: Optional[ + "aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.references.Keyring" + ] = None, + ): + """Inputs for creating a Multi-Keyring. + + :param child_keyrings: A list of keyrings (other than the + generator) responsible for wrapping and unwrapping the data + key. + :param generator: A keyring responsible for wrapping and + unwrapping the data key. This is the first keyring that will + be used to wrap the data key, and may be responsible for + additionally generating the data key. + """ + self.child_keyrings = child_keyrings + self.generator = generator + + def as_dict(self) -> Dict[str, Any]: + """Converts the CreateMultiKeyringInput to a dictionary.""" + d: Dict[str, Any] = { + "child_keyrings": self.child_keyrings, + } + + if self.generator is not None: + d["generator"] = self.generator.as_dict() + + return d + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "CreateMultiKeyringInput": + """Creates a CreateMultiKeyringInput from a dictionary.""" + from aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.references import ( + Keyring, + ) + + kwargs: Dict[str, Any] = { + "child_keyrings": d["child_keyrings"], + } + + if "generator" in d: + kwargs["generator"] = Keyring.from_dict(d["generator"]) + + return CreateMultiKeyringInput(**kwargs) + + def __repr__(self) -> str: + result = "CreateMultiKeyringInput(" + if self.generator is not None: + result += f"generator={repr(self.generator)}, " + + if self.child_keyrings is not None: + result += f"child_keyrings={repr(self.child_keyrings)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, CreateMultiKeyringInput): + return False + attributes: list[str] = [ + "generator", + "child_keyrings", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class CreateRawAesKeyringInput: + key_namespace: str + key_name: str + wrapping_key: bytes | bytearray + wrapping_alg: str + + def __init__( + self, + *, + key_namespace: str, + key_name: str, + wrapping_key: bytes | bytearray, + wrapping_alg: str, + ): + """Inputs for creating a Raw AES Keyring. + + :param key_namespace: A namespace associated with this wrapping + key. + :param key_name: A name associated with this wrapping key. + :param wrapping_key: The AES key used with AES_GCM encryption + and decryption. + :param wrapping_alg: The AES_GCM algorithm this Keyring uses to + wrap and unwrap data keys. + """ + self.key_namespace = key_namespace + self.key_name = key_name + self.wrapping_key = wrapping_key + self.wrapping_alg = wrapping_alg + + def as_dict(self) -> Dict[str, Any]: + """Converts the CreateRawAesKeyringInput to a dictionary.""" + return { + "key_namespace": self.key_namespace, + "key_name": self.key_name, + "wrapping_key": self.wrapping_key, + "wrapping_alg": self.wrapping_alg, + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "CreateRawAesKeyringInput": + """Creates a CreateRawAesKeyringInput from a dictionary.""" + kwargs: Dict[str, Any] = { + "key_namespace": d["key_namespace"], + "key_name": d["key_name"], + "wrapping_key": d["wrapping_key"], + "wrapping_alg": d["wrapping_alg"], + } + + return CreateRawAesKeyringInput(**kwargs) + + def __repr__(self) -> str: + result = "CreateRawAesKeyringInput(" + if self.key_namespace is not None: + result += f"key_namespace={repr(self.key_namespace)}, " + + if self.key_name is not None: + result += f"key_name={repr(self.key_name)}, " + + if self.wrapping_key is not None: + result += f"wrapping_key={repr(self.wrapping_key)}, " + + if self.wrapping_alg is not None: + result += f"wrapping_alg={repr(self.wrapping_alg)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, CreateRawAesKeyringInput): + return False + attributes: list[str] = [ + "key_namespace", + "key_name", + "wrapping_key", + "wrapping_alg", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class EphemeralPrivateKeyToStaticPublicKeyInput: + recipient_public_key: bytes | bytearray + + def __init__( + self, + *, + recipient_public_key: bytes | bytearray, + ): + """Inputs for creating a EphemeralPrivateKeyToStaticPublicKey + Configuration. + + :param recipient_public_key: The recipient's public key. MUST be + DER encoded. + """ + self.recipient_public_key = recipient_public_key + + def as_dict(self) -> Dict[str, Any]: + """Converts the EphemeralPrivateKeyToStaticPublicKeyInput to a + dictionary.""" + return { + "recipient_public_key": self.recipient_public_key, + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "EphemeralPrivateKeyToStaticPublicKeyInput": + """Creates a EphemeralPrivateKeyToStaticPublicKeyInput from a + dictionary.""" + kwargs: Dict[str, Any] = { + "recipient_public_key": d["recipient_public_key"], + } + + return EphemeralPrivateKeyToStaticPublicKeyInput(**kwargs) + + def __repr__(self) -> str: + result = "EphemeralPrivateKeyToStaticPublicKeyInput(" + if self.recipient_public_key is not None: + result += f"recipient_public_key={repr(self.recipient_public_key)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, EphemeralPrivateKeyToStaticPublicKeyInput): + return False + attributes: list[str] = [ + "recipient_public_key", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class PublicKeyDiscoveryInput: + recipient_static_private_key: bytes | bytearray + + def __init__( + self, + *, + recipient_static_private_key: bytes | bytearray, + ): + """Inputs for creating a PublicKeyDiscovery Configuration. + + :param recipient_static_private_key: The sender's private key. + MUST be PEM encoded. + """ + self.recipient_static_private_key = recipient_static_private_key + + def as_dict(self) -> Dict[str, Any]: + """Converts the PublicKeyDiscoveryInput to a dictionary.""" + return { + "recipient_static_private_key": self.recipient_static_private_key, + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "PublicKeyDiscoveryInput": + """Creates a PublicKeyDiscoveryInput from a dictionary.""" + kwargs: Dict[str, Any] = { + "recipient_static_private_key": d["recipient_static_private_key"], + } + + return PublicKeyDiscoveryInput(**kwargs) + + def __repr__(self) -> str: + result = "PublicKeyDiscoveryInput(" + if self.recipient_static_private_key is not None: + result += f"recipient_static_private_key={repr(self.recipient_static_private_key)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, PublicKeyDiscoveryInput): + return False + attributes: list[str] = [ + "recipient_static_private_key", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class RawPrivateKeyToStaticPublicKeyInput: + sender_static_private_key: bytes | bytearray + recipient_public_key: bytes | bytearray + + def __init__( + self, + *, + sender_static_private_key: bytes | bytearray, + recipient_public_key: bytes | bytearray, + ): + """Inputs for creating a RawPrivateKeyToStaticPublicKey Configuration. + + :param sender_static_private_key: The sender's private key. MUST + be PEM encoded. + :param recipient_public_key: The recipient's public key. MUST be + DER encoded. + """ + self.sender_static_private_key = sender_static_private_key + self.recipient_public_key = recipient_public_key + + def as_dict(self) -> Dict[str, Any]: + """Converts the RawPrivateKeyToStaticPublicKeyInput to a dictionary.""" + return { + "sender_static_private_key": self.sender_static_private_key, + "recipient_public_key": self.recipient_public_key, + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "RawPrivateKeyToStaticPublicKeyInput": + """Creates a RawPrivateKeyToStaticPublicKeyInput from a dictionary.""" + kwargs: Dict[str, Any] = { + "sender_static_private_key": d["sender_static_private_key"], + "recipient_public_key": d["recipient_public_key"], + } + + return RawPrivateKeyToStaticPublicKeyInput(**kwargs) + + def __repr__(self) -> str: + result = "RawPrivateKeyToStaticPublicKeyInput(" + if self.sender_static_private_key is not None: + result += ( + f"sender_static_private_key={repr(self.sender_static_private_key)}, " + ) + + if self.recipient_public_key is not None: + result += f"recipient_public_key={repr(self.recipient_public_key)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, RawPrivateKeyToStaticPublicKeyInput): + return False + attributes: list[str] = [ + "sender_static_private_key", + "recipient_public_key", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class RawEcdhStaticConfigurationsPublicKeyDiscovery: + """Inputs for creating a PublicKeyDiscovery Configuration.""" + + def __init__(self, value: PublicKeyDiscoveryInput): + self.value = value + + def as_dict(self) -> Dict[str, Any]: + return {"PublicKeyDiscovery": self.value.as_dict()} + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "RawEcdhStaticConfigurationsPublicKeyDiscovery": + if len(d) != 1: + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + + return RawEcdhStaticConfigurationsPublicKeyDiscovery( + PublicKeyDiscoveryInput.from_dict(d["PublicKeyDiscovery"]) + ) + + def __repr__(self) -> str: + return f"RawEcdhStaticConfigurationsPublicKeyDiscovery(value=repr(self.value))" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, RawEcdhStaticConfigurationsPublicKeyDiscovery): + return False + return self.value == other.value + + +class RawEcdhStaticConfigurationsRawPrivateKeyToStaticPublicKey: + """Inputs for creating a RawPrivateKeyToStaticPublicKey Configuration.""" + + def __init__(self, value: RawPrivateKeyToStaticPublicKeyInput): + self.value = value + + def as_dict(self) -> Dict[str, Any]: + return {"RawPrivateKeyToStaticPublicKey": self.value.as_dict()} + + @staticmethod + def from_dict( + d: Dict[str, Any] + ) -> "RawEcdhStaticConfigurationsRawPrivateKeyToStaticPublicKey": + if len(d) != 1: + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + + return RawEcdhStaticConfigurationsRawPrivateKeyToStaticPublicKey( + RawPrivateKeyToStaticPublicKeyInput.from_dict( + d["RawPrivateKeyToStaticPublicKey"] + ) + ) + + def __repr__(self) -> str: + return f"RawEcdhStaticConfigurationsRawPrivateKeyToStaticPublicKey(value=repr(self.value))" + + def __eq__(self, other: Any) -> bool: + if not isinstance( + other, RawEcdhStaticConfigurationsRawPrivateKeyToStaticPublicKey + ): + return False + return self.value == other.value + + +class RawEcdhStaticConfigurationsEphemeralPrivateKeyToStaticPublicKey: + """Inputs for creating a EphemeralPrivateKeyToStaticPublicKey + Configuration.""" + + def __init__(self, value: EphemeralPrivateKeyToStaticPublicKeyInput): + self.value = value + + def as_dict(self) -> Dict[str, Any]: + return {"EphemeralPrivateKeyToStaticPublicKey": self.value.as_dict()} + + @staticmethod + def from_dict( + d: Dict[str, Any] + ) -> "RawEcdhStaticConfigurationsEphemeralPrivateKeyToStaticPublicKey": + if len(d) != 1: + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + + return RawEcdhStaticConfigurationsEphemeralPrivateKeyToStaticPublicKey( + EphemeralPrivateKeyToStaticPublicKeyInput.from_dict( + d["EphemeralPrivateKeyToStaticPublicKey"] + ) + ) + + def __repr__(self) -> str: + return f"RawEcdhStaticConfigurationsEphemeralPrivateKeyToStaticPublicKey(value=repr(self.value))" + + def __eq__(self, other: Any) -> bool: + if not isinstance( + other, RawEcdhStaticConfigurationsEphemeralPrivateKeyToStaticPublicKey + ): + return False + return self.value == other.value + + +class RawEcdhStaticConfigurationsUnknown: + """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]) -> "RawEcdhStaticConfigurationsUnknown": + if len(d) != 1: + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + return RawEcdhStaticConfigurationsUnknown(d["SDK_UNKNOWN_MEMBER"]["name"]) + + def __repr__(self) -> str: + return f"RawEcdhStaticConfigurationsUnknown(tag={self.tag})" + + +# List of configurations when using RawEcdhStaticConfigurations. +RawEcdhStaticConfigurations = Union[ + RawEcdhStaticConfigurationsPublicKeyDiscovery, + RawEcdhStaticConfigurationsRawPrivateKeyToStaticPublicKey, + RawEcdhStaticConfigurationsEphemeralPrivateKeyToStaticPublicKey, + RawEcdhStaticConfigurationsUnknown, +] + + +def _raw_ecdh_static_configurations_from_dict( + d: Dict[str, Any] +) -> RawEcdhStaticConfigurations: + if "PublicKeyDiscovery" in d: + return RawEcdhStaticConfigurationsPublicKeyDiscovery.from_dict(d) + + if "RawPrivateKeyToStaticPublicKey" in d: + return RawEcdhStaticConfigurationsRawPrivateKeyToStaticPublicKey.from_dict(d) + + if "EphemeralPrivateKeyToStaticPublicKey" in d: + return ( + RawEcdhStaticConfigurationsEphemeralPrivateKeyToStaticPublicKey.from_dict(d) + ) + + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + + +class CreateRawEcdhKeyringInput: + key_agreement_scheme: RawEcdhStaticConfigurations + curve_spec: str + + def __init__( + self, + *, + key_agreement_scheme: RawEcdhStaticConfigurations, + curve_spec: str, + ): + """Inputs for creating a raw ECDH Keyring. + + :param key_agreement_scheme: The Key Agreement Scheme + configuration that is responsible for how the shared secret + is calculated. + :param curve_spec: The the curve on which the points for the + sender's private and recipient's public key lie. + """ + self.key_agreement_scheme = key_agreement_scheme + self.curve_spec = curve_spec + + def as_dict(self) -> Dict[str, Any]: + """Converts the CreateRawEcdhKeyringInput to a dictionary.""" + return { + "key_agreement_scheme": self.key_agreement_scheme.as_dict(), + "curve_spec": self.curve_spec, + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "CreateRawEcdhKeyringInput": + """Creates a CreateRawEcdhKeyringInput from a dictionary.""" + kwargs: Dict[str, Any] = { + "key_agreement_scheme": _raw_ecdh_static_configurations_from_dict( + d["key_agreement_scheme"] + ), + "curve_spec": d["curve_spec"], + } + + return CreateRawEcdhKeyringInput(**kwargs) + + def __repr__(self) -> str: + result = "CreateRawEcdhKeyringInput(" + if self.key_agreement_scheme is not None: + result += f"key_agreement_scheme={repr(self.key_agreement_scheme)}, " + + if self.curve_spec is not None: + result += f"curve_spec={repr(self.curve_spec)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, CreateRawEcdhKeyringInput): + return False + attributes: list[str] = [ + "key_agreement_scheme", + "curve_spec", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class PaddingScheme: + PKCS1 = "PKCS1" + + OAEP_SHA1_MGF1 = "OAEP_SHA1_MGF1" + + OAEP_SHA256_MGF1 = "OAEP_SHA256_MGF1" + + OAEP_SHA384_MGF1 = "OAEP_SHA384_MGF1" + + OAEP_SHA512_MGF1 = "OAEP_SHA512_MGF1" + + # This set contains every possible value known at the time this was generated. New + # values may be added in the future. + values = frozenset( + { + "PKCS1", + "OAEP_SHA1_MGF1", + "OAEP_SHA256_MGF1", + "OAEP_SHA384_MGF1", + "OAEP_SHA512_MGF1", + } + ) + + +class CreateRawRsaKeyringInput: + key_namespace: str + key_name: str + padding_scheme: str + public_key: Optional[bytes | bytearray] + private_key: Optional[bytes | bytearray] + + def __init__( + self, + *, + key_namespace: str, + key_name: str, + padding_scheme: str, + public_key: Optional[bytes | bytearray] = None, + private_key: Optional[bytes | bytearray] = None, + ): + """Inputs for creating a Raw RAW Keyring. + + :param key_namespace: A namespace associated with this wrapping + key. + :param key_name: A name associated with this wrapping key. + :param padding_scheme: The RSA padding scheme to use with this + keyring. + :param public_key: The public RSA Key responsible for wrapping + data keys, as a UTF8 encoded, PEM encoded X.509 + SubjectPublicKeyInfo structure. If not specified, this + Keyring cannot be used on encrypt. A public key and/or a + private key must be specified. + :param private_key: The private RSA Key responsible for wrapping + data keys, as a UTF8 encoded, PEM encoded PKCS #8 + PrivateKeyInfo structure. If not specified, this Keyring + cannot be used on decrypt. A public key and/or a private key + must be specified. + """ + self.key_namespace = key_namespace + self.key_name = key_name + self.padding_scheme = padding_scheme + self.public_key = public_key + self.private_key = private_key + + def as_dict(self) -> Dict[str, Any]: + """Converts the CreateRawRsaKeyringInput to a dictionary.""" + d: Dict[str, Any] = { + "key_namespace": self.key_namespace, + "key_name": self.key_name, + "padding_scheme": self.padding_scheme, + } + + if self.public_key is not None: + d["public_key"] = self.public_key + + if self.private_key is not None: + d["private_key"] = self.private_key + + return d + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "CreateRawRsaKeyringInput": + """Creates a CreateRawRsaKeyringInput from a dictionary.""" + kwargs: Dict[str, Any] = { + "key_namespace": d["key_namespace"], + "key_name": d["key_name"], + "padding_scheme": d["padding_scheme"], + } + + if "public_key" in d: + kwargs["public_key"] = d["public_key"] + + if "private_key" in d: + kwargs["private_key"] = d["private_key"] + + return CreateRawRsaKeyringInput(**kwargs) + + def __repr__(self) -> str: + result = "CreateRawRsaKeyringInput(" + if self.key_namespace is not None: + result += f"key_namespace={repr(self.key_namespace)}, " + + if self.key_name is not None: + result += f"key_name={repr(self.key_name)}, " + + if self.padding_scheme is not None: + result += f"padding_scheme={repr(self.padding_scheme)}, " + + if self.public_key is not None: + result += f"public_key={repr(self.public_key)}, " + + if self.private_key is not None: + result += f"private_key={repr(self.private_key)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, CreateRawRsaKeyringInput): + return False + attributes: list[str] = [ + "key_namespace", + "key_name", + "padding_scheme", + "public_key", + "private_key", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class CreateRequiredEncryptionContextCMMInput: + underlying_cmm: Optional[ + "aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.references.CryptographicMaterialsManager" + ] + keyring: Optional[ + "aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.references.Keyring" + ] + required_encryption_context_keys: list[str] + + def __init__( + self, + *, + required_encryption_context_keys: list[str], + underlying_cmm: Optional[ + "aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.references.CryptographicMaterialsManager" + ] = None, + keyring: Optional[ + "aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.references.Keyring" + ] = None, + ): + """Inputs for creating an Required Encryption Context Cryptographic + Materials Manager. + + :param required_encryption_context_keys: A list of Encryption + Context keys which are required to be supplied during + encryption and decryption, and correspond to Encryption + Context key-value pairs which are not stored on the + resulting message. + :param underlying_cmm: The Cryprographic Materials Manager that + the created Required Encryption Context Cryptographic + Materials Manager will delegate to. Either a Keyring or + underlying Cryprographic Materials Manager must be + specified. + :param keyring: The Keyring that the created Cryprographic + Materials Manager will use to wrap data keys. The created + Required Encryption Context CMM will delegate to a Default + Cryptographic Materials Manager created with this Keyring. + Either a Keyring or an underlying Cryprographic Materials + Manager must be specified as input. + """ + self.required_encryption_context_keys = required_encryption_context_keys + self.underlying_cmm = underlying_cmm + self.keyring = keyring + + def as_dict(self) -> Dict[str, Any]: + """Converts the CreateRequiredEncryptionContextCMMInput to a + dictionary.""" + d: Dict[str, Any] = { + "required_encryption_context_keys": self.required_encryption_context_keys, + } + + if self.underlying_cmm is not None: + d["underlying_cmm"] = self.underlying_cmm.as_dict() + + if self.keyring is not None: + d["keyring"] = self.keyring.as_dict() + + return d + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "CreateRequiredEncryptionContextCMMInput": + """Creates a CreateRequiredEncryptionContextCMMInput from a + dictionary.""" + from aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.references import ( + CryptographicMaterialsManager, + ) + from aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.references import ( + Keyring, + ) + + kwargs: Dict[str, Any] = { + "required_encryption_context_keys": d["required_encryption_context_keys"], + } + + if "underlying_cmm" in d: + kwargs["underlying_cmm"] = CryptographicMaterialsManager.from_dict( + d["underlying_cmm"] + ) + + if "keyring" in d: + kwargs["keyring"] = Keyring.from_dict(d["keyring"]) + + return CreateRequiredEncryptionContextCMMInput(**kwargs) + + def __repr__(self) -> str: + result = "CreateRequiredEncryptionContextCMMInput(" + if self.underlying_cmm is not None: + result += f"underlying_cmm={repr(self.underlying_cmm)}, " + + if self.keyring is not None: + result += f"keyring={repr(self.keyring)}, " + + if self.required_encryption_context_keys is not None: + result += f"required_encryption_context_keys={repr(self.required_encryption_context_keys)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, CreateRequiredEncryptionContextCMMInput): + return False + attributes: list[str] = [ + "underlying_cmm", + "keyring", + "required_encryption_context_keys", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class DeleteCacheEntryInput: + identifier: bytes | bytearray + + def __init__( + self, + *, + identifier: bytes | bytearray, + ): + self.identifier = identifier + + def as_dict(self) -> Dict[str, Any]: + """Converts the DeleteCacheEntryInput to a dictionary.""" + return { + "identifier": self.identifier, + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "DeleteCacheEntryInput": + """Creates a DeleteCacheEntryInput from a dictionary.""" + kwargs: Dict[str, Any] = { + "identifier": d["identifier"], + } + + return DeleteCacheEntryInput(**kwargs) + + def __repr__(self) -> str: + result = "DeleteCacheEntryInput(" + if self.identifier is not None: + result += f"identifier={repr(self.identifier)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, DeleteCacheEntryInput): + return False + attributes: list[str] = [ + "identifier", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class GetCacheEntryInput: + identifier: bytes | bytearray + bytes_used: Optional[int] + + def __init__( + self, + *, + identifier: bytes | bytearray, + bytes_used: Optional[int] = None, + ): + self.identifier = identifier + self.bytes_used = bytes_used + + def as_dict(self) -> Dict[str, Any]: + """Converts the GetCacheEntryInput to a dictionary.""" + d: Dict[str, Any] = { + "identifier": self.identifier, + } + + if self.bytes_used is not None: + d["bytes_used"] = self.bytes_used + + return d + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "GetCacheEntryInput": + """Creates a GetCacheEntryInput from a dictionary.""" + kwargs: Dict[str, Any] = { + "identifier": d["identifier"], + } + + if "bytes_used" in d: + kwargs["bytes_used"] = d["bytes_used"] + + return GetCacheEntryInput(**kwargs) + + def __repr__(self) -> str: + result = "GetCacheEntryInput(" + if self.identifier is not None: + result += f"identifier={repr(self.identifier)}, " + + if self.bytes_used is not None: + result += f"bytes_used={repr(self.bytes_used)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, GetCacheEntryInput): + return False + attributes: list[str] = [ + "identifier", + "bytes_used", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class DecryptionMaterials: + algorithm_suite: AlgorithmSuiteInfo + encryption_context: dict[str, str] + required_encryption_context_keys: list[str] + plaintext_data_key: Optional[bytes | bytearray] + verification_key: Optional[bytes | bytearray] + symmetric_signing_key: Optional[bytes | bytearray] + + def __init__( + self, + *, + algorithm_suite: AlgorithmSuiteInfo, + encryption_context: dict[str, str], + required_encryption_context_keys: list[str], + plaintext_data_key: Optional[bytes | bytearray] = None, + verification_key: Optional[bytes | bytearray] = None, + symmetric_signing_key: Optional[bytes | bytearray] = None, + ): + self.algorithm_suite = algorithm_suite + self.encryption_context = encryption_context + self.required_encryption_context_keys = required_encryption_context_keys + self.plaintext_data_key = plaintext_data_key + self.verification_key = verification_key + self.symmetric_signing_key = symmetric_signing_key + + def as_dict(self) -> Dict[str, Any]: + """Converts the DecryptionMaterials to a dictionary.""" + d: Dict[str, Any] = { + "algorithm_suite": self.algorithm_suite.as_dict(), + "encryption_context": self.encryption_context, + "required_encryption_context_keys": self.required_encryption_context_keys, + } + + if self.plaintext_data_key is not None: + d["plaintext_data_key"] = self.plaintext_data_key + + if self.verification_key is not None: + d["verification_key"] = self.verification_key + + if self.symmetric_signing_key is not None: + d["symmetric_signing_key"] = self.symmetric_signing_key + + return d + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "DecryptionMaterials": + """Creates a DecryptionMaterials from a dictionary.""" + kwargs: Dict[str, Any] = { + "algorithm_suite": AlgorithmSuiteInfo.from_dict(d["algorithm_suite"]), + "encryption_context": d["encryption_context"], + "required_encryption_context_keys": d["required_encryption_context_keys"], + } + + if "plaintext_data_key" in d: + kwargs["plaintext_data_key"] = d["plaintext_data_key"] + + if "verification_key" in d: + kwargs["verification_key"] = d["verification_key"] + + if "symmetric_signing_key" in d: + kwargs["symmetric_signing_key"] = d["symmetric_signing_key"] + + return DecryptionMaterials(**kwargs) + + def __repr__(self) -> str: + result = "DecryptionMaterials(" + if self.algorithm_suite is not None: + result += f"algorithm_suite={repr(self.algorithm_suite)}, " + + if self.encryption_context is not None: + result += f"encryption_context={repr(self.encryption_context)}, " + + if self.required_encryption_context_keys is not None: + result += f"required_encryption_context_keys={repr(self.required_encryption_context_keys)}, " + + if self.plaintext_data_key is not None: + result += f"plaintext_data_key={repr(self.plaintext_data_key)}, " + + if self.verification_key is not None: + result += f"verification_key={repr(self.verification_key)}, " + + if self.symmetric_signing_key is not None: + result += f"symmetric_signing_key={repr(self.symmetric_signing_key)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, DecryptionMaterials): + return False + attributes: list[str] = [ + "algorithm_suite", + "encryption_context", + "required_encryption_context_keys", + "plaintext_data_key", + "verification_key", + "symmetric_signing_key", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class EncryptedDataKey: + key_provider_id: str + key_provider_info: bytes | bytearray + ciphertext: bytes | bytearray + + def __init__( + self, + *, + key_provider_id: str, + key_provider_info: bytes | bytearray, + ciphertext: bytes | bytearray, + ): + self.key_provider_id = key_provider_id + self.key_provider_info = key_provider_info + self.ciphertext = ciphertext + + def as_dict(self) -> Dict[str, Any]: + """Converts the EncryptedDataKey to a dictionary.""" + return { + "key_provider_id": self.key_provider_id, + "key_provider_info": self.key_provider_info, + "ciphertext": self.ciphertext, + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "EncryptedDataKey": + """Creates a EncryptedDataKey from a dictionary.""" + kwargs: Dict[str, Any] = { + "key_provider_id": d["key_provider_id"], + "key_provider_info": d["key_provider_info"], + "ciphertext": d["ciphertext"], + } + + return EncryptedDataKey(**kwargs) + + def __repr__(self) -> str: + result = "EncryptedDataKey(" + if self.key_provider_id is not None: + result += f"key_provider_id={repr(self.key_provider_id)}, " + + if self.key_provider_info is not None: + result += f"key_provider_info={repr(self.key_provider_info)}, " + + if self.ciphertext is not None: + result += f"ciphertext={repr(self.ciphertext)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, EncryptedDataKey): + return False + attributes: list[str] = [ + "key_provider_id", + "key_provider_info", + "ciphertext", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class EncryptionMaterials: + algorithm_suite: AlgorithmSuiteInfo + encryption_context: dict[str, str] + encrypted_data_keys: list[EncryptedDataKey] + required_encryption_context_keys: list[str] + plaintext_data_key: Optional[bytes | bytearray] + signing_key: Optional[bytes | bytearray] + symmetric_signing_keys: Optional[list[bytes | bytearray]] + + def __init__( + self, + *, + algorithm_suite: AlgorithmSuiteInfo, + encryption_context: dict[str, str], + encrypted_data_keys: list[EncryptedDataKey], + required_encryption_context_keys: list[str], + plaintext_data_key: Optional[bytes | bytearray] = None, + signing_key: Optional[bytes | bytearray] = None, + symmetric_signing_keys: Optional[list[bytes | bytearray]] = None, + ): + self.algorithm_suite = algorithm_suite + self.encryption_context = encryption_context + self.encrypted_data_keys = encrypted_data_keys + self.required_encryption_context_keys = required_encryption_context_keys + self.plaintext_data_key = plaintext_data_key + self.signing_key = signing_key + self.symmetric_signing_keys = symmetric_signing_keys + + def as_dict(self) -> Dict[str, Any]: + """Converts the EncryptionMaterials to a dictionary.""" + d: Dict[str, Any] = { + "algorithm_suite": self.algorithm_suite.as_dict(), + "encryption_context": self.encryption_context, + "encrypted_data_keys": _encrypted_data_key_list_as_dict( + self.encrypted_data_keys + ), + "required_encryption_context_keys": self.required_encryption_context_keys, + } + + if self.plaintext_data_key is not None: + d["plaintext_data_key"] = self.plaintext_data_key + + if self.signing_key is not None: + d["signing_key"] = self.signing_key + + if self.symmetric_signing_keys is not None: + d["symmetric_signing_keys"] = self.symmetric_signing_keys + + return d + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "EncryptionMaterials": + """Creates a EncryptionMaterials from a dictionary.""" + kwargs: Dict[str, Any] = { + "algorithm_suite": AlgorithmSuiteInfo.from_dict(d["algorithm_suite"]), + "encryption_context": d["encryption_context"], + "encrypted_data_keys": _encrypted_data_key_list_from_dict( + d["encrypted_data_keys"] + ), + "required_encryption_context_keys": d["required_encryption_context_keys"], + } + + if "plaintext_data_key" in d: + kwargs["plaintext_data_key"] = d["plaintext_data_key"] + + if "signing_key" in d: + kwargs["signing_key"] = d["signing_key"] + + if "symmetric_signing_keys" in d: + kwargs["symmetric_signing_keys"] = d["symmetric_signing_keys"] + + return EncryptionMaterials(**kwargs) + + def __repr__(self) -> str: + result = "EncryptionMaterials(" + if self.algorithm_suite is not None: + result += f"algorithm_suite={repr(self.algorithm_suite)}, " + + if self.encryption_context is not None: + result += f"encryption_context={repr(self.encryption_context)}, " + + if self.encrypted_data_keys is not None: + result += f"encrypted_data_keys={repr(self.encrypted_data_keys)}, " + + if self.required_encryption_context_keys is not None: + result += f"required_encryption_context_keys={repr(self.required_encryption_context_keys)}, " + + if self.plaintext_data_key is not None: + result += f"plaintext_data_key={repr(self.plaintext_data_key)}, " + + if self.signing_key is not None: + result += f"signing_key={repr(self.signing_key)}, " + + if self.symmetric_signing_keys is not None: + result += f"symmetric_signing_keys={repr(self.symmetric_signing_keys)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, EncryptionMaterials): + return False + attributes: list[str] = [ + "algorithm_suite", + "encryption_context", + "encrypted_data_keys", + "required_encryption_context_keys", + "plaintext_data_key", + "signing_key", + "symmetric_signing_keys", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class MaterialsEncryption: + def __init__(self, value: EncryptionMaterials): + self.value = value + + def as_dict(self) -> Dict[str, Any]: + return {"Encryption": self.value.as_dict()} + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "MaterialsEncryption": + if len(d) != 1: + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + + return MaterialsEncryption(EncryptionMaterials.from_dict(d["Encryption"])) + + def __repr__(self) -> str: + return f"MaterialsEncryption(value=repr(self.value))" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, MaterialsEncryption): + return False + return self.value == other.value + + +class MaterialsDecryption: + def __init__(self, value: DecryptionMaterials): + self.value = value + + def as_dict(self) -> Dict[str, Any]: + return {"Decryption": self.value.as_dict()} + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "MaterialsDecryption": + if len(d) != 1: + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + + return MaterialsDecryption(DecryptionMaterials.from_dict(d["Decryption"])) + + def __repr__(self) -> str: + return f"MaterialsDecryption(value=repr(self.value))" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, MaterialsDecryption): + return False + return self.value == other.value + + +class MaterialsBranchKey: + def __init__(self, value: BranchKeyMaterials): + self.value = value + + def as_dict(self) -> Dict[str, Any]: + return {"BranchKey": self.value.as_dict()} + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "MaterialsBranchKey": + if len(d) != 1: + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + + return MaterialsBranchKey(BranchKeyMaterials.from_dict(d["BranchKey"])) + + def __repr__(self) -> str: + return f"MaterialsBranchKey(value=repr(self.value))" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, MaterialsBranchKey): + return False + return self.value == other.value + + +class MaterialsBeaconKey: + def __init__(self, value: BeaconKeyMaterials): + self.value = value + + def as_dict(self) -> Dict[str, Any]: + return {"BeaconKey": self.value.as_dict()} + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "MaterialsBeaconKey": + if len(d) != 1: + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + + return MaterialsBeaconKey(BeaconKeyMaterials.from_dict(d["BeaconKey"])) + + def __repr__(self) -> str: + return f"MaterialsBeaconKey(value=repr(self.value))" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, MaterialsBeaconKey): + return False + return self.value == other.value + + +class MaterialsUnknown: + """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]) -> "MaterialsUnknown": + if len(d) != 1: + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + return MaterialsUnknown(d["SDK_UNKNOWN_MEMBER"]["name"]) + + def __repr__(self) -> str: + return f"MaterialsUnknown(tag={self.tag})" + + +Materials = Union[ + MaterialsEncryption, + MaterialsDecryption, + MaterialsBranchKey, + MaterialsBeaconKey, + MaterialsUnknown, +] + + +def _materials_from_dict(d: Dict[str, Any]) -> Materials: + if "Encryption" in d: + return MaterialsEncryption.from_dict(d) + + if "Decryption" in d: + return MaterialsDecryption.from_dict(d) + + if "BranchKey" in d: + return MaterialsBranchKey.from_dict(d) + + if "BeaconKey" in d: + return MaterialsBeaconKey.from_dict(d) + + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + + +class GetCacheEntryOutput: + materials: Materials + creation_time: int + expiry_time: int + messages_used: int + bytes_used: int + + def __init__( + self, + *, + materials: Materials, + creation_time: int = 0, + expiry_time: int = 0, + messages_used: int = 0, + bytes_used: int = 0, + ): + self.materials = materials + if (creation_time is not None) and (creation_time < 0): + raise ValueError("creation_time must be greater than or equal to 0") + + self.creation_time = creation_time + if (expiry_time is not None) and (expiry_time < 0): + raise ValueError("expiry_time must be greater than or equal to 0") + + self.expiry_time = expiry_time + if (messages_used is not None) and (messages_used < 0): + raise ValueError("messages_used must be greater than or equal to 0") + + self.messages_used = messages_used + if (bytes_used is not None) and (bytes_used < 0): + raise ValueError("bytes_used must be greater than or equal to 0") + + self.bytes_used = bytes_used + + def as_dict(self) -> Dict[str, Any]: + """Converts the GetCacheEntryOutput to a dictionary.""" + d: Dict[str, Any] = { + "materials": self.materials.as_dict(), + } + + if self.creation_time is not None: + d["creation_time"] = self.creation_time + + if self.expiry_time is not None: + d["expiry_time"] = self.expiry_time + + if self.messages_used is not None: + d["messages_used"] = self.messages_used + + if self.bytes_used is not None: + d["bytes_used"] = self.bytes_used + + return d + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "GetCacheEntryOutput": + """Creates a GetCacheEntryOutput from a dictionary.""" + kwargs: Dict[str, Any] = { + "materials": _materials_from_dict(d["materials"]), + } + + if "creation_time" in d: + kwargs["creation_time"] = d["creation_time"] + + if "expiry_time" in d: + kwargs["expiry_time"] = d["expiry_time"] + + if "messages_used" in d: + kwargs["messages_used"] = d["messages_used"] + + if "bytes_used" in d: + kwargs["bytes_used"] = d["bytes_used"] + + return GetCacheEntryOutput(**kwargs) + + def __repr__(self) -> str: + result = "GetCacheEntryOutput(" + if self.materials is not None: + result += f"materials={repr(self.materials)}, " + + if self.creation_time is not None: + result += f"creation_time={repr(self.creation_time)}, " + + if self.expiry_time is not None: + result += f"expiry_time={repr(self.expiry_time)}, " + + if self.messages_used is not None: + result += f"messages_used={repr(self.messages_used)}, " + + if self.bytes_used is not None: + result += f"bytes_used={repr(self.bytes_used)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, GetCacheEntryOutput): + return False + attributes: list[str] = [ + "materials", + "creation_time", + "expiry_time", + "messages_used", + "bytes_used", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class PutCacheEntryInput: + identifier: bytes | bytearray + materials: Materials + creation_time: int + expiry_time: int + messages_used: int + bytes_used: int + + def __init__( + self, + *, + identifier: bytes | bytearray, + materials: Materials, + creation_time: int = 0, + expiry_time: int = 0, + messages_used: int = 0, + bytes_used: int = 0, + ): + self.identifier = identifier + self.materials = materials + if (creation_time is not None) and (creation_time < 0): + raise ValueError("creation_time must be greater than or equal to 0") + + self.creation_time = creation_time + if (expiry_time is not None) and (expiry_time < 0): + raise ValueError("expiry_time must be greater than or equal to 0") + + self.expiry_time = expiry_time + if (messages_used is not None) and (messages_used < 0): + raise ValueError("messages_used must be greater than or equal to 0") + + self.messages_used = messages_used + if (bytes_used is not None) and (bytes_used < 0): + raise ValueError("bytes_used must be greater than or equal to 0") + + self.bytes_used = bytes_used + + def as_dict(self) -> Dict[str, Any]: + """Converts the PutCacheEntryInput to a dictionary.""" + d: Dict[str, Any] = { + "identifier": self.identifier, + "materials": self.materials.as_dict(), + } + + if self.creation_time is not None: + d["creation_time"] = self.creation_time + + if self.expiry_time is not None: + d["expiry_time"] = self.expiry_time + + if self.messages_used is not None: + d["messages_used"] = self.messages_used + + if self.bytes_used is not None: + d["bytes_used"] = self.bytes_used + + return d + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "PutCacheEntryInput": + """Creates a PutCacheEntryInput from a dictionary.""" + kwargs: Dict[str, Any] = { + "identifier": d["identifier"], + "materials": _materials_from_dict(d["materials"]), + } + + if "creation_time" in d: + kwargs["creation_time"] = d["creation_time"] + + if "expiry_time" in d: + kwargs["expiry_time"] = d["expiry_time"] + + if "messages_used" in d: + kwargs["messages_used"] = d["messages_used"] + + if "bytes_used" in d: + kwargs["bytes_used"] = d["bytes_used"] + + return PutCacheEntryInput(**kwargs) + + def __repr__(self) -> str: + result = "PutCacheEntryInput(" + if self.identifier is not None: + result += f"identifier={repr(self.identifier)}, " + + if self.materials is not None: + result += f"materials={repr(self.materials)}, " + + if self.creation_time is not None: + result += f"creation_time={repr(self.creation_time)}, " + + if self.expiry_time is not None: + result += f"expiry_time={repr(self.expiry_time)}, " + + if self.messages_used is not None: + result += f"messages_used={repr(self.messages_used)}, " + + if self.bytes_used is not None: + result += f"bytes_used={repr(self.bytes_used)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, PutCacheEntryInput): + return False + attributes: list[str] = [ + "identifier", + "materials", + "creation_time", + "expiry_time", + "messages_used", + "bytes_used", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class UpdateUsageMetadataInput: + identifier: bytes | bytearray + bytes_used: int + + def __init__( + self, + *, + identifier: bytes | bytearray, + bytes_used: int = 0, + ): + self.identifier = identifier + if (bytes_used is not None) and (bytes_used < 0): + raise ValueError("bytes_used must be greater than or equal to 0") + + self.bytes_used = bytes_used + + def as_dict(self) -> Dict[str, Any]: + """Converts the UpdateUsageMetadataInput to a dictionary.""" + d: Dict[str, Any] = { + "identifier": self.identifier, + } + + if self.bytes_used is not None: + d["bytes_used"] = self.bytes_used + + return d + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "UpdateUsageMetadataInput": + """Creates a UpdateUsageMetadataInput from a dictionary.""" + kwargs: Dict[str, Any] = { + "identifier": d["identifier"], + } + + if "bytes_used" in d: + kwargs["bytes_used"] = d["bytes_used"] + + return UpdateUsageMetadataInput(**kwargs) + + def __repr__(self) -> str: + result = "UpdateUsageMetadataInput(" + if self.identifier is not None: + result += f"identifier={repr(self.identifier)}, " + + if self.bytes_used is not None: + result += f"bytes_used={repr(self.bytes_used)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, UpdateUsageMetadataInput): + return False + attributes: list[str] = [ + "identifier", + "bytes_used", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class DBECommitmentPolicy: + REQUIRE_ENCRYPT_REQUIRE_DECRYPT = "REQUIRE_ENCRYPT_REQUIRE_DECRYPT" + + # This set contains every possible value known at the time this was generated. New + # values may be added in the future. + values = frozenset({"REQUIRE_ENCRYPT_REQUIRE_DECRYPT"}) + + +class ESDKCommitmentPolicy: + FORBID_ENCRYPT_ALLOW_DECRYPT = "FORBID_ENCRYPT_ALLOW_DECRYPT" + + REQUIRE_ENCRYPT_ALLOW_DECRYPT = "REQUIRE_ENCRYPT_ALLOW_DECRYPT" + + REQUIRE_ENCRYPT_REQUIRE_DECRYPT = "REQUIRE_ENCRYPT_REQUIRE_DECRYPT" + + # This set contains every possible value known at the time this was generated. New + # values may be added in the future. + values = frozenset( + { + "FORBID_ENCRYPT_ALLOW_DECRYPT", + "REQUIRE_ENCRYPT_ALLOW_DECRYPT", + "REQUIRE_ENCRYPT_REQUIRE_DECRYPT", + } + ) + + +class CommitmentPolicyESDK: + def __init__(self, value: str): + self.value = value + + def as_dict(self) -> Dict[str, Any]: + return {"ESDK": self.value} + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "CommitmentPolicyESDK": + if len(d) != 1: + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + + return CommitmentPolicyESDK(d["ESDK"]) + + def __repr__(self) -> str: + return f"CommitmentPolicyESDK(value=repr(self.value))" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, CommitmentPolicyESDK): + return False + return self.value == other.value + + +class CommitmentPolicyDBE: + def __init__(self, value: str): + self.value = value + + def as_dict(self) -> Dict[str, Any]: + return {"DBE": self.value} + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "CommitmentPolicyDBE": + if len(d) != 1: + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + + return CommitmentPolicyDBE(d["DBE"]) + + def __repr__(self) -> str: + return f"CommitmentPolicyDBE(value=repr(self.value))" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, CommitmentPolicyDBE): + return False + return self.value == other.value + + +class CommitmentPolicyUnknown: + """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]) -> "CommitmentPolicyUnknown": + if len(d) != 1: + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + return CommitmentPolicyUnknown(d["SDK_UNKNOWN_MEMBER"]["name"]) + + def __repr__(self) -> str: + return f"CommitmentPolicyUnknown(tag={self.tag})" + + +CommitmentPolicy = Union[ + CommitmentPolicyESDK, CommitmentPolicyDBE, CommitmentPolicyUnknown +] + + +def _commitment_policy_from_dict(d: Dict[str, Any]) -> CommitmentPolicy: + if "ESDK" in d: + return CommitmentPolicyESDK.from_dict(d) + + if "DBE" in d: + return CommitmentPolicyDBE.from_dict(d) + + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + + +class DecryptMaterialsInput: + algorithm_suite_id: AlgorithmSuiteId + commitment_policy: CommitmentPolicy + encrypted_data_keys: list[EncryptedDataKey] + encryption_context: dict[str, str] + reproduced_encryption_context: Optional[dict[str, str]] + + def __init__( + self, + *, + algorithm_suite_id: AlgorithmSuiteId, + commitment_policy: CommitmentPolicy, + encrypted_data_keys: list[EncryptedDataKey], + encryption_context: dict[str, str], + reproduced_encryption_context: Optional[dict[str, str]] = None, + ): + self.algorithm_suite_id = algorithm_suite_id + self.commitment_policy = commitment_policy + self.encrypted_data_keys = encrypted_data_keys + self.encryption_context = encryption_context + self.reproduced_encryption_context = reproduced_encryption_context + + def as_dict(self) -> Dict[str, Any]: + """Converts the DecryptMaterialsInput to a dictionary.""" + d: Dict[str, Any] = { + "algorithm_suite_id": self.algorithm_suite_id.as_dict(), + "commitment_policy": self.commitment_policy.as_dict(), + "encrypted_data_keys": _encrypted_data_key_list_as_dict( + self.encrypted_data_keys + ), + "encryption_context": self.encryption_context, + } + + if self.reproduced_encryption_context is not None: + d["reproduced_encryption_context"] = self.reproduced_encryption_context + + return d + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "DecryptMaterialsInput": + """Creates a DecryptMaterialsInput from a dictionary.""" + kwargs: Dict[str, Any] = { + "algorithm_suite_id": _algorithm_suite_id_from_dict( + d["algorithm_suite_id"] + ), + "commitment_policy": _commitment_policy_from_dict(d["commitment_policy"]), + "encrypted_data_keys": _encrypted_data_key_list_from_dict( + d["encrypted_data_keys"] + ), + "encryption_context": d["encryption_context"], + } + + if "reproduced_encryption_context" in d: + kwargs["reproduced_encryption_context"] = d["reproduced_encryption_context"] + + return DecryptMaterialsInput(**kwargs) + + def __repr__(self) -> str: + result = "DecryptMaterialsInput(" + if self.algorithm_suite_id is not None: + result += f"algorithm_suite_id={repr(self.algorithm_suite_id)}, " + + if self.commitment_policy is not None: + result += f"commitment_policy={repr(self.commitment_policy)}, " + + if self.encrypted_data_keys is not None: + result += f"encrypted_data_keys={repr(self.encrypted_data_keys)}, " + + if self.encryption_context is not None: + result += f"encryption_context={repr(self.encryption_context)}, " + + if self.reproduced_encryption_context is not None: + result += f"reproduced_encryption_context={repr(self.reproduced_encryption_context)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, DecryptMaterialsInput): + return False + attributes: list[str] = [ + "algorithm_suite_id", + "commitment_policy", + "encrypted_data_keys", + "encryption_context", + "reproduced_encryption_context", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class DecryptMaterialsOutput: + decryption_materials: DecryptionMaterials + + def __init__( + self, + *, + decryption_materials: DecryptionMaterials, + ): + self.decryption_materials = decryption_materials + + def as_dict(self) -> Dict[str, Any]: + """Converts the DecryptMaterialsOutput to a dictionary.""" + return { + "decryption_materials": self.decryption_materials.as_dict(), + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "DecryptMaterialsOutput": + """Creates a DecryptMaterialsOutput from a dictionary.""" + kwargs: Dict[str, Any] = { + "decryption_materials": DecryptionMaterials.from_dict( + d["decryption_materials"] + ), + } + + return DecryptMaterialsOutput(**kwargs) + + def __repr__(self) -> str: + result = "DecryptMaterialsOutput(" + if self.decryption_materials is not None: + result += f"decryption_materials={repr(self.decryption_materials)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, DecryptMaterialsOutput): + return False + attributes: list[str] = [ + "decryption_materials", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class GetEncryptionMaterialsInput: + encryption_context: dict[str, str] + commitment_policy: CommitmentPolicy + algorithm_suite_id: Optional[AlgorithmSuiteId] + max_plaintext_length: Optional[int] + required_encryption_context_keys: Optional[list[str]] + + def __init__( + self, + *, + encryption_context: dict[str, str], + commitment_policy: CommitmentPolicy, + algorithm_suite_id: Optional[AlgorithmSuiteId] = None, + max_plaintext_length: Optional[int] = None, + required_encryption_context_keys: Optional[list[str]] = None, + ): + self.encryption_context = encryption_context + self.commitment_policy = commitment_policy + self.algorithm_suite_id = algorithm_suite_id + self.max_plaintext_length = max_plaintext_length + self.required_encryption_context_keys = required_encryption_context_keys + + def as_dict(self) -> Dict[str, Any]: + """Converts the GetEncryptionMaterialsInput to a dictionary.""" + d: Dict[str, Any] = { + "encryption_context": self.encryption_context, + "commitment_policy": self.commitment_policy.as_dict(), + } + + if self.algorithm_suite_id is not None: + d["algorithm_suite_id"] = self.algorithm_suite_id.as_dict() + + if self.max_plaintext_length is not None: + d["max_plaintext_length"] = self.max_plaintext_length + + if self.required_encryption_context_keys is not None: + d["required_encryption_context_keys"] = ( + self.required_encryption_context_keys + ) + + return d + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "GetEncryptionMaterialsInput": + """Creates a GetEncryptionMaterialsInput from a dictionary.""" + kwargs: Dict[str, Any] = { + "encryption_context": d["encryption_context"], + "commitment_policy": _commitment_policy_from_dict(d["commitment_policy"]), + } + + if "algorithm_suite_id" in d: + kwargs["algorithm_suite_id"] = ( + _algorithm_suite_id_from_dict(d["algorithm_suite_id"]), + ) + + if "max_plaintext_length" in d: + kwargs["max_plaintext_length"] = d["max_plaintext_length"] + + if "required_encryption_context_keys" in d: + kwargs["required_encryption_context_keys"] = d[ + "required_encryption_context_keys" + ] + + return GetEncryptionMaterialsInput(**kwargs) + + def __repr__(self) -> str: + result = "GetEncryptionMaterialsInput(" + if self.encryption_context is not None: + result += f"encryption_context={repr(self.encryption_context)}, " + + if self.commitment_policy is not None: + result += f"commitment_policy={repr(self.commitment_policy)}, " + + if self.algorithm_suite_id is not None: + result += f"algorithm_suite_id={repr(self.algorithm_suite_id)}, " + + if self.max_plaintext_length is not None: + result += f"max_plaintext_length={repr(self.max_plaintext_length)}, " + + if self.required_encryption_context_keys is not None: + result += f"required_encryption_context_keys={repr(self.required_encryption_context_keys)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, GetEncryptionMaterialsInput): + return False + attributes: list[str] = [ + "encryption_context", + "commitment_policy", + "algorithm_suite_id", + "max_plaintext_length", + "required_encryption_context_keys", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class GetEncryptionMaterialsOutput: + encryption_materials: EncryptionMaterials + + def __init__( + self, + *, + encryption_materials: EncryptionMaterials, + ): + self.encryption_materials = encryption_materials + + def as_dict(self) -> Dict[str, Any]: + """Converts the GetEncryptionMaterialsOutput to a dictionary.""" + return { + "encryption_materials": self.encryption_materials.as_dict(), + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "GetEncryptionMaterialsOutput": + """Creates a GetEncryptionMaterialsOutput from a dictionary.""" + kwargs: Dict[str, Any] = { + "encryption_materials": EncryptionMaterials.from_dict( + d["encryption_materials"] + ), + } + + return GetEncryptionMaterialsOutput(**kwargs) + + def __repr__(self) -> str: + result = "GetEncryptionMaterialsOutput(" + if self.encryption_materials is not None: + result += f"encryption_materials={repr(self.encryption_materials)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, GetEncryptionMaterialsOutput): + return False + attributes: list[str] = [ + "encryption_materials", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class InitializeDecryptionMaterialsInput: + algorithm_suite_id: AlgorithmSuiteId + encryption_context: dict[str, str] + required_encryption_context_keys: list[str] + + def __init__( + self, + *, + algorithm_suite_id: AlgorithmSuiteId, + encryption_context: dict[str, str], + required_encryption_context_keys: list[str], + ): + self.algorithm_suite_id = algorithm_suite_id + self.encryption_context = encryption_context + self.required_encryption_context_keys = required_encryption_context_keys + + def as_dict(self) -> Dict[str, Any]: + """Converts the InitializeDecryptionMaterialsInput to a dictionary.""" + return { + "algorithm_suite_id": self.algorithm_suite_id.as_dict(), + "encryption_context": self.encryption_context, + "required_encryption_context_keys": self.required_encryption_context_keys, + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "InitializeDecryptionMaterialsInput": + """Creates a InitializeDecryptionMaterialsInput from a dictionary.""" + kwargs: Dict[str, Any] = { + "algorithm_suite_id": _algorithm_suite_id_from_dict( + d["algorithm_suite_id"] + ), + "encryption_context": d["encryption_context"], + "required_encryption_context_keys": d["required_encryption_context_keys"], + } + + return InitializeDecryptionMaterialsInput(**kwargs) + + def __repr__(self) -> str: + result = "InitializeDecryptionMaterialsInput(" + if self.algorithm_suite_id is not None: + result += f"algorithm_suite_id={repr(self.algorithm_suite_id)}, " + + if self.encryption_context is not None: + result += f"encryption_context={repr(self.encryption_context)}, " + + if self.required_encryption_context_keys is not None: + result += f"required_encryption_context_keys={repr(self.required_encryption_context_keys)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, InitializeDecryptionMaterialsInput): + return False + attributes: list[str] = [ + "algorithm_suite_id", + "encryption_context", + "required_encryption_context_keys", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class InitializeEncryptionMaterialsInput: + algorithm_suite_id: AlgorithmSuiteId + encryption_context: dict[str, str] + required_encryption_context_keys: list[str] + signing_key: Optional[bytes | bytearray] + verification_key: Optional[bytes | bytearray] + + def __init__( + self, + *, + algorithm_suite_id: AlgorithmSuiteId, + encryption_context: dict[str, str], + required_encryption_context_keys: list[str], + signing_key: Optional[bytes | bytearray] = None, + verification_key: Optional[bytes | bytearray] = None, + ): + self.algorithm_suite_id = algorithm_suite_id + self.encryption_context = encryption_context + self.required_encryption_context_keys = required_encryption_context_keys + self.signing_key = signing_key + self.verification_key = verification_key + + def as_dict(self) -> Dict[str, Any]: + """Converts the InitializeEncryptionMaterialsInput to a dictionary.""" + d: Dict[str, Any] = { + "algorithm_suite_id": self.algorithm_suite_id.as_dict(), + "encryption_context": self.encryption_context, + "required_encryption_context_keys": self.required_encryption_context_keys, + } + + if self.signing_key is not None: + d["signing_key"] = self.signing_key + + if self.verification_key is not None: + d["verification_key"] = self.verification_key + + return d + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "InitializeEncryptionMaterialsInput": + """Creates a InitializeEncryptionMaterialsInput from a dictionary.""" + kwargs: Dict[str, Any] = { + "algorithm_suite_id": _algorithm_suite_id_from_dict( + d["algorithm_suite_id"] + ), + "encryption_context": d["encryption_context"], + "required_encryption_context_keys": d["required_encryption_context_keys"], + } + + if "signing_key" in d: + kwargs["signing_key"] = d["signing_key"] + + if "verification_key" in d: + kwargs["verification_key"] = d["verification_key"] + + return InitializeEncryptionMaterialsInput(**kwargs) + + def __repr__(self) -> str: + result = "InitializeEncryptionMaterialsInput(" + if self.algorithm_suite_id is not None: + result += f"algorithm_suite_id={repr(self.algorithm_suite_id)}, " + + if self.encryption_context is not None: + result += f"encryption_context={repr(self.encryption_context)}, " + + if self.required_encryption_context_keys is not None: + result += f"required_encryption_context_keys={repr(self.required_encryption_context_keys)}, " + + if self.signing_key is not None: + result += f"signing_key={repr(self.signing_key)}, " + + if self.verification_key is not None: + result += f"verification_key={repr(self.verification_key)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, InitializeEncryptionMaterialsInput): + return False + attributes: list[str] = [ + "algorithm_suite_id", + "encryption_context", + "required_encryption_context_keys", + "signing_key", + "verification_key", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class OnDecryptInput: + materials: DecryptionMaterials + encrypted_data_keys: list[EncryptedDataKey] + + def __init__( + self, + *, + materials: DecryptionMaterials, + encrypted_data_keys: list[EncryptedDataKey], + ): + self.materials = materials + self.encrypted_data_keys = encrypted_data_keys + + def as_dict(self) -> Dict[str, Any]: + """Converts the OnDecryptInput to a dictionary.""" + return { + "materials": self.materials.as_dict(), + "encrypted_data_keys": _encrypted_data_key_list_as_dict( + self.encrypted_data_keys + ), + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "OnDecryptInput": + """Creates a OnDecryptInput from a dictionary.""" + kwargs: Dict[str, Any] = { + "materials": DecryptionMaterials.from_dict(d["materials"]), + "encrypted_data_keys": _encrypted_data_key_list_from_dict( + d["encrypted_data_keys"] + ), + } + + return OnDecryptInput(**kwargs) + + def __repr__(self) -> str: + result = "OnDecryptInput(" + if self.materials is not None: + result += f"materials={repr(self.materials)}, " + + if self.encrypted_data_keys is not None: + result += f"encrypted_data_keys={repr(self.encrypted_data_keys)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, OnDecryptInput): + return False + attributes: list[str] = [ + "materials", + "encrypted_data_keys", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class OnDecryptOutput: + materials: DecryptionMaterials + + def __init__( + self, + *, + materials: DecryptionMaterials, + ): + self.materials = materials + + def as_dict(self) -> Dict[str, Any]: + """Converts the OnDecryptOutput to a dictionary.""" + return { + "materials": self.materials.as_dict(), + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "OnDecryptOutput": + """Creates a OnDecryptOutput from a dictionary.""" + kwargs: Dict[str, Any] = { + "materials": DecryptionMaterials.from_dict(d["materials"]), + } + + return OnDecryptOutput(**kwargs) + + def __repr__(self) -> str: + result = "OnDecryptOutput(" + if self.materials is not None: + result += f"materials={repr(self.materials)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, OnDecryptOutput): + return False + attributes: list[str] = [ + "materials", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class OnEncryptInput: + materials: EncryptionMaterials + + def __init__( + self, + *, + materials: EncryptionMaterials, + ): + self.materials = materials + + def as_dict(self) -> Dict[str, Any]: + """Converts the OnEncryptInput to a dictionary.""" + return { + "materials": self.materials.as_dict(), + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "OnEncryptInput": + """Creates a OnEncryptInput from a dictionary.""" + kwargs: Dict[str, Any] = { + "materials": EncryptionMaterials.from_dict(d["materials"]), + } + + return OnEncryptInput(**kwargs) + + def __repr__(self) -> str: + result = "OnEncryptInput(" + if self.materials is not None: + result += f"materials={repr(self.materials)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, OnEncryptInput): + return False + attributes: list[str] = [ + "materials", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class OnEncryptOutput: + materials: EncryptionMaterials + + def __init__( + self, + *, + materials: EncryptionMaterials, + ): + self.materials = materials + + def as_dict(self) -> Dict[str, Any]: + """Converts the OnEncryptOutput to a dictionary.""" + return { + "materials": self.materials.as_dict(), + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "OnEncryptOutput": + """Creates a OnEncryptOutput from a dictionary.""" + kwargs: Dict[str, Any] = { + "materials": EncryptionMaterials.from_dict(d["materials"]), + } + + return OnEncryptOutput(**kwargs) + + def __repr__(self) -> str: + result = "OnEncryptOutput(" + if self.materials is not None: + result += f"materials={repr(self.materials)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, OnEncryptOutput): + return False + attributes: list[str] = [ + "materials", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class ValidateCommitmentPolicyOnDecryptInput: + algorithm: AlgorithmSuiteId + commitment_policy: CommitmentPolicy + + def __init__( + self, + *, + algorithm: AlgorithmSuiteId, + commitment_policy: CommitmentPolicy, + ): + self.algorithm = algorithm + self.commitment_policy = commitment_policy + + def as_dict(self) -> Dict[str, Any]: + """Converts the ValidateCommitmentPolicyOnDecryptInput to a + dictionary.""" + return { + "algorithm": self.algorithm.as_dict(), + "commitment_policy": self.commitment_policy.as_dict(), + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "ValidateCommitmentPolicyOnDecryptInput": + """Creates a ValidateCommitmentPolicyOnDecryptInput from a + dictionary.""" + kwargs: Dict[str, Any] = { + "algorithm": _algorithm_suite_id_from_dict(d["algorithm"]), + "commitment_policy": _commitment_policy_from_dict(d["commitment_policy"]), + } + + return ValidateCommitmentPolicyOnDecryptInput(**kwargs) + + def __repr__(self) -> str: + result = "ValidateCommitmentPolicyOnDecryptInput(" + if self.algorithm is not None: + result += f"algorithm={repr(self.algorithm)}, " + + if self.commitment_policy is not None: + result += f"commitment_policy={repr(self.commitment_policy)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, ValidateCommitmentPolicyOnDecryptInput): + return False + attributes: list[str] = [ + "algorithm", + "commitment_policy", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class ValidateCommitmentPolicyOnEncryptInput: + algorithm: AlgorithmSuiteId + commitment_policy: CommitmentPolicy + + def __init__( + self, + *, + algorithm: AlgorithmSuiteId, + commitment_policy: CommitmentPolicy, + ): + self.algorithm = algorithm + self.commitment_policy = commitment_policy + + def as_dict(self) -> Dict[str, Any]: + """Converts the ValidateCommitmentPolicyOnEncryptInput to a + dictionary.""" + return { + "algorithm": self.algorithm.as_dict(), + "commitment_policy": self.commitment_policy.as_dict(), + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "ValidateCommitmentPolicyOnEncryptInput": + """Creates a ValidateCommitmentPolicyOnEncryptInput from a + dictionary.""" + kwargs: Dict[str, Any] = { + "algorithm": _algorithm_suite_id_from_dict(d["algorithm"]), + "commitment_policy": _commitment_policy_from_dict(d["commitment_policy"]), + } + + return ValidateCommitmentPolicyOnEncryptInput(**kwargs) + + def __repr__(self) -> str: + result = "ValidateCommitmentPolicyOnEncryptInput(" + if self.algorithm is not None: + result += f"algorithm={repr(self.algorithm)}, " + + if self.commitment_policy is not None: + result += f"commitment_policy={repr(self.commitment_policy)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, ValidateCommitmentPolicyOnEncryptInput): + return False + attributes: list[str] = [ + "algorithm", + "commitment_policy", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class ValidDecryptionMaterialsTransitionInput: + start: DecryptionMaterials + stop: DecryptionMaterials + + def __init__( + self, + *, + start: DecryptionMaterials, + stop: DecryptionMaterials, + ): + self.start = start + self.stop = stop + + def as_dict(self) -> Dict[str, Any]: + """Converts the ValidDecryptionMaterialsTransitionInput to a + dictionary.""" + return { + "start": self.start.as_dict(), + "stop": self.stop.as_dict(), + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "ValidDecryptionMaterialsTransitionInput": + """Creates a ValidDecryptionMaterialsTransitionInput from a + dictionary.""" + kwargs: Dict[str, Any] = { + "start": DecryptionMaterials.from_dict(d["start"]), + "stop": DecryptionMaterials.from_dict(d["stop"]), + } + + return ValidDecryptionMaterialsTransitionInput(**kwargs) + + def __repr__(self) -> str: + result = "ValidDecryptionMaterialsTransitionInput(" + if self.start is not None: + result += f"start={repr(self.start)}, " + + if self.stop is not None: + result += f"stop={repr(self.stop)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, ValidDecryptionMaterialsTransitionInput): + return False + attributes: list[str] = [ + "start", + "stop", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class ValidEncryptionMaterialsTransitionInput: + start: EncryptionMaterials + stop: EncryptionMaterials + + def __init__( + self, + *, + start: EncryptionMaterials, + stop: EncryptionMaterials, + ): + self.start = start + self.stop = stop + + def as_dict(self) -> Dict[str, Any]: + """Converts the ValidEncryptionMaterialsTransitionInput to a + dictionary.""" + return { + "start": self.start.as_dict(), + "stop": self.stop.as_dict(), + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "ValidEncryptionMaterialsTransitionInput": + """Creates a ValidEncryptionMaterialsTransitionInput from a + dictionary.""" + kwargs: Dict[str, Any] = { + "start": EncryptionMaterials.from_dict(d["start"]), + "stop": EncryptionMaterials.from_dict(d["stop"]), + } + + return ValidEncryptionMaterialsTransitionInput(**kwargs) + + def __repr__(self) -> str: + result = "ValidEncryptionMaterialsTransitionInput(" + if self.start is not None: + result += f"start={repr(self.start)}, " + + if self.stop is not None: + result += f"stop={repr(self.stop)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, ValidEncryptionMaterialsTransitionInput): + return False + attributes: list[str] = [ + "start", + "stop", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +def _encrypted_data_key_list_as_dict(given: list[EncryptedDataKey]) -> List[Any]: + return [v.as_dict() for v in given] + + +def _encrypted_data_key_list_from_dict(given: List[Any]) -> list[EncryptedDataKey]: + return [EncryptedDataKey.from_dict(v) for v in given] + + +class Unit: + pass diff --git a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/smithygenerated/aws_cryptography_materialproviders/plugin.py b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/smithygenerated/aws_cryptography_materialproviders/plugin.py new file mode 100644 index 000000000..dd523c834 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/smithygenerated/aws_cryptography_materialproviders/plugin.py @@ -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. + +from .config import ( + Config, + Plugin, + smithy_config_to_dafny_config, + MaterialProvidersConfig, +) +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, MaterialProvidersConfig): + from aws_cryptographic_materialproviders.internaldafny.generated.MaterialProviders import ( + default__, + ) + + config.dafnyImplInterface.impl = default__.MaterialProviders( + 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_materialproviders/smithygenerated/aws_cryptography_materialproviders/references.py b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/smithygenerated/aws_cryptography_materialproviders/references.py new file mode 100644 index 000000000..5470a5c4e --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/smithygenerated/aws_cryptography_materialproviders/references.py @@ -0,0 +1,710 @@ +# 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_materialproviders.internaldafny.generated.AwsCryptographyMaterialProvidersTypes +from aws_cryptographic_materialproviders.internaldafny.generated.AwsCryptographyMaterialProvidersTypes import ( + DecryptMaterialsInput_DecryptMaterialsInput as DafnyDecryptMaterialsInput, + DecryptMaterialsOutput_DecryptMaterialsOutput as DafnyDecryptMaterialsOutput, + DeleteCacheEntryInput_DeleteCacheEntryInput as DafnyDeleteCacheEntryInput, + GetBranchKeyIdInput_GetBranchKeyIdInput as DafnyGetBranchKeyIdInput, + GetBranchKeyIdOutput_GetBranchKeyIdOutput as DafnyGetBranchKeyIdOutput, + GetCacheEntryInput_GetCacheEntryInput as DafnyGetCacheEntryInput, + GetCacheEntryOutput_GetCacheEntryOutput as DafnyGetCacheEntryOutput, + GetClientInput_GetClientInput as DafnyGetClientInput, + GetEncryptionMaterialsInput_GetEncryptionMaterialsInput as DafnyGetEncryptionMaterialsInput, + GetEncryptionMaterialsOutput_GetEncryptionMaterialsOutput as DafnyGetEncryptionMaterialsOutput, + OnDecryptInput_OnDecryptInput as DafnyOnDecryptInput, + OnDecryptOutput_OnDecryptOutput as DafnyOnDecryptOutput, + OnEncryptInput_OnEncryptInput as DafnyOnEncryptInput, + OnEncryptOutput_OnEncryptOutput as DafnyOnEncryptOutput, + PutCacheEntryInput_PutCacheEntryInput as DafnyPutCacheEntryInput, + UpdateUsageMetadataInput_UpdateUsageMetadataInput as DafnyUpdateUsageMetadataInput, +) +import aws_cryptographic_materialproviders.internaldafny.generated.module_ +import aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy +from aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.errors import ( + _smithy_error_to_dafny_error, +) +import aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models +import aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny +import botocore.client +from smithy_dafny_standard_library.internaldafny.generated import Wrappers +from typing import Any, Dict + + +class IBranchKeyIdSupplier(metaclass=abc.ABCMeta): + + @classmethod + def __subclasshook__(cls, subclass): + return hasattr(subclass, "GetBranchKeyId") and callable(subclass.GetBranchKeyId) + + @abc.abstractmethod + def get_branch_key_id( + self, + param: "aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.GetBranchKeyIdInput", + ) -> "aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.GetBranchKeyIdOutput": + """Given the Encryption Context associated with this encryption or + decryption, returns the branch key that should be responsible for + unwrapping or wrapping the data key. + + :param param: Inputs for determining the Branch Key which should + be used to wrap or unwrap the data key for this encryption + or decryption + :returns: Outputs for the Branch Key responsible for wrapping or + unwrapping the data key in this encryption or decryption. + """ + raise NotImplementedError + + def GetBranchKeyId( + self, dafny_input: "DafnyGetBranchKeyIdInput" + ) -> "DafnyGetBranchKeyIdOutput": + """Do not use. + + This method allows custom implementations of this interface to + interact with generated code. + """ + native_input = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_GetBranchKeyIdInput( + dafny_input + ) + try: + native_output = self.get_branch_key_id(native_input) + dafny_output = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_GetBranchKeyIdOutput( + 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 BranchKeyIdSupplier(IBranchKeyIdSupplier): + + _impl: ( + aws_cryptographic_materialproviders.internaldafny.generated.AwsCryptographyMaterialProvidersTypes.IBranchKeyIdSupplier + ) + + def __init__( + self, + _impl: aws_cryptographic_materialproviders.internaldafny.generated.AwsCryptographyMaterialProvidersTypes.IBranchKeyIdSupplier, + ): + self._impl = _impl + + def get_branch_key_id( + self, + param: "aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.GetBranchKeyIdInput", + ) -> "aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.GetBranchKeyIdOutput": + """Given the Encryption Context associated with this encryption or + decryption, returns the branch key that should be responsible for + unwrapping or wrapping the data key. + + :param param: Inputs for determining the Branch Key which should + be used to wrap or unwrap the data key for this encryption + or decryption + :returns: Outputs for the Branch Key responsible for wrapping or + unwrapping the data key in this encryption or decryption. + """ + dafny_output = self._impl.GetBranchKeyId( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_GetBranchKeyIdInput( + param + ) + ) + if dafny_output.IsFailure(): + from aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.deserialize import ( + _deserialize_error as aws_cryptography_materialproviders_deserialize_error, + ) + + raise aws_cryptography_materialproviders_deserialize_error( + dafny_output.error + ) + + else: + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_GetBranchKeyIdOutput( + dafny_output.value + ) + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "BranchKeyIdSupplier": + return BranchKeyIdSupplier(d["_impl"]) + + def as_dict(self) -> Dict[str, Any]: + return {"_impl": self._impl} + + +class IClientSupplier(metaclass=abc.ABCMeta): + + @classmethod + def __subclasshook__(cls, subclass): + return hasattr(subclass, "GetClient") and callable(subclass.GetClient) + + @abc.abstractmethod + def get_client( + self, + param: "aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.GetClientInput", + ) -> "botocore.client.BaseClient": + """Returns an AWS KMS Client. + + :param param: Inputs for getting a AWS KMS Client. + """ + raise NotImplementedError + + def GetClient(self, dafny_input: "DafnyGetClientInput") -> "DafnyGetClientOutput": + """Do not use. + + This method allows custom implementations of this interface to + interact with generated code. + """ + native_input = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_GetClientInput( + dafny_input + ) + try: + native_output = self.get_client(native_input) + dafny_output = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_GetClientOutput( + 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 ClientSupplier(IClientSupplier): + + _impl: ( + aws_cryptographic_materialproviders.internaldafny.generated.AwsCryptographyMaterialProvidersTypes.IClientSupplier + ) + + def __init__( + self, + _impl: aws_cryptographic_materialproviders.internaldafny.generated.AwsCryptographyMaterialProvidersTypes.IClientSupplier, + ): + self._impl = _impl + + def get_client( + self, + param: "aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.GetClientInput", + ) -> "botocore.client.BaseClient": + """Returns an AWS KMS Client. + + :param param: Inputs for getting a AWS KMS Client. + """ + dafny_output = self._impl.GetClient( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_GetClientInput( + param + ) + ) + if dafny_output.IsFailure(): + from aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.deserialize import ( + _deserialize_error as aws_cryptography_materialproviders_deserialize_error, + ) + + raise aws_cryptography_materialproviders_deserialize_error( + dafny_output.error + ) + + else: + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_GetClientOutput( + dafny_output.value + ) + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "ClientSupplier": + return ClientSupplier(d["_impl"]) + + def as_dict(self) -> Dict[str, Any]: + return {"_impl": self._impl} + + +class ICryptographicMaterialsCache(metaclass=abc.ABCMeta): + + @classmethod + def __subclasshook__(cls, subclass): + return ( + hasattr(subclass, "PutCacheEntry") + and callable(subclass.PutCacheEntry) + and hasattr(subclass, "GetCacheEntry") + and callable(subclass.GetCacheEntry) + and hasattr(subclass, "UpdateUsageMetadata") + and callable(subclass.UpdateUsageMetadata) + and hasattr(subclass, "DeleteCacheEntry") + and callable(subclass.DeleteCacheEntry) + ) + + @abc.abstractmethod + def put_cache_entry( + self, + param: "aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.PutCacheEntryInput", + ) -> "aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.Unit": + raise NotImplementedError + + @abc.abstractmethod + def get_cache_entry( + self, + param: "aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.GetCacheEntryInput", + ) -> "aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.GetCacheEntryOutput": + raise NotImplementedError + + @abc.abstractmethod + def update_usage_metadata( + self, + param: "aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.UpdateUsageMetadataInput", + ) -> "aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.Unit": + raise NotImplementedError + + @abc.abstractmethod + def delete_cache_entry( + self, + param: "aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.DeleteCacheEntryInput", + ) -> "aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.Unit": + raise NotImplementedError + + def PutCacheEntry(self, dafny_input: "DafnyPutCacheEntryInput") -> "None": + """Do not use. + + This method allows custom implementations of this interface to + interact with generated code. + """ + native_input = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_PutCacheEntryInput( + dafny_input + ) + try: + native_output = self.put_cache_entry(native_input) + dafny_output = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.smithy_api_Unit( + 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 GetCacheEntry( + self, dafny_input: "DafnyGetCacheEntryInput" + ) -> "DafnyGetCacheEntryOutput": + """Do not use. + + This method allows custom implementations of this interface to + interact with generated code. + """ + native_input = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_GetCacheEntryInput( + dafny_input + ) + try: + native_output = self.get_cache_entry(native_input) + dafny_output = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_GetCacheEntryOutput( + 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 UpdateUsageMetadata( + self, dafny_input: "DafnyUpdateUsageMetadataInput" + ) -> "None": + """Do not use. + + This method allows custom implementations of this interface to + interact with generated code. + """ + native_input = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_UpdateUsageMetadataInput( + dafny_input + ) + try: + native_output = self.update_usage_metadata(native_input) + dafny_output = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.smithy_api_Unit( + 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 DeleteCacheEntry(self, dafny_input: "DafnyDeleteCacheEntryInput") -> "None": + """Do not use. + + This method allows custom implementations of this interface to + interact with generated code. + """ + native_input = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_DeleteCacheEntryInput( + dafny_input + ) + try: + native_output = self.delete_cache_entry(native_input) + dafny_output = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.smithy_api_Unit( + 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 CryptographicMaterialsCache(ICryptographicMaterialsCache): + + _impl: ( + aws_cryptographic_materialproviders.internaldafny.generated.AwsCryptographyMaterialProvidersTypes.ICryptographicMaterialsCache + ) + + def __init__( + self, + _impl: aws_cryptographic_materialproviders.internaldafny.generated.AwsCryptographyMaterialProvidersTypes.ICryptographicMaterialsCache, + ): + self._impl = _impl + + def put_cache_entry( + self, + param: "aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.PutCacheEntryInput", + ) -> "aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.Unit": + dafny_output = self._impl.PutCacheEntry( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_PutCacheEntryInput( + param + ) + ) + if dafny_output.IsFailure(): + from aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.deserialize import ( + _deserialize_error as smithy_api_deserialize_error, + ) + + raise smithy_api_deserialize_error(dafny_output.error) + + else: + return ( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.smithy_api_Unit() + ) + + def get_cache_entry( + self, + param: "aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.GetCacheEntryInput", + ) -> "aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.GetCacheEntryOutput": + dafny_output = self._impl.GetCacheEntry( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_GetCacheEntryInput( + param + ) + ) + if dafny_output.IsFailure(): + from aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.deserialize import ( + _deserialize_error as aws_cryptography_materialproviders_deserialize_error, + ) + + raise aws_cryptography_materialproviders_deserialize_error( + dafny_output.error + ) + + else: + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_GetCacheEntryOutput( + dafny_output.value + ) + + def update_usage_metadata( + self, + param: "aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.UpdateUsageMetadataInput", + ) -> "aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.Unit": + dafny_output = self._impl.UpdateUsageMetadata( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_UpdateUsageMetadataInput( + param + ) + ) + if dafny_output.IsFailure(): + from aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.deserialize import ( + _deserialize_error as smithy_api_deserialize_error, + ) + + raise smithy_api_deserialize_error(dafny_output.error) + + else: + return ( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.smithy_api_Unit() + ) + + def delete_cache_entry( + self, + param: "aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.DeleteCacheEntryInput", + ) -> "aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.Unit": + dafny_output = self._impl.DeleteCacheEntry( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_DeleteCacheEntryInput( + param + ) + ) + if dafny_output.IsFailure(): + from aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.deserialize import ( + _deserialize_error as smithy_api_deserialize_error, + ) + + raise smithy_api_deserialize_error(dafny_output.error) + + else: + return ( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.smithy_api_Unit() + ) + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "CryptographicMaterialsCache": + return CryptographicMaterialsCache(d["_impl"]) + + def as_dict(self) -> Dict[str, Any]: + return {"_impl": self._impl} + + +class ICryptographicMaterialsManager(metaclass=abc.ABCMeta): + + @classmethod + def __subclasshook__(cls, subclass): + return ( + hasattr(subclass, "GetEncryptionMaterials") + and callable(subclass.GetEncryptionMaterials) + and hasattr(subclass, "DecryptMaterials") + and callable(subclass.DecryptMaterials) + ) + + @abc.abstractmethod + def get_encryption_materials( + self, + param: "aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.GetEncryptionMaterialsInput", + ) -> "aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.GetEncryptionMaterialsOutput": + raise NotImplementedError + + @abc.abstractmethod + def decrypt_materials( + self, + param: "aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.DecryptMaterialsInput", + ) -> "aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.DecryptMaterialsOutput": + raise NotImplementedError + + def GetEncryptionMaterials( + self, dafny_input: "DafnyGetEncryptionMaterialsInput" + ) -> "DafnyGetEncryptionMaterialsOutput": + """Do not use. + + This method allows custom implementations of this interface to + interact with generated code. + """ + native_input = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_GetEncryptionMaterialsInput( + dafny_input + ) + try: + native_output = self.get_encryption_materials(native_input) + dafny_output = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_GetEncryptionMaterialsOutput( + 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 DecryptMaterials( + self, dafny_input: "DafnyDecryptMaterialsInput" + ) -> "DafnyDecryptMaterialsOutput": + """Do not use. + + This method allows custom implementations of this interface to + interact with generated code. + """ + native_input = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_DecryptMaterialsInput( + dafny_input + ) + try: + native_output = self.decrypt_materials(native_input) + dafny_output = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_DecryptMaterialsOutput( + 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 CryptographicMaterialsManager(ICryptographicMaterialsManager): + + _impl: ( + aws_cryptographic_materialproviders.internaldafny.generated.AwsCryptographyMaterialProvidersTypes.ICryptographicMaterialsManager + ) + + def __init__( + self, + _impl: aws_cryptographic_materialproviders.internaldafny.generated.AwsCryptographyMaterialProvidersTypes.ICryptographicMaterialsManager, + ): + self._impl = _impl + + def get_encryption_materials( + self, + param: "aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.GetEncryptionMaterialsInput", + ) -> "aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.GetEncryptionMaterialsOutput": + dafny_output = self._impl.GetEncryptionMaterials( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_GetEncryptionMaterialsInput( + param + ) + ) + if dafny_output.IsFailure(): + from aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.deserialize import ( + _deserialize_error as aws_cryptography_materialproviders_deserialize_error, + ) + + raise aws_cryptography_materialproviders_deserialize_error( + dafny_output.error + ) + + else: + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_GetEncryptionMaterialsOutput( + dafny_output.value + ) + + def decrypt_materials( + self, + param: "aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.DecryptMaterialsInput", + ) -> "aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.DecryptMaterialsOutput": + dafny_output = self._impl.DecryptMaterials( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_DecryptMaterialsInput( + param + ) + ) + if dafny_output.IsFailure(): + from aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.deserialize import ( + _deserialize_error as aws_cryptography_materialproviders_deserialize_error, + ) + + raise aws_cryptography_materialproviders_deserialize_error( + dafny_output.error + ) + + else: + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_DecryptMaterialsOutput( + dafny_output.value + ) + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "CryptographicMaterialsManager": + return CryptographicMaterialsManager(d["_impl"]) + + def as_dict(self) -> Dict[str, Any]: + return {"_impl": self._impl} + + +class IKeyring(metaclass=abc.ABCMeta): + + @classmethod + def __subclasshook__(cls, subclass): + return ( + hasattr(subclass, "OnEncrypt") + and callable(subclass.OnEncrypt) + and hasattr(subclass, "OnDecrypt") + and callable(subclass.OnDecrypt) + ) + + @abc.abstractmethod + def on_encrypt( + self, + param: "aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.OnEncryptInput", + ) -> "aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.OnEncryptOutput": + raise NotImplementedError + + @abc.abstractmethod + def on_decrypt( + self, + param: "aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.OnDecryptInput", + ) -> "aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.OnDecryptOutput": + raise NotImplementedError + + def OnEncrypt(self, dafny_input: "DafnyOnEncryptInput") -> "DafnyOnEncryptOutput": + """Do not use. + + This method allows custom implementations of this interface to + interact with generated code. + """ + native_input = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_OnEncryptInput( + dafny_input + ) + try: + native_output = self.on_encrypt(native_input) + dafny_output = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_OnEncryptOutput( + 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 OnDecrypt(self, dafny_input: "DafnyOnDecryptInput") -> "DafnyOnDecryptOutput": + """Do not use. + + This method allows custom implementations of this interface to + interact with generated code. + """ + native_input = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_OnDecryptInput( + dafny_input + ) + try: + native_output = self.on_decrypt(native_input) + dafny_output = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_OnDecryptOutput( + 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 Keyring(IKeyring): + + _impl: ( + aws_cryptographic_materialproviders.internaldafny.generated.AwsCryptographyMaterialProvidersTypes.IKeyring + ) + + def __init__( + self, + _impl: aws_cryptographic_materialproviders.internaldafny.generated.AwsCryptographyMaterialProvidersTypes.IKeyring, + ): + self._impl = _impl + + def on_encrypt( + self, + param: "aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.OnEncryptInput", + ) -> "aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.OnEncryptOutput": + dafny_output = self._impl.OnEncrypt( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_OnEncryptInput( + param + ) + ) + if dafny_output.IsFailure(): + from aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.deserialize import ( + _deserialize_error as aws_cryptography_materialproviders_deserialize_error, + ) + + raise aws_cryptography_materialproviders_deserialize_error( + dafny_output.error + ) + + else: + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_OnEncryptOutput( + dafny_output.value + ) + + def on_decrypt( + self, + param: "aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.OnDecryptInput", + ) -> "aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.OnDecryptOutput": + dafny_output = self._impl.OnDecrypt( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_OnDecryptInput( + param + ) + ) + if dafny_output.IsFailure(): + from aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.deserialize import ( + _deserialize_error as aws_cryptography_materialproviders_deserialize_error, + ) + + raise aws_cryptography_materialproviders_deserialize_error( + dafny_output.error + ) + + else: + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_OnDecryptOutput( + dafny_output.value + ) + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "Keyring": + return Keyring(d["_impl"]) + + def as_dict(self) -> Dict[str, Any]: + return {"_impl": self._impl} diff --git a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/smithygenerated/aws_cryptography_materialproviders/serialize.py b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/smithygenerated/aws_cryptography_materialproviders/serialize.py new file mode 100644 index 000000000..98cf560f8 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/smithygenerated/aws_cryptography_materialproviders/serialize.py @@ -0,0 +1,296 @@ +# 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_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny + +from .dafny_protocol import DafnyRequest + +from .config import Config + + +def _serialize_create_aws_kms_keyring(input, config: Config) -> DafnyRequest: + return DafnyRequest( + operation_name="CreateAwsKmsKeyring", + dafny_operation_input=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_CreateAwsKmsKeyringInput( + input + ), + ) + + +def _serialize_create_aws_kms_discovery_keyring(input, config: Config) -> DafnyRequest: + return DafnyRequest( + operation_name="CreateAwsKmsDiscoveryKeyring", + dafny_operation_input=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_CreateAwsKmsDiscoveryKeyringInput( + input + ), + ) + + +def _serialize_create_aws_kms_multi_keyring(input, config: Config) -> DafnyRequest: + return DafnyRequest( + operation_name="CreateAwsKmsMultiKeyring", + dafny_operation_input=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_CreateAwsKmsMultiKeyringInput( + input + ), + ) + + +def _serialize_create_aws_kms_discovery_multi_keyring( + input, config: Config +) -> DafnyRequest: + return DafnyRequest( + operation_name="CreateAwsKmsDiscoveryMultiKeyring", + dafny_operation_input=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_CreateAwsKmsDiscoveryMultiKeyringInput( + input + ), + ) + + +def _serialize_create_aws_kms_mrk_keyring(input, config: Config) -> DafnyRequest: + return DafnyRequest( + operation_name="CreateAwsKmsMrkKeyring", + dafny_operation_input=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_CreateAwsKmsMrkKeyringInput( + input + ), + ) + + +def _serialize_create_aws_kms_mrk_multi_keyring(input, config: Config) -> DafnyRequest: + return DafnyRequest( + operation_name="CreateAwsKmsMrkMultiKeyring", + dafny_operation_input=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_CreateAwsKmsMrkMultiKeyringInput( + input + ), + ) + + +def _serialize_create_aws_kms_mrk_discovery_keyring( + input, config: Config +) -> DafnyRequest: + return DafnyRequest( + operation_name="CreateAwsKmsMrkDiscoveryKeyring", + dafny_operation_input=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_CreateAwsKmsMrkDiscoveryKeyringInput( + input + ), + ) + + +def _serialize_create_aws_kms_mrk_discovery_multi_keyring( + input, config: Config +) -> DafnyRequest: + return DafnyRequest( + operation_name="CreateAwsKmsMrkDiscoveryMultiKeyring", + dafny_operation_input=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_CreateAwsKmsMrkDiscoveryMultiKeyringInput( + input + ), + ) + + +def _serialize_create_aws_kms_hierarchical_keyring( + input, config: Config +) -> DafnyRequest: + return DafnyRequest( + operation_name="CreateAwsKmsHierarchicalKeyring", + dafny_operation_input=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_CreateAwsKmsHierarchicalKeyringInput( + input + ), + ) + + +def _serialize_create_aws_kms_rsa_keyring(input, config: Config) -> DafnyRequest: + return DafnyRequest( + operation_name="CreateAwsKmsRsaKeyring", + dafny_operation_input=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_CreateAwsKmsRsaKeyringInput( + input + ), + ) + + +def _serialize_create_aws_kms_ecdh_keyring(input, config: Config) -> DafnyRequest: + return DafnyRequest( + operation_name="CreateAwsKmsEcdhKeyring", + dafny_operation_input=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_CreateAwsKmsEcdhKeyringInput( + input + ), + ) + + +def _serialize_create_multi_keyring(input, config: Config) -> DafnyRequest: + return DafnyRequest( + operation_name="CreateMultiKeyring", + dafny_operation_input=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_CreateMultiKeyringInput( + input + ), + ) + + +def _serialize_create_raw_aes_keyring(input, config: Config) -> DafnyRequest: + return DafnyRequest( + operation_name="CreateRawAesKeyring", + dafny_operation_input=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_CreateRawAesKeyringInput( + input + ), + ) + + +def _serialize_create_raw_rsa_keyring(input, config: Config) -> DafnyRequest: + return DafnyRequest( + operation_name="CreateRawRsaKeyring", + dafny_operation_input=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_CreateRawRsaKeyringInput( + input + ), + ) + + +def _serialize_create_raw_ecdh_keyring(input, config: Config) -> DafnyRequest: + return DafnyRequest( + operation_name="CreateRawEcdhKeyring", + dafny_operation_input=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_CreateRawEcdhKeyringInput( + input + ), + ) + + +def _serialize_create_default_cryptographic_materials_manager( + input, config: Config +) -> DafnyRequest: + return DafnyRequest( + operation_name="CreateDefaultCryptographicMaterialsManager", + dafny_operation_input=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_CreateDefaultCryptographicMaterialsManagerInput( + input + ), + ) + + +def _serialize_create_required_encryption_context_cmm( + input, config: Config +) -> DafnyRequest: + return DafnyRequest( + operation_name="CreateRequiredEncryptionContextCMM", + dafny_operation_input=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_CreateRequiredEncryptionContextCMMInput( + input + ), + ) + + +def _serialize_create_cryptographic_materials_cache( + input, config: Config +) -> DafnyRequest: + return DafnyRequest( + operation_name="CreateCryptographicMaterialsCache", + dafny_operation_input=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_CreateCryptographicMaterialsCacheInput( + input + ), + ) + + +def _serialize_create_default_client_supplier(input, config: Config) -> DafnyRequest: + return DafnyRequest( + operation_name="CreateDefaultClientSupplier", + dafny_operation_input=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_CreateDefaultClientSupplierInput( + input + ), + ) + + +def _serialize_initialize_encryption_materials(input, config: Config) -> DafnyRequest: + return DafnyRequest( + operation_name="InitializeEncryptionMaterials", + dafny_operation_input=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_InitializeEncryptionMaterialsInput( + input + ), + ) + + +def _serialize_initialize_decryption_materials(input, config: Config) -> DafnyRequest: + return DafnyRequest( + operation_name="InitializeDecryptionMaterials", + dafny_operation_input=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_InitializeDecryptionMaterialsInput( + input + ), + ) + + +def _serialize_valid_encryption_materials_transition( + input, config: Config +) -> DafnyRequest: + return DafnyRequest( + operation_name="ValidEncryptionMaterialsTransition", + dafny_operation_input=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_ValidEncryptionMaterialsTransitionInput( + input + ), + ) + + +def _serialize_valid_decryption_materials_transition( + input, config: Config +) -> DafnyRequest: + return DafnyRequest( + operation_name="ValidDecryptionMaterialsTransition", + dafny_operation_input=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_ValidDecryptionMaterialsTransitionInput( + input + ), + ) + + +def _serialize_encryption_materials_has_plaintext_data_key( + input, config: Config +) -> DafnyRequest: + return DafnyRequest( + operation_name="EncryptionMaterialsHasPlaintextDataKey", + dafny_operation_input=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_EncryptionMaterials( + input + ), + ) + + +def _serialize_decryption_materials_with_plaintext_data_key( + input, config: Config +) -> DafnyRequest: + return DafnyRequest( + operation_name="DecryptionMaterialsWithPlaintextDataKey", + dafny_operation_input=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_DecryptionMaterials( + input + ), + ) + + +def _serialize_get_algorithm_suite_info(input, config: Config) -> DafnyRequest: + return DafnyRequest( + operation_name="GetAlgorithmSuiteInfo", + dafny_operation_input=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_GetAlgorithmSuiteInfoInput( + input + ), + ) + + +def _serialize_valid_algorithm_suite_info(input, config: Config) -> DafnyRequest: + return DafnyRequest( + operation_name="ValidAlgorithmSuiteInfo", + dafny_operation_input=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_AlgorithmSuiteInfo( + input + ), + ) + + +def _serialize_validate_commitment_policy_on_encrypt( + input, config: Config +) -> DafnyRequest: + return DafnyRequest( + operation_name="ValidateCommitmentPolicyOnEncrypt", + dafny_operation_input=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_ValidateCommitmentPolicyOnEncryptInput( + input + ), + ) + + +def _serialize_validate_commitment_policy_on_decrypt( + input, config: Config +) -> DafnyRequest: + return DafnyRequest( + operation_name="ValidateCommitmentPolicyOnDecrypt", + dafny_operation_input=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_ValidateCommitmentPolicyOnDecryptInput( + input + ), + ) diff --git a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/smithygenerated/aws_cryptography_materialproviders/shim.py b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/smithygenerated/aws_cryptography_materialproviders/shim.py new file mode 100644 index 000000000..af4e9769b --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/smithygenerated/aws_cryptography_materialproviders/shim.py @@ -0,0 +1,548 @@ +# Code generated by smithy-python-codegen DO NOT EDIT. + +import aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy +import aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.errors +import aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models +import aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny +import module_ +from software_amazon_cryptography_materialproviders_internaldafny_types import ( + AlgorithmSuiteInfo_AlgorithmSuiteInfo as DafnyAlgorithmSuiteInfo, + CreateAwsKmsDiscoveryKeyringInput_CreateAwsKmsDiscoveryKeyringInput as DafnyCreateAwsKmsDiscoveryKeyringInput, + CreateAwsKmsDiscoveryMultiKeyringInput_CreateAwsKmsDiscoveryMultiKeyringInput as DafnyCreateAwsKmsDiscoveryMultiKeyringInput, + CreateAwsKmsHierarchicalKeyringInput_CreateAwsKmsHierarchicalKeyringInput as DafnyCreateAwsKmsHierarchicalKeyringInput, + CreateAwsKmsKeyringInput_CreateAwsKmsKeyringInput as DafnyCreateAwsKmsKeyringInput, + CreateAwsKmsMrkDiscoveryKeyringInput_CreateAwsKmsMrkDiscoveryKeyringInput as DafnyCreateAwsKmsMrkDiscoveryKeyringInput, + CreateAwsKmsMrkDiscoveryMultiKeyringInput_CreateAwsKmsMrkDiscoveryMultiKeyringInput as DafnyCreateAwsKmsMrkDiscoveryMultiKeyringInput, + CreateAwsKmsMrkKeyringInput_CreateAwsKmsMrkKeyringInput as DafnyCreateAwsKmsMrkKeyringInput, + CreateAwsKmsMrkMultiKeyringInput_CreateAwsKmsMrkMultiKeyringInput as DafnyCreateAwsKmsMrkMultiKeyringInput, + CreateAwsKmsMultiKeyringInput_CreateAwsKmsMultiKeyringInput as DafnyCreateAwsKmsMultiKeyringInput, + CreateAwsKmsRsaKeyringInput_CreateAwsKmsRsaKeyringInput as DafnyCreateAwsKmsRsaKeyringInput, + CreateCryptographicMaterialsCacheInput_CreateCryptographicMaterialsCacheInput as DafnyCreateCryptographicMaterialsCacheInput, + CreateDefaultClientSupplierInput_CreateDefaultClientSupplierInput as DafnyCreateDefaultClientSupplierInput, + CreateDefaultCryptographicMaterialsManagerInput_CreateDefaultCryptographicMaterialsManagerInput as DafnyCreateDefaultCryptographicMaterialsManagerInput, + CreateMultiKeyringInput_CreateMultiKeyringInput as DafnyCreateMultiKeyringInput, + CreateRawAesKeyringInput_CreateRawAesKeyringInput as DafnyCreateRawAesKeyringInput, + CreateRawRsaKeyringInput_CreateRawRsaKeyringInput as DafnyCreateRawRsaKeyringInput, + CreateRequiredEncryptionContextCMMInput_CreateRequiredEncryptionContextCMMInput as DafnyCreateRequiredEncryptionContextCMMInput, + DecryptionMaterials_DecryptionMaterials as DafnyDecryptionMaterials, + EncryptionMaterials_EncryptionMaterials as DafnyEncryptionMaterials, + InitializeDecryptionMaterialsInput_InitializeDecryptionMaterialsInput as DafnyInitializeDecryptionMaterialsInput, + InitializeEncryptionMaterialsInput_InitializeEncryptionMaterialsInput as DafnyInitializeEncryptionMaterialsInput, + ValidDecryptionMaterialsTransitionInput_ValidDecryptionMaterialsTransitionInput as DafnyValidDecryptionMaterialsTransitionInput, + ValidEncryptionMaterialsTransitionInput_ValidEncryptionMaterialsTransitionInput as DafnyValidEncryptionMaterialsTransitionInput, + ValidateCommitmentPolicyOnDecryptInput_ValidateCommitmentPolicyOnDecryptInput as DafnyValidateCommitmentPolicyOnDecryptInput, + ValidateCommitmentPolicyOnEncryptInput_ValidateCommitmentPolicyOnEncryptInput as DafnyValidateCommitmentPolicyOnEncryptInput, +) +from typing import Any + +from .errors import ( + CollectionOfErrors, + OpaqueError, + ServiceError, + _smithy_error_to_dafny_error, +) + + +import Wrappers +import software_amazon_cryptography_materialproviders_internaldafny_types +import aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.client as client_impl + + +class MaterialProvidersShim( + software_amazon_cryptography_materialproviders_internaldafny_types.IAwsCryptographicMaterialProvidersClient +): + def __init__(self, _impl: client_impl): + self._impl = _impl + + def CreateAwsKmsKeyring(self, input): + smithy_client_request: ( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.CreateAwsKmsKeyringInput + ) = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_CreateAwsKmsKeyringInput( + input + ) + try: + smithy_client_response = self._impl.create_aws_kms_keyring( + smithy_client_request + ) + except ServiceError as e: + return Wrappers.Result_Failure(_smithy_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_CreateKeyringOutput( + smithy_client_response + ) + ) + + def CreateAwsKmsDiscoveryKeyring(self, input): + smithy_client_request: ( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.CreateAwsKmsDiscoveryKeyringInput + ) = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_CreateAwsKmsDiscoveryKeyringInput( + input + ) + try: + smithy_client_response = self._impl.create_aws_kms_discovery_keyring( + smithy_client_request + ) + except ServiceError as e: + return Wrappers.Result_Failure(_smithy_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_CreateKeyringOutput( + smithy_client_response + ) + ) + + def CreateAwsKmsMultiKeyring(self, input): + smithy_client_request: ( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.CreateAwsKmsMultiKeyringInput + ) = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_CreateAwsKmsMultiKeyringInput( + input + ) + try: + smithy_client_response = self._impl.create_aws_kms_multi_keyring( + smithy_client_request + ) + except ServiceError as e: + return Wrappers.Result_Failure(_smithy_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_CreateKeyringOutput( + smithy_client_response + ) + ) + + def CreateAwsKmsDiscoveryMultiKeyring(self, input): + smithy_client_request: ( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.CreateAwsKmsDiscoveryMultiKeyringInput + ) = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_CreateAwsKmsDiscoveryMultiKeyringInput( + input + ) + try: + smithy_client_response = self._impl.create_aws_kms_discovery_multi_keyring( + smithy_client_request + ) + except ServiceError as e: + return Wrappers.Result_Failure(_smithy_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_CreateKeyringOutput( + smithy_client_response + ) + ) + + def CreateAwsKmsMrkKeyring(self, input): + smithy_client_request: ( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.CreateAwsKmsMrkKeyringInput + ) = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_CreateAwsKmsMrkKeyringInput( + input + ) + try: + smithy_client_response = self._impl.create_aws_kms_mrk_keyring( + smithy_client_request + ) + except ServiceError as e: + return Wrappers.Result_Failure(_smithy_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_CreateKeyringOutput( + smithy_client_response + ) + ) + + def CreateAwsKmsMrkMultiKeyring(self, input): + smithy_client_request: ( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.CreateAwsKmsMrkMultiKeyringInput + ) = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_CreateAwsKmsMrkMultiKeyringInput( + input + ) + try: + smithy_client_response = self._impl.create_aws_kms_mrk_multi_keyring( + smithy_client_request + ) + except ServiceError as e: + return Wrappers.Result_Failure(_smithy_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_CreateKeyringOutput( + smithy_client_response + ) + ) + + def CreateAwsKmsMrkDiscoveryKeyring(self, input): + smithy_client_request: ( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.CreateAwsKmsMrkDiscoveryKeyringInput + ) = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_CreateAwsKmsMrkDiscoveryKeyringInput( + input + ) + try: + smithy_client_response = self._impl.create_aws_kms_mrk_discovery_keyring( + smithy_client_request + ) + except ServiceError as e: + return Wrappers.Result_Failure(_smithy_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_CreateKeyringOutput( + smithy_client_response + ) + ) + + def CreateAwsKmsMrkDiscoveryMultiKeyring(self, input): + smithy_client_request: ( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.CreateAwsKmsMrkDiscoveryMultiKeyringInput + ) = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_CreateAwsKmsMrkDiscoveryMultiKeyringInput( + input + ) + try: + smithy_client_response = ( + self._impl.create_aws_kms_mrk_discovery_multi_keyring( + smithy_client_request + ) + ) + except ServiceError as e: + return Wrappers.Result_Failure(_smithy_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_CreateKeyringOutput( + smithy_client_response + ) + ) + + def CreateAwsKmsHierarchicalKeyring(self, input): + smithy_client_request: ( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.CreateAwsKmsHierarchicalKeyringInput + ) = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_CreateAwsKmsHierarchicalKeyringInput( + input + ) + try: + smithy_client_response = self._impl.create_aws_kms_hierarchical_keyring( + smithy_client_request + ) + except Exception as e: + return Wrappers.Result_Failure(_smithy_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_CreateKeyringOutput( + smithy_client_response + ) + ) + + def CreateMultiKeyring(self, input): + smithy_client_request: ( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.CreateMultiKeyringInput + ) = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_CreateMultiKeyringInput( + input + ) + try: + smithy_client_response = self._impl.create_multi_keyring( + smithy_client_request + ) + except ServiceError as e: + return Wrappers.Result_Failure(_smithy_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_CreateKeyringOutput( + smithy_client_response + ) + ) + + def CreateRawAesKeyring(self, input): + smithy_client_request: ( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.CreateRawAesKeyringInput + ) = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_CreateRawAesKeyringInput( + input + ) + try: + smithy_client_response = self._impl.create_raw_aes_keyring( + smithy_client_request + ) + except ServiceError as e: + return Wrappers.Result_Failure(_smithy_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_CreateKeyringOutput( + smithy_client_response + ) + ) + + def CreateRawRsaKeyring(self, input): + smithy_client_request: ( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.CreateRawRsaKeyringInput + ) = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_CreateRawRsaKeyringInput( + input + ) + try: + smithy_client_response = self._impl.create_raw_rsa_keyring( + smithy_client_request + ) + except ServiceError as e: + return Wrappers.Result_Failure(_smithy_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_CreateKeyringOutput( + smithy_client_response + ) + ) + + def CreateAwsKmsRsaKeyring(self, input): + smithy_client_request: ( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.CreateAwsKmsRsaKeyringInput + ) = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_CreateAwsKmsRsaKeyringInput( + input + ) + try: + smithy_client_response = self._impl.create_aws_kms_rsa_keyring( + smithy_client_request + ) + except ServiceError as e: + return Wrappers.Result_Failure(_smithy_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_CreateKeyringOutput( + smithy_client_response + ) + ) + + def CreateDefaultCryptographicMaterialsManager(self, input): + smithy_client_request: ( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.CreateDefaultCryptographicMaterialsManagerInput + ) = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_CreateDefaultCryptographicMaterialsManagerInput( + input + ) + try: + smithy_client_response = ( + self._impl.create_default_cryptographic_materials_manager( + smithy_client_request + ) + ) + except ServiceError as e: + return Wrappers.Result_Failure(_smithy_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_CreateCryptographicMaterialsManagerOutput( + smithy_client_response + ) + ) + + def CreateRequiredEncryptionContextCMM(self, input): + smithy_client_request: ( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.CreateRequiredEncryptionContextCMMInput + ) = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_CreateRequiredEncryptionContextCMMInput( + input + ) + try: + smithy_client_response = self._impl.create_required_encryption_context_cmm( + smithy_client_request + ) + except ServiceError as e: + return Wrappers.Result_Failure(_smithy_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_CreateRequiredEncryptionContextCMMOutput( + smithy_client_response + ) + ) + + def CreateCryptographicMaterialsCache(self, input): + smithy_client_request: ( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.CreateCryptographicMaterialsCacheInput + ) = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_CreateCryptographicMaterialsCacheInput( + input + ) + try: + smithy_client_response = self._impl.create_cryptographic_materials_cache( + smithy_client_request + ) + except ServiceError as e: + return Wrappers.Result_Failure(_smithy_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_CreateCryptographicMaterialsCacheOutput( + smithy_client_response + ) + ) + + def CreateDefaultClientSupplier(self, input): + smithy_client_request: ( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.CreateDefaultClientSupplierInput + ) = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_CreateDefaultClientSupplierInput( + input + ) + try: + smithy_client_response = self._impl.create_default_client_supplier( + smithy_client_request + ) + except ServiceError as e: + return Wrappers.Result_Failure(_smithy_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_CreateDefaultClientSupplierOutput( + smithy_client_response + ) + ) + + def InitializeEncryptionMaterials(self, input): + smithy_client_request: ( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.InitializeEncryptionMaterialsInput + ) = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_InitializeEncryptionMaterialsInput( + input + ) + try: + smithy_client_response = self._impl.initialize_encryption_materials( + smithy_client_request + ) + except ServiceError as e: + return Wrappers.Result_Failure(_smithy_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_EncryptionMaterials( + smithy_client_response + ) + ) + + def InitializeDecryptionMaterials(self, input): + smithy_client_request: ( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.InitializeDecryptionMaterialsInput + ) = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_InitializeDecryptionMaterialsInput( + input + ) + try: + smithy_client_response = self._impl.initialize_decryption_materials( + smithy_client_request + ) + except ServiceError as e: + return Wrappers.Result_Failure(_smithy_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_DecryptionMaterials( + smithy_client_response + ) + ) + + def ValidEncryptionMaterialsTransition(self, input): + smithy_client_request: ( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.ValidEncryptionMaterialsTransitionInput + ) = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_ValidEncryptionMaterialsTransitionInput( + input + ) + try: + smithy_client_response = self._impl.valid_encryption_materials_transition( + smithy_client_request + ) + except ServiceError as e: + return Wrappers.Result_Failure(_smithy_error_to_dafny_error(e)) + + return Wrappers.Result_Success(None) + + def ValidDecryptionMaterialsTransition(self, input): + smithy_client_request: ( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.ValidDecryptionMaterialsTransitionInput + ) = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_ValidDecryptionMaterialsTransitionInput( + input + ) + try: + smithy_client_response = self._impl.valid_decryption_materials_transition( + smithy_client_request + ) + except ServiceError as e: + return Wrappers.Result_Failure(_smithy_error_to_dafny_error(e)) + + return Wrappers.Result_Success(None) + + def EncryptionMaterialsHasPlaintextDataKey(self, input): + smithy_client_request: ( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.EncryptionMaterials + ) = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_EncryptionMaterials( + input + ) + try: + smithy_client_response = ( + self._impl.encryption_materials_has_plaintext_data_key( + smithy_client_request + ) + ) + except ServiceError as e: + return Wrappers.Result_Failure(_smithy_error_to_dafny_error(e)) + + return Wrappers.Result_Success(None) + + def DecryptionMaterialsWithPlaintextDataKey(self, input): + smithy_client_request: ( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.DecryptionMaterials + ) = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_DecryptionMaterials( + input + ) + try: + smithy_client_response = ( + self._impl.decryption_materials_with_plaintext_data_key( + smithy_client_request + ) + ) + except ServiceError as e: + return Wrappers.Result_Failure(_smithy_error_to_dafny_error(e)) + + return Wrappers.Result_Success(None) + + def GetAlgorithmSuiteInfo(self, input): + smithy_client_request: ( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.GetAlgorithmSuiteInfoInput + ) = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_GetAlgorithmSuiteInfoInput( + input + ) + try: + smithy_client_response = self._impl.get_algorithm_suite_info( + smithy_client_request + ) + except ServiceError as e: + return Wrappers.Result_Failure(_smithy_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_AlgorithmSuiteInfo( + smithy_client_response + ) + ) + + def ValidAlgorithmSuiteInfo(self, input): + smithy_client_request: ( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.AlgorithmSuiteInfo + ) = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_AlgorithmSuiteInfo( + input + ) + try: + smithy_client_response = self._impl.valid_algorithm_suite_info( + smithy_client_request + ) + except ServiceError as e: + return Wrappers.Result_Failure(_smithy_error_to_dafny_error(e)) + + return Wrappers.Result_Success(None) + + def ValidateCommitmentPolicyOnEncrypt(self, input): + smithy_client_request: ( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.ValidateCommitmentPolicyOnEncryptInput + ) = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_ValidateCommitmentPolicyOnEncryptInput( + input + ) + try: + smithy_client_response = self._impl.validate_commitment_policy_on_encrypt( + smithy_client_request + ) + except ServiceError as e: + return Wrappers.Result_Failure(_smithy_error_to_dafny_error(e)) + + return Wrappers.Result_Success(None) + + def ValidateCommitmentPolicyOnDecrypt(self, input): + smithy_client_request: ( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.ValidateCommitmentPolicyOnDecryptInput + ) = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_ValidateCommitmentPolicyOnDecryptInput( + input + ) + try: + smithy_client_response = self._impl.validate_commitment_policy_on_decrypt( + smithy_client_request + ) + except ServiceError as e: + return Wrappers.Result_Failure(_smithy_error_to_dafny_error(e)) + + return Wrappers.Result_Success(None) diff --git a/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/smithygenerated/aws_cryptography_materialproviders/smithy_to_dafny.py b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/smithygenerated/aws_cryptography_materialproviders/smithy_to_dafny.py new file mode 100644 index 000000000..1721426a8 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/smithygenerated/aws_cryptography_materialproviders/smithy_to_dafny.py @@ -0,0 +1,2280 @@ +# 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_materialproviders.internaldafny.generated.AwsCryptographyMaterialProvidersTypes import ( + AesWrappingAlg_ALG__AES128__GCM__IV12__TAG16, + AesWrappingAlg_ALG__AES192__GCM__IV12__TAG16, + AesWrappingAlg_ALG__AES256__GCM__IV12__TAG16, + AlgorithmSuiteId_DBE, + AlgorithmSuiteId_ESDK, + AlgorithmSuiteInfo_AlgorithmSuiteInfo as DafnyAlgorithmSuiteInfo, + CacheType_Default, + CacheType_MultiThreaded, + CacheType_No, + CacheType_Shared, + CacheType_SingleThreaded, + CacheType_StormTracking, + CommitmentPolicy_DBE, + CommitmentPolicy_ESDK, + CreateAwsKmsDiscoveryKeyringInput_CreateAwsKmsDiscoveryKeyringInput as DafnyCreateAwsKmsDiscoveryKeyringInput, + CreateAwsKmsDiscoveryMultiKeyringInput_CreateAwsKmsDiscoveryMultiKeyringInput as DafnyCreateAwsKmsDiscoveryMultiKeyringInput, + CreateAwsKmsEcdhKeyringInput_CreateAwsKmsEcdhKeyringInput as DafnyCreateAwsKmsEcdhKeyringInput, + CreateAwsKmsHierarchicalKeyringInput_CreateAwsKmsHierarchicalKeyringInput as DafnyCreateAwsKmsHierarchicalKeyringInput, + CreateAwsKmsKeyringInput_CreateAwsKmsKeyringInput as DafnyCreateAwsKmsKeyringInput, + CreateAwsKmsMrkDiscoveryKeyringInput_CreateAwsKmsMrkDiscoveryKeyringInput as DafnyCreateAwsKmsMrkDiscoveryKeyringInput, + CreateAwsKmsMrkDiscoveryMultiKeyringInput_CreateAwsKmsMrkDiscoveryMultiKeyringInput as DafnyCreateAwsKmsMrkDiscoveryMultiKeyringInput, + CreateAwsKmsMrkKeyringInput_CreateAwsKmsMrkKeyringInput as DafnyCreateAwsKmsMrkKeyringInput, + CreateAwsKmsMrkMultiKeyringInput_CreateAwsKmsMrkMultiKeyringInput as DafnyCreateAwsKmsMrkMultiKeyringInput, + CreateAwsKmsMultiKeyringInput_CreateAwsKmsMultiKeyringInput as DafnyCreateAwsKmsMultiKeyringInput, + CreateAwsKmsRsaKeyringInput_CreateAwsKmsRsaKeyringInput as DafnyCreateAwsKmsRsaKeyringInput, + CreateCryptographicMaterialsCacheInput_CreateCryptographicMaterialsCacheInput as DafnyCreateCryptographicMaterialsCacheInput, + CreateDefaultClientSupplierInput_CreateDefaultClientSupplierInput as DafnyCreateDefaultClientSupplierInput, + CreateDefaultCryptographicMaterialsManagerInput_CreateDefaultCryptographicMaterialsManagerInput as DafnyCreateDefaultCryptographicMaterialsManagerInput, + CreateMultiKeyringInput_CreateMultiKeyringInput as DafnyCreateMultiKeyringInput, + CreateRawAesKeyringInput_CreateRawAesKeyringInput as DafnyCreateRawAesKeyringInput, + CreateRawEcdhKeyringInput_CreateRawEcdhKeyringInput as DafnyCreateRawEcdhKeyringInput, + CreateRawRsaKeyringInput_CreateRawRsaKeyringInput as DafnyCreateRawRsaKeyringInput, + CreateRequiredEncryptionContextCMMInput_CreateRequiredEncryptionContextCMMInput as DafnyCreateRequiredEncryptionContextCMMInput, + DBEAlgorithmSuiteId_ALG__AES__256__GCM__HKDF__SHA512__COMMIT__KEY__ECDSA__P384__SYMSIG__HMAC__SHA384, + DBEAlgorithmSuiteId_ALG__AES__256__GCM__HKDF__SHA512__COMMIT__KEY__SYMSIG__HMAC__SHA384, + DBECommitmentPolicy_REQUIRE__ENCRYPT__REQUIRE__DECRYPT, + DIRECT__KEY__WRAPPING_DIRECT__KEY__WRAPPING as DafnyDIRECT_KEY_WRAPPING, + DecryptMaterialsInput_DecryptMaterialsInput as DafnyDecryptMaterialsInput, + DecryptMaterialsOutput_DecryptMaterialsOutput as DafnyDecryptMaterialsOutput, + DecryptionMaterials_DecryptionMaterials as DafnyDecryptionMaterials, + DefaultCache_DefaultCache as DafnyDefaultCache, + DeleteCacheEntryInput_DeleteCacheEntryInput as DafnyDeleteCacheEntryInput, + DerivationAlgorithm_HKDF, + DerivationAlgorithm_IDENTITY, + DerivationAlgorithm_None, + DiscoveryFilter_DiscoveryFilter as DafnyDiscoveryFilter, + ECDSA_ECDSA as DafnyECDSA, + ESDKAlgorithmSuiteId_ALG__AES__128__GCM__IV12__TAG16__HKDF__SHA256, + ESDKAlgorithmSuiteId_ALG__AES__128__GCM__IV12__TAG16__HKDF__SHA256__ECDSA__P256, + ESDKAlgorithmSuiteId_ALG__AES__128__GCM__IV12__TAG16__NO__KDF, + ESDKAlgorithmSuiteId_ALG__AES__192__GCM__IV12__TAG16__HKDF__SHA256, + ESDKAlgorithmSuiteId_ALG__AES__192__GCM__IV12__TAG16__HKDF__SHA384__ECDSA__P384, + ESDKAlgorithmSuiteId_ALG__AES__192__GCM__IV12__TAG16__NO__KDF, + ESDKAlgorithmSuiteId_ALG__AES__256__GCM__HKDF__SHA512__COMMIT__KEY, + ESDKAlgorithmSuiteId_ALG__AES__256__GCM__HKDF__SHA512__COMMIT__KEY__ECDSA__P384, + ESDKAlgorithmSuiteId_ALG__AES__256__GCM__IV12__TAG16__HKDF__SHA256, + ESDKAlgorithmSuiteId_ALG__AES__256__GCM__IV12__TAG16__HKDF__SHA384__ECDSA__P384, + ESDKAlgorithmSuiteId_ALG__AES__256__GCM__IV12__TAG16__NO__KDF, + ESDKCommitmentPolicy_FORBID__ENCRYPT__ALLOW__DECRYPT, + ESDKCommitmentPolicy_REQUIRE__ENCRYPT__ALLOW__DECRYPT, + ESDKCommitmentPolicy_REQUIRE__ENCRYPT__REQUIRE__DECRYPT, + EdkWrappingAlgorithm_DIRECT__KEY__WRAPPING, + EdkWrappingAlgorithm_IntermediateKeyWrapping, + Encrypt_AES__GCM, + EncryptedDataKey_EncryptedDataKey as DafnyEncryptedDataKey, + EncryptionMaterials_EncryptionMaterials as DafnyEncryptionMaterials, + EphemeralPrivateKeyToStaticPublicKeyInput_EphemeralPrivateKeyToStaticPublicKeyInput as DafnyEphemeralPrivateKeyToStaticPublicKeyInput, + GetBranchKeyIdInput_GetBranchKeyIdInput as DafnyGetBranchKeyIdInput, + GetBranchKeyIdOutput_GetBranchKeyIdOutput as DafnyGetBranchKeyIdOutput, + GetCacheEntryInput_GetCacheEntryInput as DafnyGetCacheEntryInput, + GetCacheEntryOutput_GetCacheEntryOutput as DafnyGetCacheEntryOutput, + GetClientInput_GetClientInput as DafnyGetClientInput, + GetEncryptionMaterialsInput_GetEncryptionMaterialsInput as DafnyGetEncryptionMaterialsInput, + GetEncryptionMaterialsOutput_GetEncryptionMaterialsOutput as DafnyGetEncryptionMaterialsOutput, + HKDF_HKDF as DafnyHKDF, + IDENTITY_IDENTITY as DafnyIDENTITY, + InitializeDecryptionMaterialsInput_InitializeDecryptionMaterialsInput as DafnyInitializeDecryptionMaterialsInput, + InitializeEncryptionMaterialsInput_InitializeEncryptionMaterialsInput as DafnyInitializeEncryptionMaterialsInput, + IntermediateKeyWrapping_IntermediateKeyWrapping as DafnyIntermediateKeyWrapping, + KmsEcdhStaticConfigurations_KmsPrivateKeyToStaticPublicKey, + KmsEcdhStaticConfigurations_KmsPublicKeyDiscovery, + KmsPrivateKeyToStaticPublicKeyInput_KmsPrivateKeyToStaticPublicKeyInput as DafnyKmsPrivateKeyToStaticPublicKeyInput, + KmsPublicKeyDiscoveryInput_KmsPublicKeyDiscoveryInput as DafnyKmsPublicKeyDiscoveryInput, + MaterialProvidersConfig_MaterialProvidersConfig as DafnyMaterialProvidersConfig, + Materials_BeaconKey, + Materials_BranchKey, + Materials_Decryption, + Materials_Encryption, + MultiThreadedCache_MultiThreadedCache as DafnyMultiThreadedCache, + NoCache_NoCache as DafnyNoCache, + None__None as DafnyNone, + OnDecryptInput_OnDecryptInput as DafnyOnDecryptInput, + OnDecryptOutput_OnDecryptOutput as DafnyOnDecryptOutput, + OnEncryptInput_OnEncryptInput as DafnyOnEncryptInput, + OnEncryptOutput_OnEncryptOutput as DafnyOnEncryptOutput, + PaddingScheme_OAEP__SHA1__MGF1, + PaddingScheme_OAEP__SHA256__MGF1, + PaddingScheme_OAEP__SHA384__MGF1, + PaddingScheme_OAEP__SHA512__MGF1, + PaddingScheme_PKCS1, + PublicKeyDiscoveryInput_PublicKeyDiscoveryInput as DafnyPublicKeyDiscoveryInput, + PutCacheEntryInput_PutCacheEntryInput as DafnyPutCacheEntryInput, + RawEcdhStaticConfigurations_EphemeralPrivateKeyToStaticPublicKey, + RawEcdhStaticConfigurations_PublicKeyDiscovery, + RawEcdhStaticConfigurations_RawPrivateKeyToStaticPublicKey, + RawPrivateKeyToStaticPublicKeyInput_RawPrivateKeyToStaticPublicKeyInput as DafnyRawPrivateKeyToStaticPublicKeyInput, + SignatureAlgorithm_ECDSA, + SignatureAlgorithm_None, + SingleThreadedCache_SingleThreadedCache as DafnySingleThreadedCache, + StormTrackingCache_StormTrackingCache as DafnyStormTrackingCache, + SymmetricSignatureAlgorithm_HMAC, + SymmetricSignatureAlgorithm_None, + UpdateUsageMetadataInput_UpdateUsageMetadataInput as DafnyUpdateUsageMetadataInput, + ValidDecryptionMaterialsTransitionInput_ValidDecryptionMaterialsTransitionInput as DafnyValidDecryptionMaterialsTransitionInput, + ValidEncryptionMaterialsTransitionInput_ValidEncryptionMaterialsTransitionInput as DafnyValidEncryptionMaterialsTransitionInput, + ValidateCommitmentPolicyOnDecryptInput_ValidateCommitmentPolicyOnDecryptInput as DafnyValidateCommitmentPolicyOnDecryptInput, + ValidateCommitmentPolicyOnEncryptInput_ValidateCommitmentPolicyOnEncryptInput as DafnyValidateCommitmentPolicyOnEncryptInput, +) +import aws_cryptographic_materialproviders.internaldafny.generated.module_ +import aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_keystore.smithy_to_dafny +import aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models +import aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny +from aws_cryptography_internal_kms.internaldafny.generated.ComAmazonawsKmsTypes import ( + IKMSClient, +) +import aws_cryptography_internal_kms.internaldafny.generated.module_ +import aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny +import aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.smithy_to_dafny +from smithy_dafny_standard_library.internaldafny.generated.Wrappers import ( + Option_None, + Option_Some, +) + + +def aws_cryptography_materialproviders_GetBranchKeyIdInput(native_input): + return DafnyGetBranchKeyIdInput( + encryptionContext=Map( + { + Seq(key.encode("utf-8")): Seq(value.encode("utf-8")) + for (key, value) in native_input.encryption_context.items() + } + ), + ) + + +def aws_cryptography_materialproviders_GetBranchKeyIdOutput(native_input): + return DafnyGetBranchKeyIdOutput( + branchKeyId=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input.branch_key_id.encode("utf-16-be"))] * 2 + ) + ] + ) + ), + ) + + +def aws_cryptography_materialproviders_GetClientInput(native_input): + return DafnyGetClientInput( + region=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input.region.encode("utf-16-be"))] * 2 + ) + ] + ) + ), + ) + + +def aws_cryptography_materialproviders_GetClientOutput(native_input): + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_KmsClientReference( + native_input + ) + + +def aws_cryptography_materialproviders_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 + + +def aws_cryptography_materialproviders_PutCacheEntryInput(native_input): + return DafnyPutCacheEntryInput( + identifier=Seq(native_input.identifier), + materials=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_Materials( + native_input.materials + ), + creationTime=native_input.creation_time, + expiryTime=native_input.expiry_time, + messagesUsed=( + (Option_Some(native_input.messages_used)) + if (native_input.messages_used is not None) + else (Option_None()) + ), + bytesUsed=( + (Option_Some(native_input.bytes_used)) + if (native_input.bytes_used is not None) + else (Option_None()) + ), + ) + + +def aws_cryptography_materialproviders_Materials(native_input): + if isinstance( + native_input, + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.MaterialsEncryption, + ): + Materials_union_value = Materials_Encryption( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_EncryptionMaterials( + native_input.value + ) + ) + elif isinstance( + native_input, + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.MaterialsDecryption, + ): + Materials_union_value = Materials_Decryption( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_DecryptionMaterials( + native_input.value + ) + ) + elif isinstance( + native_input, + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.MaterialsBranchKey, + ): + Materials_union_value = Materials_BranchKey( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_BranchKeyMaterials( + native_input.value + ) + ) + elif isinstance( + native_input, + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.MaterialsBeaconKey, + ): + Materials_union_value = Materials_BeaconKey( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_keystore.smithy_to_dafny.aws_cryptography_keystore_BeaconKeyMaterials( + native_input.value + ) + ) + else: + raise ValueError( + "No recognized union value in union type: " + str(native_input) + ) + + return Materials_union_value + + +def aws_cryptography_materialproviders_EncryptionMaterials(native_input): + return DafnyEncryptionMaterials( + algorithmSuite=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_AlgorithmSuiteInfo( + native_input.algorithm_suite + ), + encryptionContext=Map( + { + Seq(key.encode("utf-8")): Seq(value.encode("utf-8")) + for (key, value) in native_input.encryption_context.items() + } + ), + encryptedDataKeys=Seq( + [ + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_EncryptedDataKey( + list_element + ) + for list_element in native_input.encrypted_data_keys + ] + ), + requiredEncryptionContextKeys=Seq( + [ + Seq(list_element.encode("utf-8")) + for list_element in native_input.required_encryption_context_keys + ] + ), + plaintextDataKey=( + (Option_Some(Seq(native_input.plaintext_data_key))) + if (native_input.plaintext_data_key is not None) + else (Option_None()) + ), + signingKey=( + (Option_Some(Seq(native_input.signing_key))) + if (native_input.signing_key is not None) + else (Option_None()) + ), + symmetricSigningKeys=( + ( + Option_Some( + Seq( + [ + Seq(list_element) + for list_element in native_input.symmetric_signing_keys + ] + ) + ) + ) + if (native_input.symmetric_signing_keys is not None) + else (Option_None()) + ), + ) + + +def aws_cryptography_materialproviders_DecryptionMaterials(native_input): + return DafnyDecryptionMaterials( + algorithmSuite=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_AlgorithmSuiteInfo( + native_input.algorithm_suite + ), + encryptionContext=Map( + { + Seq(key.encode("utf-8")): Seq(value.encode("utf-8")) + for (key, value) in native_input.encryption_context.items() + } + ), + requiredEncryptionContextKeys=Seq( + [ + Seq(list_element.encode("utf-8")) + for list_element in native_input.required_encryption_context_keys + ] + ), + plaintextDataKey=( + (Option_Some(Seq(native_input.plaintext_data_key))) + if (native_input.plaintext_data_key is not None) + else (Option_None()) + ), + verificationKey=( + (Option_Some(Seq(native_input.verification_key))) + if (native_input.verification_key is not None) + else (Option_None()) + ), + symmetricSigningKey=( + (Option_Some(Seq(native_input.symmetric_signing_key))) + if (native_input.symmetric_signing_key is not None) + else (Option_None()) + ), + ) + + +def aws_cryptography_materialproviders_AlgorithmSuiteInfo(native_input): + return DafnyAlgorithmSuiteInfo( + id=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_AlgorithmSuiteId( + native_input.id + ), + binaryId=Seq(native_input.binary_id), + messageVersion=native_input.message_version, + encrypt=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_Encrypt( + native_input.encrypt + ), + kdf=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_DerivationAlgorithm( + native_input.kdf + ), + commitment=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_DerivationAlgorithm( + native_input.commitment + ), + signature=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_SignatureAlgorithm( + native_input.signature + ), + symmetricSignature=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_SymmetricSignatureAlgorithm( + native_input.symmetric_signature + ), + edkWrapping=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_EdkWrappingAlgorithm( + native_input.edk_wrapping + ), + ) + + +def aws_cryptography_materialproviders_EncryptedDataKey(native_input): + return DafnyEncryptedDataKey( + keyProviderId=Seq(native_input.key_provider_id.encode("utf-8")), + keyProviderInfo=Seq(native_input.key_provider_info), + ciphertext=Seq(native_input.ciphertext), + ) + + +def aws_cryptography_materialproviders_AlgorithmSuiteId(native_input): + if isinstance( + native_input, + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.AlgorithmSuiteIdESDK, + ): + AlgorithmSuiteId_union_value = AlgorithmSuiteId_ESDK( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_ESDKAlgorithmSuiteId( + native_input.value + ) + ) + elif isinstance( + native_input, + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.AlgorithmSuiteIdDBE, + ): + AlgorithmSuiteId_union_value = AlgorithmSuiteId_DBE( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_DBEAlgorithmSuiteId( + native_input.value + ) + ) + else: + raise ValueError( + "No recognized union value in union type: " + str(native_input) + ) + + return AlgorithmSuiteId_union_value + + +def aws_cryptography_materialproviders_Encrypt(native_input): + if isinstance( + native_input, + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.EncryptAES_GCM, + ): + Encrypt_union_value = Encrypt_AES__GCM( + aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.smithy_to_dafny.aws_cryptography_primitives_AES_GCM( + native_input.value + ) + ) + else: + raise ValueError( + "No recognized union value in union type: " + str(native_input) + ) + + return Encrypt_union_value + + +def aws_cryptography_materialproviders_DerivationAlgorithm(native_input): + if isinstance( + native_input, + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.DerivationAlgorithmHKDF, + ): + DerivationAlgorithm_union_value = DerivationAlgorithm_HKDF( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_HKDF( + native_input.value + ) + ) + elif isinstance( + native_input, + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.DerivationAlgorithmIDENTITY, + ): + DerivationAlgorithm_union_value = DerivationAlgorithm_IDENTITY( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_IDENTITY( + native_input.value + ) + ) + elif isinstance( + native_input, + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.DerivationAlgorithmNone, + ): + DerivationAlgorithm_union_value = DerivationAlgorithm_None( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_None( + native_input.value + ) + ) + else: + raise ValueError( + "No recognized union value in union type: " + str(native_input) + ) + + return DerivationAlgorithm_union_value + + +def aws_cryptography_materialproviders_SignatureAlgorithm(native_input): + if isinstance( + native_input, + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.SignatureAlgorithmECDSA, + ): + SignatureAlgorithm_union_value = SignatureAlgorithm_ECDSA( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_ECDSA( + native_input.value + ) + ) + elif isinstance( + native_input, + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.SignatureAlgorithmNone, + ): + SignatureAlgorithm_union_value = SignatureAlgorithm_None( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_None( + native_input.value + ) + ) + else: + raise ValueError( + "No recognized union value in union type: " + str(native_input) + ) + + return SignatureAlgorithm_union_value + + +def aws_cryptography_materialproviders_SymmetricSignatureAlgorithm(native_input): + if isinstance( + native_input, + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.SymmetricSignatureAlgorithmHMAC, + ): + SymmetricSignatureAlgorithm_union_value = SymmetricSignatureAlgorithm_HMAC( + aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.smithy_to_dafny.aws_cryptography_primitives_DigestAlgorithm( + native_input.value + ) + ) + elif isinstance( + native_input, + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.SymmetricSignatureAlgorithmNone, + ): + SymmetricSignatureAlgorithm_union_value = SymmetricSignatureAlgorithm_None( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_None( + native_input.value + ) + ) + else: + raise ValueError( + "No recognized union value in union type: " + str(native_input) + ) + + return SymmetricSignatureAlgorithm_union_value + + +def aws_cryptography_materialproviders_EdkWrappingAlgorithm(native_input): + if isinstance( + native_input, + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.EdkWrappingAlgorithmDIRECT_KEY_WRAPPING, + ): + EdkWrappingAlgorithm_union_value = EdkWrappingAlgorithm_DIRECT__KEY__WRAPPING( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_DIRECT_KEY_WRAPPING( + native_input.value + ) + ) + elif isinstance( + native_input, + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.EdkWrappingAlgorithmIntermediateKeyWrapping, + ): + EdkWrappingAlgorithm_union_value = EdkWrappingAlgorithm_IntermediateKeyWrapping( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_IntermediateKeyWrapping( + native_input.value + ) + ) + else: + raise ValueError( + "No recognized union value in union type: " + str(native_input) + ) + + return EdkWrappingAlgorithm_union_value + + +def aws_cryptography_materialproviders_ESDKAlgorithmSuiteId(native_input): + if native_input == "0x0014": + return ESDKAlgorithmSuiteId_ALG__AES__128__GCM__IV12__TAG16__NO__KDF() + + elif native_input == "0x0046": + return ESDKAlgorithmSuiteId_ALG__AES__192__GCM__IV12__TAG16__NO__KDF() + + elif native_input == "0x0078": + return ESDKAlgorithmSuiteId_ALG__AES__256__GCM__IV12__TAG16__NO__KDF() + + elif native_input == "0x0114": + return ESDKAlgorithmSuiteId_ALG__AES__128__GCM__IV12__TAG16__HKDF__SHA256() + + elif native_input == "0x0146": + return ESDKAlgorithmSuiteId_ALG__AES__192__GCM__IV12__TAG16__HKDF__SHA256() + + elif native_input == "0x0178": + return ESDKAlgorithmSuiteId_ALG__AES__256__GCM__IV12__TAG16__HKDF__SHA256() + + elif native_input == "0x0214": + return ( + ESDKAlgorithmSuiteId_ALG__AES__128__GCM__IV12__TAG16__HKDF__SHA256__ECDSA__P256() + ) + + elif native_input == "0x0346": + return ( + ESDKAlgorithmSuiteId_ALG__AES__192__GCM__IV12__TAG16__HKDF__SHA384__ECDSA__P384() + ) + + elif native_input == "0x0378": + return ( + ESDKAlgorithmSuiteId_ALG__AES__256__GCM__IV12__TAG16__HKDF__SHA384__ECDSA__P384() + ) + + elif native_input == "0x0478": + return ESDKAlgorithmSuiteId_ALG__AES__256__GCM__HKDF__SHA512__COMMIT__KEY() + + elif native_input == "0x0578": + return ( + ESDKAlgorithmSuiteId_ALG__AES__256__GCM__HKDF__SHA512__COMMIT__KEY__ECDSA__P384() + ) + + else: + raise ValueError(f"No recognized enum value in enum type: {native_input=}") + + +def aws_cryptography_materialproviders_DBEAlgorithmSuiteId(native_input): + if native_input == "0x6700": + return ( + DBEAlgorithmSuiteId_ALG__AES__256__GCM__HKDF__SHA512__COMMIT__KEY__SYMSIG__HMAC__SHA384() + ) + + elif native_input == "0x6701": + return ( + DBEAlgorithmSuiteId_ALG__AES__256__GCM__HKDF__SHA512__COMMIT__KEY__ECDSA__P384__SYMSIG__HMAC__SHA384() + ) + + else: + raise ValueError(f"No recognized enum value in enum type: {native_input=}") + + +def aws_cryptography_materialproviders_HKDF(native_input): + return DafnyHKDF( + hmac=aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.smithy_to_dafny.aws_cryptography_primitives_DigestAlgorithm( + native_input.hmac + ), + saltLength=native_input.salt_length, + inputKeyLength=native_input.input_key_length, + outputKeyLength=native_input.output_key_length, + ) + + +def aws_cryptography_materialproviders_IDENTITY(native_input): + return DafnyIDENTITY() + + +def aws_cryptography_materialproviders_None(native_input): + return DafnyNone() + + +def aws_cryptography_materialproviders_ECDSA(native_input): + return DafnyECDSA( + curve=aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.smithy_to_dafny.aws_cryptography_primitives_ECDSASignatureAlgorithm( + native_input.curve + ), + ) + + +def aws_cryptography_materialproviders_DIRECT_KEY_WRAPPING(native_input): + return DafnyDIRECT_KEY_WRAPPING() + + +def aws_cryptography_materialproviders_IntermediateKeyWrapping(native_input): + return DafnyIntermediateKeyWrapping( + keyEncryptionKeyKdf=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_DerivationAlgorithm( + native_input.key_encryption_key_kdf + ), + macKeyKdf=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_DerivationAlgorithm( + native_input.mac_key_kdf + ), + pdkEncryptAlgorithm=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_Encrypt( + native_input.pdk_encrypt_algorithm + ), + ) + + +def smithy_api_Unit(native_input): + return None + + +def aws_cryptography_materialproviders_GetCacheEntryInput(native_input): + return DafnyGetCacheEntryInput( + identifier=Seq(native_input.identifier), + bytesUsed=( + (Option_Some(native_input.bytes_used)) + if (native_input.bytes_used is not None) + else (Option_None()) + ), + ) + + +def aws_cryptography_materialproviders_GetCacheEntryOutput(native_input): + return DafnyGetCacheEntryOutput( + materials=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_Materials( + native_input.materials + ), + creationTime=native_input.creation_time, + expiryTime=native_input.expiry_time, + messagesUsed=native_input.messages_used, + bytesUsed=native_input.bytes_used, + ) + + +def aws_cryptography_materialproviders_UpdateUsageMetadataInput(native_input): + return DafnyUpdateUsageMetadataInput( + identifier=Seq(native_input.identifier), + bytesUsed=native_input.bytes_used, + ) + + +def aws_cryptography_materialproviders_DeleteCacheEntryInput(native_input): + return DafnyDeleteCacheEntryInput( + identifier=Seq(native_input.identifier), + ) + + +def aws_cryptography_materialproviders_GetEncryptionMaterialsInput(native_input): + return DafnyGetEncryptionMaterialsInput( + encryptionContext=Map( + { + Seq(key.encode("utf-8")): Seq(value.encode("utf-8")) + for (key, value) in native_input.encryption_context.items() + } + ), + commitmentPolicy=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_CommitmentPolicy( + native_input.commitment_policy + ), + algorithmSuiteId=( + ( + Option_Some( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_AlgorithmSuiteId( + native_input.algorithm_suite_id + ) + ) + ) + if (native_input.algorithm_suite_id is not None) + else (Option_None()) + ), + maxPlaintextLength=( + (Option_Some(native_input.max_plaintext_length)) + if (native_input.max_plaintext_length is not None) + else (Option_None()) + ), + requiredEncryptionContextKeys=( + ( + Option_Some( + Seq( + [ + Seq(list_element.encode("utf-8")) + for list_element in native_input.required_encryption_context_keys + ] + ) + ) + ) + if (native_input.required_encryption_context_keys is not None) + else (Option_None()) + ), + ) + + +def aws_cryptography_materialproviders_CommitmentPolicy(native_input): + if isinstance( + native_input, + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.CommitmentPolicyESDK, + ): + CommitmentPolicy_union_value = CommitmentPolicy_ESDK( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_ESDKCommitmentPolicy( + native_input.value + ) + ) + elif isinstance( + native_input, + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.CommitmentPolicyDBE, + ): + CommitmentPolicy_union_value = CommitmentPolicy_DBE( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_DBECommitmentPolicy( + native_input.value + ) + ) + else: + raise ValueError( + "No recognized union value in union type: " + str(native_input) + ) + + return CommitmentPolicy_union_value + + +def aws_cryptography_materialproviders_ESDKCommitmentPolicy(native_input): + if native_input == "FORBID_ENCRYPT_ALLOW_DECRYPT": + return ESDKCommitmentPolicy_FORBID__ENCRYPT__ALLOW__DECRYPT() + + elif native_input == "REQUIRE_ENCRYPT_ALLOW_DECRYPT": + return ESDKCommitmentPolicy_REQUIRE__ENCRYPT__ALLOW__DECRYPT() + + elif native_input == "REQUIRE_ENCRYPT_REQUIRE_DECRYPT": + return ESDKCommitmentPolicy_REQUIRE__ENCRYPT__REQUIRE__DECRYPT() + + else: + raise ValueError(f"No recognized enum value in enum type: {native_input=}") + + +def aws_cryptography_materialproviders_DBECommitmentPolicy(native_input): + if native_input == "REQUIRE_ENCRYPT_REQUIRE_DECRYPT": + return DBECommitmentPolicy_REQUIRE__ENCRYPT__REQUIRE__DECRYPT() + + else: + raise ValueError(f"No recognized enum value in enum type: {native_input=}") + + +def aws_cryptography_materialproviders_GetEncryptionMaterialsOutput(native_input): + return DafnyGetEncryptionMaterialsOutput( + encryptionMaterials=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_EncryptionMaterials( + native_input.encryption_materials + ), + ) + + +def aws_cryptography_materialproviders_DecryptMaterialsInput(native_input): + return DafnyDecryptMaterialsInput( + algorithmSuiteId=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_AlgorithmSuiteId( + native_input.algorithm_suite_id + ), + commitmentPolicy=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_CommitmentPolicy( + native_input.commitment_policy + ), + encryptedDataKeys=Seq( + [ + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_EncryptedDataKey( + list_element + ) + for list_element in native_input.encrypted_data_keys + ] + ), + encryptionContext=Map( + { + Seq(key.encode("utf-8")): Seq(value.encode("utf-8")) + for (key, value) in native_input.encryption_context.items() + } + ), + reproducedEncryptionContext=( + ( + Option_Some( + Map( + { + Seq(key.encode("utf-8")): Seq(value.encode("utf-8")) + for ( + key, + value, + ) in native_input.reproduced_encryption_context.items() + } + ) + ) + ) + if (native_input.reproduced_encryption_context is not None) + else (Option_None()) + ), + ) + + +def aws_cryptography_materialproviders_DecryptMaterialsOutput(native_input): + return DafnyDecryptMaterialsOutput( + decryptionMaterials=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_DecryptionMaterials( + native_input.decryption_materials + ), + ) + + +def aws_cryptography_materialproviders_OnEncryptInput(native_input): + return DafnyOnEncryptInput( + materials=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_EncryptionMaterials( + native_input.materials + ), + ) + + +def aws_cryptography_materialproviders_OnEncryptOutput(native_input): + return DafnyOnEncryptOutput( + materials=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_EncryptionMaterials( + native_input.materials + ), + ) + + +def aws_cryptography_materialproviders_OnDecryptInput(native_input): + return DafnyOnDecryptInput( + materials=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_DecryptionMaterials( + native_input.materials + ), + encryptedDataKeys=Seq( + [ + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_EncryptedDataKey( + list_element + ) + for list_element in native_input.encrypted_data_keys + ] + ), + ) + + +def aws_cryptography_materialproviders_OnDecryptOutput(native_input): + return DafnyOnDecryptOutput( + materials=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_DecryptionMaterials( + native_input.materials + ), + ) + + +def aws_cryptography_materialproviders_CreateAwsKmsKeyringInput(native_input): + return DafnyCreateAwsKmsKeyringInput( + kmsKeyId=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input.kms_key_id.encode("utf-16-be"))] * 2 + ) + ] + ) + ), + kmsClient=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_KmsClientReference( + native_input.kms_client + ), + 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()) + ), + ) + + +def aws_cryptography_materialproviders_CreateAwsKmsDiscoveryKeyringInput(native_input): + return DafnyCreateAwsKmsDiscoveryKeyringInput( + kmsClient=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_KmsClientReference( + native_input.kms_client + ), + discoveryFilter=( + ( + Option_Some( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_DiscoveryFilter( + native_input.discovery_filter + ) + ) + ) + if (native_input.discovery_filter is not None) + else (Option_None()) + ), + 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()) + ), + ) + + +def aws_cryptography_materialproviders_DiscoveryFilter(native_input): + return DafnyDiscoveryFilter( + accountIds=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.account_ids + ] + ), + partition=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input.partition.encode("utf-16-be"))] * 2 + ) + ] + ) + ), + ) + + +def aws_cryptography_materialproviders_CreateAwsKmsMultiKeyringInput(native_input): + return DafnyCreateAwsKmsMultiKeyringInput( + generator=( + ( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input.generator.encode("utf-16-be"))] + * 2 + ) + ] + ) + ) + ) + ) + if (native_input.generator is not None) + else (Option_None()) + ), + kmsKeyIds=( + ( + 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.kms_key_ids + ] + ) + ) + ) + if (native_input.kms_key_ids is not None) + else (Option_None()) + ), + clientSupplier=( + ( + Option_Some( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_ClientSupplierReference( + native_input.client_supplier + ) + ) + ) + if ( + (native_input.client_supplier is not None) + and ( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_ClientSupplierReference( + native_input.client_supplier + ) + is not None + ) + ) + else (Option_None()) + ), + 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()) + ), + ) + + +def aws_cryptography_materialproviders_ClientSupplierReference(native_input): + if hasattr(native_input, "_impl"): + return native_input._impl + + else: + return native_input + + +def aws_cryptography_materialproviders_CreateAwsKmsDiscoveryMultiKeyringInput( + native_input, +): + return DafnyCreateAwsKmsDiscoveryMultiKeyringInput( + regions=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.regions + ] + ), + discoveryFilter=( + ( + Option_Some( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_DiscoveryFilter( + native_input.discovery_filter + ) + ) + ) + if (native_input.discovery_filter is not None) + else (Option_None()) + ), + clientSupplier=( + ( + Option_Some( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_ClientSupplierReference( + native_input.client_supplier + ) + ) + ) + if ( + (native_input.client_supplier is not None) + and ( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_ClientSupplierReference( + native_input.client_supplier + ) + is not None + ) + ) + else (Option_None()) + ), + 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()) + ), + ) + + +def aws_cryptography_materialproviders_CreateAwsKmsMrkKeyringInput(native_input): + return DafnyCreateAwsKmsMrkKeyringInput( + kmsKeyId=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input.kms_key_id.encode("utf-16-be"))] * 2 + ) + ] + ) + ), + kmsClient=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_KmsClientReference( + native_input.kms_client + ), + 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()) + ), + ) + + +def aws_cryptography_materialproviders_CreateAwsKmsMrkMultiKeyringInput(native_input): + return DafnyCreateAwsKmsMrkMultiKeyringInput( + generator=( + ( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input.generator.encode("utf-16-be"))] + * 2 + ) + ] + ) + ) + ) + ) + if (native_input.generator is not None) + else (Option_None()) + ), + kmsKeyIds=( + ( + 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.kms_key_ids + ] + ) + ) + ) + if (native_input.kms_key_ids is not None) + else (Option_None()) + ), + clientSupplier=( + ( + Option_Some( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_ClientSupplierReference( + native_input.client_supplier + ) + ) + ) + if ( + (native_input.client_supplier is not None) + and ( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_ClientSupplierReference( + native_input.client_supplier + ) + is not None + ) + ) + else (Option_None()) + ), + 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()) + ), + ) + + +def aws_cryptography_materialproviders_CreateAwsKmsMrkDiscoveryKeyringInput( + native_input, +): + return DafnyCreateAwsKmsMrkDiscoveryKeyringInput( + kmsClient=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_KmsClientReference( + native_input.kms_client + ), + discoveryFilter=( + ( + Option_Some( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_DiscoveryFilter( + native_input.discovery_filter + ) + ) + ) + if (native_input.discovery_filter is not None) + else (Option_None()) + ), + 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()) + ), + region=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input.region.encode("utf-16-be"))] * 2 + ) + ] + ) + ), + ) + + +def aws_cryptography_materialproviders_CreateAwsKmsMrkDiscoveryMultiKeyringInput( + native_input, +): + return DafnyCreateAwsKmsMrkDiscoveryMultiKeyringInput( + regions=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.regions + ] + ), + discoveryFilter=( + ( + Option_Some( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_DiscoveryFilter( + native_input.discovery_filter + ) + ) + ) + if (native_input.discovery_filter is not None) + else (Option_None()) + ), + clientSupplier=( + ( + Option_Some( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_ClientSupplierReference( + native_input.client_supplier + ) + ) + ) + if ( + (native_input.client_supplier is not None) + and ( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_ClientSupplierReference( + native_input.client_supplier + ) + is not None + ) + ) + else (Option_None()) + ), + 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()) + ), + ) + + +def aws_cryptography_materialproviders_CreateAwsKmsHierarchicalKeyringInput( + native_input, +): + return DafnyCreateAwsKmsHierarchicalKeyringInput( + branchKeyId=( + ( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[ + iter( + native_input.branch_key_id.encode( + "utf-16-be" + ) + ) + ] + * 2 + ) + ] + ) + ) + ) + ) + if (native_input.branch_key_id is not None) + else (Option_None()) + ), + branchKeyIdSupplier=( + ( + Option_Some( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_BranchKeyIdSupplierReference( + native_input.branch_key_id_supplier + ) + ) + ) + if ( + (native_input.branch_key_id_supplier is not None) + and ( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_BranchKeyIdSupplierReference( + native_input.branch_key_id_supplier + ) + is not None + ) + ) + else (Option_None()) + ), + keyStore=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_KeyStoreReference( + native_input.key_store + ), + ttlSeconds=native_input.ttl_seconds, + cache=( + ( + Option_Some( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_CacheType( + native_input.cache + ) + ) + ) + if (native_input.cache is not None) + else (Option_None()) + ), + partitionId=( + ( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[ + iter( + native_input.partition_id.encode( + "utf-16-be" + ) + ) + ] + * 2 + ) + ] + ) + ) + ) + ) + if (native_input.partition_id is not None) + else (Option_None()) + ), + ) + + +def aws_cryptography_materialproviders_BranchKeyIdSupplierReference(native_input): + if hasattr(native_input, "_impl"): + return native_input._impl + + else: + return native_input + + +def aws_cryptography_materialproviders_KeyStoreReference(native_input): + return native_input._config.dafnyImplInterface.impl + + +def aws_cryptography_materialproviders_CacheType(native_input): + if isinstance( + native_input, + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.CacheTypeDefault, + ): + CacheType_union_value = CacheType_Default( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_DefaultCache( + native_input.value + ) + ) + elif isinstance( + native_input, + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.CacheTypeNo, + ): + CacheType_union_value = CacheType_No( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_NoCache( + native_input.value + ) + ) + elif isinstance( + native_input, + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.CacheTypeSingleThreaded, + ): + CacheType_union_value = CacheType_SingleThreaded( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_SingleThreadedCache( + native_input.value + ) + ) + elif isinstance( + native_input, + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.CacheTypeMultiThreaded, + ): + CacheType_union_value = CacheType_MultiThreaded( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_MultiThreadedCache( + native_input.value + ) + ) + elif isinstance( + native_input, + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.CacheTypeStormTracking, + ): + CacheType_union_value = CacheType_StormTracking( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_StormTrackingCache( + native_input.value + ) + ) + elif isinstance( + native_input, + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.CacheTypeShared, + ): + CacheType_union_value = CacheType_Shared( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_CryptographicMaterialsCacheReference( + native_input.value + ) + ) + else: + raise ValueError( + "No recognized union value in union type: " + str(native_input) + ) + + return CacheType_union_value + + +def aws_cryptography_materialproviders_DefaultCache(native_input): + return DafnyDefaultCache( + entryCapacity=native_input.entry_capacity, + ) + + +def aws_cryptography_materialproviders_NoCache(native_input): + return DafnyNoCache() + + +def aws_cryptography_materialproviders_SingleThreadedCache(native_input): + return DafnySingleThreadedCache( + entryCapacity=native_input.entry_capacity, + entryPruningTailSize=( + (Option_Some(native_input.entry_pruning_tail_size)) + if (native_input.entry_pruning_tail_size is not None) + else (Option_None()) + ), + ) + + +def aws_cryptography_materialproviders_MultiThreadedCache(native_input): + return DafnyMultiThreadedCache( + entryCapacity=native_input.entry_capacity, + entryPruningTailSize=( + (Option_Some(native_input.entry_pruning_tail_size)) + if (native_input.entry_pruning_tail_size is not None) + else (Option_None()) + ), + ) + + +def aws_cryptography_materialproviders_StormTrackingCache(native_input): + return DafnyStormTrackingCache( + entryCapacity=native_input.entry_capacity, + entryPruningTailSize=( + (Option_Some(native_input.entry_pruning_tail_size)) + if (native_input.entry_pruning_tail_size is not None) + else (Option_None()) + ), + gracePeriod=native_input.grace_period, + graceInterval=native_input.grace_interval, + fanOut=native_input.fan_out, + inFlightTTL=native_input.in_flight_ttl, + sleepMilli=native_input.sleep_milli, + ) + + +def aws_cryptography_materialproviders_CryptographicMaterialsCacheReference( + native_input, +): + if hasattr(native_input, "_impl"): + return native_input._impl + + else: + return native_input + + +def aws_cryptography_materialproviders_CreateAwsKmsRsaKeyringInput(native_input): + return DafnyCreateAwsKmsRsaKeyringInput( + publicKey=( + (Option_Some(Seq(native_input.public_key))) + if (native_input.public_key is not None) + else (Option_None()) + ), + kmsKeyId=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input.kms_key_id.encode("utf-16-be"))] * 2 + ) + ] + ) + ), + encryptionAlgorithm=aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_EncryptionAlgorithmSpec( + native_input.encryption_algorithm + ), + kmsClient=( + ( + Option_Some( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_KmsClientReference( + native_input.kms_client + ) + ) + ) + if ( + (native_input.kms_client is not None) + and ( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_KmsClientReference( + native_input.kms_client + ) + is not None + ) + ) + else (Option_None()) + ), + 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()) + ), + ) + + +def aws_cryptography_materialproviders_CreateAwsKmsEcdhKeyringInput(native_input): + return DafnyCreateAwsKmsEcdhKeyringInput( + KeyAgreementScheme=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_KmsEcdhStaticConfigurations( + native_input.key_agreement_scheme + ), + curveSpec=aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.smithy_to_dafny.aws_cryptography_primitives_ECDHCurveSpec( + native_input.curve_spec + ), + kmsClient=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_KmsClientReference( + native_input.kms_client + ), + 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()) + ), + ) + + +def aws_cryptography_materialproviders_KmsEcdhStaticConfigurations(native_input): + if isinstance( + native_input, + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.KmsEcdhStaticConfigurationsKmsPublicKeyDiscovery, + ): + KmsEcdhStaticConfigurations_union_value = KmsEcdhStaticConfigurations_KmsPublicKeyDiscovery( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_KmsPublicKeyDiscoveryInput( + native_input.value + ) + ) + elif isinstance( + native_input, + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.KmsEcdhStaticConfigurationsKmsPrivateKeyToStaticPublicKey, + ): + KmsEcdhStaticConfigurations_union_value = KmsEcdhStaticConfigurations_KmsPrivateKeyToStaticPublicKey( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_KmsPrivateKeyToStaticPublicKeyInput( + native_input.value + ) + ) + else: + raise ValueError( + "No recognized union value in union type: " + str(native_input) + ) + + return KmsEcdhStaticConfigurations_union_value + + +def aws_cryptography_materialproviders_KmsPublicKeyDiscoveryInput(native_input): + return DafnyKmsPublicKeyDiscoveryInput( + recipientKmsIdentifier=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[ + iter( + native_input.recipient_kms_identifier.encode( + "utf-16-be" + ) + ) + ] + * 2 + ) + ] + ) + ), + ) + + +def aws_cryptography_materialproviders_KmsPrivateKeyToStaticPublicKeyInput( + native_input, +): + return DafnyKmsPrivateKeyToStaticPublicKeyInput( + senderKmsIdentifier=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input.sender_kms_identifier.encode("utf-16-be"))] + * 2 + ) + ] + ) + ), + senderPublicKey=( + (Option_Some(Seq(native_input.sender_public_key))) + if (native_input.sender_public_key is not None) + else (Option_None()) + ), + recipientPublicKey=Seq(native_input.recipient_public_key), + ) + + +def aws_cryptography_materialproviders_CreateMultiKeyringInput(native_input): + return DafnyCreateMultiKeyringInput( + generator=( + ( + Option_Some( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_KeyringReference( + native_input.generator + ) + ) + ) + if ( + (native_input.generator is not None) + and ( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_KeyringReference( + native_input.generator + ) + is not None + ) + ) + else (Option_None()) + ), + childKeyrings=Seq( + [ + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_KeyringReference( + list_element + ) + for list_element in native_input.child_keyrings + ] + ), + ) + + +def aws_cryptography_materialproviders_KeyringReference(native_input): + if hasattr(native_input, "_impl"): + return native_input._impl + + else: + return native_input + + +def aws_cryptography_materialproviders_CreateRawAesKeyringInput(native_input): + return DafnyCreateRawAesKeyringInput( + keyNamespace=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input.key_namespace.encode("utf-16-be"))] * 2 + ) + ] + ) + ), + keyName=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input.key_name.encode("utf-16-be"))] * 2 + ) + ] + ) + ), + wrappingKey=Seq(native_input.wrapping_key), + wrappingAlg=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_AesWrappingAlg( + native_input.wrapping_alg + ), + ) + + +def aws_cryptography_materialproviders_AesWrappingAlg(native_input): + if native_input == "ALG_AES128_GCM_IV12_TAG16": + return AesWrappingAlg_ALG__AES128__GCM__IV12__TAG16() + + elif native_input == "ALG_AES192_GCM_IV12_TAG16": + return AesWrappingAlg_ALG__AES192__GCM__IV12__TAG16() + + elif native_input == "ALG_AES256_GCM_IV12_TAG16": + return AesWrappingAlg_ALG__AES256__GCM__IV12__TAG16() + + else: + raise ValueError(f"No recognized enum value in enum type: {native_input=}") + + +def aws_cryptography_materialproviders_CreateRawRsaKeyringInput(native_input): + return DafnyCreateRawRsaKeyringInput( + keyNamespace=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input.key_namespace.encode("utf-16-be"))] * 2 + ) + ] + ) + ), + keyName=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input.key_name.encode("utf-16-be"))] * 2 + ) + ] + ) + ), + paddingScheme=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_PaddingScheme( + native_input.padding_scheme + ), + publicKey=( + (Option_Some(Seq(native_input.public_key))) + if (native_input.public_key is not None) + else (Option_None()) + ), + privateKey=( + (Option_Some(Seq(native_input.private_key))) + if (native_input.private_key is not None) + else (Option_None()) + ), + ) + + +def aws_cryptography_materialproviders_PaddingScheme(native_input): + if native_input == "PKCS1": + return PaddingScheme_PKCS1() + + elif native_input == "OAEP_SHA1_MGF1": + return PaddingScheme_OAEP__SHA1__MGF1() + + elif native_input == "OAEP_SHA256_MGF1": + return PaddingScheme_OAEP__SHA256__MGF1() + + elif native_input == "OAEP_SHA384_MGF1": + return PaddingScheme_OAEP__SHA384__MGF1() + + elif native_input == "OAEP_SHA512_MGF1": + return PaddingScheme_OAEP__SHA512__MGF1() + + else: + raise ValueError(f"No recognized enum value in enum type: {native_input=}") + + +def aws_cryptography_materialproviders_CreateRawEcdhKeyringInput(native_input): + return DafnyCreateRawEcdhKeyringInput( + KeyAgreementScheme=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_RawEcdhStaticConfigurations( + native_input.key_agreement_scheme + ), + curveSpec=aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.smithy_to_dafny.aws_cryptography_primitives_ECDHCurveSpec( + native_input.curve_spec + ), + ) + + +def aws_cryptography_materialproviders_RawEcdhStaticConfigurations(native_input): + if isinstance( + native_input, + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.RawEcdhStaticConfigurationsPublicKeyDiscovery, + ): + RawEcdhStaticConfigurations_union_value = RawEcdhStaticConfigurations_PublicKeyDiscovery( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_PublicKeyDiscoveryInput( + native_input.value + ) + ) + elif isinstance( + native_input, + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.RawEcdhStaticConfigurationsRawPrivateKeyToStaticPublicKey, + ): + RawEcdhStaticConfigurations_union_value = RawEcdhStaticConfigurations_RawPrivateKeyToStaticPublicKey( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_RawPrivateKeyToStaticPublicKeyInput( + native_input.value + ) + ) + elif isinstance( + native_input, + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.RawEcdhStaticConfigurationsEphemeralPrivateKeyToStaticPublicKey, + ): + RawEcdhStaticConfigurations_union_value = RawEcdhStaticConfigurations_EphemeralPrivateKeyToStaticPublicKey( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_EphemeralPrivateKeyToStaticPublicKeyInput( + native_input.value + ) + ) + else: + raise ValueError( + "No recognized union value in union type: " + str(native_input) + ) + + return RawEcdhStaticConfigurations_union_value + + +def aws_cryptography_materialproviders_PublicKeyDiscoveryInput(native_input): + return DafnyPublicKeyDiscoveryInput( + recipientStaticPrivateKey=Seq(native_input.recipient_static_private_key), + ) + + +def aws_cryptography_materialproviders_RawPrivateKeyToStaticPublicKeyInput( + native_input, +): + return DafnyRawPrivateKeyToStaticPublicKeyInput( + senderStaticPrivateKey=Seq(native_input.sender_static_private_key), + recipientPublicKey=Seq(native_input.recipient_public_key), + ) + + +def aws_cryptography_materialproviders_EphemeralPrivateKeyToStaticPublicKeyInput( + native_input, +): + return DafnyEphemeralPrivateKeyToStaticPublicKeyInput( + recipientPublicKey=Seq(native_input.recipient_public_key), + ) + + +def aws_cryptography_materialproviders_CreateDefaultCryptographicMaterialsManagerInput( + native_input, +): + return DafnyCreateDefaultCryptographicMaterialsManagerInput( + keyring=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_KeyringReference( + native_input.keyring + ), + ) + + +def aws_cryptography_materialproviders_CreateRequiredEncryptionContextCMMInput( + native_input, +): + return DafnyCreateRequiredEncryptionContextCMMInput( + underlyingCMM=( + ( + Option_Some( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_CryptographicMaterialsManagerReference( + native_input.underlying_cmm + ) + ) + ) + if ( + (native_input.underlying_cmm is not None) + and ( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_CryptographicMaterialsManagerReference( + native_input.underlying_cmm + ) + is not None + ) + ) + else (Option_None()) + ), + keyring=( + ( + Option_Some( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_KeyringReference( + native_input.keyring + ) + ) + ) + if ( + (native_input.keyring is not None) + and ( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_KeyringReference( + native_input.keyring + ) + is not None + ) + ) + else (Option_None()) + ), + requiredEncryptionContextKeys=Seq( + [ + Seq(list_element.encode("utf-8")) + for list_element in native_input.required_encryption_context_keys + ] + ), + ) + + +def aws_cryptography_materialproviders_CryptographicMaterialsManagerReference( + native_input, +): + if hasattr(native_input, "_impl"): + return native_input._impl + + else: + return native_input + + +def aws_cryptography_materialproviders_CreateCryptographicMaterialsCacheInput( + native_input, +): + return DafnyCreateCryptographicMaterialsCacheInput( + cache=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_CacheType( + native_input.cache + ), + ) + + +def aws_cryptography_materialproviders_CreateDefaultClientSupplierInput(native_input): + return DafnyCreateDefaultClientSupplierInput() + + +def aws_cryptography_materialproviders_InitializeEncryptionMaterialsInput(native_input): + return DafnyInitializeEncryptionMaterialsInput( + algorithmSuiteId=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_AlgorithmSuiteId( + native_input.algorithm_suite_id + ), + encryptionContext=Map( + { + Seq(key.encode("utf-8")): Seq(value.encode("utf-8")) + for (key, value) in native_input.encryption_context.items() + } + ), + requiredEncryptionContextKeys=Seq( + [ + Seq(list_element.encode("utf-8")) + for list_element in native_input.required_encryption_context_keys + ] + ), + signingKey=( + (Option_Some(Seq(native_input.signing_key))) + if (native_input.signing_key is not None) + else (Option_None()) + ), + verificationKey=( + (Option_Some(Seq(native_input.verification_key))) + if (native_input.verification_key is not None) + else (Option_None()) + ), + ) + + +def aws_cryptography_materialproviders_InitializeDecryptionMaterialsInput(native_input): + return DafnyInitializeDecryptionMaterialsInput( + algorithmSuiteId=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_AlgorithmSuiteId( + native_input.algorithm_suite_id + ), + encryptionContext=Map( + { + Seq(key.encode("utf-8")): Seq(value.encode("utf-8")) + for (key, value) in native_input.encryption_context.items() + } + ), + requiredEncryptionContextKeys=Seq( + [ + Seq(list_element.encode("utf-8")) + for list_element in native_input.required_encryption_context_keys + ] + ), + ) + + +def aws_cryptography_materialproviders_ValidEncryptionMaterialsTransitionInput( + native_input, +): + return DafnyValidEncryptionMaterialsTransitionInput( + start=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_EncryptionMaterials( + native_input.start + ), + stop=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_EncryptionMaterials( + native_input.stop + ), + ) + + +def aws_cryptography_materialproviders_ValidDecryptionMaterialsTransitionInput( + native_input, +): + return DafnyValidDecryptionMaterialsTransitionInput( + start=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_DecryptionMaterials( + native_input.start + ), + stop=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_DecryptionMaterials( + native_input.stop + ), + ) + + +def aws_cryptography_materialproviders_GetAlgorithmSuiteInfoInput(native_input): + return Seq(native_input) + + +def aws_cryptography_materialproviders_ValidateCommitmentPolicyOnEncryptInput( + native_input, +): + return DafnyValidateCommitmentPolicyOnEncryptInput( + algorithm=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_AlgorithmSuiteId( + native_input.algorithm + ), + commitmentPolicy=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_CommitmentPolicy( + native_input.commitment_policy + ), + ) + + +def aws_cryptography_materialproviders_ValidateCommitmentPolicyOnDecryptInput( + native_input, +): + return DafnyValidateCommitmentPolicyOnDecryptInput( + algorithm=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_AlgorithmSuiteId( + native_input.algorithm + ), + commitmentPolicy=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_CommitmentPolicy( + native_input.commitment_policy + ), + ) + + +def aws_cryptography_materialproviders_CreateKeyringOutput(native_input): + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_KeyringReference( + native_input + ) + + +def aws_cryptography_materialproviders_CreateCryptographicMaterialsManagerOutput( + native_input, +): + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_CryptographicMaterialsManagerReference( + native_input + ) + + +def aws_cryptography_materialproviders_CreateRequiredEncryptionContextCMMOutput( + native_input, +): + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_CryptographicMaterialsManagerReference( + native_input + ) + + +def aws_cryptography_materialproviders_CreateCryptographicMaterialsCacheOutput( + native_input, +): + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_CryptographicMaterialsCacheReference( + native_input + ) + + +def aws_cryptography_materialproviders_CreateDefaultClientSupplierOutput(native_input): + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_ClientSupplierReference( + native_input + ) + + +def aws_cryptography_materialproviders_MaterialProvidersConfig(native_input): + return DafnyMaterialProvidersConfig() diff --git a/AwsCryptographicMaterialProviders/runtimes/python/test/__init__.py b/AwsCryptographicMaterialProviders/runtimes/python/test/__init__.py new file mode 100644 index 000000000..f94fd12a2 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/python/test/__init__.py @@ -0,0 +1,2 @@ +# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 diff --git a/AwsCryptographicMaterialProviders/runtimes/python/test/internaldafny/__init__.py b/AwsCryptographicMaterialProviders/runtimes/python/test/internaldafny/__init__.py new file mode 100644 index 000000000..f94fd12a2 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/python/test/internaldafny/__init__.py @@ -0,0 +1,2 @@ +# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 diff --git a/AwsCryptographicMaterialProviders/runtimes/python/test/internaldafny/test_dafny_wrapper.py b/AwsCryptographicMaterialProviders/runtimes/python/test/internaldafny/test_dafny_wrapper.py new file mode 100644 index 000000000..931442bdf --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/python/test/internaldafny/test_dafny_wrapper.py @@ -0,0 +1,20 @@ +# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 +""" +Wrapper file for executing Dafny tests from pytest. +This allows us to import modules required by Dafny-generated tests +before executing Dafny-generated tests. +pytest will find and execute the `test_dafny` method below, +which will execute the `internaldafny_test_executor.py` file in the `dafny` directory. +""" + +import sys + +internaldafny_dir = '/'.join(__file__.split("/")[:-1]) + +sys.path.append(internaldafny_dir + "/extern") +sys.path.append(internaldafny_dir + "/generated") + + +def test_dafny(): + from .generated import __main__ diff --git a/AwsCryptographicMaterialProviders/runtimes/python/tox.ini b/AwsCryptographicMaterialProviders/runtimes/python/tox.ini new file mode 100644 index 000000000..b81a4c954 --- /dev/null +++ b/AwsCryptographicMaterialProviders/runtimes/python/tox.ini @@ -0,0 +1,87 @@ +[tox] +isolated_build = True +envlist = + py{311,312}-{dafnytests} + docs + +[testenv:base-command] +commands = poetry run pytest -l {posargs} + +[testenv] +skip_install = True +allowlist_externals = poetry +passenv = AWS_* +commands_pre = + poetry lock + poetry install --with test +commands = + dafnytests: {[testenv:base-command]commands} test/internaldafny -s -v + +# Release tooling +[testenv:build] +basepython = python3 +skip_install = True +allowlist_externals = poetry +commands = + poetry install --no-root --with release + poetry build + +[testenv:release-base] +basepython = python3 +skip_install = True +allowlist_externals = poetry +comands_pre = + poetry install --no-root --with release +passenv = + # Intentionally omit TWINE_REPOSITORY_URL from the passenv list, + # as this overrides other ways of setting the repository and could + # unexpectedly result in releasing to the wrong repo + {[testenv]passenv} \ + TWINE_USERNAME \ + TWINE_PASSWORD +commands = + {[testenv:build]commands} + +[testenv:release-private] +basepython = python3 +skip_install = True +allowlist_externals = poetry +comands_pre = + poetry install --no-root --with release +passenv = + {[testenv:release-base]passenv} \ + TWINE_REPOSITORY_URL +setenv = + # Explicitly set the URL as the env variable value, which will cause us to + # throw an error if the variable is not set. Otherwise, omission of the + # env variable could cause us to unintentionally upload to the wrong repo + TWINE_REPOSITORY_URL = {env:TWINE_REPOSITORY_URL} +commands = + {[testenv:release-base]commands} + # Omitting an explicit repository will cause twine to use the repository + # specified in the environment variable + poetry run twine upload --skip-existing {toxinidir}/dist/* + +[testenv:test-release] +basepython = python3 +skip_install = True +allowlist_externals = poetry +comands_pre = + poetry install --no-root --with release +passenv = + {[testenv:release-base]passenv} +commands = + {[testenv:release-base]commands} + poetry run twine upload --skip-existing --repository testpypi {toxinidir}/dist/* + +[testenv:release] +basepython = python3 +skip_install = True +allowlist_externals = poetry +comands_pre = + poetry install --no-root --with release +passenv = + {[testenv:release-base]passenv} +commands = + {[testenv:release-base]commands} + poetry run twine upload --skip-existing --repository pypi {toxinidir}/dist/* diff --git a/AwsCryptographyPrimitives/Makefile b/AwsCryptographyPrimitives/Makefile index 9bc61019a..89f7fa132 100644 --- a/AwsCryptographyPrimitives/Makefile +++ b/AwsCryptographyPrimitives/Makefile @@ -3,10 +3,12 @@ CORES=2 +ENABLE_EXTERN_PROCESSING=1 + include ../SharedMakefileV2.mk PROJECT_SERVICES := \ - AwsCryptographyPrimitives \ + AwsCryptographyPrimitives SERVICE_NAMESPACE_AwsCryptographyPrimitives=aws.cryptography.primitives MAX_RESOURCE_COUNT=10000000 @@ -14,3 +16,19 @@ MAX_RESOURCE_COUNT=10000000 STD_LIBRARY=StandardLibrary SMITHY_DEPS=model +# Constants for languages that drop extern names (Python, Go) + +TYPES_FILE_PATH=Model/AwsCryptographyPrimitivesTypes.dfy +TYPES_FILE_WITH_EXTERN_STRING="module {:extern \"software.amazon.cryptography.primitives.internaldafny.types\" } AwsCryptographyPrimitivesTypes" +TYPES_FILE_WITHOUT_EXTERN_STRING="module AwsCryptographyPrimitivesTypes" + +INDEX_FILE_PATH=src/Index.dfy +INDEX_FILE_WITH_EXTERN_STRING="module {:extern \"software.amazon.cryptography.primitives.internaldafny\" } AtomicPrimitives refines AbstractAwsCryptographyPrimitivesService {" +INDEX_FILE_WITHOUT_EXTERN_STRING="module AtomicPrimitives refines AbstractAwsCryptographyPrimitivesService {" + +# Python + +PYTHON_MODULE_NAME=aws_cryptography_primitives + +TRANSLATION_RECORD_PYTHON := \ + --translation-record ../StandardLibrary/runtimes/python/src/smithy_dafny_standard_library/internaldafny/generated/dafny_src-py.dtr diff --git a/AwsCryptographyPrimitives/codebuild/release-python/prod-release.yml b/AwsCryptographyPrimitives/codebuild/release-python/prod-release.yml new file mode 100644 index 000000000..4c9a1e974 --- /dev/null +++ b/AwsCryptographyPrimitives/codebuild/release-python/prod-release.yml @@ -0,0 +1,63 @@ +version: 0.2 + +env: + variables: + BRANCH: "main" + secrets-manager: + TWINE_USERNAME: PyPiAPIToken:username + TWINE_PASSWORD: PyPiAPIToken:password + +phases: + install: + commands: + - pip install "tox < 4.0" + - pip install --upgrade pip + runtime-versions: + python: latest + pre_build: + commands: + # Get Dafny + - export dafnyVersion=$(grep '^dafnyVersion=' project.properties | cut -d '=' -f 2) + - cd .. + - curl https://github.com/dafny-lang/dafny/releases/download/v$dafnyVersion/dafny-$dafnyVersion-x64-ubuntu-20.04.zip -L -o dafny.zip + - unzip -qq dafny.zip && rm dafny.zip + - export PATH="$PWD/dafny:$PATH" + # Switch back to the main directory + - cd aws-cryptographic-material-providers-library + # Assert that project version is the expected released version + - git checkout $COMMIT_ID + - FOUND_VERSION=$(sed -n 's/version = "\(.*\)"/\1/p' AwsCryptographyPrimitives/runtimes/python/pyproject.toml) + - | + if expr ${FOUND_VERSION} != ${VERSION}; then + echo "pyproject.toml version (${FOUND_VERSION}) does not match expected version (${VERSION}), stopping" + exit 1; + fi + - cd AwsCryptographyPrimitives + # Build Dafny test source code + - make transpile_only_test_python + build: + commands: + - cd runtimes/python/ + # Install poetry + # https://python-poetry.org/docs/#installing-manually + - pip install poetry + # Install project dependencies with release dependencies + - poetry install --with release + # Build whl/sdist, upload to PyPI + # TODO: When ready to prod release, uncomment this line + # tox -e release + +batch: + fast-fail: true + build-graph: + - identifier: release_to_prod + env: + image: aws/codebuild/standard:7.0 + - identifier: validate_prod_release + depend-on: + - release_to_prod + buildspec: AwsCryptographyPrimitives/codebuild/release-python/validate.yml + env: + variables: + PIP_INDEX_URL: https://pypi.python.org/simple/ + image: aws/codebuild/standard:7.0 diff --git a/AwsCryptographyPrimitives/codebuild/release-python/test-release.yml b/AwsCryptographyPrimitives/codebuild/release-python/test-release.yml new file mode 100644 index 000000000..97c345667 --- /dev/null +++ b/AwsCryptographyPrimitives/codebuild/release-python/test-release.yml @@ -0,0 +1,65 @@ +version: 0.2 + +env: + variables: + BRANCH: "main" + secrets-manager: + TWINE_USERNAME: TestPyPiAPIToken:username + TWINE_PASSWORD: TestPyPiAPIToken:password + +phases: + install: + commands: + - pip install "tox < 4.0" + - pip install --upgrade pip + runtime-versions: + python: latest + pre_build: + commands: + # Get Dafny + - export dafnyVersion=$(grep '^dafnyVersion=' project.properties | cut -d '=' -f 2) + - cd .. + - curl https://github.com/dafny-lang/dafny/releases/download/v$dafnyVersion/dafny-$dafnyVersion-x64-ubuntu-20.04.zip -L -o dafny.zip + - unzip -qq dafny.zip && rm dafny.zip + - export PATH="$PWD/dafny:$PATH" + # Switch back to the main directory + - cd aws-cryptographic-material-providers-library + # Assert that project version is the expected released version + - git checkout $COMMIT_ID + - FOUND_VERSION=$(sed -n 's/version = "\(.*\)"/\1/p' AwsCryptographyPrimitives/runtimes/python/pyproject.toml) + - | + if expr ${FOUND_VERSION} != ${VERSION}; then + echo "pyproject.toml version (${FOUND_VERSION}) does not match expected version (${VERSION}), stopping" + exit 1; + fi + - cd AwsCryptographyPrimitives + # Build Dafny test source code + - make transpile_only_test_python + build: + commands: + - cd runtimes/python/ + # Install poetry + # https://python-poetry.org/docs/#installing-manually + - pip install poetry + # Add test PyPI as a supplemental repo for installing previously published test packages + - poetry source add --priority=supplemental test https://test.pypi.org/simple/ + # Install project dependencies with release dependencies + - poetry install --with release + # Build whl/sdist, upload to test PyPI + - tox -e test-release + +batch: + fast-fail: true + build-graph: + - identifier: release_to_staging + env: + image: aws/codebuild/standard:7.0 + - identifier: validate_staging_release + depend-on: + - release_to_staging + buildspec: AwsCryptographyPrimitives/codebuild/release-python/validate.yml + env: + variables: + PIP_INDEX_URL: https://test.pypi.org/simple/ + PIP_EXTRA_INDEX_URL: https://pypi.python.org/simple/ + image: aws/codebuild/standard:7.0 diff --git a/AwsCryptographyPrimitives/codebuild/release-python/validate.yml b/AwsCryptographyPrimitives/codebuild/release-python/validate.yml new file mode 100644 index 000000000..a7b526577 --- /dev/null +++ b/AwsCryptographyPrimitives/codebuild/release-python/validate.yml @@ -0,0 +1,39 @@ +version: 0.2 + +# Validate that the released artifact is usable +# by installing it from PyPI +# then running tests from source against the published artifact. + +phases: + install: + commands: + - pip install "tox < 4.0" + runtime-versions: + python: latest + pre_build: + commands: + # Get Dafny + - export dafnyVersion=$(grep '^dafnyVersion=' project.properties | cut -d '=' -f 2) + - cd .. + - curl https://github.com/dafny-lang/dafny/releases/download/v$dafnyVersion/dafny-$dafnyVersion-x64-ubuntu-20.04.zip -L -o dafny.zip + - unzip -qq dafny.zip && rm dafny.zip + - export PATH="$PWD/dafny:$PATH" + # Switch back to the main directory + - cd aws-cryptographic-material-providers-library + # Install test dependencies + - pyenv install --skip-existing 3.11 + - pyenv local 3.11 + - pip install "tox < 4.0" + - pip install pytest pyasn1 + # Install the published artifact from PyPI. + # The tests will use the installed package, not the local code. + # The actual test code must be from local, since we don't publish tests. + - pip install aws-cryptography-internal-primitives==$VERSION + build: + commands: + - NUM_RETRIES=3 + - cd AwsCryptographyPrimitives + # Transpile code (for tests) + - make transpile_python + - cd runtimes/python + - python -m pytest test/ -s -v diff --git a/AwsCryptographyPrimitives/runtimes/python/.gitignore b/AwsCryptographyPrimitives/runtimes/python/.gitignore new file mode 100644 index 000000000..9cb72dcab --- /dev/null +++ b/AwsCryptographyPrimitives/runtimes/python/.gitignore @@ -0,0 +1,16 @@ +# Python build artifacts +__pycache__ +**/__pycache__ +*.pyc +src/**.egg-info/ +build +poetry.lock +**/poetry.lock +dist + +# Dafny-generated Python +**/internaldafny/generated/*.py + +# Python test artifacts +.tox +.pytest_cache diff --git a/AwsCryptographyPrimitives/runtimes/python/pyproject.toml b/AwsCryptographyPrimitives/runtimes/python/pyproject.toml new file mode 100644 index 000000000..d9c55f081 --- /dev/null +++ b/AwsCryptographyPrimitives/runtimes/python/pyproject.toml @@ -0,0 +1,39 @@ +[tool.poetry] +name = "aws-cryptography-internal-primitives" +version = "0.1.0" +description = "" +authors = ["AWS Crypto Tools "] +packages = [ + { include = "aws_cryptography_primitives", from = "src" } +] +# Include generated internaldafny files in package distributions, +# even though they are not included in version control +include = ["**/internaldafny/generated/*.py"] + +[tool.poetry.dependencies] +python = "^3.11.0" +aws-cryptography-internal-standard-library = {path = "../../../StandardLibrary/runtimes/python"} +cryptography = "^41.0.3" + +# Package testing + +[tool.poetry.group.test] +optional = true + +[tool.poetry.group.test.dependencies] +pytest = "^7.4.0" +pyasn1 = "^0.6.0" + +# Package release + +[tool.poetry.group.release] +optional = true + +[tool.poetry.group.release.dependencies] +poetry = "1.8.3" +twine = "5.1.1" +wheel = "0.38.4" + +[build-system] +requires = ["poetry-core"] +build-backend = "poetry.core.masonry.api" diff --git a/AwsCryptographyPrimitives/runtimes/python/src/aws_cryptography_primitives/__init__.py b/AwsCryptographyPrimitives/runtimes/python/src/aws_cryptography_primitives/__init__.py new file mode 100644 index 000000000..b9427e19d --- /dev/null +++ b/AwsCryptographyPrimitives/runtimes/python/src/aws_cryptography_primitives/__init__.py @@ -0,0 +1,8 @@ +# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 + +# Initialize generated Dafny +from .internaldafny.generated import module_ + +# Initialize externs +from .internaldafny import extern diff --git a/AwsCryptographyPrimitives/runtimes/python/src/aws_cryptography_primitives/internaldafny/extern/AESEncryption.py b/AwsCryptographyPrimitives/runtimes/python/src/aws_cryptography_primitives/internaldafny/extern/AESEncryption.py new file mode 100644 index 000000000..a3de55304 --- /dev/null +++ b/AwsCryptographyPrimitives/runtimes/python/src/aws_cryptography_primitives/internaldafny/extern/AESEncryption.py @@ -0,0 +1,74 @@ +# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 +from cryptography.hazmat.primitives.ciphers.aead import AESGCM +from cryptography.exceptions import InvalidTag + +import _dafny + +import smithy_dafny_standard_library.internaldafny.generated.Wrappers as Wrappers +import aws_cryptography_primitives.internaldafny.generated.AESEncryption +from aws_cryptography_primitives.internaldafny.generated.AESEncryption import * +from aws_cryptography_primitives.internaldafny.generated.HMAC import * +from aws_cryptography_primitives.internaldafny.generated.AwsCryptographyPrimitivesTypes import Error_Opaque + + +# Get generated methods +default__ = aws_cryptography_primitives.internaldafny.generated.AESEncryption.default__ + +class AESEncryption: + + class AES_GCM: + + @staticmethod + def AESEncryptExtern( + enc_alg, + iv, + key, + message, + aad + ) -> Wrappers.Result: + key_bytes = bytes(key) + iv_bytes = bytes(iv) + plaintext_bytes = bytes(message) + aad_bytes = bytes(aad) + + aesgcm = AESGCM(key_bytes) + try: + ct = aesgcm.encrypt(iv_bytes, plaintext_bytes, aad_bytes) + except OverflowError: + return Wrappers.Result_Failure(Error_Opaque( + "AES-GCM cannot encrypt plaintext data larger than 2^31-1 bytes" + )) + + return Wrappers.Result_Success( + default__.EncryptionOutputFromByteSeq(_dafny.Seq(ct), enc_alg) + ) + + @staticmethod + def AESDecryptExtern( + enc_alg, + key, + ciphertext, + auth_tag, + iv, + aad + ) -> Wrappers.Result: + key_bytes = bytes(key) + iv_bytes = bytes(iv) + ciphertext_bytes = bytes(ciphertext) + tag_bytes = bytes(auth_tag) + aad_bytes = bytes(aad) + + ct_and_tag = ciphertext_bytes + tag_bytes + aesgcm = AESGCM(key_bytes) + try: + plaintext = aesgcm.decrypt(iv_bytes, ct_and_tag, aad_bytes) + except InvalidTag: + return Wrappers.Result_Failure(Error_Opaque( + "AES-GCM decrypt failed to validate authentication tag for ciphertext" + )) + + return Wrappers.Result_Success(_dafny.Seq(plaintext)) + +# Export externs into generated class so references to it have the externs +aws_cryptography_primitives.internaldafny.generated.AESEncryption.AESEncryption = AESEncryption diff --git a/AwsCryptographyPrimitives/runtimes/python/src/aws_cryptography_primitives/internaldafny/extern/AesKdfCtr.py b/AwsCryptographyPrimitives/runtimes/python/src/aws_cryptography_primitives/internaldafny/extern/AesKdfCtr.py new file mode 100644 index 000000000..e71e38ce0 --- /dev/null +++ b/AwsCryptographyPrimitives/runtimes/python/src/aws_cryptography_primitives/internaldafny/extern/AesKdfCtr.py @@ -0,0 +1,37 @@ +# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 +from cryptography.hazmat.primitives.ciphers import algorithms, modes +from cryptography.hazmat.primitives.ciphers import Cipher +from cryptography.exceptions import AlreadyFinalized + +import _dafny + +import smithy_dafny_standard_library.internaldafny.generated.Wrappers as Wrappers +import aws_cryptography_primitives.internaldafny.generated.AesKdfCtr +from aws_cryptography_primitives.internaldafny.generated.AwsCryptographyPrimitivesTypes import Error_Opaque + + +# Extend generated class +class default__(aws_cryptography_primitives.internaldafny.generated.AesKdfCtr.default__): + + @staticmethod + def AesKdfCtrStream(nonce, key, length): + cipher = Cipher( + algorithms.AES(bytes(key)), modes.CTR(bytes(nonce)), + ) + plaintext = bytearray(length) + encryptor = cipher.encryptor() + try: + ciphertext = encryptor.update(plaintext) + encryptor.finalize() + except ValueError: + return Wrappers.Result_Failure(Error_Opaque( + "Cannot finalize an encryptor when the plaintext data is not a multiple of the algorithm block size" + )) + except AlreadyFinalized: + return Wrappers.Result_Failure(Error_Opaque( + "Cannot update or finalize an encryptor which was already finalized" + )) + return Wrappers.Result_Success(_dafny.Seq(ciphertext)) + +# Export extern-extended class into generated class +aws_cryptography_primitives.internaldafny.generated.AesKdfCtr.default__ = default__ \ No newline at end of file diff --git a/AwsCryptographyPrimitives/runtimes/python/src/aws_cryptography_primitives/internaldafny/extern/ECDH.py b/AwsCryptographyPrimitives/runtimes/python/src/aws_cryptography_primitives/internaldafny/extern/ECDH.py new file mode 100644 index 000000000..7647c8697 --- /dev/null +++ b/AwsCryptographyPrimitives/runtimes/python/src/aws_cryptography_primitives/internaldafny/extern/ECDH.py @@ -0,0 +1,381 @@ +# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 +from enum import Enum + +import smithy_dafny_standard_library.internaldafny.generated.Wrappers as Wrappers +from aws_cryptography_primitives.internaldafny.generated.ECDH import default__ +from aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.errors import ( + AwsCryptographicPrimitivesError, + _smithy_error_to_dafny_error +) + +import _dafny +import cryptography.hazmat.primitives.asymmetric.ec +from aws_cryptography_primitives.internaldafny.extern.Signature import ( + _ecc_decode_compressed_point, + _ecc_encode_compressed_point_public_key, +) + +from aws_cryptography_primitives.internaldafny.generated.ECDH import \ + EccKeyPair_EccKeyPair +from cryptography.hazmat.backends import default_backend +from cryptography.hazmat.primitives.asymmetric import ec +from cryptography.hazmat.primitives.asymmetric.ec import EllipticCurvePublicKey +from cryptography.hazmat.primitives.serialization import (Encoding, + NoEncryption, + PrivateFormat, + PublicFormat, + load_der_public_key, + load_pem_private_key) + +from aws_cryptography_primitives.internaldafny.extern.Signature import \ + _ECC_CURVE_PARAMETERS + + +curve_mapping = { + "secp256r1": _ECC_CURVE_PARAMETERS["secp256r1"], + "secp384r1": _ECC_CURVE_PARAMETERS["secp384r1"], + "secp521r1": _ECC_CURVE_PARAMETERS["secp521r1"], +} + +def _validate_point(curve, x, y): + """ + Validate that the coordinates x, y: + - lie within the elliptic curve field + - satisfy the elliptic curve equation + """ + # Get curve parameters + a = curve.a + b = curve.b + p = curve.p + + # Check if point is within the field range + if not (0 <= x < p and 0 <= y < p): + return False + + # Check if the point satisfies the elliptic curve equation + left = (y * y) % p + right = (x * x * x + a * x + b) % p + return left == right + + +class DeriveSharedSecret: + def CalculateSharedSecret( + dafny_eccAlgorithm, + dafny_privateKey, + dafny_publicKey, + ) -> Wrappers.Result: + public_key_der_bytes = bytes(dafny_publicKey.der) + private_key_pem_bytes = bytes(dafny_privateKey.pem) + + maybe_ecc_algorithm = ECCAlgorithms.eccAlgorithm(dafny_eccAlgorithm) + if maybe_ecc_algorithm.is_Failure: + return default__.CreateExternDerivesharedSecretError( + maybe_ecc_algorithm.error + ) + + curve = maybe_ecc_algorithm.value + + if curve.name != "SM2": + try: + private_key = load_pem_private_key(private_key_pem_bytes, None) + public_key = load_der_public_key(public_key_der_bytes) + + shared_key = private_key.exchange( + ec.ECDH(), + public_key + ) + + return default__.CreateExternDerivesharedSecretSuccess( + _dafny.Seq( + shared_key + ) + ) + except Exception as e: + return default__.CreateExternDerivesharedSecretError( + _smithy_error_to_dafny_error( + AwsCryptographicPrimitivesError( + message=str(e) + ) + ) + ) + else: + return default__.CreateExternDerivesharedSecretError( + _smithy_error_to_dafny_error( + ValueError( + "SM2 not yet supported." + ) + ) + ) + +class KeyGeneration: + + @staticmethod + def GenerateKeyPair(dafny_eccAlgorithm) -> Wrappers.Result: + maybe_ecc_algorithm = ECCAlgorithms.eccAlgorithm(dafny_eccAlgorithm) + if maybe_ecc_algorithm.is_Failure: + return default__.CreateExternEccKeyGenFailure( + maybe_ecc_algorithm.error + ) + + curve = maybe_ecc_algorithm.value + + if curve.name != "SM2": + try: + private_key = ec.generate_private_key( + maybe_ecc_algorithm.value.value + ) + + private_key_pem_bytes = private_key.private_bytes(Encoding.PEM, PrivateFormat.PKCS8, NoEncryption()) + public_key_der_bytes = private_key.public_key().public_bytes(Encoding.DER, PublicFormat.SubjectPublicKeyInfo) + + return default__.CreateExternEccKeyGenSuccess(EccKeyPair_EccKeyPair( + publicKey=_dafny.Seq(public_key_der_bytes), + privateKey=_dafny.Seq(private_key_pem_bytes) + )) + except Exception as e: + return default__.CreateExternEccKeyGenFailure( + _smithy_error_to_dafny_error( + AwsCryptographicPrimitivesError( + message=str(e) + ) + ) + ) + else: + return default__.CreateExternEccKeyGenFailure( + _smithy_error_to_dafny_error( + ValueError( + "SM2 not supported." + ) + ) + ) + + +class ECCUtils: + + CURVE_TO_ECC_SECRET_LENGTH_MAP = { + "secp256r1": int(256 / 8), + "secp384r1": int(384 / 8), + "secp521r1": int(521 / 8 + 1) # 521/8 is not a whole number + } + + def ParsePublicKey(dafny_publicKey: _dafny.Seq) -> Wrappers.Result: + try: + public_key_bytes = bytes(dafny_publicKey) + public_key = load_der_public_key(public_key_bytes) + public_bytes = public_key.public_bytes(Encoding.DER, PublicFormat.SubjectPublicKeyInfo) + + return default__.CreateExternParsePublicKeySuccess( + _dafny.Seq( + public_bytes + ) + ) + except Exception as e: + return default__.CreateExternParsePublicKeyError( + _smithy_error_to_dafny_error( + AwsCryptographicPrimitivesError( + message=str(e) + ) + ) + ) + + def GetPublicKey(dafny_eccAlgorithm, dafny_privateKey): + maybe_ecc_algorithm = ECCAlgorithms.eccAlgorithm(dafny_eccAlgorithm) + if maybe_ecc_algorithm.is_Failure: + return default__.CreateExternGetPublicKeyFromPrivateError( + maybe_ecc_algorithm.error + ) + + curve = maybe_ecc_algorithm.value + + if curve.name != "SM2": + try: + # get order for parsed private key + private_key_pem = bytes(dafny_privateKey.pem) + private_key = load_pem_private_key(private_key_pem, None) + private_key_curve = curve_mapping[private_key.curve.name] + private_key_order = private_key_curve.order + + # get expected curve order + ecdh_curve = curve_mapping[curve.name] + curve_order = ecdh_curve.order + + if private_key_order != curve_order: + return default__.CreateExternGetPublicKeyFromPrivateError( + _smithy_error_to_dafny_error( + AwsCryptographicPrimitivesError( + message="Private Key NOT on configured curve spec." + ) + ) + ) + + public_key = private_key.public_key() + public_key_der = public_key.public_bytes(Encoding.DER, PublicFormat.SubjectPublicKeyInfo) + + return Wrappers.Result_Success( + _dafny.Seq( + public_key_der + ) + ) + except Exception as e: + return default__.CreateExternGetPublicKeyFromPrivateError( + _smithy_error_to_dafny_error( + AwsCryptographicPrimitivesError( + message=str(e) + ) + ) + ) + + def ValidatePublicKey(dafny_eccAlgorithm, dafny_publicKey): + public_key_bytes = bytes(dafny_publicKey) + + maybe_ecc_algorithm = ECCAlgorithms.eccAlgorithm(dafny_eccAlgorithm) + if maybe_ecc_algorithm.is_Failure: + return default__.CreateExternValidatePublicKeyError( + maybe_ecc_algorithm.error + ) + + curve = maybe_ecc_algorithm.value + + if curve.name != "SM2": + try: + public_key = load_der_public_key(public_key_bytes) + public_key_curve_name = public_key.curve.name + if not (public_key_curve_name == curve.name): + return default__.CreateExternValidatePublicKeyError( + _smithy_error_to_dafny_error( + AwsCryptographicPrimitivesError( + message="Provided public key is not on configured curve." + ) + ) + ) + + valid_public_key = ECCUtils.NistPublicKeyValidationCriteria(public_key) + + return default__.CreateExternValidatePublicKeySuccess( + valid_public_key + ) + except Exception as e: + return default__.CreateExternValidatePublicKeyError( + _smithy_error_to_dafny_error( + AwsCryptographicPrimitivesError( + message=str(e) + ) + ) + ) + else: + return default__.CreateExternValidatePublicKeyError( + _smithy_error_to_dafny_error( + ValueError( + "SM2 Not yet Supported." + ) + ) + ) + + def NistPublicKeyValidationCriteria(public_key): + public_numbers = public_key.public_numbers() + pyca_curve_name = public_key.curve.name + ecdsa_curve = curve_mapping[pyca_curve_name] + + _validate_point(ecdsa_curve, public_numbers.x, public_numbers.y) + + return ( + ECCUtils.ValidatePublicKeyIsNotInfinity(public_numbers) and + ECCUtils.CoordinateBetween0AndP(public_numbers.x, ecdsa_curve) and + ECCUtils.CoordinateBetween0AndP(public_numbers.y, ecdsa_curve) + ) + + def ValidatePublicKeyIsNotInfinity(point): + return not (point.x == 0 and point.y == 0) + + def CoordinateBetween0AndP(coordinate, curve): + return ( + coordinate > 0 and + coordinate < curve.p + ) + + def CompressPublicKey(dafny_publicKeyDerBytes, dafny_eccAlgorithm): + try: + public_key_bytes = bytes(dafny_publicKeyDerBytes) + public_key = load_der_public_key(public_key_bytes) + compressed_public_key = _ecc_encode_compressed_point_public_key(public_key) + return default__.CreateExternCompressPublicKeySuccess( + _dafny.Seq( + compressed_public_key + ) + ) + except Exception as e: + return default__.CreateExternCompressPublicKeyError( + _smithy_error_to_dafny_error( + AwsCryptographicPrimitivesError( + message=str(e) + ) + ) + ) + + def DecompressPublicKey(dafny_compressedPublicKey, dafny_eccAlgorithm): + try: + maybe_ecc_algorithm = ECCAlgorithms.eccAlgorithm(dafny_eccAlgorithm) + if maybe_ecc_algorithm.is_Failure: + return default__.CreateExternDecompressPublicKeyError( + maybe_ecc_algorithm.error + ) + + compressed_public_key_bytes = bytes(dafny_compressedPublicKey) + curve = maybe_ecc_algorithm.value + + x, y = _ecc_decode_compressed_point(curve, compressed_public_key_bytes) + public_numbers = ec.EllipticCurvePublicNumbers(x=x, y=y, curve=curve.value) + public_key = public_numbers.public_key(backend=default_backend()) + + return default__.CreateExternDecompressPublicKeySuccess( + _dafny.Seq( + public_key.public_bytes(Encoding.DER, PublicFormat.SubjectPublicKeyInfo) + ) + ) + except Exception as e: + return default__.CreateExternDecompressPublicKeyError( + _smithy_error_to_dafny_error( + AwsCryptographicPrimitivesError( + message=str(e) + ) + ) + ) + +class ECCAlgorithms(Enum): + """Enum for supported ECC algorithms.""" + secp256r1 = cryptography.hazmat.primitives.asymmetric.ec.SECP256R1() + secp384r1 = cryptography.hazmat.primitives.asymmetric.ec.SECP384R1() + secp521r1 = cryptography.hazmat.primitives.asymmetric.ec.SECP521R1() + + @staticmethod + def eccAlgorithm(dafny_eccAlgorithm) -> Wrappers.Result: + if dafny_eccAlgorithm.is_ECC__NIST__P256: + named_curve_algorithm = ECCAlgorithms.secp256r1 + elif dafny_eccAlgorithm.is_ECC__NIST__P384: + named_curve_algorithm = ECCAlgorithms.secp384r1 + elif dafny_eccAlgorithm.is_ECC__NIST__P521: + named_curve_algorithm = ECCAlgorithms.secp521r1 + else: + return Wrappers.Result_Failure( + _smithy_error_to_dafny_error( + AwsCryptographicPrimitivesError( + message = f"Requested Curve is not supported. Requested {dafny_eccAlgorithm}" + ) + ) + ) + return Wrappers.Result_Success(named_curve_algorithm) + + +# Empty class to hold extern functions. +# This is exported to the generated class +# in a way that the generated code +# expects to access extern methods. +class ECDH_externs: + pass + +import aws_cryptography_primitives.internaldafny.generated.ECDH +aws_cryptography_primitives.internaldafny.generated.ECDH.ECDH = ECDH_externs +aws_cryptography_primitives.internaldafny.generated.ECDH.ECDH.DeriveSharedSecret = DeriveSharedSecret +aws_cryptography_primitives.internaldafny.generated.ECDH.ECDH.KeyGeneration = KeyGeneration +aws_cryptography_primitives.internaldafny.generated.ECDH.ECDH.ECCUtils = ECCUtils diff --git a/AwsCryptographyPrimitives/runtimes/python/src/aws_cryptography_primitives/internaldafny/extern/ExternDigest.py b/AwsCryptographyPrimitives/runtimes/python/src/aws_cryptography_primitives/internaldafny/extern/ExternDigest.py new file mode 100644 index 000000000..b457dee4c --- /dev/null +++ b/AwsCryptographyPrimitives/runtimes/python/src/aws_cryptography_primitives/internaldafny/extern/ExternDigest.py @@ -0,0 +1,52 @@ +# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 +from cryptography.hazmat.primitives import hashes + +import _dafny + +import smithy_dafny_standard_library.internaldafny.generated.Wrappers as Wrappers +import aws_cryptography_primitives.internaldafny.generated.AwsCryptographyPrimitivesTypes +import aws_cryptography_primitives.internaldafny.generated.Digest +import aws_cryptography_primitives.internaldafny.generated.ExternDigest +from aws_cryptography_primitives.internaldafny.generated.Digest import * + + +# Extend generated class +class default__(aws_cryptography_primitives.internaldafny.generated.ExternDigest.default__): + + @staticmethod + def get_hash(digest_algorithm): + if digest_algorithm.is_SHA__256: + return hashes.Hash(hashes.SHA256()) + elif digest_algorithm.is_SHA__384: + return hashes.Hash(hashes.SHA384()) + elif digest_algorithm.is_SHA__512: + return hashes.Hash(hashes.SHA512()) + else: + raise ValueError(f"Unsupported digest algorithm: {digest_algorithm}") + + @staticmethod + def internal_digest(digest_algorithm, message): + try: + hash = default__.get_hash(digest_algorithm) + message_bytes = bytes(message) + hash.update(message_bytes) + digest = hash.finalize() + return Wrappers.Result_Success(digest) + except ValueError as e: + error = aws_cryptography_primitives.internaldafny.generated.AwsCryptographyPrimitivesTypes.Error_AwsCryptographicPrimitivesError( + message="Requested digest Algorithm is not supported." + ) + return Wrappers.Result_Failure(error=error) + + + @staticmethod + def Digest(digest_algorithm, message): + maybe_digest = default__.internal_digest(digest_algorithm, message) + if maybe_digest.is_Failure: + return maybe_digest.PropagateFailure() + else: + return Wrappers.Result_Success(_dafny.Seq(maybe_digest.value)) + +# Export extern-extended class into generated class +aws_cryptography_primitives.internaldafny.generated.ExternDigest.default__ = default__ diff --git a/AwsCryptographyPrimitives/runtimes/python/src/aws_cryptography_primitives/internaldafny/extern/ExternRandom.py b/AwsCryptographyPrimitives/runtimes/python/src/aws_cryptography_primitives/internaldafny/extern/ExternRandom.py new file mode 100644 index 000000000..2ffed8403 --- /dev/null +++ b/AwsCryptographyPrimitives/runtimes/python/src/aws_cryptography_primitives/internaldafny/extern/ExternRandom.py @@ -0,0 +1,27 @@ +# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 +import secrets + +import _dafny + +import aws_cryptography_primitives.internaldafny.generated.ExternRandom +import smithy_dafny_standard_library.internaldafny.generated.Wrappers as Wrappers +import aws_cryptography_primitives.internaldafny.generated.ExternRandom +from aws_cryptography_primitives.internaldafny.generated.ExternRandom import * + +# Extend generated class +class default__(aws_cryptography_primitives.internaldafny.generated.ExternRandom.default__): + + @staticmethod + def GenerateBytes(i): + #= compliance/data-format/message-header.txt#2.5.1.6 + # While + # implementations cannot guarantee complete uniqueness, implementations + # MUST use a good source of randomness when generating messages IDs in + # order to make the chance of duplicate IDs negligible. + return Wrappers.Result_Success( + _dafny.Seq(secrets.token_bytes(i)) + ) + +# Export extern-extended class into generated class +aws_cryptography_primitives.internaldafny.generated.ExternRandom.default__ = default__ diff --git a/AwsCryptographyPrimitives/runtimes/python/src/aws_cryptography_primitives/internaldafny/extern/HMAC.py b/AwsCryptographyPrimitives/runtimes/python/src/aws_cryptography_primitives/internaldafny/extern/HMAC.py new file mode 100644 index 000000000..4755e3f3d --- /dev/null +++ b/AwsCryptographyPrimitives/runtimes/python/src/aws_cryptography_primitives/internaldafny/extern/HMAC.py @@ -0,0 +1,80 @@ +# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 +from cryptography.hazmat.primitives.hmac import HMAC +from cryptography.hazmat.primitives import hashes + +import _dafny + +import smithy_dafny_standard_library.internaldafny.generated.Wrappers as Wrappers +import aws_cryptography_primitives.internaldafny.generated.Digest +from aws_cryptography_primitives.internaldafny.generated.AwsCryptographyPrimitivesTypes import ( + HMacInput +) +import aws_cryptography_primitives.internaldafny.generated.HMAC +from aws_cryptography_primitives.internaldafny.generated.HMAC import * + +# Extend generated class +class default__(aws_cryptography_primitives.internaldafny.generated.HMAC.default__): + + @staticmethod + def Digest(input: HMacInput): + maybe_hmac = HMac.Build(input.digestAlgorithm) + if maybe_hmac.IsFailure(): + return maybe_hmac.PropagateFailure() + hmac = maybe_hmac.Extract() + hmac.Init(input.key) + hmac.BlockUpdate(input.message) + output = hmac.GetResult() + return Wrappers.Result_Success(_dafny.Seq(output)) + +# Extend generated class +class HMac(aws_cryptography_primitives.internaldafny.generated.HMAC.HMac): + + @staticmethod + def Build(digest): + output = HMac(digest) + return Wrappers.Result_Success(output) + + def __init__(self, digest): + if digest.is_SHA__256: + self.algorithm = hashes.SHA256() + elif digest.is_SHA__384: + self.algorithm = hashes.SHA384() + elif digest.is_SHA__512: + self.algorithm = hashes.SHA512() + else: + raise ValueError() + # self.hmac cannot be used until Init is called + + def Init(self, key): + key_bytes = bytes(key) + self.hmac = HMAC(key_bytes, self.algorithm) + # Store a copy of the key_bytes at `Init` state. + # The Dafny implementation expects that calling `GetResult` will reset + # the HMAC back to its initial state when `Init` is called. + # This is the default behavior for our HMAC libraries in .NET and Java + # but PyCA HMAC does not do this. + # We must manually reset the HMAC. + self.initial_key_bytes = key_bytes + + def BlockUpdate(self, input): + input_bytes = bytes(input) + self.hmac.update(input_bytes) + + def GetResult(self): + """ + Finishes the MAC operation. + A call to this method resets this + Mac object to the state it was in when + previously initialized via a call to Init(Key). + That is, the object is reset and available to + generate another MAC from the same key, if desired, + via new calls to update and doFinal. + """ + digest = _dafny.Seq(self.hmac.finalize()) + self.hmac = HMAC(self.initial_key_bytes, self.algorithm) + return digest + +# Export extern-extended classes into generated classes +aws_cryptography_primitives.internaldafny.generated.HMAC.default__ = default__ +aws_cryptography_primitives.internaldafny.generated.HMAC.HMac = HMac \ No newline at end of file diff --git a/AwsCryptographyPrimitives/runtimes/python/src/aws_cryptography_primitives/internaldafny/extern/RSAEncryption.py b/AwsCryptographyPrimitives/runtimes/python/src/aws_cryptography_primitives/internaldafny/extern/RSAEncryption.py new file mode 100644 index 000000000..794775438 --- /dev/null +++ b/AwsCryptographyPrimitives/runtimes/python/src/aws_cryptography_primitives/internaldafny/extern/RSAEncryption.py @@ -0,0 +1,130 @@ +# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 +from cryptography.hazmat.primitives.asymmetric import rsa +from cryptography.hazmat.primitives.asymmetric import padding +from cryptography.hazmat.primitives.serialization import ( + NoEncryption, + Encoding, + PrivateFormat, + PublicFormat, + load_pem_public_key, + load_pem_private_key, +) +from cryptography.hazmat.primitives import hashes + +import _dafny + +from aws_cryptography_primitives.internaldafny.generated.RSAEncryption import * +import aws_cryptography_primitives.internaldafny.generated.RSAEncryption +from aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.errors import _smithy_error_to_dafny_error + +# No generated class to extend +class RSA: + + RSA_KEY_LEN_MAX = 4096 + RSA_PUBLIC_EXPONENT = 65537 + RSA_ERROR_MSG = "AWS Crypto will not generate an RSA Key with length greater than " + str(RSA_KEY_LEN_MAX) + + @classmethod + def GenerateKeyPairExtern(cls, length_bits): + if length_bits > cls.RSA_KEY_LEN_MAX: + raise Exception(cls.RSA_ERROR_MSG) + private_key = rsa.generate_private_key( + public_exponent=cls.RSA_PUBLIC_EXPONENT, + key_size=length_bits, + ) + private_key_pem_bytes = private_key.private_bytes(Encoding.PEM, PrivateFormat.PKCS8, NoEncryption()) + public_key = private_key.public_key() + public_key_pem_bytes = public_key.public_bytes(Encoding.PEM, PublicFormat.SubjectPublicKeyInfo) + return _dafny.Seq(public_key_pem_bytes), _dafny.Seq(private_key_pem_bytes) + + @staticmethod + def GetPaddingForPaddingMode(padding_mode): + if padding_mode.is_OAEP__SHA1: + return padding.OAEP( + mgf=padding.MGF1(algorithm=hashes.SHA1()), + algorithm=hashes.SHA1(), + label=None + ) + elif padding_mode.is_OAEP__SHA256: + return padding.OAEP( + mgf=padding.MGF1(algorithm=hashes.SHA256()), + algorithm=hashes.SHA256(), + label=None + ) + elif padding_mode.is_OAEP__SHA384: + return padding.OAEP( + mgf=padding.MGF1(algorithm=hashes.SHA384()), + algorithm=hashes.SHA384(), + label=None + ) + elif padding_mode.is_OAEP__SHA512: + return padding.OAEP( + mgf=padding.MGF1(algorithm=hashes.SHA512()), + algorithm=hashes.SHA512(), + label=None + ) + elif padding_mode.is_PKCS1: + return padding.PKCS1v15() + + @staticmethod + def EncryptExtern(padding_mode, public_key_der, plaintext): + try: + plaintext_bytes = bytes(plaintext) + public_key = load_pem_public_key(bytes(public_key_der)) + + ct = public_key.encrypt( + plaintext_bytes, + RSA.GetPaddingForPaddingMode(padding_mode) + ) + + return Wrappers.Result_Success(_dafny.Seq(ct)) + except Exception as e: + return Wrappers.Result_Failure( + _smithy_error_to_dafny_error( + e + ) + ) + + @staticmethod + def DecryptExtern(padding_mode, private_key_der, ciphertext): + ciphertext_bytes = bytes(ciphertext) + private_key = load_pem_private_key(bytes(private_key_der), None) + + try: + pt = private_key.decrypt( + ciphertext_bytes, + RSA.GetPaddingForPaddingMode(padding_mode) + ) + + return Wrappers.Result_Success(_dafny.Seq(pt)) + except Exception as e: + return Wrappers.Result_Failure( + _smithy_error_to_dafny_error( + e + ) + ) + + @staticmethod + def GetRSAKeyModulusLengthExtern(public_key_pem): + try: + public_key = load_pem_public_key(bytes(public_key_pem)) + modulus_bit_length = public_key.key_size + return Wrappers.Result_Success(modulus_bit_length) + except Exception as e: + return Wrappers.Result_Failure( + _smithy_error_to_dafny_error( + e + ) + ) + +class EmptyClass: + pass +# Export extern class into the generated module +aws_cryptography_primitives.internaldafny.generated.RSAEncryption.RSA = RSA +aws_cryptography_primitives.internaldafny.generated.RSAEncryption.RSAEncryption = EmptyClass +aws_cryptography_primitives.internaldafny.generated.RSAEncryption.RSAEncryption.RSA = RSA +# Remove following lines after https://github.com/dafny-lang/dafny/issues/4853 is resolved +aws_cryptography_primitives.internaldafny.generated.RSAEncryption.RSA_GetRSAKeyModulusLengthExtern = RSA.GetRSAKeyModulusLengthExtern +aws_cryptography_primitives.internaldafny.generated.RSAEncryption.RSAEncryption.RSA_GetRSAKeyModulusLengthExtern = RSA.GetRSAKeyModulusLengthExtern +RSA_GetRSAKeyModulusLengthExtern = RSA.GetRSAKeyModulusLengthExtern \ No newline at end of file diff --git a/AwsCryptographyPrimitives/runtimes/python/src/aws_cryptography_primitives/internaldafny/extern/Signature.py b/AwsCryptographyPrimitives/runtimes/python/src/aws_cryptography_primitives/internaldafny/extern/Signature.py new file mode 100644 index 000000000..f32e96ff3 --- /dev/null +++ b/AwsCryptographyPrimitives/runtimes/python/src/aws_cryptography_primitives/internaldafny/extern/Signature.py @@ -0,0 +1,362 @@ +# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 +from cryptography.exceptions import ( + InvalidSignature, + UnsupportedAlgorithm +) +from cryptography.hazmat.primitives.asymmetric.ec import EllipticCurvePublicKey +from cryptography.hazmat.primitives import hashes +from cryptography.hazmat.primitives.serialization import ( + NoEncryption, + Encoding, + PrivateFormat, + load_pem_private_key, +) +import cryptography.hazmat.primitives.asymmetric.ec as ec +from cryptography.hazmat.primitives.asymmetric.ec import ( + SECP256R1, + SECP384R1, +) +from cryptography.hazmat.primitives.asymmetric.utils import ( + decode_dss_signature, + encode_dss_signature +) + +from collections import namedtuple +import _dafny +from enum import Enum + +import smithy_dafny_standard_library.internaldafny.generated.Wrappers as Wrappers +import aws_cryptography_primitives.internaldafny.generated.ExternDigest as ExternDigest +from aws_cryptography_primitives.internaldafny.generated.Signature import * +import aws_cryptography_primitives.internaldafny.generated.Signature +from aws_cryptography_primitives.internaldafny.generated.AwsCryptographyPrimitivesTypes import ( + DigestAlgorithm_SHA__256, + DigestAlgorithm_SHA__384, + Error_AwsCryptographicPrimitivesError +) + + +# Extend generated class +class default__(aws_cryptography_primitives.internaldafny.generated.Signature.default__): + class ECDSA: + + @staticmethod + def ExternKeyGen(signature_algorithm): + maybe_signature_algorithm = SignatureAlgorithms.signatureAlgorithm(signature_algorithm) + if maybe_signature_algorithm.is_Failure: + return Wrappers.Result_Failure(maybe_signature_algorithm.error) + + private_key = ec.generate_private_key( + maybe_signature_algorithm.value.value.curve + ) + + private_key_pem_bytes = private_key.private_bytes(Encoding.PEM, PrivateFormat.PKCS8, NoEncryption()) + public_key_pem_bytes = _ecc_encode_compressed_point(private_key) + + return Wrappers.Result_Success(SignatureKeyPair_SignatureKeyPair( + verificationKey=_dafny.Seq(public_key_pem_bytes), + signingKey=_dafny.Seq(private_key_pem_bytes) + )) + + @staticmethod + def Sign(signature_algorithm, signing_key, message): + maybe_signature_algorithm = SignatureAlgorithms.signatureAlgorithm(signature_algorithm) + if maybe_signature_algorithm.is_Failure: + return Wrappers.Result_Failure(maybe_signature_algorithm.error) + + try: + private_key = load_pem_private_key(bytes(signing_key), None) + except ValueError: + return Wrappers.Result_Failure(Error_AwsCryptographicPrimitivesError( + message="Could not decode signing_key" + )) + except TypeError: + return Wrappers.Result_Failure(Error_AwsCryptographicPrimitivesError( + message="Provided signing_key is encrypted, but encrypted signing_keys are not supported" + )) + except UnsupportedAlgorithm: + return Wrappers.Result_Failure(Error_AwsCryptographicPrimitivesError( + message="Serialized key type is not supported by cryptography provider" + )) + + maybe_digest = ExternDigest.default__.internal_digest( + maybe_signature_algorithm.value.value.message_digest_algorithm, + message + ) + if maybe_digest.is_Failure: + return Wrappers.Result_Failure(maybe_digest.error) + digest = maybe_digest.value + + signature_algorithm = maybe_signature_algorithm.value.value + signature = _ecc_static_length_signature(private_key, signature_algorithm, digest) + + return Wrappers.Result_Success(_dafny.Seq(signature)) + + @staticmethod + def Verify(signature_algorithm, verification_key, message, signature): + maybe_signature_algorithm = SignatureAlgorithms.signatureAlgorithm(signature_algorithm) + if maybe_signature_algorithm.is_Failure: + return Wrappers.Result_Failure(maybe_signature_algorithm.error) + + message_digest_algorithm = maybe_signature_algorithm.value.value.message_digest_algorithm + if message_digest_algorithm.is_SHA__256: + sign_algo = ec.ECDSA(hashes.SHA256()) + elif message_digest_algorithm.is_SHA__384: + sign_algo = ec.ECDSA(hashes.SHA384()) + else: + return Wrappers.Result_Failure(Error_AwsCryptographicPrimitivesError( + message=f"Requested Digest Algorithm is not supported. Requested {message_digest_algorithm}" + )) + + curve = maybe_signature_algorithm.value.value.curve() + + try: + public_key = _ecc_public_numbers_from_compressed_point(curve, verification_key).public_key() + except (TypeError, NotImplementedError) as e: + return Wrappers.Result_Failure(Error_AwsCryptographicPrimitivesError( + message=str(e) + )) + + maybe_digest = ExternDigest.default__.internal_digest( + maybe_signature_algorithm.value.value.message_digest_algorithm, + message + ) + if maybe_digest.is_Failure: + return Wrappers.Result_Failure(maybe_digest.error) + digest = maybe_digest.value + + try: + public_key.verify(bytes(signature), + digest, + sign_algo) + except InvalidSignature: + # If signature fails to validate, return Success(False) + return Wrappers.Result_Success(False) + + # If signature validates, return Success(True) + return Wrappers.Result_Success(True) + +# Export extern-extended class into generated class +aws_cryptography_primitives.internaldafny.generated.Signature.default__ = default__ + +class SignatureAlgorithm: + def __init__(self, curve, message_digest_algorithm, raw_signature_algorithm, expected_signature_length): + self.curve = curve + self.message_digest_algorithm = message_digest_algorithm + self.raw_signature_algorithm = raw_signature_algorithm + self.expected_signature_length = expected_signature_length + +class SignatureAlgorithms(Enum): + P256 = SignatureAlgorithm( + SECP256R1, + DigestAlgorithm_SHA__256(), + "NONEwithECDSA", + 71 + ) + P384 = SignatureAlgorithm( + SECP384R1, + DigestAlgorithm_SHA__384(), + "NONEwithECDSA", + 103 + ) + + @classmethod + def signatureAlgorithm(self, sig_alg): + #= aws-encryption-sdk-specification/framework/transitive-requirements.md#ecdsa + ## If specified to use ECDSA, the AWS Encryption SDK MUST use ECDSA with the following specifics: + ## - The elliptic curve is specified by the algorithm suite. + ## The specific curves are defined in + ## [Digital Signature Standard (DSS) (FIPS PUB 186-4)](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf). + if sig_alg.is_ECDSA__P256: + signature_algorithm = SignatureAlgorithms.P256 + elif sig_alg.is_ECDSA__P384: + signature_algorithm = SignatureAlgorithms.P384 + else: + return Wrappers.Result_Failure(Error_AwsCryptographicPrimitivesError( + message=f"Requested Curve is not supported. Requested {sig_alg}" + )) + return Wrappers.Result_Success(signature_algorithm) + +# Export extern class +aws_cryptography_primitives.internaldafny.generated.Signature.ECDSA = default__.ECDSA +# Weirdness with how we've named the extern in Dafny... +aws_cryptography_primitives.internaldafny.generated.Signature.Signature = aws_cryptography_primitives.internaldafny.generated.Signature +aws_cryptography_primitives.internaldafny.generated.Signature.Signature.ECDSA = default__.ECDSA +# Remove after https://github.com/dafny-lang/dafny/issues/4853 +aws_cryptography_primitives.internaldafny.generated.Signature.ECDSA_Verify = default__.ECDSA.Verify +ECDSA_Verify = default__.ECDSA.Verify + +### Following are copied, lightly modified, and pasted util functions/constant definitions +### from the AWS Encryption SDK for Python. +### Reference: https://github.com/aws/aws-encryption-sdk-python/blob/ad6b02c69523d71181734ee42cc9a1debefb8631/src/aws_encryption_sdk/internal/crypto/elliptic_curve.py + +def _to_bytes(data): + """Takes an input str or bytes object and returns an equivalent bytes object. + + :param data: Input data + :type data: str or bytes + :returns: Data normalized to bytes + :rtype: bytes + """ + if isinstance(data, str) and not isinstance(data, bytes): + return str.encode(data) + return data + +def _int_to_bytes(integer, length = None): + return integer.to_bytes( + length or (integer.bit_length() + 7) // 8 or 1, "big" + ) + +_ECCCurveParameters = namedtuple("_ECCCurveParameters", ["p", "a", "b", "order"]) +_ECC_CURVE_PARAMETERS = { + "secp256r1": _ECCCurveParameters( + p=0xFFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF, + a=0xFFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC, + b=0x5AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B, + order=0xFFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551, + ), + "secp384r1": _ECCCurveParameters( + p=0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFF0000000000000000FFFFFFFF, + a=0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFF0000000000000000FFFFFFFC, + b=0xB3312FA7E23EE7E4988E056BE3F82D19181D9C6EFE8141120314088F5013875AC656398D8A2ED19D2A85C8EDD3EC2AEF, + order=0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC7634D81F4372DDF581A0DB248B0A77AECEC196ACCC52973, + ), + "secp521r1": _ECCCurveParameters( + p=0x01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF, # noqa pylint: disable=line-too-long + a=0x01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC, # noqa pylint: disable=line-too-long + b=0x0051953EB9618E1C9A1F929A21A0B68540EEA2DA725B99B315F3B8B489918EF109E156193951EC7E937B1652C0BD3BB1BF073573DF883D2C34F1EF451FD46B503F00, # noqa pylint: disable=line-too-long + order=0x01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFA51868783BF2F966B7FCC0148F709A5D03BB5C9B8899C47AEBB6FB71E91386409, # noqa pylint: disable=line-too-long + ), +} + +def _ecc_static_length_signature(key, algorithm, digest): + """Calculates an elliptic curve signature with a static length using pre-calculated hash. + + :param key: Elliptic curve private key + :type key: cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePrivateKey + :param algorithm: Master algorithm to use + :type algorithm: aws_encryption_sdk.identifiers.Algorithm + :param bytes digest: Pre-calculated hash digest + :returns: Signature with required length + :rtype: bytes + """ + if algorithm.message_digest_algorithm.is_SHA__256: + sign_algo = ec.ECDSA(hashes.SHA256()) + elif algorithm.message_digest_algorithm.is_SHA__384: + sign_algo = ec.ECDSA(hashes.SHA384()) + pre_hashed_algorithm = sign_algo + signature = b"" + while len(signature) != algorithm.expected_signature_length: + signature = key.sign(digest, pre_hashed_algorithm) + if len(signature) != algorithm.expected_signature_length: + # Most of the time, a signature of the wrong length can be fixed + # by negating s in the signature relative to the group order. + r, s = decode_dss_signature(signature) + s = _ECC_CURVE_PARAMETERS[algorithm.curve.name].order - s + signature = encode_dss_signature(r, s) + return signature + +def _ecc_encode_compressed_point_public_key(public_key: EllipticCurvePublicKey): + """Encodes a compressed elliptic curve point + as described in SEC-1 v2 section 2.3.3 + http://www.secg.org/sec1-v2.pdf + + :param private_key: Private key from which to extract point data + :type private_key: cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePrivateKey + :returns: Encoded compressed elliptic curve point + :rtype: bytes + :raises NotImplementedError: for non-prime curves + """ + public_numbers = public_key.public_numbers() + # key_size is in bits. Convert to bytes and round up + byte_length = (public_key.curve.key_size + 7) // 8 + y_map = [b"\x02", b"\x03"] + # If curve in prime field. + if public_key.curve.name.startswith("secp"): + y_order = public_numbers.y % 2 + y = y_map[y_order] + else: + raise NotImplementedError("Non-prime curves are not supported at this time") + return y + _int_to_bytes(public_numbers.x, byte_length) + +def _ecc_encode_compressed_point(private_key): + """Encodes a compressed elliptic curve point + as described in SEC-1 v2 section 2.3.3 + http://www.secg.org/sec1-v2.pdf + + :param private_key: Private key from which to extract point data + :type private_key: cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePrivateKey + :returns: Encoded compressed elliptic curve point + :rtype: bytes + :raises NotImplementedError: for non-prime curves + """ + public_key = private_key.public_key() + return _ecc_encode_compressed_point_public_key(public_key) + +def _ecc_decode_compressed_point(curve, compressed_point): + """Decodes a compressed elliptic curve point + as described in SEC-1 v2 section 2.3.4 + http://www.secg.org/sec1-v2.pdf + + :param curve: Elliptic curve type to generate + :type curve: cryptography.hazmat.primitives.asymmetric.ec.EllipticCurve + :param bytes compressed_point: Encoded compressed elliptic curve point + :returns: X and Y coordinates from compressed point + :rtype: tuple of longs + :raises NotImplementedError: for non-prime curves and unsupported prime curves + :raises TypeError: for points at infinity + """ + if not compressed_point: + raise TypeError("Points at infinity are not allowed") + y_order_map = {b"\x02": 0, b"\x03": 1} + raw_x = compressed_point[1:] + raw_x = _to_bytes(raw_x) + x = int.from_bytes(raw_x, "big") + raw_y = compressed_point[0] + # In Python3, bytes index calls return int values rather than strings + if isinstance(raw_y, int): + raw_y = str.encode(chr(raw_y)) + elif isinstance(raw_y, str): + raw_y = str.encode(raw_y) + y_order = y_order_map[raw_y] + # If curve in prime field. + if curve.name.startswith("secp"): + try: + params = _ECC_CURVE_PARAMETERS[curve.name] + except KeyError: + raise NotImplementedError("Curve {name} is not supported at this time".format(name=curve.name)) + alpha = (pow(x, 3, params.p) + (params.a * x % params.p) + params.b) % params.p + # Only works for p % 4 == 3 at this time. + # This is the case for all currently supported algorithms. + # This will need to be expanded if curves which do not match this are added. + # Python-ecdsa has these algorithms implemented. Copy or reference? + # https://en.wikipedia.org/wiki/Tonelli%E2%80%93Shanks_algorithm + # Handbook of Applied Cryptography, algorithms 3.34 - 3.39 + if params.p % 4 == 3: + beta = pow(alpha, (params.p + 1) // 4, params.p) + else: + raise NotImplementedError("S not 1 :: Curve not supported at this time") + if beta % 2 == y_order: + y = beta + else: + y = params.p - beta + else: + raise NotImplementedError("Non-prime curves are not supported at this time") + return x, y + +def _ecc_public_numbers_from_compressed_point(curve, compressed_point): + """Decodes a compressed elliptic curve point + as described in SEC-1 v2 section 2.3.3 + and returns a PublicNumbers instance + based on the decoded point. + http://www.secg.org/sec1-v2.pdf + + :param curve: Elliptic curve type to generate + :type curve: cryptography.hazmat.primitives.asymmetric.ec.EllipticCurve + :param bytes compressed_point: Encoded compressed elliptic curve point + :returns: EllipticCurvePublicNumbers instance generated from compressed point and curve + :rtype: cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePublicNumbers + """ + x, y = _ecc_decode_compressed_point(curve, compressed_point) + return ec.EllipticCurvePublicNumbers(x=x, y=y, curve=curve) \ No newline at end of file diff --git a/AwsCryptographyPrimitives/runtimes/python/src/aws_cryptography_primitives/internaldafny/extern/__init__.py b/AwsCryptographyPrimitives/runtimes/python/src/aws_cryptography_primitives/internaldafny/extern/__init__.py new file mode 100644 index 000000000..1cf8baeda --- /dev/null +++ b/AwsCryptographyPrimitives/runtimes/python/src/aws_cryptography_primitives/internaldafny/extern/__init__.py @@ -0,0 +1,12 @@ +# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 +from . import ( + AESEncryption, + AesKdfCtr, + ECDH, + ExternDigest, + ExternRandom, + HMAC, + RSAEncryption, + Signature, +) \ No newline at end of file diff --git a/AwsCryptographyPrimitives/runtimes/python/src/aws_cryptography_primitives/internaldafny/generated/dafny_src-py.dtr b/AwsCryptographyPrimitives/runtimes/python/src/aws_cryptography_primitives/internaldafny/generated/dafny_src-py.dtr new file mode 100644 index 000000000..603c44587 --- /dev/null +++ b/AwsCryptographyPrimitives/runtimes/python/src/aws_cryptography_primitives/internaldafny/generated/dafny_src-py.dtr @@ -0,0 +1,59 @@ +file_format_version = "1.0" +dafny_version = "4.8.0.0" +[options_by_module.AwsCryptographyPrimitivesTypes] +legacy-module-names = false +python-module-name = "aws_cryptography_primitives.internaldafny.generated" +[options_by_module.AbstractAwsCryptographyPrimitivesOperations] +legacy-module-names = false +python-module-name = "aws_cryptography_primitives.internaldafny.generated" +[options_by_module.AbstractAwsCryptographyPrimitivesService] +legacy-module-names = false +python-module-name = "aws_cryptography_primitives.internaldafny.generated" +[options_by_module.ExternRandom] +legacy-module-names = false +python-module-name = "aws_cryptography_primitives.internaldafny.generated" +[options_by_module.Random] +legacy-module-names = false +python-module-name = "aws_cryptography_primitives.internaldafny.generated" +[options_by_module.AESEncryption] +legacy-module-names = false +python-module-name = "aws_cryptography_primitives.internaldafny.generated" +[options_by_module.ExternDigest] +legacy-module-names = false +python-module-name = "aws_cryptography_primitives.internaldafny.generated" +[options_by_module.Digest] +legacy-module-names = false +python-module-name = "aws_cryptography_primitives.internaldafny.generated" +[options_by_module.HMAC] +legacy-module-names = false +python-module-name = "aws_cryptography_primitives.internaldafny.generated" +[options_by_module.WrappedHMAC] +legacy-module-names = false +python-module-name = "aws_cryptography_primitives.internaldafny.generated" +[options_by_module.HKDF] +legacy-module-names = false +python-module-name = "aws_cryptography_primitives.internaldafny.generated" +[options_by_module.WrappedHKDF] +legacy-module-names = false +python-module-name = "aws_cryptography_primitives.internaldafny.generated" +[options_by_module.Signature] +legacy-module-names = false +python-module-name = "aws_cryptography_primitives.internaldafny.generated" +[options_by_module.KdfCtr] +legacy-module-names = false +python-module-name = "aws_cryptography_primitives.internaldafny.generated" +[options_by_module.RSAEncryption] +legacy-module-names = false +python-module-name = "aws_cryptography_primitives.internaldafny.generated" +[options_by_module.ECDH] +legacy-module-names = false +python-module-name = "aws_cryptography_primitives.internaldafny.generated" +[options_by_module.AwsCryptographyPrimitivesOperations] +legacy-module-names = false +python-module-name = "aws_cryptography_primitives.internaldafny.generated" +[options_by_module.AtomicPrimitives] +legacy-module-names = false +python-module-name = "aws_cryptography_primitives.internaldafny.generated" +[options_by_module.AesKdfCtr] +legacy-module-names = false +python-module-name = "aws_cryptography_primitives.internaldafny.generated" diff --git a/AwsCryptographyPrimitives/runtimes/python/src/aws_cryptography_primitives/smithygenerated/aws_cryptography_primitives/__init__.py b/AwsCryptographyPrimitives/runtimes/python/src/aws_cryptography_primitives/smithygenerated/aws_cryptography_primitives/__init__.py new file mode 100644 index 000000000..09be6133b --- /dev/null +++ b/AwsCryptographyPrimitives/runtimes/python/src/aws_cryptography_primitives/smithygenerated/aws_cryptography_primitives/__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/AwsCryptographyPrimitives/runtimes/python/src/aws_cryptography_primitives/smithygenerated/aws_cryptography_primitives/client.py b/AwsCryptographyPrimitives/runtimes/python/src/aws_cryptography_primitives/smithygenerated/aws_cryptography_primitives/client.py new file mode 100644 index 000000000..34f26b828 --- /dev/null +++ b/AwsCryptographyPrimitives/runtimes/python/src/aws_cryptography_primitives/smithygenerated/aws_cryptography_primitives/client.py @@ -0,0 +1,756 @@ +# 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_cryptography_primitives.internaldafny.generated.AwsCryptographyPrimitivesTypes import ( + IAwsCryptographicPrimitivesClient, +) +from typing import Callable, TypeVar, cast + +from .config import Config, CryptoConfig +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_aes_decrypt, + _deserialize_aes_encrypt, + _deserialize_aes_kdf_counter_mode, + _deserialize_compress_public_key, + _deserialize_decompress_public_key, + _deserialize_derive_shared_secret, + _deserialize_digest, + _deserialize_ecdsa_sign, + _deserialize_ecdsa_verify, + _deserialize_generate_ecc_key_pair, + _deserialize_generate_ecdsa_signature_key, + _deserialize_generate_random_bytes, + _deserialize_generate_rsa_key_pair, + _deserialize_get_public_key_from_private_key, + _deserialize_get_rsa_key_modulus_length, + _deserialize_h_mac, + _deserialize_hkdf, + _deserialize_hkdf_expand, + _deserialize_hkdf_extract, + _deserialize_kdf_counter_mode, + _deserialize_parse_public_key, + _deserialize_rsa_decrypt, + _deserialize_rsa_encrypt, + _deserialize_validate_public_key, +) +from .errors import ServiceError +from .models import ( + AESDecryptInput, + AESEncryptInput, + AESEncryptOutput, + AesKdfCtrInput, + CompressPublicKeyInput, + CompressPublicKeyOutput, + DecompressPublicKeyInput, + DecompressPublicKeyOutput, + DeriveSharedSecretInput, + DeriveSharedSecretOutput, + DigestInput, + ECDSASignInput, + ECDSAVerifyInput, + GenerateECCKeyPairInput, + GenerateECCKeyPairOutput, + GenerateECDSASignatureKeyInput, + GenerateECDSASignatureKeyOutput, + GenerateRSAKeyPairInput, + GenerateRSAKeyPairOutput, + GenerateRandomBytesInput, + GetPublicKeyFromPrivateKeyInput, + GetPublicKeyFromPrivateKeyOutput, + GetRSAKeyModulusLengthInput, + GetRSAKeyModulusLengthOutput, + HMacInput, + HkdfExpandInput, + HkdfExtractInput, + HkdfInput, + KdfCtrInput, + ParsePublicKeyInput, + ParsePublicKeyOutput, + RSADecryptInput, + RSAEncryptInput, + ValidatePublicKeyInput, + ValidatePublicKeyOutput, +) +from .serialize import ( + _serialize_aes_decrypt, + _serialize_aes_encrypt, + _serialize_aes_kdf_counter_mode, + _serialize_compress_public_key, + _serialize_decompress_public_key, + _serialize_derive_shared_secret, + _serialize_digest, + _serialize_ecdsa_sign, + _serialize_ecdsa_verify, + _serialize_generate_ecc_key_pair, + _serialize_generate_ecdsa_signature_key, + _serialize_generate_random_bytes, + _serialize_generate_rsa_key_pair, + _serialize_get_public_key_from_private_key, + _serialize_get_rsa_key_modulus_length, + _serialize_h_mac, + _serialize_hkdf, + _serialize_hkdf_expand, + _serialize_hkdf_extract, + _serialize_kdf_counter_mode, + _serialize_parse_public_key, + _serialize_rsa_decrypt, + _serialize_rsa_encrypt, + _serialize_validate_public_key, +) + + +Input = TypeVar("Input") +Output = TypeVar("Output") + + +class AwsCryptographicPrimitives: + """Client for AwsCryptographicPrimitives. + + :param config: Configuration for the client. + """ + + def __init__( + self, + config: CryptoConfig | None = None, + dafny_client: IAwsCryptographicPrimitivesClient | 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 generate_random_bytes( + self, input: GenerateRandomBytesInput + ) -> bytes | bytearray: + """Invokes the GenerateRandomBytes operation. + + :param input: The operation's input. + """ + return self._execute_operation( + input=input, + plugins=[], + serialize=_serialize_generate_random_bytes, + deserialize=_deserialize_generate_random_bytes, + config=self._config, + operation_name="GenerateRandomBytes", + ) + + def digest(self, input: DigestInput) -> bytes | bytearray: + """Invokes the Digest operation. + + :param input: The operation's input. + """ + return self._execute_operation( + input=input, + plugins=[], + serialize=_serialize_digest, + deserialize=_deserialize_digest, + config=self._config, + operation_name="Digest", + ) + + def h_mac(self, input: HMacInput) -> bytes | bytearray: + """Invokes the HMac operation. + + :param input: The operation's input. + """ + return self._execute_operation( + input=input, + plugins=[], + serialize=_serialize_h_mac, + deserialize=_deserialize_h_mac, + config=self._config, + operation_name="HMac", + ) + + def hkdf_extract(self, input: HkdfExtractInput) -> bytes | bytearray: + """Invokes the HkdfExtract operation. + + :param input: The operation's input. + """ + return self._execute_operation( + input=input, + plugins=[], + serialize=_serialize_hkdf_extract, + deserialize=_deserialize_hkdf_extract, + config=self._config, + operation_name="HkdfExtract", + ) + + def hkdf_expand(self, input: HkdfExpandInput) -> bytes | bytearray: + """Invokes the HkdfExpand operation. + + :param input: The operation's input. + """ + return self._execute_operation( + input=input, + plugins=[], + serialize=_serialize_hkdf_expand, + deserialize=_deserialize_hkdf_expand, + config=self._config, + operation_name="HkdfExpand", + ) + + def hkdf(self, input: HkdfInput) -> bytes | bytearray: + """Invokes the Hkdf operation. + + :param input: The operation's input. + """ + return self._execute_operation( + input=input, + plugins=[], + serialize=_serialize_hkdf, + deserialize=_deserialize_hkdf, + config=self._config, + operation_name="Hkdf", + ) + + def kdf_counter_mode(self, input: KdfCtrInput) -> bytes | bytearray: + """Invokes the KdfCounterMode operation. + + :param input: The operation's input. + """ + return self._execute_operation( + input=input, + plugins=[], + serialize=_serialize_kdf_counter_mode, + deserialize=_deserialize_kdf_counter_mode, + config=self._config, + operation_name="KdfCounterMode", + ) + + def aes_kdf_counter_mode(self, input: AesKdfCtrInput) -> bytes | bytearray: + """Invokes the AesKdfCounterMode operation. + + :param input: The operation's input. + """ + return self._execute_operation( + input=input, + plugins=[], + serialize=_serialize_aes_kdf_counter_mode, + deserialize=_deserialize_aes_kdf_counter_mode, + config=self._config, + operation_name="AesKdfCounterMode", + ) + + def aes_encrypt(self, input: AESEncryptInput) -> AESEncryptOutput: + """Invokes the AESEncrypt operation. + + :param input: The operation's input. + """ + return self._execute_operation( + input=input, + plugins=[], + serialize=_serialize_aes_encrypt, + deserialize=_deserialize_aes_encrypt, + config=self._config, + operation_name="AESEncrypt", + ) + + def aes_decrypt(self, input: AESDecryptInput) -> bytes | bytearray: + """Invokes the AESDecrypt operation. + + :param input: The operation's input. + """ + return self._execute_operation( + input=input, + plugins=[], + serialize=_serialize_aes_decrypt, + deserialize=_deserialize_aes_decrypt, + config=self._config, + operation_name="AESDecrypt", + ) + + def generate_rsa_key_pair( + self, input: GenerateRSAKeyPairInput + ) -> GenerateRSAKeyPairOutput: + """Invokes the GenerateRSAKeyPair operation. + + :param input: The operation's input. + """ + return self._execute_operation( + input=input, + plugins=[], + serialize=_serialize_generate_rsa_key_pair, + deserialize=_deserialize_generate_rsa_key_pair, + config=self._config, + operation_name="GenerateRSAKeyPair", + ) + + def get_rsa_key_modulus_length( + self, input: GetRSAKeyModulusLengthInput + ) -> GetRSAKeyModulusLengthOutput: + """Invokes the GetRSAKeyModulusLength operation. + + :param input: The operation's input. + """ + return self._execute_operation( + input=input, + plugins=[], + serialize=_serialize_get_rsa_key_modulus_length, + deserialize=_deserialize_get_rsa_key_modulus_length, + config=self._config, + operation_name="GetRSAKeyModulusLength", + ) + + def rsa_decrypt(self, input: RSADecryptInput) -> bytes | bytearray: + """Invokes the RSADecrypt operation. + + :param input: The operation's input. + """ + return self._execute_operation( + input=input, + plugins=[], + serialize=_serialize_rsa_decrypt, + deserialize=_deserialize_rsa_decrypt, + config=self._config, + operation_name="RSADecrypt", + ) + + def rsa_encrypt(self, input: RSAEncryptInput) -> bytes | bytearray: + """Invokes the RSAEncrypt operation. + + :param input: The operation's input. + """ + return self._execute_operation( + input=input, + plugins=[], + serialize=_serialize_rsa_encrypt, + deserialize=_deserialize_rsa_encrypt, + config=self._config, + operation_name="RSAEncrypt", + ) + + def generate_ecdsa_signature_key( + self, input: GenerateECDSASignatureKeyInput + ) -> GenerateECDSASignatureKeyOutput: + """Invokes the GenerateECDSASignatureKey operation. + + :param input: The operation's input. + """ + return self._execute_operation( + input=input, + plugins=[], + serialize=_serialize_generate_ecdsa_signature_key, + deserialize=_deserialize_generate_ecdsa_signature_key, + config=self._config, + operation_name="GenerateECDSASignatureKey", + ) + + def ecdsa_sign(self, input: ECDSASignInput) -> bytes | bytearray: + """Invokes the ECDSASign operation. + + :param input: The operation's input. + """ + return self._execute_operation( + input=input, + plugins=[], + serialize=_serialize_ecdsa_sign, + deserialize=_deserialize_ecdsa_sign, + config=self._config, + operation_name="ECDSASign", + ) + + def ecdsa_verify(self, input: ECDSAVerifyInput) -> bool: + """Invokes the ECDSAVerify operation. + + :param input: The operation's input. + """ + return self._execute_operation( + input=input, + plugins=[], + serialize=_serialize_ecdsa_verify, + deserialize=_deserialize_ecdsa_verify, + config=self._config, + operation_name="ECDSAVerify", + ) + + def generate_ecc_key_pair( + self, input: GenerateECCKeyPairInput + ) -> GenerateECCKeyPairOutput: + """Invokes the GenerateECCKeyPair operation. + + :param input: The operation's input. + """ + return self._execute_operation( + input=input, + plugins=[], + serialize=_serialize_generate_ecc_key_pair, + deserialize=_deserialize_generate_ecc_key_pair, + config=self._config, + operation_name="GenerateECCKeyPair", + ) + + def get_public_key_from_private_key( + self, input: GetPublicKeyFromPrivateKeyInput + ) -> GetPublicKeyFromPrivateKeyOutput: + """Invokes the GetPublicKeyFromPrivateKey operation. + + :param input: The operation's input. + """ + return self._execute_operation( + input=input, + plugins=[], + serialize=_serialize_get_public_key_from_private_key, + deserialize=_deserialize_get_public_key_from_private_key, + config=self._config, + operation_name="GetPublicKeyFromPrivateKey", + ) + + def validate_public_key( + self, input: ValidatePublicKeyInput + ) -> ValidatePublicKeyOutput: + """Invokes the ValidatePublicKey operation. + + :param input: The operation's input. + """ + return self._execute_operation( + input=input, + plugins=[], + serialize=_serialize_validate_public_key, + deserialize=_deserialize_validate_public_key, + config=self._config, + operation_name="ValidatePublicKey", + ) + + def derive_shared_secret( + self, input: DeriveSharedSecretInput + ) -> DeriveSharedSecretOutput: + """Invokes the DeriveSharedSecret operation. + + :param input: The operation's input. + """ + return self._execute_operation( + input=input, + plugins=[], + serialize=_serialize_derive_shared_secret, + deserialize=_deserialize_derive_shared_secret, + config=self._config, + operation_name="DeriveSharedSecret", + ) + + def compress_public_key( + self, input: CompressPublicKeyInput + ) -> CompressPublicKeyOutput: + """Invokes the CompressPublicKey operation. + + :param input: The operation's input. + """ + return self._execute_operation( + input=input, + plugins=[], + serialize=_serialize_compress_public_key, + deserialize=_deserialize_compress_public_key, + config=self._config, + operation_name="CompressPublicKey", + ) + + def decompress_public_key( + self, input: DecompressPublicKeyInput + ) -> DecompressPublicKeyOutput: + """Invokes the DecompressPublicKey operation. + + :param input: The operation's input. + """ + return self._execute_operation( + input=input, + plugins=[], + serialize=_serialize_decompress_public_key, + deserialize=_deserialize_decompress_public_key, + config=self._config, + operation_name="DecompressPublicKey", + ) + + def parse_public_key(self, input: ParsePublicKeyInput) -> ParsePublicKeyOutput: + """Invokes the ParsePublicKey operation. + + :param input: The operation's input. + """ + return self._execute_operation( + input=input, + plugins=[], + serialize=_serialize_parse_public_key, + deserialize=_deserialize_parse_public_key, + config=self._config, + operation_name="ParsePublicKey", + ) + + 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/AwsCryptographyPrimitives/runtimes/python/src/aws_cryptography_primitives/smithygenerated/aws_cryptography_primitives/config.py b/AwsCryptographyPrimitives/runtimes/python/src/aws_cryptography_primitives/smithygenerated/aws_cryptography_primitives/config.py new file mode 100644 index 000000000..8858396f2 --- /dev/null +++ b/AwsCryptographyPrimitives/runtimes/python/src/aws_cryptography_primitives/smithygenerated/aws_cryptography_primitives/config.py @@ -0,0 +1,77 @@ +# 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_cryptography_primitives.internaldafny.generated.AwsCryptographyPrimitivesTypes import ( + CryptoConfig_CryptoConfig as DafnyCryptoConfig, +) +import aws_cryptography_primitives.internaldafny.generated.module_ +import aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.dafny_to_smithy +import aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.smithy_to_dafny +from dataclasses import dataclass +from typing import Any, Callable, TypeAlias + +from .dafnyImplInterface import DafnyImplInterface +from smithy_python._private.retries import SimpleRetryStrategy +from smithy_python.interfaces.retries import RetryStrategy + + +_ServiceInterceptor = Any + + +@dataclass(init=False) +class Config: + """Configuration for AwsCryptographicPrimitives.""" + + 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 CryptoConfig(Config): + """Smithy-modelled localService Config shape for this localService.""" + + def __init__( + self, + ): + """Constructor for CryptoConfig.""" + super().__init__() + + +def dafny_config_to_smithy_config(dafny_config) -> CryptoConfig: + """Converts the provided Dafny shape for this localService's config into + the corresponding Smithy-modelled shape.""" + return aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.dafny_to_smithy.aws_cryptography_primitives_CryptoConfig( + dafny_config + ) + + +def smithy_config_to_dafny_config(smithy_config) -> DafnyCryptoConfig: + """Converts the provided Smithy-modelled shape for this localService's + config into the corresponding Dafny shape.""" + return aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.smithy_to_dafny.aws_cryptography_primitives_CryptoConfig( + smithy_config + ) diff --git a/AwsCryptographyPrimitives/runtimes/python/src/aws_cryptography_primitives/smithygenerated/aws_cryptography_primitives/dafnyImplInterface.py b/AwsCryptographyPrimitives/runtimes/python/src/aws_cryptography_primitives/smithygenerated/aws_cryptography_primitives/dafnyImplInterface.py new file mode 100644 index 000000000..97262b1c6 --- /dev/null +++ b/AwsCryptographyPrimitives/runtimes/python/src/aws_cryptography_primitives/smithygenerated/aws_cryptography_primitives/dafnyImplInterface.py @@ -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. + +from aws_cryptography_primitives.internaldafny.generated.AtomicPrimitives import ( + AtomicPrimitivesClient, +) +from .dafny_protocol import DafnyRequest + + +class DafnyImplInterface: + impl: AtomicPrimitivesClient | 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 = { + "GenerateRandomBytes": self.impl.GenerateRandomBytes, + "Digest": self.impl.Digest, + "HMac": self.impl.HMac, + "HkdfExtract": self.impl.HkdfExtract, + "HkdfExpand": self.impl.HkdfExpand, + "Hkdf": self.impl.Hkdf, + "KdfCounterMode": self.impl.KdfCounterMode, + "AesKdfCounterMode": self.impl.AesKdfCounterMode, + "AESEncrypt": self.impl.AESEncrypt, + "AESDecrypt": self.impl.AESDecrypt, + "GenerateRSAKeyPair": self.impl.GenerateRSAKeyPair, + "GetRSAKeyModulusLength": self.impl.GetRSAKeyModulusLength, + "RSADecrypt": self.impl.RSADecrypt, + "RSAEncrypt": self.impl.RSAEncrypt, + "GenerateECDSASignatureKey": self.impl.GenerateECDSASignatureKey, + "ECDSASign": self.impl.ECDSASign, + "ECDSAVerify": self.impl.ECDSAVerify, + "GenerateECCKeyPair": self.impl.GenerateECCKeyPair, + "GetPublicKeyFromPrivateKey": self.impl.GetPublicKeyFromPrivateKey, + "ValidatePublicKey": self.impl.ValidatePublicKey, + "DeriveSharedSecret": self.impl.DeriveSharedSecret, + "CompressPublicKey": self.impl.CompressPublicKey, + "DecompressPublicKey": self.impl.DecompressPublicKey, + "ParsePublicKey": self.impl.ParsePublicKey, + } + + # 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/AwsCryptographyPrimitives/runtimes/python/src/aws_cryptography_primitives/smithygenerated/aws_cryptography_primitives/dafny_protocol.py b/AwsCryptographyPrimitives/runtimes/python/src/aws_cryptography_primitives/smithygenerated/aws_cryptography_primitives/dafny_protocol.py new file mode 100644 index 000000000..cc3901213 --- /dev/null +++ b/AwsCryptographyPrimitives/runtimes/python/src/aws_cryptography_primitives/smithygenerated/aws_cryptography_primitives/dafny_protocol.py @@ -0,0 +1,77 @@ +# 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_cryptography_primitives.internaldafny.generated.AwsCryptographyPrimitivesTypes import ( + AESDecryptInput_AESDecryptInput as DafnyAESDecryptInput, + AESEncryptInput_AESEncryptInput as DafnyAESEncryptInput, + AesKdfCtrInput_AesKdfCtrInput as DafnyAesKdfCtrInput, + CompressPublicKeyInput_CompressPublicKeyInput as DafnyCompressPublicKeyInput, + DecompressPublicKeyInput_DecompressPublicKeyInput as DafnyDecompressPublicKeyInput, + DeriveSharedSecretInput_DeriveSharedSecretInput as DafnyDeriveSharedSecretInput, + DigestInput_DigestInput as DafnyDigestInput, + ECDSASignInput_ECDSASignInput as DafnyECDSASignInput, + ECDSAVerifyInput_ECDSAVerifyInput as DafnyECDSAVerifyInput, + GenerateECCKeyPairInput_GenerateECCKeyPairInput as DafnyGenerateECCKeyPairInput, + GenerateECDSASignatureKeyInput_GenerateECDSASignatureKeyInput as DafnyGenerateECDSASignatureKeyInput, + GenerateRSAKeyPairInput_GenerateRSAKeyPairInput as DafnyGenerateRSAKeyPairInput, + GenerateRandomBytesInput_GenerateRandomBytesInput as DafnyGenerateRandomBytesInput, + GetPublicKeyFromPrivateKeyInput_GetPublicKeyFromPrivateKeyInput as DafnyGetPublicKeyFromPrivateKeyInput, + GetRSAKeyModulusLengthInput_GetRSAKeyModulusLengthInput as DafnyGetRSAKeyModulusLengthInput, + HMacInput_HMacInput as DafnyHMacInput, + HkdfExpandInput_HkdfExpandInput as DafnyHkdfExpandInput, + HkdfExtractInput_HkdfExtractInput as DafnyHkdfExtractInput, + HkdfInput_HkdfInput as DafnyHkdfInput, + KdfCtrInput_KdfCtrInput as DafnyKdfCtrInput, + ParsePublicKeyInput_ParsePublicKeyInput as DafnyParsePublicKeyInput, + RSADecryptInput_RSADecryptInput as DafnyRSADecryptInput, + RSAEncryptInput_RSAEncryptInput as DafnyRSAEncryptInput, + ValidatePublicKeyInput_ValidatePublicKeyInput as DafnyValidatePublicKeyInput, +) +import aws_cryptography_primitives.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[ + DafnyGetRSAKeyModulusLengthInput, + DafnyGetPublicKeyFromPrivateKeyInput, + DafnyGenerateECDSASignatureKeyInput, + DafnyHkdfExtractInput, + DafnyECDSASignInput, + DafnyHkdfInput, + DafnyRSADecryptInput, + DafnyDigestInput, + DafnyHMacInput, + DafnyHkdfExpandInput, + DafnyParsePublicKeyInput, + DafnyECDSAVerifyInput, + DafnyCompressPublicKeyInput, + DafnyAESDecryptInput, + DafnyGenerateECCKeyPairInput, + DafnyDeriveSharedSecretInput, + DafnyAESEncryptInput, + DafnyDecompressPublicKeyInput, + DafnyAesKdfCtrInput, + DafnyKdfCtrInput, + DafnyGenerateRSAKeyPairInput, + DafnyValidatePublicKeyInput, + DafnyGenerateRandomBytesInput, + DafnyRSAEncryptInput, + ] + + 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/AwsCryptographyPrimitives/runtimes/python/src/aws_cryptography_primitives/smithygenerated/aws_cryptography_primitives/dafny_to_smithy.py b/AwsCryptographyPrimitives/runtimes/python/src/aws_cryptography_primitives/smithygenerated/aws_cryptography_primitives/dafny_to_smithy.py new file mode 100644 index 000000000..5f3d1b3ff --- /dev/null +++ b/AwsCryptographyPrimitives/runtimes/python/src/aws_cryptography_primitives/smithygenerated/aws_cryptography_primitives/dafny_to_smithy.py @@ -0,0 +1,510 @@ +# 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_cryptography_primitives.internaldafny.generated.AwsCryptographyPrimitivesTypes import ( + DigestAlgorithm_SHA__256, + DigestAlgorithm_SHA__384, + DigestAlgorithm_SHA__512, + ECDHCurveSpec_ECC__NIST__P256, + ECDHCurveSpec_ECC__NIST__P384, + ECDHCurveSpec_ECC__NIST__P521, + ECDHCurveSpec_SM2, + ECDSASignatureAlgorithm_ECDSA__P256, + ECDSASignatureAlgorithm_ECDSA__P384, + RSAPaddingMode_OAEP__SHA1, + RSAPaddingMode_OAEP__SHA256, + RSAPaddingMode_OAEP__SHA384, + RSAPaddingMode_OAEP__SHA512, + RSAPaddingMode_PKCS1, +) +import aws_cryptography_primitives.internaldafny.generated.module_ +import aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.dafny_to_smithy +import aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.models + + +def aws_cryptography_primitives_GenerateRandomBytesInput(dafny_input): + return aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.models.GenerateRandomBytesInput( + length=dafny_input.length, + ) + + +def aws_cryptography_primitives_DigestAlgorithm(dafny_input): + if isinstance(dafny_input, DigestAlgorithm_SHA__512): + return "SHA_512" + + elif isinstance(dafny_input, DigestAlgorithm_SHA__384): + return "SHA_384" + + elif isinstance(dafny_input, DigestAlgorithm_SHA__256): + return "SHA_256" + + else: + raise ValueError(f"No recognized enum value in enum type: {dafny_input=}") + + +def aws_cryptography_primitives_DigestInput(dafny_input): + return aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.models.DigestInput( + digest_algorithm=aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.dafny_to_smithy.aws_cryptography_primitives_DigestAlgorithm( + dafny_input.digestAlgorithm + ), + message=bytes(dafny_input.message), + ) + + +def aws_cryptography_primitives_HMacInput(dafny_input): + return aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.models.HMacInput( + digest_algorithm=aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.dafny_to_smithy.aws_cryptography_primitives_DigestAlgorithm( + dafny_input.digestAlgorithm + ), + key=bytes(dafny_input.key), + message=bytes(dafny_input.message), + ) + + +def aws_cryptography_primitives_HkdfExtractInput(dafny_input): + return aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.models.HkdfExtractInput( + digest_algorithm=aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.dafny_to_smithy.aws_cryptography_primitives_DigestAlgorithm( + dafny_input.digestAlgorithm + ), + salt=(bytes(dafny_input.salt.value)) if (dafny_input.salt.is_Some) else None, + ikm=bytes(dafny_input.ikm), + ) + + +def aws_cryptography_primitives_HkdfExpandInput(dafny_input): + return aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.models.HkdfExpandInput( + digest_algorithm=aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.dafny_to_smithy.aws_cryptography_primitives_DigestAlgorithm( + dafny_input.digestAlgorithm + ), + prk=bytes(dafny_input.prk), + info=bytes(dafny_input.info), + expected_length=dafny_input.expectedLength, + ) + + +def aws_cryptography_primitives_HkdfInput(dafny_input): + return aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.models.HkdfInput( + digest_algorithm=aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.dafny_to_smithy.aws_cryptography_primitives_DigestAlgorithm( + dafny_input.digestAlgorithm + ), + salt=(bytes(dafny_input.salt.value)) if (dafny_input.salt.is_Some) else None, + ikm=bytes(dafny_input.ikm), + info=bytes(dafny_input.info), + expected_length=dafny_input.expectedLength, + ) + + +def aws_cryptography_primitives_KdfCtrInput(dafny_input): + return aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.models.KdfCtrInput( + digest_algorithm=aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.dafny_to_smithy.aws_cryptography_primitives_DigestAlgorithm( + dafny_input.digestAlgorithm + ), + ikm=bytes(dafny_input.ikm), + expected_length=dafny_input.expectedLength, + purpose=( + (bytes(dafny_input.purpose.value)) + if (dafny_input.purpose.is_Some) + else None + ), + nonce=(bytes(dafny_input.nonce.value)) if (dafny_input.nonce.is_Some) else None, + ) + + +def aws_cryptography_primitives_AesKdfCtrInput(dafny_input): + return aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.models.AesKdfCtrInput( + ikm=bytes(dafny_input.ikm), + expected_length=dafny_input.expectedLength, + nonce=(bytes(dafny_input.nonce.value)) if (dafny_input.nonce.is_Some) else None, + ) + + +def aws_cryptography_primitives_AES_GCM(dafny_input): + return aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.models.AES_GCM( + key_length=dafny_input.keyLength, + tag_length=dafny_input.tagLength, + iv_length=dafny_input.ivLength, + ) + + +def aws_cryptography_primitives_AESEncryptInput(dafny_input): + return aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.models.AESEncryptInput( + enc_alg=aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.dafny_to_smithy.aws_cryptography_primitives_AES_GCM( + dafny_input.encAlg + ), + iv=bytes(dafny_input.iv), + key=bytes(dafny_input.key), + msg=bytes(dafny_input.msg), + aad=bytes(dafny_input.aad), + ) + + +def aws_cryptography_primitives_AESDecryptInput(dafny_input): + return aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.models.AESDecryptInput( + enc_alg=aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.dafny_to_smithy.aws_cryptography_primitives_AES_GCM( + dafny_input.encAlg + ), + key=bytes(dafny_input.key), + cipher_txt=bytes(dafny_input.cipherTxt), + auth_tag=bytes(dafny_input.authTag), + iv=bytes(dafny_input.iv), + aad=bytes(dafny_input.aad), + ) + + +def aws_cryptography_primitives_GenerateRSAKeyPairInput(dafny_input): + return aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.models.GenerateRSAKeyPairInput( + length_bits=dafny_input.lengthBits, + ) + + +def aws_cryptography_primitives_GetRSAKeyModulusLengthInput(dafny_input): + return aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.models.GetRSAKeyModulusLengthInput( + public_key=bytes(dafny_input.publicKey), + ) + + +def aws_cryptography_primitives_RSAPaddingMode(dafny_input): + if isinstance(dafny_input, RSAPaddingMode_PKCS1): + return "PKCS1" + + elif isinstance(dafny_input, RSAPaddingMode_OAEP__SHA1): + return "OAEP_SHA1" + + elif isinstance(dafny_input, RSAPaddingMode_OAEP__SHA256): + return "OAEP_SHA256" + + elif isinstance(dafny_input, RSAPaddingMode_OAEP__SHA384): + return "OAEP_SHA384" + + elif isinstance(dafny_input, RSAPaddingMode_OAEP__SHA512): + return "OAEP_SHA512" + + else: + raise ValueError(f"No recognized enum value in enum type: {dafny_input=}") + + +def aws_cryptography_primitives_RSADecryptInput(dafny_input): + return aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.models.RSADecryptInput( + padding=aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.dafny_to_smithy.aws_cryptography_primitives_RSAPaddingMode( + dafny_input.padding + ), + private_key=bytes(dafny_input.privateKey), + cipher_text=bytes(dafny_input.cipherText), + ) + + +def aws_cryptography_primitives_RSAEncryptInput(dafny_input): + return aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.models.RSAEncryptInput( + padding=aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.dafny_to_smithy.aws_cryptography_primitives_RSAPaddingMode( + dafny_input.padding + ), + public_key=bytes(dafny_input.publicKey), + plaintext=bytes(dafny_input.plaintext), + ) + + +def aws_cryptography_primitives_ECDSASignatureAlgorithm(dafny_input): + if isinstance(dafny_input, ECDSASignatureAlgorithm_ECDSA__P384): + return "ECDSA_P384" + + elif isinstance(dafny_input, ECDSASignatureAlgorithm_ECDSA__P256): + return "ECDSA_P256" + + else: + raise ValueError(f"No recognized enum value in enum type: {dafny_input=}") + + +def aws_cryptography_primitives_GenerateECDSASignatureKeyInput(dafny_input): + return aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.models.GenerateECDSASignatureKeyInput( + signature_algorithm=aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.dafny_to_smithy.aws_cryptography_primitives_ECDSASignatureAlgorithm( + dafny_input.signatureAlgorithm + ), + ) + + +def aws_cryptography_primitives_ECDSASignInput(dafny_input): + return aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.models.ECDSASignInput( + signature_algorithm=aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.dafny_to_smithy.aws_cryptography_primitives_ECDSASignatureAlgorithm( + dafny_input.signatureAlgorithm + ), + signing_key=bytes(dafny_input.signingKey), + message=bytes(dafny_input.message), + ) + + +def aws_cryptography_primitives_ECDSAVerifyInput(dafny_input): + return aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.models.ECDSAVerifyInput( + signature_algorithm=aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.dafny_to_smithy.aws_cryptography_primitives_ECDSASignatureAlgorithm( + dafny_input.signatureAlgorithm + ), + verification_key=bytes(dafny_input.verificationKey), + message=bytes(dafny_input.message), + signature=bytes(dafny_input.signature), + ) + + +def aws_cryptography_primitives_ECDHCurveSpec(dafny_input): + if isinstance(dafny_input, ECDHCurveSpec_ECC__NIST__P256): + return "ECC_NIST_P256" + + elif isinstance(dafny_input, ECDHCurveSpec_ECC__NIST__P384): + return "ECC_NIST_P384" + + elif isinstance(dafny_input, ECDHCurveSpec_ECC__NIST__P521): + return "ECC_NIST_P521" + + elif isinstance(dafny_input, ECDHCurveSpec_SM2): + return "SM2" + + else: + raise ValueError(f"No recognized enum value in enum type: {dafny_input=}") + + +def aws_cryptography_primitives_GenerateECCKeyPairInput(dafny_input): + return aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.models.GenerateECCKeyPairInput( + ecc_curve=aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.dafny_to_smithy.aws_cryptography_primitives_ECDHCurveSpec( + dafny_input.eccCurve + ), + ) + + +def aws_cryptography_primitives_ECCPrivateKey(dafny_input): + return aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.models.ECCPrivateKey( + pem=bytes(dafny_input.pem), + ) + + +def aws_cryptography_primitives_GetPublicKeyFromPrivateKeyInput(dafny_input): + return aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.models.GetPublicKeyFromPrivateKeyInput( + ecc_curve=aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.dafny_to_smithy.aws_cryptography_primitives_ECDHCurveSpec( + dafny_input.eccCurve + ), + private_key=aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.dafny_to_smithy.aws_cryptography_primitives_ECCPrivateKey( + dafny_input.privateKey + ), + ) + + +def aws_cryptography_primitives_ValidatePublicKeyInput(dafny_input): + return aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.models.ValidatePublicKeyInput( + ecc_curve=aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.dafny_to_smithy.aws_cryptography_primitives_ECDHCurveSpec( + dafny_input.eccCurve + ), + public_key=bytes(dafny_input.publicKey), + ) + + +def aws_cryptography_primitives_ECCPublicKey(dafny_input): + return aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.models.ECCPublicKey( + der=bytes(dafny_input.der), + ) + + +def aws_cryptography_primitives_DeriveSharedSecretInput(dafny_input): + return aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.models.DeriveSharedSecretInput( + ecc_curve=aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.dafny_to_smithy.aws_cryptography_primitives_ECDHCurveSpec( + dafny_input.eccCurve + ), + private_key=aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.dafny_to_smithy.aws_cryptography_primitives_ECCPrivateKey( + dafny_input.privateKey + ), + public_key=aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.dafny_to_smithy.aws_cryptography_primitives_ECCPublicKey( + dafny_input.publicKey + ), + ) + + +def aws_cryptography_primitives_CompressPublicKeyInput(dafny_input): + return aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.models.CompressPublicKeyInput( + public_key=aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.dafny_to_smithy.aws_cryptography_primitives_ECCPublicKey( + dafny_input.publicKey + ), + ecc_curve=aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.dafny_to_smithy.aws_cryptography_primitives_ECDHCurveSpec( + dafny_input.eccCurve + ), + ) + + +def aws_cryptography_primitives_DecompressPublicKeyInput(dafny_input): + return aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.models.DecompressPublicKeyInput( + compressed_public_key=bytes(dafny_input.compressedPublicKey), + ecc_curve=aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.dafny_to_smithy.aws_cryptography_primitives_ECDHCurveSpec( + dafny_input.eccCurve + ), + ) + + +def aws_cryptography_primitives_ParsePublicKeyInput(dafny_input): + return aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.models.ParsePublicKeyInput( + public_key=bytes(dafny_input.publicKey), + ) + + +def aws_cryptography_primitives_GenerateRandomBytesOutput(dafny_input): + return bytes(dafny_input) + + +def aws_cryptography_primitives_DigestOutput(dafny_input): + return bytes(dafny_input) + + +def aws_cryptography_primitives_HMacOutput(dafny_input): + return bytes(dafny_input) + + +def aws_cryptography_primitives_HkdfExtractOutput(dafny_input): + return bytes(dafny_input) + + +def aws_cryptography_primitives_HkdfExpandOutput(dafny_input): + return bytes(dafny_input) + + +def aws_cryptography_primitives_HkdfOutput(dafny_input): + return bytes(dafny_input) + + +def aws_cryptography_primitives_KdfCtrOutput(dafny_input): + return bytes(dafny_input) + + +def aws_cryptography_primitives_AesKdfCtrOutput(dafny_input): + return bytes(dafny_input) + + +def aws_cryptography_primitives_AESEncryptOutput(dafny_input): + return aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.models.AESEncryptOutput( + cipher_text=bytes(dafny_input.cipherText), + auth_tag=bytes(dafny_input.authTag), + ) + + +def aws_cryptography_primitives_AESDecryptOutput(dafny_input): + return bytes(dafny_input) + + +def aws_cryptography_primitives_RSAPublicKey(dafny_input): + return aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.models.RSAPublicKey( + length_bits=dafny_input.lengthBits, + pem=bytes(dafny_input.pem), + ) + + +def aws_cryptography_primitives_RSAPrivateKey(dafny_input): + return aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.models.RSAPrivateKey( + length_bits=dafny_input.lengthBits, + pem=bytes(dafny_input.pem), + ) + + +def aws_cryptography_primitives_GenerateRSAKeyPairOutput(dafny_input): + return aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.models.GenerateRSAKeyPairOutput( + public_key=aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.dafny_to_smithy.aws_cryptography_primitives_RSAPublicKey( + dafny_input.publicKey + ), + private_key=aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.dafny_to_smithy.aws_cryptography_primitives_RSAPrivateKey( + dafny_input.privateKey + ), + ) + + +def aws_cryptography_primitives_GetRSAKeyModulusLengthOutput(dafny_input): + return aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.models.GetRSAKeyModulusLengthOutput( + length=dafny_input.length, + ) + + +def aws_cryptography_primitives_RSADecryptOutput(dafny_input): + return bytes(dafny_input) + + +def aws_cryptography_primitives_RSAEncryptOutput(dafny_input): + return bytes(dafny_input) + + +def aws_cryptography_primitives_GenerateECDSASignatureKeyOutput(dafny_input): + return aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.models.GenerateECDSASignatureKeyOutput( + signature_algorithm=aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.dafny_to_smithy.aws_cryptography_primitives_ECDSASignatureAlgorithm( + dafny_input.signatureAlgorithm + ), + verification_key=bytes(dafny_input.verificationKey), + signing_key=bytes(dafny_input.signingKey), + ) + + +def aws_cryptography_primitives_ECDSASignOutput(dafny_input): + return bytes(dafny_input) + + +def aws_cryptography_primitives_ECDSAVerifyOutput(dafny_input): + return dafny_input + + +def aws_cryptography_primitives_GenerateECCKeyPairOutput(dafny_input): + return aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.models.GenerateECCKeyPairOutput( + ecc_curve=aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.dafny_to_smithy.aws_cryptography_primitives_ECDHCurveSpec( + dafny_input.eccCurve + ), + private_key=aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.dafny_to_smithy.aws_cryptography_primitives_ECCPrivateKey( + dafny_input.privateKey + ), + public_key=aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.dafny_to_smithy.aws_cryptography_primitives_ECCPublicKey( + dafny_input.publicKey + ), + ) + + +def aws_cryptography_primitives_GetPublicKeyFromPrivateKeyOutput(dafny_input): + return aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.models.GetPublicKeyFromPrivateKeyOutput( + ecc_curve=aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.dafny_to_smithy.aws_cryptography_primitives_ECDHCurveSpec( + dafny_input.eccCurve + ), + private_key=aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.dafny_to_smithy.aws_cryptography_primitives_ECCPrivateKey( + dafny_input.privateKey + ), + public_key=bytes(dafny_input.publicKey), + ) + + +def aws_cryptography_primitives_ValidatePublicKeyOutput(dafny_input): + return aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.models.ValidatePublicKeyOutput( + success=dafny_input.success, + ) + + +def aws_cryptography_primitives_DeriveSharedSecretOutput(dafny_input): + return aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.models.DeriveSharedSecretOutput( + shared_secret=bytes(dafny_input.sharedSecret), + ) + + +def aws_cryptography_primitives_CompressPublicKeyOutput(dafny_input): + return aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.models.CompressPublicKeyOutput( + compressed_public_key=bytes(dafny_input.compressedPublicKey), + ) + + +def aws_cryptography_primitives_DecompressPublicKeyOutput(dafny_input): + return aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.models.DecompressPublicKeyOutput( + public_key=aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.dafny_to_smithy.aws_cryptography_primitives_ECCPublicKey( + dafny_input.publicKey + ), + ) + + +def aws_cryptography_primitives_ParsePublicKeyOutput(dafny_input): + return aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.models.ParsePublicKeyOutput( + public_key=aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.dafny_to_smithy.aws_cryptography_primitives_ECCPublicKey( + dafny_input.publicKey + ), + ) + + +def aws_cryptography_primitives_CryptoConfig(dafny_input): + # Deferred import of .config to avoid circular dependency + import aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.config + + return ( + aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.config.CryptoConfig() + ) diff --git a/AwsCryptographyPrimitives/runtimes/python/src/aws_cryptography_primitives/smithygenerated/aws_cryptography_primitives/deserialize.py b/AwsCryptographyPrimitives/runtimes/python/src/aws_cryptography_primitives/smithygenerated/aws_cryptography_primitives/deserialize.py new file mode 100644 index 000000000..2556ced3a --- /dev/null +++ b/AwsCryptographyPrimitives/runtimes/python/src/aws_cryptography_primitives/smithygenerated/aws_cryptography_primitives/deserialize.py @@ -0,0 +1,263 @@ +# 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_cryptography_primitives.internaldafny.generated.AwsCryptographyPrimitivesTypes import ( + AESEncryptOutput_AESEncryptOutput as DafnyAESEncryptOutput, + CompressPublicKeyOutput_CompressPublicKeyOutput as DafnyCompressPublicKeyOutput, + DecompressPublicKeyOutput_DecompressPublicKeyOutput as DafnyDecompressPublicKeyOutput, + DeriveSharedSecretOutput_DeriveSharedSecretOutput as DafnyDeriveSharedSecretOutput, + Error, + Error_AwsCryptographicPrimitivesError, + GenerateECCKeyPairOutput_GenerateECCKeyPairOutput as DafnyGenerateECCKeyPairOutput, + GenerateECDSASignatureKeyOutput_GenerateECDSASignatureKeyOutput as DafnyGenerateECDSASignatureKeyOutput, + GenerateRSAKeyPairOutput_GenerateRSAKeyPairOutput as DafnyGenerateRSAKeyPairOutput, + GetPublicKeyFromPrivateKeyOutput_GetPublicKeyFromPrivateKeyOutput as DafnyGetPublicKeyFromPrivateKeyOutput, + GetRSAKeyModulusLengthOutput_GetRSAKeyModulusLengthOutput as DafnyGetRSAKeyModulusLengthOutput, + ParsePublicKeyOutput_ParsePublicKeyOutput as DafnyParsePublicKeyOutput, + ValidatePublicKeyOutput_ValidatePublicKeyOutput as DafnyValidatePublicKeyOutput, +) +import aws_cryptography_primitives.internaldafny.generated.module_ +import aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.dafny_to_smithy +from typing import Any + +from .dafny_protocol import DafnyResponse +from .errors import ( + AwsCryptographicPrimitivesError, + CollectionOfErrors, + OpaqueError, + ServiceError, +) + +from .config import Config + + +def _deserialize_generate_random_bytes(input: DafnyResponse, config: Config): + + if input.IsFailure(): + return _deserialize_error(input.error) + return aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.dafny_to_smithy.aws_cryptography_primitives_GenerateRandomBytesOutput( + input.value + ) + + +def _deserialize_digest(input: DafnyResponse, config: Config): + + if input.IsFailure(): + return _deserialize_error(input.error) + return aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.dafny_to_smithy.aws_cryptography_primitives_DigestOutput( + input.value + ) + + +def _deserialize_h_mac(input: DafnyResponse, config: Config): + + if input.IsFailure(): + return _deserialize_error(input.error) + return aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.dafny_to_smithy.aws_cryptography_primitives_HMacOutput( + input.value + ) + + +def _deserialize_hkdf_extract(input: DafnyResponse, config: Config): + + if input.IsFailure(): + return _deserialize_error(input.error) + return aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.dafny_to_smithy.aws_cryptography_primitives_HkdfExtractOutput( + input.value + ) + + +def _deserialize_hkdf_expand(input: DafnyResponse, config: Config): + + if input.IsFailure(): + return _deserialize_error(input.error) + return aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.dafny_to_smithy.aws_cryptography_primitives_HkdfExpandOutput( + input.value + ) + + +def _deserialize_hkdf(input: DafnyResponse, config: Config): + + if input.IsFailure(): + return _deserialize_error(input.error) + return aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.dafny_to_smithy.aws_cryptography_primitives_HkdfOutput( + input.value + ) + + +def _deserialize_kdf_counter_mode(input: DafnyResponse, config: Config): + + if input.IsFailure(): + return _deserialize_error(input.error) + return aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.dafny_to_smithy.aws_cryptography_primitives_KdfCtrOutput( + input.value + ) + + +def _deserialize_aes_kdf_counter_mode(input: DafnyResponse, config: Config): + + if input.IsFailure(): + return _deserialize_error(input.error) + return aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.dafny_to_smithy.aws_cryptography_primitives_AesKdfCtrOutput( + input.value + ) + + +def _deserialize_aes_encrypt(input: DafnyResponse, config: Config): + + if input.IsFailure(): + return _deserialize_error(input.error) + return aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.dafny_to_smithy.aws_cryptography_primitives_AESEncryptOutput( + input.value + ) + + +def _deserialize_aes_decrypt(input: DafnyResponse, config: Config): + + if input.IsFailure(): + return _deserialize_error(input.error) + return aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.dafny_to_smithy.aws_cryptography_primitives_AESDecryptOutput( + input.value + ) + + +def _deserialize_generate_rsa_key_pair(input: DafnyResponse, config: Config): + + if input.IsFailure(): + return _deserialize_error(input.error) + return aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.dafny_to_smithy.aws_cryptography_primitives_GenerateRSAKeyPairOutput( + input.value + ) + + +def _deserialize_get_rsa_key_modulus_length(input: DafnyResponse, config: Config): + + if input.IsFailure(): + return _deserialize_error(input.error) + return aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.dafny_to_smithy.aws_cryptography_primitives_GetRSAKeyModulusLengthOutput( + input.value + ) + + +def _deserialize_rsa_decrypt(input: DafnyResponse, config: Config): + + if input.IsFailure(): + return _deserialize_error(input.error) + return aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.dafny_to_smithy.aws_cryptography_primitives_RSADecryptOutput( + input.value + ) + + +def _deserialize_rsa_encrypt(input: DafnyResponse, config: Config): + + if input.IsFailure(): + return _deserialize_error(input.error) + return aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.dafny_to_smithy.aws_cryptography_primitives_RSAEncryptOutput( + input.value + ) + + +def _deserialize_generate_ecdsa_signature_key(input: DafnyResponse, config: Config): + + if input.IsFailure(): + return _deserialize_error(input.error) + return aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.dafny_to_smithy.aws_cryptography_primitives_GenerateECDSASignatureKeyOutput( + input.value + ) + + +def _deserialize_ecdsa_sign(input: DafnyResponse, config: Config): + + if input.IsFailure(): + return _deserialize_error(input.error) + return aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.dafny_to_smithy.aws_cryptography_primitives_ECDSASignOutput( + input.value + ) + + +def _deserialize_ecdsa_verify(input: DafnyResponse, config: Config): + + if input.IsFailure(): + return _deserialize_error(input.error) + return aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.dafny_to_smithy.aws_cryptography_primitives_ECDSAVerifyOutput( + input.value + ) + + +def _deserialize_generate_ecc_key_pair(input: DafnyResponse, config: Config): + + if input.IsFailure(): + return _deserialize_error(input.error) + return aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.dafny_to_smithy.aws_cryptography_primitives_GenerateECCKeyPairOutput( + input.value + ) + + +def _deserialize_get_public_key_from_private_key(input: DafnyResponse, config: Config): + + if input.IsFailure(): + return _deserialize_error(input.error) + return aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.dafny_to_smithy.aws_cryptography_primitives_GetPublicKeyFromPrivateKeyOutput( + input.value + ) + + +def _deserialize_validate_public_key(input: DafnyResponse, config: Config): + + if input.IsFailure(): + return _deserialize_error(input.error) + return aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.dafny_to_smithy.aws_cryptography_primitives_ValidatePublicKeyOutput( + input.value + ) + + +def _deserialize_derive_shared_secret(input: DafnyResponse, config: Config): + + if input.IsFailure(): + return _deserialize_error(input.error) + return aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.dafny_to_smithy.aws_cryptography_primitives_DeriveSharedSecretOutput( + input.value + ) + + +def _deserialize_compress_public_key(input: DafnyResponse, config: Config): + + if input.IsFailure(): + return _deserialize_error(input.error) + return aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.dafny_to_smithy.aws_cryptography_primitives_CompressPublicKeyOutput( + input.value + ) + + +def _deserialize_decompress_public_key(input: DafnyResponse, config: Config): + + if input.IsFailure(): + return _deserialize_error(input.error) + return aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.dafny_to_smithy.aws_cryptography_primitives_DecompressPublicKeyOutput( + input.value + ) + + +def _deserialize_parse_public_key(input: DafnyResponse, config: Config): + + if input.IsFailure(): + return _deserialize_error(input.error) + return aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.dafny_to_smithy.aws_cryptography_primitives_ParsePublicKeyOutput( + input.value + ) + + +def _deserialize_error(error: Error) -> ServiceError: + if error.is_Opaque: + return OpaqueError(obj=error.obj) + 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_AwsCryptographicPrimitivesError: + return AwsCryptographicPrimitivesError(message=_dafny.string_of(error.message)) + else: + return OpaqueError(obj=error) diff --git a/AwsCryptographyPrimitives/runtimes/python/src/aws_cryptography_primitives/smithygenerated/aws_cryptography_primitives/errors.py b/AwsCryptographyPrimitives/runtimes/python/src/aws_cryptography_primitives/smithygenerated/aws_cryptography_primitives/errors.py new file mode 100644 index 000000000..59b8ea560 --- /dev/null +++ b/AwsCryptographyPrimitives/runtimes/python/src/aws_cryptography_primitives/smithygenerated/aws_cryptography_primitives/errors.py @@ -0,0 +1,218 @@ +# 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_cryptography_primitives.internaldafny.generated +import aws_cryptography_primitives.internaldafny.generated.AwsCryptographyPrimitivesTypes +import aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.errors +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 AwsCryptographicPrimitivesError( + ApiError[Literal["AwsCryptographicPrimitivesError"]] +): + code: Literal["AwsCryptographicPrimitivesError"] = "AwsCryptographicPrimitivesError" + message: str + + def __init__( + self, + *, + message: str, + ): + super().__init__(message) + + def as_dict(self) -> Dict[str, Any]: + """Converts the AwsCryptographicPrimitivesError to a dictionary.""" + return { + "message": self.message, + "code": self.code, + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "AwsCryptographicPrimitivesError": + """Creates a AwsCryptographicPrimitivesError from a dictionary.""" + kwargs: Dict[str, Any] = { + "message": d["message"], + } + + return AwsCryptographicPrimitivesError(**kwargs) + + def __repr__(self) -> str: + result = "AwsCryptographicPrimitivesError(" + if self.message is not None: + result += f"message={repr(self.message)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, AwsCryptographicPrimitivesError): + return False + attributes: list[str] = [ + "message", + "message", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class AwsCryptographicPrimitivesError( + ApiError[Literal["AwsCryptographicPrimitivesError"]] +): + code: Literal["AwsCryptographicPrimitivesError"] = "AwsCryptographicPrimitivesError" + message: str + + +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) + + +def _smithy_error_to_dafny_error(e: ServiceError): + """Converts the provided native Smithy-modeled error into the corresponding + Dafny error.""" + if isinstance( + e, + aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.errors.AwsCryptographicPrimitivesError, + ): + return aws_cryptography_primitives.internaldafny.generated.AwsCryptographyPrimitivesTypes.Error_AwsCryptographicPrimitivesError( + message=_dafny.Seq(e.message) + ) + + if isinstance(e, CollectionOfErrors): + return aws_cryptography_primitives.internaldafny.generated.AwsCryptographyPrimitivesTypes.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_cryptography_primitives.internaldafny.generated.AwsCryptographyPrimitivesTypes.Error_Opaque( + obj=e.obj + ) + + else: + return aws_cryptography_primitives.internaldafny.generated.AwsCryptographyPrimitivesTypes.Error_Opaque( + obj=e + ) diff --git a/AwsCryptographyPrimitives/runtimes/python/src/aws_cryptography_primitives/smithygenerated/aws_cryptography_primitives/models.py b/AwsCryptographyPrimitives/runtimes/python/src/aws_cryptography_primitives/smithygenerated/aws_cryptography_primitives/models.py new file mode 100644 index 000000000..5ac9c9507 --- /dev/null +++ b/AwsCryptographyPrimitives/runtimes/python/src/aws_cryptography_primitives/smithygenerated/aws_cryptography_primitives/models.py @@ -0,0 +1,2319 @@ +# 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, Optional + + +class AES_GCM: + key_length: int + tag_length: int + iv_length: int + + def __init__( + self, + *, + key_length: int = 0, + tag_length: int = 0, + iv_length: int = 0, + ): + if (key_length is not None) and (key_length < 1): + raise ValueError("key_length must be greater than or equal to 1") + + if (key_length is not None) and (key_length > 32): + raise ValueError("key_length must be less than or equal to 32") + + self.key_length = key_length + if (tag_length is not None) and (tag_length < 0): + raise ValueError("tag_length must be greater than or equal to 0") + + if (tag_length is not None) and (tag_length > 32): + raise ValueError("tag_length must be less than or equal to 32") + + self.tag_length = tag_length + if (iv_length is not None) and (iv_length < 0): + raise ValueError("iv_length must be greater than or equal to 0") + + if (iv_length is not None) and (iv_length > 255): + raise ValueError("iv_length must be less than or equal to 255") + + self.iv_length = iv_length + + def as_dict(self) -> Dict[str, Any]: + """Converts the AES_GCM to a dictionary.""" + d: Dict[str, Any] = {} + + if self.key_length is not None: + d["key_length"] = self.key_length + + if self.tag_length is not None: + d["tag_length"] = self.tag_length + + if self.iv_length is not None: + d["iv_length"] = self.iv_length + + return d + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "AES_GCM": + """Creates a AES_GCM from a dictionary.""" + kwargs: Dict[str, Any] = {} + + if "key_length" in d: + kwargs["key_length"] = d["key_length"] + + if "tag_length" in d: + kwargs["tag_length"] = d["tag_length"] + + if "iv_length" in d: + kwargs["iv_length"] = d["iv_length"] + + return AES_GCM(**kwargs) + + def __repr__(self) -> str: + result = "AES_GCM(" + if self.key_length is not None: + result += f"key_length={repr(self.key_length)}, " + + if self.tag_length is not None: + result += f"tag_length={repr(self.tag_length)}, " + + if self.iv_length is not None: + result += f"iv_length={repr(self.iv_length)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, AES_GCM): + return False + attributes: list[str] = [ + "key_length", + "tag_length", + "iv_length", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class AESDecryptInput: + enc_alg: AES_GCM + key: bytes | bytearray + cipher_txt: bytes | bytearray + auth_tag: bytes | bytearray + iv: bytes | bytearray + aad: bytes | bytearray + + def __init__( + self, + *, + enc_alg: AES_GCM, + key: bytes | bytearray, + cipher_txt: bytes | bytearray, + auth_tag: bytes | bytearray, + iv: bytes | bytearray, + aad: bytes | bytearray, + ): + self.enc_alg = enc_alg + self.key = key + self.cipher_txt = cipher_txt + self.auth_tag = auth_tag + self.iv = iv + self.aad = aad + + def as_dict(self) -> Dict[str, Any]: + """Converts the AESDecryptInput to a dictionary.""" + return { + "enc_alg": self.enc_alg.as_dict(), + "key": self.key, + "cipher_txt": self.cipher_txt, + "auth_tag": self.auth_tag, + "iv": self.iv, + "aad": self.aad, + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "AESDecryptInput": + """Creates a AESDecryptInput from a dictionary.""" + kwargs: Dict[str, Any] = { + "enc_alg": AES_GCM.from_dict(d["enc_alg"]), + "key": d["key"], + "cipher_txt": d["cipher_txt"], + "auth_tag": d["auth_tag"], + "iv": d["iv"], + "aad": d["aad"], + } + + return AESDecryptInput(**kwargs) + + def __repr__(self) -> str: + result = "AESDecryptInput(" + if self.enc_alg is not None: + result += f"enc_alg={repr(self.enc_alg)}, " + + if self.key is not None: + result += f"key={repr(self.key)}, " + + if self.cipher_txt is not None: + result += f"cipher_txt={repr(self.cipher_txt)}, " + + if self.auth_tag is not None: + result += f"auth_tag={repr(self.auth_tag)}, " + + if self.iv is not None: + result += f"iv={repr(self.iv)}, " + + if self.aad is not None: + result += f"aad={repr(self.aad)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, AESDecryptInput): + return False + attributes: list[str] = [ + "enc_alg", + "key", + "cipher_txt", + "auth_tag", + "iv", + "aad", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class AESEncryptInput: + enc_alg: AES_GCM + iv: bytes | bytearray + key: bytes | bytearray + msg: bytes | bytearray + aad: bytes | bytearray + + def __init__( + self, + *, + enc_alg: AES_GCM, + iv: bytes | bytearray, + key: bytes | bytearray, + msg: bytes | bytearray, + aad: bytes | bytearray, + ): + self.enc_alg = enc_alg + self.iv = iv + self.key = key + self.msg = msg + self.aad = aad + + def as_dict(self) -> Dict[str, Any]: + """Converts the AESEncryptInput to a dictionary.""" + return { + "enc_alg": self.enc_alg.as_dict(), + "iv": self.iv, + "key": self.key, + "msg": self.msg, + "aad": self.aad, + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "AESEncryptInput": + """Creates a AESEncryptInput from a dictionary.""" + kwargs: Dict[str, Any] = { + "enc_alg": AES_GCM.from_dict(d["enc_alg"]), + "iv": d["iv"], + "key": d["key"], + "msg": d["msg"], + "aad": d["aad"], + } + + return AESEncryptInput(**kwargs) + + def __repr__(self) -> str: + result = "AESEncryptInput(" + if self.enc_alg is not None: + result += f"enc_alg={repr(self.enc_alg)}, " + + if self.iv is not None: + result += f"iv={repr(self.iv)}, " + + if self.key is not None: + result += f"key={repr(self.key)}, " + + if self.msg is not None: + result += f"msg={repr(self.msg)}, " + + if self.aad is not None: + result += f"aad={repr(self.aad)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, AESEncryptInput): + return False + attributes: list[str] = [ + "enc_alg", + "iv", + "key", + "msg", + "aad", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class AESEncryptOutput: + cipher_text: bytes | bytearray + auth_tag: bytes | bytearray + + def __init__( + self, + *, + cipher_text: bytes | bytearray, + auth_tag: bytes | bytearray, + ): + self.cipher_text = cipher_text + self.auth_tag = auth_tag + + def as_dict(self) -> Dict[str, Any]: + """Converts the AESEncryptOutput to a dictionary.""" + return { + "cipher_text": self.cipher_text, + "auth_tag": self.auth_tag, + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "AESEncryptOutput": + """Creates a AESEncryptOutput from a dictionary.""" + kwargs: Dict[str, Any] = { + "cipher_text": d["cipher_text"], + "auth_tag": d["auth_tag"], + } + + return AESEncryptOutput(**kwargs) + + def __repr__(self) -> str: + result = "AESEncryptOutput(" + if self.cipher_text is not None: + result += f"cipher_text={repr(self.cipher_text)}, " + + if self.auth_tag is not None: + result += f"auth_tag={repr(self.auth_tag)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, AESEncryptOutput): + return False + attributes: list[str] = [ + "cipher_text", + "auth_tag", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class AesKdfCtrInput: + ikm: bytes | bytearray + expected_length: int + nonce: Optional[bytes | bytearray] + + def __init__( + self, + *, + ikm: bytes | bytearray, + expected_length: int = 0, + nonce: Optional[bytes | bytearray] = None, + ): + self.ikm = ikm + if (expected_length is not None) and (expected_length < 0): + raise ValueError("expected_length must be greater than or equal to 0") + + self.expected_length = expected_length + self.nonce = nonce + + def as_dict(self) -> Dict[str, Any]: + """Converts the AesKdfCtrInput to a dictionary.""" + d: Dict[str, Any] = { + "ikm": self.ikm, + } + + if self.expected_length is not None: + d["expected_length"] = self.expected_length + + if self.nonce is not None: + d["nonce"] = self.nonce + + return d + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "AesKdfCtrInput": + """Creates a AesKdfCtrInput from a dictionary.""" + kwargs: Dict[str, Any] = { + "ikm": d["ikm"], + } + + if "expected_length" in d: + kwargs["expected_length"] = d["expected_length"] + + if "nonce" in d: + kwargs["nonce"] = d["nonce"] + + return AesKdfCtrInput(**kwargs) + + def __repr__(self) -> str: + result = "AesKdfCtrInput(" + if self.ikm is not None: + result += f"ikm={repr(self.ikm)}, " + + if self.expected_length is not None: + result += f"expected_length={repr(self.expected_length)}, " + + if self.nonce is not None: + result += f"nonce={repr(self.nonce)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, AesKdfCtrInput): + return False + attributes: list[str] = [ + "ikm", + "expected_length", + "nonce", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class ECDHCurveSpec: + ECC_NIST_P256 = "ECC_NIST_P256" + + ECC_NIST_P384 = "ECC_NIST_P384" + + ECC_NIST_P521 = "ECC_NIST_P521" + + SM2 = "SM2" + + # This set contains every possible value known at the time this was generated. New + # values may be added in the future. + values = frozenset({"ECC_NIST_P256", "ECC_NIST_P384", "ECC_NIST_P521", "SM2"}) + + +class ECCPublicKey: + der: bytes | bytearray + + def __init__( + self, + *, + der: bytes | bytearray, + ): + self.der = der + + def as_dict(self) -> Dict[str, Any]: + """Converts the ECCPublicKey to a dictionary.""" + return { + "der": self.der, + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "ECCPublicKey": + """Creates a ECCPublicKey from a dictionary.""" + kwargs: Dict[str, Any] = { + "der": d["der"], + } + + return ECCPublicKey(**kwargs) + + def __repr__(self) -> str: + result = "ECCPublicKey(" + if self.der is not None: + result += f"der={repr(self.der)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, ECCPublicKey): + return False + attributes: list[str] = [ + "der", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class CompressPublicKeyInput: + public_key: ECCPublicKey + ecc_curve: str + + def __init__( + self, + *, + public_key: ECCPublicKey, + ecc_curve: str, + ): + self.public_key = public_key + self.ecc_curve = ecc_curve + + def as_dict(self) -> Dict[str, Any]: + """Converts the CompressPublicKeyInput to a dictionary.""" + return { + "public_key": self.public_key.as_dict(), + "ecc_curve": self.ecc_curve, + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "CompressPublicKeyInput": + """Creates a CompressPublicKeyInput from a dictionary.""" + kwargs: Dict[str, Any] = { + "public_key": ECCPublicKey.from_dict(d["public_key"]), + "ecc_curve": d["ecc_curve"], + } + + return CompressPublicKeyInput(**kwargs) + + def __repr__(self) -> str: + result = "CompressPublicKeyInput(" + if self.public_key is not None: + result += f"public_key={repr(self.public_key)}, " + + if self.ecc_curve is not None: + result += f"ecc_curve={repr(self.ecc_curve)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, CompressPublicKeyInput): + return False + attributes: list[str] = [ + "public_key", + "ecc_curve", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class CompressPublicKeyOutput: + compressed_public_key: bytes | bytearray + + def __init__( + self, + *, + compressed_public_key: bytes | bytearray, + ): + self.compressed_public_key = compressed_public_key + + def as_dict(self) -> Dict[str, Any]: + """Converts the CompressPublicKeyOutput to a dictionary.""" + return { + "compressed_public_key": self.compressed_public_key, + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "CompressPublicKeyOutput": + """Creates a CompressPublicKeyOutput from a dictionary.""" + kwargs: Dict[str, Any] = { + "compressed_public_key": d["compressed_public_key"], + } + + return CompressPublicKeyOutput(**kwargs) + + def __repr__(self) -> str: + result = "CompressPublicKeyOutput(" + if self.compressed_public_key is not None: + result += f"compressed_public_key={repr(self.compressed_public_key)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, CompressPublicKeyOutput): + return False + attributes: list[str] = [ + "compressed_public_key", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class DecompressPublicKeyInput: + compressed_public_key: bytes | bytearray + ecc_curve: str + + def __init__( + self, + *, + compressed_public_key: bytes | bytearray, + ecc_curve: str, + ): + self.compressed_public_key = compressed_public_key + self.ecc_curve = ecc_curve + + def as_dict(self) -> Dict[str, Any]: + """Converts the DecompressPublicKeyInput to a dictionary.""" + return { + "compressed_public_key": self.compressed_public_key, + "ecc_curve": self.ecc_curve, + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "DecompressPublicKeyInput": + """Creates a DecompressPublicKeyInput from a dictionary.""" + kwargs: Dict[str, Any] = { + "compressed_public_key": d["compressed_public_key"], + "ecc_curve": d["ecc_curve"], + } + + return DecompressPublicKeyInput(**kwargs) + + def __repr__(self) -> str: + result = "DecompressPublicKeyInput(" + if self.compressed_public_key is not None: + result += f"compressed_public_key={repr(self.compressed_public_key)}, " + + if self.ecc_curve is not None: + result += f"ecc_curve={repr(self.ecc_curve)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, DecompressPublicKeyInput): + return False + attributes: list[str] = [ + "compressed_public_key", + "ecc_curve", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class DecompressPublicKeyOutput: + public_key: ECCPublicKey + + def __init__( + self, + *, + public_key: ECCPublicKey, + ): + self.public_key = public_key + + def as_dict(self) -> Dict[str, Any]: + """Converts the DecompressPublicKeyOutput to a dictionary.""" + return { + "public_key": self.public_key.as_dict(), + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "DecompressPublicKeyOutput": + """Creates a DecompressPublicKeyOutput from a dictionary.""" + kwargs: Dict[str, Any] = { + "public_key": ECCPublicKey.from_dict(d["public_key"]), + } + + return DecompressPublicKeyOutput(**kwargs) + + def __repr__(self) -> str: + result = "DecompressPublicKeyOutput(" + if self.public_key is not None: + result += f"public_key={repr(self.public_key)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, DecompressPublicKeyOutput): + return False + attributes: list[str] = [ + "public_key", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class ECCPrivateKey: + pem: bytes | bytearray + + def __init__( + self, + *, + pem: bytes | bytearray, + ): + self.pem = pem + + def as_dict(self) -> Dict[str, Any]: + """Converts the ECCPrivateKey to a dictionary.""" + return { + "pem": self.pem, + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "ECCPrivateKey": + """Creates a ECCPrivateKey from a dictionary.""" + kwargs: Dict[str, Any] = { + "pem": d["pem"], + } + + return ECCPrivateKey(**kwargs) + + def __repr__(self) -> str: + result = "ECCPrivateKey(" + if self.pem is not None: + result += f"pem={repr(self.pem)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, ECCPrivateKey): + return False + attributes: list[str] = [ + "pem", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class DeriveSharedSecretInput: + ecc_curve: str + private_key: ECCPrivateKey + public_key: ECCPublicKey + + def __init__( + self, + *, + ecc_curve: str, + private_key: ECCPrivateKey, + public_key: ECCPublicKey, + ): + self.ecc_curve = ecc_curve + self.private_key = private_key + self.public_key = public_key + + def as_dict(self) -> Dict[str, Any]: + """Converts the DeriveSharedSecretInput to a dictionary.""" + return { + "ecc_curve": self.ecc_curve, + "private_key": self.private_key.as_dict(), + "public_key": self.public_key.as_dict(), + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "DeriveSharedSecretInput": + """Creates a DeriveSharedSecretInput from a dictionary.""" + kwargs: Dict[str, Any] = { + "ecc_curve": d["ecc_curve"], + "private_key": ECCPrivateKey.from_dict(d["private_key"]), + "public_key": ECCPublicKey.from_dict(d["public_key"]), + } + + return DeriveSharedSecretInput(**kwargs) + + def __repr__(self) -> str: + result = "DeriveSharedSecretInput(" + if self.ecc_curve is not None: + result += f"ecc_curve={repr(self.ecc_curve)}, " + + if self.private_key is not None: + result += f"private_key={repr(self.private_key)}, " + + if self.public_key is not None: + result += f"public_key={repr(self.public_key)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, DeriveSharedSecretInput): + return False + attributes: list[str] = [ + "ecc_curve", + "private_key", + "public_key", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class DeriveSharedSecretOutput: + shared_secret: bytes | bytearray + + def __init__( + self, + *, + shared_secret: bytes | bytearray, + ): + self.shared_secret = shared_secret + + def as_dict(self) -> Dict[str, Any]: + """Converts the DeriveSharedSecretOutput to a dictionary.""" + return { + "shared_secret": self.shared_secret, + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "DeriveSharedSecretOutput": + """Creates a DeriveSharedSecretOutput from a dictionary.""" + kwargs: Dict[str, Any] = { + "shared_secret": d["shared_secret"], + } + + return DeriveSharedSecretOutput(**kwargs) + + def __repr__(self) -> str: + result = "DeriveSharedSecretOutput(" + if self.shared_secret is not None: + result += f"shared_secret={repr(self.shared_secret)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, DeriveSharedSecretOutput): + return False + attributes: list[str] = [ + "shared_secret", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class DigestAlgorithm: + SHA_512 = "SHA_512" + + SHA_384 = "SHA_384" + + SHA_256 = "SHA_256" + + # This set contains every possible value known at the time this was generated. New + # values may be added in the future. + values = frozenset({"SHA_512", "SHA_384", "SHA_256"}) + + +class DigestInput: + digest_algorithm: str + message: bytes | bytearray + + def __init__( + self, + *, + digest_algorithm: str, + message: bytes | bytearray, + ): + self.digest_algorithm = digest_algorithm + self.message = message + + def as_dict(self) -> Dict[str, Any]: + """Converts the DigestInput to a dictionary.""" + return { + "digest_algorithm": self.digest_algorithm, + "message": self.message, + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "DigestInput": + """Creates a DigestInput from a dictionary.""" + kwargs: Dict[str, Any] = { + "digest_algorithm": d["digest_algorithm"], + "message": d["message"], + } + + return DigestInput(**kwargs) + + def __repr__(self) -> str: + result = "DigestInput(" + if self.digest_algorithm is not None: + result += f"digest_algorithm={repr(self.digest_algorithm)}, " + + if self.message is not None: + result += f"message={repr(self.message)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, DigestInput): + return False + attributes: list[str] = [ + "digest_algorithm", + "message", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class ECDSASignatureAlgorithm: + ECDSA_P384 = "ECDSA_P384" + + ECDSA_P256 = "ECDSA_P256" + + # This set contains every possible value known at the time this was generated. New + # values may be added in the future. + values = frozenset({"ECDSA_P384", "ECDSA_P256"}) + + +class ECDSASignInput: + signature_algorithm: str + signing_key: bytes | bytearray + message: bytes | bytearray + + def __init__( + self, + *, + signature_algorithm: str, + signing_key: bytes | bytearray, + message: bytes | bytearray, + ): + self.signature_algorithm = signature_algorithm + self.signing_key = signing_key + self.message = message + + def as_dict(self) -> Dict[str, Any]: + """Converts the ECDSASignInput to a dictionary.""" + return { + "signature_algorithm": self.signature_algorithm, + "signing_key": self.signing_key, + "message": self.message, + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "ECDSASignInput": + """Creates a ECDSASignInput from a dictionary.""" + kwargs: Dict[str, Any] = { + "signature_algorithm": d["signature_algorithm"], + "signing_key": d["signing_key"], + "message": d["message"], + } + + return ECDSASignInput(**kwargs) + + def __repr__(self) -> str: + result = "ECDSASignInput(" + if self.signature_algorithm is not None: + result += f"signature_algorithm={repr(self.signature_algorithm)}, " + + if self.signing_key is not None: + result += f"signing_key={repr(self.signing_key)}, " + + if self.message is not None: + result += f"message={repr(self.message)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, ECDSASignInput): + return False + attributes: list[str] = [ + "signature_algorithm", + "signing_key", + "message", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class ECDSAVerifyInput: + signature_algorithm: str + verification_key: bytes | bytearray + message: bytes | bytearray + signature: bytes | bytearray + + def __init__( + self, + *, + signature_algorithm: str, + verification_key: bytes | bytearray, + message: bytes | bytearray, + signature: bytes | bytearray, + ): + self.signature_algorithm = signature_algorithm + self.verification_key = verification_key + self.message = message + self.signature = signature + + def as_dict(self) -> Dict[str, Any]: + """Converts the ECDSAVerifyInput to a dictionary.""" + return { + "signature_algorithm": self.signature_algorithm, + "verification_key": self.verification_key, + "message": self.message, + "signature": self.signature, + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "ECDSAVerifyInput": + """Creates a ECDSAVerifyInput from a dictionary.""" + kwargs: Dict[str, Any] = { + "signature_algorithm": d["signature_algorithm"], + "verification_key": d["verification_key"], + "message": d["message"], + "signature": d["signature"], + } + + return ECDSAVerifyInput(**kwargs) + + def __repr__(self) -> str: + result = "ECDSAVerifyInput(" + if self.signature_algorithm is not None: + result += f"signature_algorithm={repr(self.signature_algorithm)}, " + + if self.verification_key is not None: + result += f"verification_key={repr(self.verification_key)}, " + + if self.message is not None: + result += f"message={repr(self.message)}, " + + if self.signature is not None: + result += f"signature={repr(self.signature)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, ECDSAVerifyInput): + return False + attributes: list[str] = [ + "signature_algorithm", + "verification_key", + "message", + "signature", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class GenerateECCKeyPairInput: + ecc_curve: str + + def __init__( + self, + *, + ecc_curve: str, + ): + self.ecc_curve = ecc_curve + + def as_dict(self) -> Dict[str, Any]: + """Converts the GenerateECCKeyPairInput to a dictionary.""" + return { + "ecc_curve": self.ecc_curve, + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "GenerateECCKeyPairInput": + """Creates a GenerateECCKeyPairInput from a dictionary.""" + kwargs: Dict[str, Any] = { + "ecc_curve": d["ecc_curve"], + } + + return GenerateECCKeyPairInput(**kwargs) + + def __repr__(self) -> str: + result = "GenerateECCKeyPairInput(" + if self.ecc_curve is not None: + result += f"ecc_curve={repr(self.ecc_curve)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, GenerateECCKeyPairInput): + return False + attributes: list[str] = [ + "ecc_curve", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class GenerateECCKeyPairOutput: + ecc_curve: str + private_key: ECCPrivateKey + public_key: ECCPublicKey + + def __init__( + self, + *, + ecc_curve: str, + private_key: ECCPrivateKey, + public_key: ECCPublicKey, + ): + self.ecc_curve = ecc_curve + self.private_key = private_key + self.public_key = public_key + + def as_dict(self) -> Dict[str, Any]: + """Converts the GenerateECCKeyPairOutput to a dictionary.""" + return { + "ecc_curve": self.ecc_curve, + "private_key": self.private_key.as_dict(), + "public_key": self.public_key.as_dict(), + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "GenerateECCKeyPairOutput": + """Creates a GenerateECCKeyPairOutput from a dictionary.""" + kwargs: Dict[str, Any] = { + "ecc_curve": d["ecc_curve"], + "private_key": ECCPrivateKey.from_dict(d["private_key"]), + "public_key": ECCPublicKey.from_dict(d["public_key"]), + } + + return GenerateECCKeyPairOutput(**kwargs) + + def __repr__(self) -> str: + result = "GenerateECCKeyPairOutput(" + if self.ecc_curve is not None: + result += f"ecc_curve={repr(self.ecc_curve)}, " + + if self.private_key is not None: + result += f"private_key={repr(self.private_key)}, " + + if self.public_key is not None: + result += f"public_key={repr(self.public_key)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, GenerateECCKeyPairOutput): + return False + attributes: list[str] = [ + "ecc_curve", + "private_key", + "public_key", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class GenerateECDSASignatureKeyInput: + signature_algorithm: str + + def __init__( + self, + *, + signature_algorithm: str, + ): + self.signature_algorithm = signature_algorithm + + def as_dict(self) -> Dict[str, Any]: + """Converts the GenerateECDSASignatureKeyInput to a dictionary.""" + return { + "signature_algorithm": self.signature_algorithm, + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "GenerateECDSASignatureKeyInput": + """Creates a GenerateECDSASignatureKeyInput from a dictionary.""" + kwargs: Dict[str, Any] = { + "signature_algorithm": d["signature_algorithm"], + } + + return GenerateECDSASignatureKeyInput(**kwargs) + + def __repr__(self) -> str: + result = "GenerateECDSASignatureKeyInput(" + if self.signature_algorithm is not None: + result += f"signature_algorithm={repr(self.signature_algorithm)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, GenerateECDSASignatureKeyInput): + return False + attributes: list[str] = [ + "signature_algorithm", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class GenerateECDSASignatureKeyOutput: + signature_algorithm: str + verification_key: bytes | bytearray + signing_key: bytes | bytearray + + def __init__( + self, + *, + signature_algorithm: str, + verification_key: bytes | bytearray, + signing_key: bytes | bytearray, + ): + self.signature_algorithm = signature_algorithm + self.verification_key = verification_key + self.signing_key = signing_key + + def as_dict(self) -> Dict[str, Any]: + """Converts the GenerateECDSASignatureKeyOutput to a dictionary.""" + return { + "signature_algorithm": self.signature_algorithm, + "verification_key": self.verification_key, + "signing_key": self.signing_key, + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "GenerateECDSASignatureKeyOutput": + """Creates a GenerateECDSASignatureKeyOutput from a dictionary.""" + kwargs: Dict[str, Any] = { + "signature_algorithm": d["signature_algorithm"], + "verification_key": d["verification_key"], + "signing_key": d["signing_key"], + } + + return GenerateECDSASignatureKeyOutput(**kwargs) + + def __repr__(self) -> str: + result = "GenerateECDSASignatureKeyOutput(" + if self.signature_algorithm is not None: + result += f"signature_algorithm={repr(self.signature_algorithm)}, " + + if self.verification_key is not None: + result += f"verification_key={repr(self.verification_key)}, " + + if self.signing_key is not None: + result += f"signing_key={repr(self.signing_key)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, GenerateECDSASignatureKeyOutput): + return False + attributes: list[str] = [ + "signature_algorithm", + "verification_key", + "signing_key", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class GenerateRandomBytesInput: + length: int + + def __init__( + self, + *, + length: int = 0, + ): + if (length is not None) and (length < 0): + raise ValueError("length must be greater than or equal to 0") + + self.length = length + + def as_dict(self) -> Dict[str, Any]: + """Converts the GenerateRandomBytesInput to a dictionary.""" + d: Dict[str, Any] = {} + + if self.length is not None: + d["length"] = self.length + + return d + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "GenerateRandomBytesInput": + """Creates a GenerateRandomBytesInput from a dictionary.""" + kwargs: Dict[str, Any] = {} + + if "length" in d: + kwargs["length"] = d["length"] + + return GenerateRandomBytesInput(**kwargs) + + def __repr__(self) -> str: + result = "GenerateRandomBytesInput(" + if self.length is not None: + result += f"length={repr(self.length)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, GenerateRandomBytesInput): + return False + attributes: list[str] = [ + "length", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class GenerateRSAKeyPairInput: + length_bits: int + + def __init__( + self, + *, + length_bits: int = 0, + ): + if (length_bits is not None) and (length_bits < 81): + raise ValueError("length_bits must be greater than or equal to 81") + + if (length_bits is not None) and (length_bits > 4096): + raise ValueError("length_bits must be less than or equal to 4096") + + self.length_bits = length_bits + + def as_dict(self) -> Dict[str, Any]: + """Converts the GenerateRSAKeyPairInput to a dictionary.""" + d: Dict[str, Any] = {} + + if self.length_bits is not None: + d["length_bits"] = self.length_bits + + return d + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "GenerateRSAKeyPairInput": + """Creates a GenerateRSAKeyPairInput from a dictionary.""" + kwargs: Dict[str, Any] = {} + + if "length_bits" in d: + kwargs["length_bits"] = d["length_bits"] + + return GenerateRSAKeyPairInput(**kwargs) + + def __repr__(self) -> str: + result = "GenerateRSAKeyPairInput(" + if self.length_bits is not None: + result += f"length_bits={repr(self.length_bits)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, GenerateRSAKeyPairInput): + return False + attributes: list[str] = [ + "length_bits", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class RSAPrivateKey: + length_bits: int + pem: bytes | bytearray + + def __init__( + self, + *, + pem: bytes | bytearray, + length_bits: int = 0, + ): + self.pem = pem + if (length_bits is not None) and (length_bits < 81): + raise ValueError("length_bits must be greater than or equal to 81") + + self.length_bits = length_bits + + def as_dict(self) -> Dict[str, Any]: + """Converts the RSAPrivateKey to a dictionary.""" + d: Dict[str, Any] = { + "pem": self.pem, + } + + if self.length_bits is not None: + d["length_bits"] = self.length_bits + + return d + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "RSAPrivateKey": + """Creates a RSAPrivateKey from a dictionary.""" + kwargs: Dict[str, Any] = { + "pem": d["pem"], + } + + if "length_bits" in d: + kwargs["length_bits"] = d["length_bits"] + + return RSAPrivateKey(**kwargs) + + def __repr__(self) -> str: + result = "RSAPrivateKey(" + if self.length_bits is not None: + result += f"length_bits={repr(self.length_bits)}, " + + if self.pem is not None: + result += f"pem={repr(self.pem)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, RSAPrivateKey): + return False + attributes: list[str] = [ + "length_bits", + "pem", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class RSAPublicKey: + length_bits: int + pem: bytes | bytearray + + def __init__( + self, + *, + pem: bytes | bytearray, + length_bits: int = 0, + ): + self.pem = pem + if (length_bits is not None) and (length_bits < 81): + raise ValueError("length_bits must be greater than or equal to 81") + + self.length_bits = length_bits + + def as_dict(self) -> Dict[str, Any]: + """Converts the RSAPublicKey to a dictionary.""" + d: Dict[str, Any] = { + "pem": self.pem, + } + + if self.length_bits is not None: + d["length_bits"] = self.length_bits + + return d + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "RSAPublicKey": + """Creates a RSAPublicKey from a dictionary.""" + kwargs: Dict[str, Any] = { + "pem": d["pem"], + } + + if "length_bits" in d: + kwargs["length_bits"] = d["length_bits"] + + return RSAPublicKey(**kwargs) + + def __repr__(self) -> str: + result = "RSAPublicKey(" + if self.length_bits is not None: + result += f"length_bits={repr(self.length_bits)}, " + + if self.pem is not None: + result += f"pem={repr(self.pem)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, RSAPublicKey): + return False + attributes: list[str] = [ + "length_bits", + "pem", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class GenerateRSAKeyPairOutput: + public_key: RSAPublicKey + private_key: RSAPrivateKey + + def __init__( + self, + *, + public_key: RSAPublicKey, + private_key: RSAPrivateKey, + ): + self.public_key = public_key + self.private_key = private_key + + def as_dict(self) -> Dict[str, Any]: + """Converts the GenerateRSAKeyPairOutput to a dictionary.""" + return { + "public_key": self.public_key.as_dict(), + "private_key": self.private_key.as_dict(), + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "GenerateRSAKeyPairOutput": + """Creates a GenerateRSAKeyPairOutput from a dictionary.""" + kwargs: Dict[str, Any] = { + "public_key": RSAPublicKey.from_dict(d["public_key"]), + "private_key": RSAPrivateKey.from_dict(d["private_key"]), + } + + return GenerateRSAKeyPairOutput(**kwargs) + + def __repr__(self) -> str: + result = "GenerateRSAKeyPairOutput(" + if self.public_key is not None: + result += f"public_key={repr(self.public_key)}, " + + if self.private_key is not None: + result += f"private_key={repr(self.private_key)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, GenerateRSAKeyPairOutput): + return False + attributes: list[str] = [ + "public_key", + "private_key", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class GetPublicKeyFromPrivateKeyInput: + ecc_curve: str + private_key: ECCPrivateKey + + def __init__( + self, + *, + ecc_curve: str, + private_key: ECCPrivateKey, + ): + self.ecc_curve = ecc_curve + self.private_key = private_key + + def as_dict(self) -> Dict[str, Any]: + """Converts the GetPublicKeyFromPrivateKeyInput to a dictionary.""" + return { + "ecc_curve": self.ecc_curve, + "private_key": self.private_key.as_dict(), + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "GetPublicKeyFromPrivateKeyInput": + """Creates a GetPublicKeyFromPrivateKeyInput from a dictionary.""" + kwargs: Dict[str, Any] = { + "ecc_curve": d["ecc_curve"], + "private_key": ECCPrivateKey.from_dict(d["private_key"]), + } + + return GetPublicKeyFromPrivateKeyInput(**kwargs) + + def __repr__(self) -> str: + result = "GetPublicKeyFromPrivateKeyInput(" + if self.ecc_curve is not None: + result += f"ecc_curve={repr(self.ecc_curve)}, " + + if self.private_key is not None: + result += f"private_key={repr(self.private_key)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, GetPublicKeyFromPrivateKeyInput): + return False + attributes: list[str] = [ + "ecc_curve", + "private_key", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class GetPublicKeyFromPrivateKeyOutput: + ecc_curve: str + private_key: ECCPrivateKey + public_key: bytes | bytearray + + def __init__( + self, + *, + ecc_curve: str, + private_key: ECCPrivateKey, + public_key: bytes | bytearray, + ): + self.ecc_curve = ecc_curve + self.private_key = private_key + self.public_key = public_key + + def as_dict(self) -> Dict[str, Any]: + """Converts the GetPublicKeyFromPrivateKeyOutput to a dictionary.""" + return { + "ecc_curve": self.ecc_curve, + "private_key": self.private_key.as_dict(), + "public_key": self.public_key, + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "GetPublicKeyFromPrivateKeyOutput": + """Creates a GetPublicKeyFromPrivateKeyOutput from a dictionary.""" + kwargs: Dict[str, Any] = { + "ecc_curve": d["ecc_curve"], + "private_key": ECCPrivateKey.from_dict(d["private_key"]), + "public_key": d["public_key"], + } + + return GetPublicKeyFromPrivateKeyOutput(**kwargs) + + def __repr__(self) -> str: + result = "GetPublicKeyFromPrivateKeyOutput(" + if self.ecc_curve is not None: + result += f"ecc_curve={repr(self.ecc_curve)}, " + + if self.private_key is not None: + result += f"private_key={repr(self.private_key)}, " + + if self.public_key is not None: + result += f"public_key={repr(self.public_key)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, GetPublicKeyFromPrivateKeyOutput): + return False + attributes: list[str] = [ + "ecc_curve", + "private_key", + "public_key", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class GetRSAKeyModulusLengthInput: + public_key: bytes | bytearray + + def __init__( + self, + *, + public_key: bytes | bytearray, + ): + self.public_key = public_key + + def as_dict(self) -> Dict[str, Any]: + """Converts the GetRSAKeyModulusLengthInput to a dictionary.""" + return { + "public_key": self.public_key, + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "GetRSAKeyModulusLengthInput": + """Creates a GetRSAKeyModulusLengthInput from a dictionary.""" + kwargs: Dict[str, Any] = { + "public_key": d["public_key"], + } + + return GetRSAKeyModulusLengthInput(**kwargs) + + def __repr__(self) -> str: + result = "GetRSAKeyModulusLengthInput(" + if self.public_key is not None: + result += f"public_key={repr(self.public_key)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, GetRSAKeyModulusLengthInput): + return False + attributes: list[str] = [ + "public_key", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class GetRSAKeyModulusLengthOutput: + length: int + + def __init__( + self, + *, + length: int = 0, + ): + if (length is not None) and (length < 81): + raise ValueError("length must be greater than or equal to 81") + + self.length = length + + def as_dict(self) -> Dict[str, Any]: + """Converts the GetRSAKeyModulusLengthOutput to a dictionary.""" + d: Dict[str, Any] = {} + + if self.length is not None: + d["length"] = self.length + + return d + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "GetRSAKeyModulusLengthOutput": + """Creates a GetRSAKeyModulusLengthOutput from a dictionary.""" + kwargs: Dict[str, Any] = {} + + if "length" in d: + kwargs["length"] = d["length"] + + return GetRSAKeyModulusLengthOutput(**kwargs) + + def __repr__(self) -> str: + result = "GetRSAKeyModulusLengthOutput(" + if self.length is not None: + result += f"length={repr(self.length)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, GetRSAKeyModulusLengthOutput): + return False + attributes: list[str] = [ + "length", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class HkdfInput: + digest_algorithm: str + salt: Optional[bytes | bytearray] + ikm: bytes | bytearray + info: bytes | bytearray + expected_length: int + + def __init__( + self, + *, + digest_algorithm: str, + ikm: bytes | bytearray, + info: bytes | bytearray, + salt: Optional[bytes | bytearray] = None, + expected_length: int = 0, + ): + self.digest_algorithm = digest_algorithm + self.ikm = ikm + self.info = info + self.salt = salt + if (expected_length is not None) and (expected_length < 0): + raise ValueError("expected_length must be greater than or equal to 0") + + self.expected_length = expected_length + + def as_dict(self) -> Dict[str, Any]: + """Converts the HkdfInput to a dictionary.""" + d: Dict[str, Any] = { + "digest_algorithm": self.digest_algorithm, + "ikm": self.ikm, + "info": self.info, + } + + if self.salt is not None: + d["salt"] = self.salt + + if self.expected_length is not None: + d["expected_length"] = self.expected_length + + return d + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "HkdfInput": + """Creates a HkdfInput from a dictionary.""" + kwargs: Dict[str, Any] = { + "digest_algorithm": d["digest_algorithm"], + "ikm": d["ikm"], + "info": d["info"], + } + + if "salt" in d: + kwargs["salt"] = d["salt"] + + if "expected_length" in d: + kwargs["expected_length"] = d["expected_length"] + + return HkdfInput(**kwargs) + + def __repr__(self) -> str: + result = "HkdfInput(" + if self.digest_algorithm is not None: + result += f"digest_algorithm={repr(self.digest_algorithm)}, " + + if self.salt is not None: + result += f"salt={repr(self.salt)}, " + + if self.ikm is not None: + result += f"ikm={repr(self.ikm)}, " + + if self.info is not None: + result += f"info={repr(self.info)}, " + + if self.expected_length is not None: + result += f"expected_length={repr(self.expected_length)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, HkdfInput): + return False + attributes: list[str] = [ + "digest_algorithm", + "salt", + "ikm", + "info", + "expected_length", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class HkdfExpandInput: + digest_algorithm: str + prk: bytes | bytearray + info: bytes | bytearray + expected_length: int + + def __init__( + self, + *, + digest_algorithm: str, + prk: bytes | bytearray, + info: bytes | bytearray, + expected_length: int = 0, + ): + self.digest_algorithm = digest_algorithm + self.prk = prk + self.info = info + if (expected_length is not None) and (expected_length < 0): + raise ValueError("expected_length must be greater than or equal to 0") + + self.expected_length = expected_length + + def as_dict(self) -> Dict[str, Any]: + """Converts the HkdfExpandInput to a dictionary.""" + d: Dict[str, Any] = { + "digest_algorithm": self.digest_algorithm, + "prk": self.prk, + "info": self.info, + } + + if self.expected_length is not None: + d["expected_length"] = self.expected_length + + return d + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "HkdfExpandInput": + """Creates a HkdfExpandInput from a dictionary.""" + kwargs: Dict[str, Any] = { + "digest_algorithm": d["digest_algorithm"], + "prk": d["prk"], + "info": d["info"], + } + + if "expected_length" in d: + kwargs["expected_length"] = d["expected_length"] + + return HkdfExpandInput(**kwargs) + + def __repr__(self) -> str: + result = "HkdfExpandInput(" + if self.digest_algorithm is not None: + result += f"digest_algorithm={repr(self.digest_algorithm)}, " + + if self.prk is not None: + result += f"prk={repr(self.prk)}, " + + if self.info is not None: + result += f"info={repr(self.info)}, " + + if self.expected_length is not None: + result += f"expected_length={repr(self.expected_length)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, HkdfExpandInput): + return False + attributes: list[str] = [ + "digest_algorithm", + "prk", + "info", + "expected_length", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class HkdfExtractInput: + digest_algorithm: str + salt: Optional[bytes | bytearray] + ikm: bytes | bytearray + + def __init__( + self, + *, + digest_algorithm: str, + ikm: bytes | bytearray, + salt: Optional[bytes | bytearray] = None, + ): + self.digest_algorithm = digest_algorithm + self.ikm = ikm + self.salt = salt + + def as_dict(self) -> Dict[str, Any]: + """Converts the HkdfExtractInput to a dictionary.""" + d: Dict[str, Any] = { + "digest_algorithm": self.digest_algorithm, + "ikm": self.ikm, + } + + if self.salt is not None: + d["salt"] = self.salt + + return d + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "HkdfExtractInput": + """Creates a HkdfExtractInput from a dictionary.""" + kwargs: Dict[str, Any] = { + "digest_algorithm": d["digest_algorithm"], + "ikm": d["ikm"], + } + + if "salt" in d: + kwargs["salt"] = d["salt"] + + return HkdfExtractInput(**kwargs) + + def __repr__(self) -> str: + result = "HkdfExtractInput(" + if self.digest_algorithm is not None: + result += f"digest_algorithm={repr(self.digest_algorithm)}, " + + if self.salt is not None: + result += f"salt={repr(self.salt)}, " + + if self.ikm is not None: + result += f"ikm={repr(self.ikm)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, HkdfExtractInput): + return False + attributes: list[str] = [ + "digest_algorithm", + "salt", + "ikm", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class HMacInput: + digest_algorithm: str + key: bytes | bytearray + message: bytes | bytearray + + def __init__( + self, + *, + digest_algorithm: str, + key: bytes | bytearray, + message: bytes | bytearray, + ): + self.digest_algorithm = digest_algorithm + self.key = key + self.message = message + + def as_dict(self) -> Dict[str, Any]: + """Converts the HMacInput to a dictionary.""" + return { + "digest_algorithm": self.digest_algorithm, + "key": self.key, + "message": self.message, + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "HMacInput": + """Creates a HMacInput from a dictionary.""" + kwargs: Dict[str, Any] = { + "digest_algorithm": d["digest_algorithm"], + "key": d["key"], + "message": d["message"], + } + + return HMacInput(**kwargs) + + def __repr__(self) -> str: + result = "HMacInput(" + if self.digest_algorithm is not None: + result += f"digest_algorithm={repr(self.digest_algorithm)}, " + + if self.key is not None: + result += f"key={repr(self.key)}, " + + if self.message is not None: + result += f"message={repr(self.message)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, HMacInput): + return False + attributes: list[str] = [ + "digest_algorithm", + "key", + "message", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class KdfCtrInput: + digest_algorithm: str + ikm: bytes | bytearray + expected_length: int + purpose: Optional[bytes | bytearray] + nonce: Optional[bytes | bytearray] + + def __init__( + self, + *, + digest_algorithm: str, + ikm: bytes | bytearray, + expected_length: int = 0, + purpose: Optional[bytes | bytearray] = None, + nonce: Optional[bytes | bytearray] = None, + ): + self.digest_algorithm = digest_algorithm + self.ikm = ikm + if (expected_length is not None) and (expected_length < 0): + raise ValueError("expected_length must be greater than or equal to 0") + + self.expected_length = expected_length + self.purpose = purpose + self.nonce = nonce + + def as_dict(self) -> Dict[str, Any]: + """Converts the KdfCtrInput to a dictionary.""" + d: Dict[str, Any] = { + "digest_algorithm": self.digest_algorithm, + "ikm": self.ikm, + } + + if self.expected_length is not None: + d["expected_length"] = self.expected_length + + if self.purpose is not None: + d["purpose"] = self.purpose + + if self.nonce is not None: + d["nonce"] = self.nonce + + return d + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "KdfCtrInput": + """Creates a KdfCtrInput from a dictionary.""" + kwargs: Dict[str, Any] = { + "digest_algorithm": d["digest_algorithm"], + "ikm": d["ikm"], + } + + if "expected_length" in d: + kwargs["expected_length"] = d["expected_length"] + + if "purpose" in d: + kwargs["purpose"] = d["purpose"] + + if "nonce" in d: + kwargs["nonce"] = d["nonce"] + + return KdfCtrInput(**kwargs) + + def __repr__(self) -> str: + result = "KdfCtrInput(" + if self.digest_algorithm is not None: + result += f"digest_algorithm={repr(self.digest_algorithm)}, " + + if self.ikm is not None: + result += f"ikm={repr(self.ikm)}, " + + if self.expected_length is not None: + result += f"expected_length={repr(self.expected_length)}, " + + if self.purpose is not None: + result += f"purpose={repr(self.purpose)}, " + + if self.nonce is not None: + result += f"nonce={repr(self.nonce)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, KdfCtrInput): + return False + attributes: list[str] = [ + "digest_algorithm", + "ikm", + "expected_length", + "purpose", + "nonce", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class ParsePublicKeyInput: + public_key: bytes | bytearray + + def __init__( + self, + *, + public_key: bytes | bytearray, + ): + self.public_key = public_key + + def as_dict(self) -> Dict[str, Any]: + """Converts the ParsePublicKeyInput to a dictionary.""" + return { + "public_key": self.public_key, + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "ParsePublicKeyInput": + """Creates a ParsePublicKeyInput from a dictionary.""" + kwargs: Dict[str, Any] = { + "public_key": d["public_key"], + } + + return ParsePublicKeyInput(**kwargs) + + def __repr__(self) -> str: + result = "ParsePublicKeyInput(" + if self.public_key is not None: + result += f"public_key={repr(self.public_key)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, ParsePublicKeyInput): + return False + attributes: list[str] = [ + "public_key", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class ParsePublicKeyOutput: + public_key: ECCPublicKey + + def __init__( + self, + *, + public_key: ECCPublicKey, + ): + self.public_key = public_key + + def as_dict(self) -> Dict[str, Any]: + """Converts the ParsePublicKeyOutput to a dictionary.""" + return { + "public_key": self.public_key.as_dict(), + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "ParsePublicKeyOutput": + """Creates a ParsePublicKeyOutput from a dictionary.""" + kwargs: Dict[str, Any] = { + "public_key": ECCPublicKey.from_dict(d["public_key"]), + } + + return ParsePublicKeyOutput(**kwargs) + + def __repr__(self) -> str: + result = "ParsePublicKeyOutput(" + if self.public_key is not None: + result += f"public_key={repr(self.public_key)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, ParsePublicKeyOutput): + return False + attributes: list[str] = [ + "public_key", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class RSAPaddingMode: + PKCS1 = "PKCS1" + + OAEP_SHA1 = "OAEP_SHA1" + + OAEP_SHA256 = "OAEP_SHA256" + + OAEP_SHA384 = "OAEP_SHA384" + + OAEP_SHA512 = "OAEP_SHA512" + + # This set contains every possible value known at the time this was generated. New + # values may be added in the future. + values = frozenset( + {"PKCS1", "OAEP_SHA1", "OAEP_SHA256", "OAEP_SHA384", "OAEP_SHA512"} + ) + + +class RSADecryptInput: + padding: str + private_key: bytes | bytearray + cipher_text: bytes | bytearray + + def __init__( + self, + *, + padding: str, + private_key: bytes | bytearray, + cipher_text: bytes | bytearray, + ): + self.padding = padding + self.private_key = private_key + self.cipher_text = cipher_text + + def as_dict(self) -> Dict[str, Any]: + """Converts the RSADecryptInput to a dictionary.""" + return { + "padding": self.padding, + "private_key": self.private_key, + "cipher_text": self.cipher_text, + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "RSADecryptInput": + """Creates a RSADecryptInput from a dictionary.""" + kwargs: Dict[str, Any] = { + "padding": d["padding"], + "private_key": d["private_key"], + "cipher_text": d["cipher_text"], + } + + return RSADecryptInput(**kwargs) + + def __repr__(self) -> str: + result = "RSADecryptInput(" + if self.padding is not None: + result += f"padding={repr(self.padding)}, " + + if self.private_key is not None: + result += f"private_key={repr(self.private_key)}, " + + if self.cipher_text is not None: + result += f"cipher_text={repr(self.cipher_text)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, RSADecryptInput): + return False + attributes: list[str] = [ + "padding", + "private_key", + "cipher_text", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class RSAEncryptInput: + padding: str + public_key: bytes | bytearray + plaintext: bytes | bytearray + + def __init__( + self, + *, + padding: str, + public_key: bytes | bytearray, + plaintext: bytes | bytearray, + ): + self.padding = padding + self.public_key = public_key + self.plaintext = plaintext + + def as_dict(self) -> Dict[str, Any]: + """Converts the RSAEncryptInput to a dictionary.""" + return { + "padding": self.padding, + "public_key": self.public_key, + "plaintext": self.plaintext, + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "RSAEncryptInput": + """Creates a RSAEncryptInput from a dictionary.""" + kwargs: Dict[str, Any] = { + "padding": d["padding"], + "public_key": d["public_key"], + "plaintext": d["plaintext"], + } + + return RSAEncryptInput(**kwargs) + + def __repr__(self) -> str: + result = "RSAEncryptInput(" + if self.padding is not None: + result += f"padding={repr(self.padding)}, " + + if self.public_key is not None: + result += f"public_key={repr(self.public_key)}, " + + if self.plaintext is not None: + result += f"plaintext={repr(self.plaintext)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, RSAEncryptInput): + return False + attributes: list[str] = [ + "padding", + "public_key", + "plaintext", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class ValidatePublicKeyInput: + ecc_curve: str + public_key: bytes | bytearray + + def __init__( + self, + *, + ecc_curve: str, + public_key: bytes | bytearray, + ): + self.ecc_curve = ecc_curve + self.public_key = public_key + + def as_dict(self) -> Dict[str, Any]: + """Converts the ValidatePublicKeyInput to a dictionary.""" + return { + "ecc_curve": self.ecc_curve, + "public_key": self.public_key, + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "ValidatePublicKeyInput": + """Creates a ValidatePublicKeyInput from a dictionary.""" + kwargs: Dict[str, Any] = { + "ecc_curve": d["ecc_curve"], + "public_key": d["public_key"], + } + + return ValidatePublicKeyInput(**kwargs) + + def __repr__(self) -> str: + result = "ValidatePublicKeyInput(" + if self.ecc_curve is not None: + result += f"ecc_curve={repr(self.ecc_curve)}, " + + if self.public_key is not None: + result += f"public_key={repr(self.public_key)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, ValidatePublicKeyInput): + return False + attributes: list[str] = [ + "ecc_curve", + "public_key", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class ValidatePublicKeyOutput: + success: bool + + def __init__( + self, + *, + success: bool, + ): + self.success = success + + def as_dict(self) -> Dict[str, Any]: + """Converts the ValidatePublicKeyOutput to a dictionary.""" + return { + "success": self.success, + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "ValidatePublicKeyOutput": + """Creates a ValidatePublicKeyOutput from a dictionary.""" + kwargs: Dict[str, Any] = { + "success": d["success"], + } + + return ValidatePublicKeyOutput(**kwargs) + + def __repr__(self) -> str: + result = "ValidatePublicKeyOutput(" + if self.success is not None: + result += f"success={repr(self.success)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, ValidatePublicKeyOutput): + return False + attributes: list[str] = [ + "success", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class Unit: + pass diff --git a/AwsCryptographyPrimitives/runtimes/python/src/aws_cryptography_primitives/smithygenerated/aws_cryptography_primitives/plugin.py b/AwsCryptographyPrimitives/runtimes/python/src/aws_cryptography_primitives/smithygenerated/aws_cryptography_primitives/plugin.py new file mode 100644 index 000000000..2598d1a9c --- /dev/null +++ b/AwsCryptographyPrimitives/runtimes/python/src/aws_cryptography_primitives/smithygenerated/aws_cryptography_primitives/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, CryptoConfig +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, CryptoConfig): + from aws_cryptography_primitives.internaldafny.generated.AtomicPrimitives import ( + default__, + ) + + config.dafnyImplInterface.impl = default__.AtomicPrimitives( + 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/AwsCryptographyPrimitives/runtimes/python/src/aws_cryptography_primitives/smithygenerated/aws_cryptography_primitives/serialize.py b/AwsCryptographyPrimitives/runtimes/python/src/aws_cryptography_primitives/smithygenerated/aws_cryptography_primitives/serialize.py new file mode 100644 index 000000000..2e392d30a --- /dev/null +++ b/AwsCryptographyPrimitives/runtimes/python/src/aws_cryptography_primitives/smithygenerated/aws_cryptography_primitives/serialize.py @@ -0,0 +1,225 @@ +# 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_cryptography_primitives.smithygenerated.aws_cryptography_primitives.smithy_to_dafny + +from .dafny_protocol import DafnyRequest + +from .config import Config + + +def _serialize_generate_random_bytes(input, config: Config) -> DafnyRequest: + return DafnyRequest( + operation_name="GenerateRandomBytes", + dafny_operation_input=aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.smithy_to_dafny.aws_cryptography_primitives_GenerateRandomBytesInput( + input + ), + ) + + +def _serialize_digest(input, config: Config) -> DafnyRequest: + return DafnyRequest( + operation_name="Digest", + dafny_operation_input=aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.smithy_to_dafny.aws_cryptography_primitives_DigestInput( + input + ), + ) + + +def _serialize_h_mac(input, config: Config) -> DafnyRequest: + return DafnyRequest( + operation_name="HMac", + dafny_operation_input=aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.smithy_to_dafny.aws_cryptography_primitives_HMacInput( + input + ), + ) + + +def _serialize_hkdf_extract(input, config: Config) -> DafnyRequest: + return DafnyRequest( + operation_name="HkdfExtract", + dafny_operation_input=aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.smithy_to_dafny.aws_cryptography_primitives_HkdfExtractInput( + input + ), + ) + + +def _serialize_hkdf_expand(input, config: Config) -> DafnyRequest: + return DafnyRequest( + operation_name="HkdfExpand", + dafny_operation_input=aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.smithy_to_dafny.aws_cryptography_primitives_HkdfExpandInput( + input + ), + ) + + +def _serialize_hkdf(input, config: Config) -> DafnyRequest: + return DafnyRequest( + operation_name="Hkdf", + dafny_operation_input=aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.smithy_to_dafny.aws_cryptography_primitives_HkdfInput( + input + ), + ) + + +def _serialize_kdf_counter_mode(input, config: Config) -> DafnyRequest: + return DafnyRequest( + operation_name="KdfCounterMode", + dafny_operation_input=aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.smithy_to_dafny.aws_cryptography_primitives_KdfCtrInput( + input + ), + ) + + +def _serialize_aes_kdf_counter_mode(input, config: Config) -> DafnyRequest: + return DafnyRequest( + operation_name="AesKdfCounterMode", + dafny_operation_input=aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.smithy_to_dafny.aws_cryptography_primitives_AesKdfCtrInput( + input + ), + ) + + +def _serialize_aes_encrypt(input, config: Config) -> DafnyRequest: + return DafnyRequest( + operation_name="AESEncrypt", + dafny_operation_input=aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.smithy_to_dafny.aws_cryptography_primitives_AESEncryptInput( + input + ), + ) + + +def _serialize_aes_decrypt(input, config: Config) -> DafnyRequest: + return DafnyRequest( + operation_name="AESDecrypt", + dafny_operation_input=aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.smithy_to_dafny.aws_cryptography_primitives_AESDecryptInput( + input + ), + ) + + +def _serialize_generate_rsa_key_pair(input, config: Config) -> DafnyRequest: + return DafnyRequest( + operation_name="GenerateRSAKeyPair", + dafny_operation_input=aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.smithy_to_dafny.aws_cryptography_primitives_GenerateRSAKeyPairInput( + input + ), + ) + + +def _serialize_get_rsa_key_modulus_length(input, config: Config) -> DafnyRequest: + return DafnyRequest( + operation_name="GetRSAKeyModulusLength", + dafny_operation_input=aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.smithy_to_dafny.aws_cryptography_primitives_GetRSAKeyModulusLengthInput( + input + ), + ) + + +def _serialize_rsa_decrypt(input, config: Config) -> DafnyRequest: + return DafnyRequest( + operation_name="RSADecrypt", + dafny_operation_input=aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.smithy_to_dafny.aws_cryptography_primitives_RSADecryptInput( + input + ), + ) + + +def _serialize_rsa_encrypt(input, config: Config) -> DafnyRequest: + return DafnyRequest( + operation_name="RSAEncrypt", + dafny_operation_input=aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.smithy_to_dafny.aws_cryptography_primitives_RSAEncryptInput( + input + ), + ) + + +def _serialize_generate_ecdsa_signature_key(input, config: Config) -> DafnyRequest: + return DafnyRequest( + operation_name="GenerateECDSASignatureKey", + dafny_operation_input=aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.smithy_to_dafny.aws_cryptography_primitives_GenerateECDSASignatureKeyInput( + input + ), + ) + + +def _serialize_ecdsa_sign(input, config: Config) -> DafnyRequest: + return DafnyRequest( + operation_name="ECDSASign", + dafny_operation_input=aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.smithy_to_dafny.aws_cryptography_primitives_ECDSASignInput( + input + ), + ) + + +def _serialize_ecdsa_verify(input, config: Config) -> DafnyRequest: + return DafnyRequest( + operation_name="ECDSAVerify", + dafny_operation_input=aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.smithy_to_dafny.aws_cryptography_primitives_ECDSAVerifyInput( + input + ), + ) + + +def _serialize_generate_ecc_key_pair(input, config: Config) -> DafnyRequest: + return DafnyRequest( + operation_name="GenerateECCKeyPair", + dafny_operation_input=aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.smithy_to_dafny.aws_cryptography_primitives_GenerateECCKeyPairInput( + input + ), + ) + + +def _serialize_get_public_key_from_private_key(input, config: Config) -> DafnyRequest: + return DafnyRequest( + operation_name="GetPublicKeyFromPrivateKey", + dafny_operation_input=aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.smithy_to_dafny.aws_cryptography_primitives_GetPublicKeyFromPrivateKeyInput( + input + ), + ) + + +def _serialize_validate_public_key(input, config: Config) -> DafnyRequest: + return DafnyRequest( + operation_name="ValidatePublicKey", + dafny_operation_input=aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.smithy_to_dafny.aws_cryptography_primitives_ValidatePublicKeyInput( + input + ), + ) + + +def _serialize_derive_shared_secret(input, config: Config) -> DafnyRequest: + return DafnyRequest( + operation_name="DeriveSharedSecret", + dafny_operation_input=aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.smithy_to_dafny.aws_cryptography_primitives_DeriveSharedSecretInput( + input + ), + ) + + +def _serialize_compress_public_key(input, config: Config) -> DafnyRequest: + return DafnyRequest( + operation_name="CompressPublicKey", + dafny_operation_input=aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.smithy_to_dafny.aws_cryptography_primitives_CompressPublicKeyInput( + input + ), + ) + + +def _serialize_decompress_public_key(input, config: Config) -> DafnyRequest: + return DafnyRequest( + operation_name="DecompressPublicKey", + dafny_operation_input=aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.smithy_to_dafny.aws_cryptography_primitives_DecompressPublicKeyInput( + input + ), + ) + + +def _serialize_parse_public_key(input, config: Config) -> DafnyRequest: + return DafnyRequest( + operation_name="ParsePublicKey", + dafny_operation_input=aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.smithy_to_dafny.aws_cryptography_primitives_ParsePublicKeyInput( + input + ), + ) diff --git a/AwsCryptographyPrimitives/runtimes/python/src/aws_cryptography_primitives/smithygenerated/aws_cryptography_primitives/smithy_to_dafny.py b/AwsCryptographyPrimitives/runtimes/python/src/aws_cryptography_primitives/smithygenerated/aws_cryptography_primitives/smithy_to_dafny.py new file mode 100644 index 000000000..726fc76f7 --- /dev/null +++ b/AwsCryptographyPrimitives/runtimes/python/src/aws_cryptography_primitives/smithygenerated/aws_cryptography_primitives/smithy_to_dafny.py @@ -0,0 +1,566 @@ +# 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 Seq +from aws_cryptography_primitives.internaldafny.generated.AwsCryptographyPrimitivesTypes import ( + AESDecryptInput_AESDecryptInput as DafnyAESDecryptInput, + AESEncryptInput_AESEncryptInput as DafnyAESEncryptInput, + AESEncryptOutput_AESEncryptOutput as DafnyAESEncryptOutput, + AES__GCM_AES__GCM as DafnyAES_GCM, + AesKdfCtrInput_AesKdfCtrInput as DafnyAesKdfCtrInput, + CompressPublicKeyInput_CompressPublicKeyInput as DafnyCompressPublicKeyInput, + CompressPublicKeyOutput_CompressPublicKeyOutput as DafnyCompressPublicKeyOutput, + CryptoConfig_CryptoConfig as DafnyCryptoConfig, + DecompressPublicKeyInput_DecompressPublicKeyInput as DafnyDecompressPublicKeyInput, + DecompressPublicKeyOutput_DecompressPublicKeyOutput as DafnyDecompressPublicKeyOutput, + DeriveSharedSecretInput_DeriveSharedSecretInput as DafnyDeriveSharedSecretInput, + DeriveSharedSecretOutput_DeriveSharedSecretOutput as DafnyDeriveSharedSecretOutput, + DigestAlgorithm_SHA__256, + DigestAlgorithm_SHA__384, + DigestAlgorithm_SHA__512, + DigestInput_DigestInput as DafnyDigestInput, + ECCPrivateKey_ECCPrivateKey as DafnyECCPrivateKey, + ECCPublicKey_ECCPublicKey as DafnyECCPublicKey, + ECDHCurveSpec_ECC__NIST__P256, + ECDHCurveSpec_ECC__NIST__P384, + ECDHCurveSpec_ECC__NIST__P521, + ECDHCurveSpec_SM2, + ECDSASignInput_ECDSASignInput as DafnyECDSASignInput, + ECDSASignatureAlgorithm_ECDSA__P256, + ECDSASignatureAlgorithm_ECDSA__P384, + ECDSAVerifyInput_ECDSAVerifyInput as DafnyECDSAVerifyInput, + GenerateECCKeyPairInput_GenerateECCKeyPairInput as DafnyGenerateECCKeyPairInput, + GenerateECCKeyPairOutput_GenerateECCKeyPairOutput as DafnyGenerateECCKeyPairOutput, + GenerateECDSASignatureKeyInput_GenerateECDSASignatureKeyInput as DafnyGenerateECDSASignatureKeyInput, + GenerateECDSASignatureKeyOutput_GenerateECDSASignatureKeyOutput as DafnyGenerateECDSASignatureKeyOutput, + GenerateRSAKeyPairInput_GenerateRSAKeyPairInput as DafnyGenerateRSAKeyPairInput, + GenerateRSAKeyPairOutput_GenerateRSAKeyPairOutput as DafnyGenerateRSAKeyPairOutput, + GenerateRandomBytesInput_GenerateRandomBytesInput as DafnyGenerateRandomBytesInput, + GetPublicKeyFromPrivateKeyInput_GetPublicKeyFromPrivateKeyInput as DafnyGetPublicKeyFromPrivateKeyInput, + GetPublicKeyFromPrivateKeyOutput_GetPublicKeyFromPrivateKeyOutput as DafnyGetPublicKeyFromPrivateKeyOutput, + GetRSAKeyModulusLengthInput_GetRSAKeyModulusLengthInput as DafnyGetRSAKeyModulusLengthInput, + GetRSAKeyModulusLengthOutput_GetRSAKeyModulusLengthOutput as DafnyGetRSAKeyModulusLengthOutput, + HMacInput_HMacInput as DafnyHMacInput, + HkdfExpandInput_HkdfExpandInput as DafnyHkdfExpandInput, + HkdfExtractInput_HkdfExtractInput as DafnyHkdfExtractInput, + HkdfInput_HkdfInput as DafnyHkdfInput, + KdfCtrInput_KdfCtrInput as DafnyKdfCtrInput, + ParsePublicKeyInput_ParsePublicKeyInput as DafnyParsePublicKeyInput, + ParsePublicKeyOutput_ParsePublicKeyOutput as DafnyParsePublicKeyOutput, + RSADecryptInput_RSADecryptInput as DafnyRSADecryptInput, + RSAEncryptInput_RSAEncryptInput as DafnyRSAEncryptInput, + RSAPaddingMode_OAEP__SHA1, + RSAPaddingMode_OAEP__SHA256, + RSAPaddingMode_OAEP__SHA384, + RSAPaddingMode_OAEP__SHA512, + RSAPaddingMode_PKCS1, + RSAPrivateKey_RSAPrivateKey as DafnyRSAPrivateKey, + RSAPublicKey_RSAPublicKey as DafnyRSAPublicKey, + ValidatePublicKeyInput_ValidatePublicKeyInput as DafnyValidatePublicKeyInput, + ValidatePublicKeyOutput_ValidatePublicKeyOutput as DafnyValidatePublicKeyOutput, +) +import aws_cryptography_primitives.internaldafny.generated.module_ +import aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.smithy_to_dafny +from smithy_dafny_standard_library.internaldafny.generated.Wrappers import ( + Option_None, + Option_Some, +) + + +def aws_cryptography_primitives_GenerateRandomBytesInput(native_input): + return DafnyGenerateRandomBytesInput( + length=native_input.length, + ) + + +def aws_cryptography_primitives_DigestInput(native_input): + return DafnyDigestInput( + digestAlgorithm=aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.smithy_to_dafny.aws_cryptography_primitives_DigestAlgorithm( + native_input.digest_algorithm + ), + message=Seq(native_input.message), + ) + + +def aws_cryptography_primitives_DigestAlgorithm(native_input): + if native_input == "SHA_512": + return DigestAlgorithm_SHA__512() + + elif native_input == "SHA_384": + return DigestAlgorithm_SHA__384() + + elif native_input == "SHA_256": + return DigestAlgorithm_SHA__256() + + else: + raise ValueError(f"No recognized enum value in enum type: {native_input=}") + + +def aws_cryptography_primitives_HMacInput(native_input): + return DafnyHMacInput( + digestAlgorithm=aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.smithy_to_dafny.aws_cryptography_primitives_DigestAlgorithm( + native_input.digest_algorithm + ), + key=Seq(native_input.key), + message=Seq(native_input.message), + ) + + +def aws_cryptography_primitives_HkdfExtractInput(native_input): + return DafnyHkdfExtractInput( + digestAlgorithm=aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.smithy_to_dafny.aws_cryptography_primitives_DigestAlgorithm( + native_input.digest_algorithm + ), + salt=( + (Option_Some(Seq(native_input.salt))) + if (native_input.salt is not None) + else (Option_None()) + ), + ikm=Seq(native_input.ikm), + ) + + +def aws_cryptography_primitives_HkdfExpandInput(native_input): + return DafnyHkdfExpandInput( + digestAlgorithm=aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.smithy_to_dafny.aws_cryptography_primitives_DigestAlgorithm( + native_input.digest_algorithm + ), + prk=Seq(native_input.prk), + info=Seq(native_input.info), + expectedLength=native_input.expected_length, + ) + + +def aws_cryptography_primitives_HkdfInput(native_input): + return DafnyHkdfInput( + digestAlgorithm=aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.smithy_to_dafny.aws_cryptography_primitives_DigestAlgorithm( + native_input.digest_algorithm + ), + salt=( + (Option_Some(Seq(native_input.salt))) + if (native_input.salt is not None) + else (Option_None()) + ), + ikm=Seq(native_input.ikm), + info=Seq(native_input.info), + expectedLength=native_input.expected_length, + ) + + +def aws_cryptography_primitives_KdfCtrInput(native_input): + return DafnyKdfCtrInput( + digestAlgorithm=aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.smithy_to_dafny.aws_cryptography_primitives_DigestAlgorithm( + native_input.digest_algorithm + ), + ikm=Seq(native_input.ikm), + expectedLength=native_input.expected_length, + purpose=( + (Option_Some(Seq(native_input.purpose))) + if (native_input.purpose is not None) + else (Option_None()) + ), + nonce=( + (Option_Some(Seq(native_input.nonce))) + if (native_input.nonce is not None) + else (Option_None()) + ), + ) + + +def aws_cryptography_primitives_AesKdfCtrInput(native_input): + return DafnyAesKdfCtrInput( + ikm=Seq(native_input.ikm), + expectedLength=native_input.expected_length, + nonce=( + (Option_Some(Seq(native_input.nonce))) + if (native_input.nonce is not None) + else (Option_None()) + ), + ) + + +def aws_cryptography_primitives_AESEncryptInput(native_input): + return DafnyAESEncryptInput( + encAlg=aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.smithy_to_dafny.aws_cryptography_primitives_AES_GCM( + native_input.enc_alg + ), + iv=Seq(native_input.iv), + key=Seq(native_input.key), + msg=Seq(native_input.msg), + aad=Seq(native_input.aad), + ) + + +def aws_cryptography_primitives_AES_GCM(native_input): + return DafnyAES_GCM( + keyLength=native_input.key_length, + tagLength=native_input.tag_length, + ivLength=native_input.iv_length, + ) + + +def aws_cryptography_primitives_AESDecryptInput(native_input): + return DafnyAESDecryptInput( + encAlg=aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.smithy_to_dafny.aws_cryptography_primitives_AES_GCM( + native_input.enc_alg + ), + key=Seq(native_input.key), + cipherTxt=Seq(native_input.cipher_txt), + authTag=Seq(native_input.auth_tag), + iv=Seq(native_input.iv), + aad=Seq(native_input.aad), + ) + + +def aws_cryptography_primitives_GenerateRSAKeyPairInput(native_input): + return DafnyGenerateRSAKeyPairInput( + lengthBits=native_input.length_bits, + ) + + +def aws_cryptography_primitives_GetRSAKeyModulusLengthInput(native_input): + return DafnyGetRSAKeyModulusLengthInput( + publicKey=Seq(native_input.public_key), + ) + + +def aws_cryptography_primitives_RSADecryptInput(native_input): + return DafnyRSADecryptInput( + padding=aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.smithy_to_dafny.aws_cryptography_primitives_RSAPaddingMode( + native_input.padding + ), + privateKey=Seq(native_input.private_key), + cipherText=Seq(native_input.cipher_text), + ) + + +def aws_cryptography_primitives_RSAPaddingMode(native_input): + if native_input == "PKCS1": + return RSAPaddingMode_PKCS1() + + elif native_input == "OAEP_SHA1": + return RSAPaddingMode_OAEP__SHA1() + + elif native_input == "OAEP_SHA256": + return RSAPaddingMode_OAEP__SHA256() + + elif native_input == "OAEP_SHA384": + return RSAPaddingMode_OAEP__SHA384() + + elif native_input == "OAEP_SHA512": + return RSAPaddingMode_OAEP__SHA512() + + else: + raise ValueError(f"No recognized enum value in enum type: {native_input=}") + + +def aws_cryptography_primitives_RSAEncryptInput(native_input): + return DafnyRSAEncryptInput( + padding=aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.smithy_to_dafny.aws_cryptography_primitives_RSAPaddingMode( + native_input.padding + ), + publicKey=Seq(native_input.public_key), + plaintext=Seq(native_input.plaintext), + ) + + +def aws_cryptography_primitives_GenerateECDSASignatureKeyInput(native_input): + return DafnyGenerateECDSASignatureKeyInput( + signatureAlgorithm=aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.smithy_to_dafny.aws_cryptography_primitives_ECDSASignatureAlgorithm( + native_input.signature_algorithm + ), + ) + + +def aws_cryptography_primitives_ECDSASignatureAlgorithm(native_input): + if native_input == "ECDSA_P384": + return ECDSASignatureAlgorithm_ECDSA__P384() + + elif native_input == "ECDSA_P256": + return ECDSASignatureAlgorithm_ECDSA__P256() + + else: + raise ValueError(f"No recognized enum value in enum type: {native_input=}") + + +def aws_cryptography_primitives_ECDSASignInput(native_input): + return DafnyECDSASignInput( + signatureAlgorithm=aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.smithy_to_dafny.aws_cryptography_primitives_ECDSASignatureAlgorithm( + native_input.signature_algorithm + ), + signingKey=Seq(native_input.signing_key), + message=Seq(native_input.message), + ) + + +def aws_cryptography_primitives_ECDSAVerifyInput(native_input): + return DafnyECDSAVerifyInput( + signatureAlgorithm=aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.smithy_to_dafny.aws_cryptography_primitives_ECDSASignatureAlgorithm( + native_input.signature_algorithm + ), + verificationKey=Seq(native_input.verification_key), + message=Seq(native_input.message), + signature=Seq(native_input.signature), + ) + + +def aws_cryptography_primitives_GenerateECCKeyPairInput(native_input): + return DafnyGenerateECCKeyPairInput( + eccCurve=aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.smithy_to_dafny.aws_cryptography_primitives_ECDHCurveSpec( + native_input.ecc_curve + ), + ) + + +def aws_cryptography_primitives_ECDHCurveSpec(native_input): + if native_input == "ECC_NIST_P256": + return ECDHCurveSpec_ECC__NIST__P256() + + elif native_input == "ECC_NIST_P384": + return ECDHCurveSpec_ECC__NIST__P384() + + elif native_input == "ECC_NIST_P521": + return ECDHCurveSpec_ECC__NIST__P521() + + elif native_input == "SM2": + return ECDHCurveSpec_SM2() + + else: + raise ValueError(f"No recognized enum value in enum type: {native_input=}") + + +def aws_cryptography_primitives_GetPublicKeyFromPrivateKeyInput(native_input): + return DafnyGetPublicKeyFromPrivateKeyInput( + eccCurve=aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.smithy_to_dafny.aws_cryptography_primitives_ECDHCurveSpec( + native_input.ecc_curve + ), + privateKey=aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.smithy_to_dafny.aws_cryptography_primitives_ECCPrivateKey( + native_input.private_key + ), + ) + + +def aws_cryptography_primitives_ECCPrivateKey(native_input): + return DafnyECCPrivateKey( + pem=Seq(native_input.pem), + ) + + +def aws_cryptography_primitives_ValidatePublicKeyInput(native_input): + return DafnyValidatePublicKeyInput( + eccCurve=aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.smithy_to_dafny.aws_cryptography_primitives_ECDHCurveSpec( + native_input.ecc_curve + ), + publicKey=Seq(native_input.public_key), + ) + + +def aws_cryptography_primitives_DeriveSharedSecretInput(native_input): + return DafnyDeriveSharedSecretInput( + eccCurve=aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.smithy_to_dafny.aws_cryptography_primitives_ECDHCurveSpec( + native_input.ecc_curve + ), + privateKey=aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.smithy_to_dafny.aws_cryptography_primitives_ECCPrivateKey( + native_input.private_key + ), + publicKey=aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.smithy_to_dafny.aws_cryptography_primitives_ECCPublicKey( + native_input.public_key + ), + ) + + +def aws_cryptography_primitives_ECCPublicKey(native_input): + return DafnyECCPublicKey( + der=Seq(native_input.der), + ) + + +def aws_cryptography_primitives_CompressPublicKeyInput(native_input): + return DafnyCompressPublicKeyInput( + publicKey=aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.smithy_to_dafny.aws_cryptography_primitives_ECCPublicKey( + native_input.public_key + ), + eccCurve=aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.smithy_to_dafny.aws_cryptography_primitives_ECDHCurveSpec( + native_input.ecc_curve + ), + ) + + +def aws_cryptography_primitives_DecompressPublicKeyInput(native_input): + return DafnyDecompressPublicKeyInput( + compressedPublicKey=Seq(native_input.compressed_public_key), + eccCurve=aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.smithy_to_dafny.aws_cryptography_primitives_ECDHCurveSpec( + native_input.ecc_curve + ), + ) + + +def aws_cryptography_primitives_ParsePublicKeyInput(native_input): + return DafnyParsePublicKeyInput( + publicKey=Seq(native_input.public_key), + ) + + +def aws_cryptography_primitives_GenerateRandomBytesOutput(native_input): + return Seq(native_input) + + +def aws_cryptography_primitives_DigestOutput(native_input): + return Seq(native_input) + + +def aws_cryptography_primitives_HMacOutput(native_input): + return Seq(native_input) + + +def aws_cryptography_primitives_HkdfExtractOutput(native_input): + return Seq(native_input) + + +def aws_cryptography_primitives_HkdfExpandOutput(native_input): + return Seq(native_input) + + +def aws_cryptography_primitives_HkdfOutput(native_input): + return Seq(native_input) + + +def aws_cryptography_primitives_KdfCtrOutput(native_input): + return Seq(native_input) + + +def aws_cryptography_primitives_AesKdfCtrOutput(native_input): + return Seq(native_input) + + +def aws_cryptography_primitives_AESEncryptOutput(native_input): + return DafnyAESEncryptOutput( + cipherText=Seq(native_input.cipher_text), + authTag=Seq(native_input.auth_tag), + ) + + +def aws_cryptography_primitives_AESDecryptOutput(native_input): + return Seq(native_input) + + +def aws_cryptography_primitives_GenerateRSAKeyPairOutput(native_input): + return DafnyGenerateRSAKeyPairOutput( + publicKey=aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.smithy_to_dafny.aws_cryptography_primitives_RSAPublicKey( + native_input.public_key + ), + privateKey=aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.smithy_to_dafny.aws_cryptography_primitives_RSAPrivateKey( + native_input.private_key + ), + ) + + +def aws_cryptography_primitives_RSAPublicKey(native_input): + return DafnyRSAPublicKey( + lengthBits=native_input.length_bits, + pem=Seq(native_input.pem), + ) + + +def aws_cryptography_primitives_RSAPrivateKey(native_input): + return DafnyRSAPrivateKey( + lengthBits=native_input.length_bits, + pem=Seq(native_input.pem), + ) + + +def aws_cryptography_primitives_GetRSAKeyModulusLengthOutput(native_input): + return DafnyGetRSAKeyModulusLengthOutput( + length=native_input.length, + ) + + +def aws_cryptography_primitives_RSADecryptOutput(native_input): + return Seq(native_input) + + +def aws_cryptography_primitives_RSAEncryptOutput(native_input): + return Seq(native_input) + + +def aws_cryptography_primitives_GenerateECDSASignatureKeyOutput(native_input): + return DafnyGenerateECDSASignatureKeyOutput( + signatureAlgorithm=aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.smithy_to_dafny.aws_cryptography_primitives_ECDSASignatureAlgorithm( + native_input.signature_algorithm + ), + verificationKey=Seq(native_input.verification_key), + signingKey=Seq(native_input.signing_key), + ) + + +def aws_cryptography_primitives_ECDSASignOutput(native_input): + return Seq(native_input) + + +def aws_cryptography_primitives_ECDSAVerifyOutput(native_input): + return native_input + + +def aws_cryptography_primitives_GenerateECCKeyPairOutput(native_input): + return DafnyGenerateECCKeyPairOutput( + eccCurve=aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.smithy_to_dafny.aws_cryptography_primitives_ECDHCurveSpec( + native_input.ecc_curve + ), + privateKey=aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.smithy_to_dafny.aws_cryptography_primitives_ECCPrivateKey( + native_input.private_key + ), + publicKey=aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.smithy_to_dafny.aws_cryptography_primitives_ECCPublicKey( + native_input.public_key + ), + ) + + +def aws_cryptography_primitives_GetPublicKeyFromPrivateKeyOutput(native_input): + return DafnyGetPublicKeyFromPrivateKeyOutput( + eccCurve=aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.smithy_to_dafny.aws_cryptography_primitives_ECDHCurveSpec( + native_input.ecc_curve + ), + privateKey=aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.smithy_to_dafny.aws_cryptography_primitives_ECCPrivateKey( + native_input.private_key + ), + publicKey=Seq(native_input.public_key), + ) + + +def aws_cryptography_primitives_ValidatePublicKeyOutput(native_input): + return DafnyValidatePublicKeyOutput( + success=native_input.success, + ) + + +def aws_cryptography_primitives_DeriveSharedSecretOutput(native_input): + return DafnyDeriveSharedSecretOutput( + sharedSecret=Seq(native_input.shared_secret), + ) + + +def aws_cryptography_primitives_CompressPublicKeyOutput(native_input): + return DafnyCompressPublicKeyOutput( + compressedPublicKey=Seq(native_input.compressed_public_key), + ) + + +def aws_cryptography_primitives_DecompressPublicKeyOutput(native_input): + return DafnyDecompressPublicKeyOutput( + publicKey=aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.smithy_to_dafny.aws_cryptography_primitives_ECCPublicKey( + native_input.public_key + ), + ) + + +def aws_cryptography_primitives_ParsePublicKeyOutput(native_input): + return DafnyParsePublicKeyOutput( + publicKey=aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.smithy_to_dafny.aws_cryptography_primitives_ECCPublicKey( + native_input.public_key + ), + ) + + +def aws_cryptography_primitives_CryptoConfig(native_input): + return DafnyCryptoConfig() diff --git a/AwsCryptographyPrimitives/runtimes/python/test/__init__.py b/AwsCryptographyPrimitives/runtimes/python/test/__init__.py new file mode 100644 index 000000000..f94fd12a2 --- /dev/null +++ b/AwsCryptographyPrimitives/runtimes/python/test/__init__.py @@ -0,0 +1,2 @@ +# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 diff --git a/AwsCryptographyPrimitives/runtimes/python/test/functional/test_ECDH_exceptions.py b/AwsCryptographyPrimitives/runtimes/python/test/functional/test_ECDH_exceptions.py new file mode 100644 index 000000000..202d9c252 --- /dev/null +++ b/AwsCryptographyPrimitives/runtimes/python/test/functional/test_ECDH_exceptions.py @@ -0,0 +1,184 @@ +# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 +""" +This file asserts properties about the exceptions +pyca raises for different public keys. + +These assertions provide evidence +that pyca (in particular, OpenSSL backend) +raises a particular exception for one "infinity" public key +that it does not raise for other public keys. + +These demonstrate that the "infinity" exception is not raised +for neither noncanonical infinity public keys +nor for other "short" keys. + +These findings validate that the MPL +will correctly detect an "infinity" public key +and will fail to load an "infinity" public key +from a DER encoding. + +This test suite is solely intended +to document and validate the expected behavior from pyca +in a particularly sensitive failure case +where the MPL should understand failure modes. + +This test suite is NOT intended to require +that pyca should continue to raise these exceptions. +If the behavior from pyca changes, +we should first understand why the behavior changed, +then update the test suite if needed. +""" +import pytest +from cryptography.hazmat.primitives.asymmetric import ec +from cryptography.hazmat.primitives.asymmetric.ec import SECP256R1 +from cryptography.hazmat.primitives.serialization import ( + Encoding, + PublicFormat, + load_der_public_key, +) +from pyasn1.codec.der.decoder import decode as der_decode +from pyasn1.codec.der.encoder import encode as der_encode +from pyasn1.type.univ import BitString, Sequence + +# This exception string is raised when pyca cannot load the DER-encoded public key. +GENERIC_EXCEPTION_STRING = "Could not deserialize key data. The data may be in an incorrect format, it may be encrypted with an unsupported algorithm, or it may be an unsupported key type (e.g. EC curves with explicit parameters" +# This exception string appears to be raised ONLY for the invalid public key for the point at infinity. +INF_EXCEPTION_STRING = "Unable to load EC key" + +def get_valid_der_components(): + """ + Generates a random valid public key, + DER-encodes it, + decodes it into an ASN.1 sequence, + and returns the two items in the ASN.1 sequence as a tuple. + The two items are (the ASN.1 encoded algorithm info, the ASN.1 encoded public key point). + """ + private_key = ec.generate_private_key( + SECP256R1 + ) + public_key_der = private_key.public_key().public_bytes(Encoding.DER, PublicFormat.SubjectPublicKeyInfo) + alg_info_seq, _ = der_decode(public_key_der, asn1Spec=Sequence()) + return alg_info_seq.getComponentByPosition(0), alg_info_seq.getComponentByPosition(1) + +def test_GIVEN_valid_seq_WHEN_load_der_public_key_THEN_no_exception(): + """Asserts that our ASN.1 sequence construction procedure CAN produce a valid DER public key.""" + # Given: Valid DER-encoded ASN.1 sequence represesenting a valid public key + valid_alg_info, valid_point = get_valid_der_components() + seq = Sequence() + seq.setComponentByPosition(0, valid_alg_info) + seq.setComponentByPosition(1, valid_point) + der_seq = der_encode(seq) + + # When: load_der_public_key + load_der_public_key(der_seq) + # Then: No exception + +def test_GIVEN_invalid_key_WHEN_load_der_public_key_THEN_generic_exception(): + """ + Asserts that our ASN.1 sequence construction procedure CAN produce an invalid DER public key, + and that a "generic" invalid DER public key raises the "generic" exception. + """ + # Given: Valid DER-encoded ASN.1 sequence representing an invalid public key + valid_alg_info, valid_point = get_valid_der_components() + # This isn't a valid point for a number of reasons + invalid_point = BitString.fromOctetString(b"\xbe" * len(valid_point)) + seq = Sequence() + seq.setComponentByPosition(0, valid_alg_info) + seq.setComponentByPosition(1, invalid_point) + der_seq = der_encode(seq) + + # Then: raises ValueError + with pytest.raises(ValueError) as e: + # When: load_der_public_key + load_der_public_key(der_seq) + + # Then: exception is the generic exception and not the infinity key exception + assert GENERIC_EXCEPTION_STRING in str(e.value) + assert INF_EXCEPTION_STRING not in str(e.value) + +def test_GIVEN_canonical_infinity_key_WHEN_load_der_public_key_THEN_special_exception(): + """ + Asserts that for the canonical "infinity" public key, + defined as one byte of 0s, + pyca raises a special exception type. + """ + # Given: Valid DER-encoded ASN.1 sequence representing the canonical "infinity" invalid public key + valid_alg_info, _ = get_valid_der_components() + # Canonical invalid point is 1 byte of 0s + invalid_point = BitString.fromOctetString(b"\x00") + seq = Sequence() + seq.setComponentByPosition(0, valid_alg_info) + seq.setComponentByPosition(1, invalid_point) + der_seq = der_encode(seq) + + # Then: raises ValueError + with pytest.raises(ValueError) as e: + # When: load_der_public_key + load_der_public_key(der_seq) + + # Then: exception is the infinity key exception and not the generic key exception + assert GENERIC_EXCEPTION_STRING not in str(e.value) + assert INF_EXCEPTION_STRING in str(e.value) + +def test_GIVEN_noncanonical_infinity_key_WHEN_load_der_public_key_THEN_generic_exception(): + """ + Asserts that for non-canonical "infinity" public key, + defined as >1 byte of 0s, + pyca raises the generic exception type. + + These are still invalid "infinity" public keys + because the encoded point is still 0, + but the exception message is different + than the one for the canonical key. + + This validates that the "infinity" exception is only raised + for the canonical infinity public key. + """ + # Given: Valid DER-encoded ASN.1 sequence representing a non-canonical "infinity" invalid public key + valid_alg_info, _ = get_valid_der_components() + # Noncanonical, but still invalid points are >=2 bytes of 0s + for i in range(2, 10): + invalid_point = BitString.fromOctetString(b"\x00" * i) + seq = Sequence() + seq.setComponentByPosition(0, valid_alg_info) + seq.setComponentByPosition(1, invalid_point) + der_seq = der_encode(seq) + + # Then: raises ValueError + with pytest.raises(ValueError) as e: + # When: load_der_public_key + load_der_public_key(der_seq) + + # Then: exception is the generic exception and not the infinity key exception + assert GENERIC_EXCEPTION_STRING in str(e.value) + assert INF_EXCEPTION_STRING not in str(e.value) + +def test_GIVEN_some_short_non_infinity_keys_WHEN_load_der_public_key_THEN_generic_exception(): + """ + Asserts that points from 0x01 - 0xFF also fail with a generic exception, + and not the "infinity" exception. + + This validates that the "infinity" exception + is not raised for other "short" public keys, + and is thus not a "short"/"decoding failure" exception. + """ + # Given: Valid DER-encoded ASN.1 sequence representing invalid public keys + valid_alg_info, _ = get_valid_der_components() + # Given: "short" invalid public keys from 0x01 - 0xFF + bytes_to_test = [bytes([num]) for num in range(1, 256)] + for bytes_under_test in bytes_to_test: + invalid_point = BitString.fromOctetString(bytes_under_test) + seq = Sequence() + seq.setComponentByPosition(0, valid_alg_info) + seq.setComponentByPosition(1, invalid_point) + der_seq = der_encode(seq) + + # Then: raises ValueError + with pytest.raises(ValueError) as e: + # When: load_der_public_key + load_der_public_key(der_seq) + + # Then: exception is the generic exception and not the infinity key exception + assert GENERIC_EXCEPTION_STRING in str(e.value) + assert INF_EXCEPTION_STRING not in str(e.value) diff --git a/AwsCryptographyPrimitives/runtimes/python/test/internaldafny/__init__.py b/AwsCryptographyPrimitives/runtimes/python/test/internaldafny/__init__.py new file mode 100644 index 000000000..f94fd12a2 --- /dev/null +++ b/AwsCryptographyPrimitives/runtimes/python/test/internaldafny/__init__.py @@ -0,0 +1,2 @@ +# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 diff --git a/AwsCryptographyPrimitives/runtimes/python/test/internaldafny/extern/ECDH.py b/AwsCryptographyPrimitives/runtimes/python/test/internaldafny/extern/ECDH.py new file mode 100644 index 000000000..76f1539ed --- /dev/null +++ b/AwsCryptographyPrimitives/runtimes/python/test/internaldafny/extern/ECDH.py @@ -0,0 +1,123 @@ +# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 +from aws_cryptography_primitives.internaldafny.extern.ECDH import ( + ECCAlgorithms, + ECCUtils as src_ECCUtils, +) + +from aws_cryptography_primitives.internaldafny.generated.ECDH import default__ + +CreateGetInfinityPublicKeyError = default__.CreateGetInfinityPublicKeyError +CreateGetInfinityPublicKeySuccess = default__.CreateGetInfinityPublicKeySuccess +CreateGetOutOfBoundsPublicKeyError = default__.CreateGetOutOfBoundsPublicKeyError +CreateGetOutOfBoundsPublicKeySuccess = default__.CreateGetOutOfBoundsPublicKeySuccess + +from cryptography.hazmat.primitives.asymmetric import ec +from cryptography.hazmat.primitives.serialization import (Encoding,PublicFormat) +import _dafny +from aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.errors import ( + AwsCryptographicPrimitivesError, + _smithy_error_to_dafny_error +) + +# Extend src extern with test utilities +class ECCUtils(src_ECCUtils): + + def GetInfinityPublicKey(dafny_eccAlgorithm): + maybe_ecc_algorithm = ECCAlgorithms.eccAlgorithm(dafny_eccAlgorithm) + if maybe_ecc_algorithm.is_Failure: + return CreateGetInfinityPublicKeyError( + maybe_ecc_algorithm.error + ) + + try: + # manually create the ASN.1 encoded public key + from pyasn1.codec.der.decoder import decode as der_decode + from pyasn1.codec.der.encoder import encode as der_encode + from pyasn1.type.univ import BitString, Sequence + + # generate a random public/private key to get valid alg_info + private_key = ec.generate_private_key( + maybe_ecc_algorithm.value.value + ) + public_key_der = private_key.public_key().public_bytes(Encoding.DER, PublicFormat.SubjectPublicKeyInfo) + + alg_info_seq, _ = der_decode(public_key_der, asn1Spec=Sequence()) + alg_info = alg_info_seq.getComponentByPosition(0) + + # inf point defined as 1 byte of 0s + point_at_infinity = BitString.fromOctetString(b'\x00') + + seq = Sequence() + seq.setComponentByPosition(0, alg_info) + seq.setComponentByPosition(1, point_at_infinity) + + return CreateGetInfinityPublicKeySuccess( + _dafny.Seq( + der_encode(seq) + ) + ) + except Exception as e: + return CreateGetInfinityPublicKeyError( + _smithy_error_to_dafny_error( + AwsCryptographicPrimitivesError( + message=str(e) + ) + ) + ) + + def GetOutOfBoundsPublicKey(dafny_eccAlgorithm): + maybe_ecc_algorithm = ECCAlgorithms.eccAlgorithm(dafny_eccAlgorithm) + if maybe_ecc_algorithm.is_Failure: + return CreateGetInfinityPublicKeyError( + maybe_ecc_algorithm.error + ) + + try: + curve = maybe_ecc_algorithm.value + + # Manually create the ASN.1 encoded public key + from pyasn1.codec.der.decoder import decode as der_decode + from pyasn1.codec.der.encoder import encode as der_encode + from pyasn1.type.univ import BitString, ObjectIdentifier, Sequence + + # generate a random public/private key to get valid alg_info + private_key = ec.generate_private_key( + maybe_ecc_algorithm.value.value + ) + public_key_der = private_key.public_key().public_bytes(Encoding.DER, PublicFormat.SubjectPublicKeyInfo) + + alg_info_seq, _ = der_decode(public_key_der, asn1Spec=Sequence()) + alg_info = alg_info_seq.getComponentByPosition(0) + + length = src_ECCUtils.CURVE_TO_ECC_SECRET_LENGTH_MAP[curve.name] + + # one possible out of bounds point + out_of_bounds_point = b'\x04' + (b'\xFF' * (2 * length)) + + point_at_infinity = BitString.fromOctetString(out_of_bounds_point) + + seq = Sequence() + seq.setComponentByPosition(0, alg_info) + seq.setComponentByPosition(1, point_at_infinity) + + return CreateGetOutOfBoundsPublicKeySuccess( + _dafny.Seq( + der_encode(seq) + ) + ) + except Exception as e: + return CreateGetOutOfBoundsPublicKeyError( + _smithy_error_to_dafny_error( + AwsCryptographicPrimitivesError( + message=str(e) + ) + ) + ) + +import aws_cryptography_primitives +# Export extended extern to the src extern. +# This will ONLY be exported if the test is loaded, +# which does not happen as part of regular operation. +aws_cryptography_primitives.internaldafny.extern.ECDH.ECCUtils = ECCUtils +aws_cryptography_primitives.internaldafny.generated.ECDH.ECCUtils = ECCUtils diff --git a/AwsCryptographyPrimitives/runtimes/python/test/internaldafny/extern/__init__.py b/AwsCryptographyPrimitives/runtimes/python/test/internaldafny/extern/__init__.py new file mode 100644 index 000000000..9d2c6e3d4 --- /dev/null +++ b/AwsCryptographyPrimitives/runtimes/python/test/internaldafny/extern/__init__.py @@ -0,0 +1,5 @@ +# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 +from . import ( + ECDH, +) \ No newline at end of file diff --git a/AwsCryptographyPrimitives/runtimes/python/test/internaldafny/test_dafny_wrapper.py b/AwsCryptographyPrimitives/runtimes/python/test/internaldafny/test_dafny_wrapper.py new file mode 100644 index 000000000..3d66f6366 --- /dev/null +++ b/AwsCryptographyPrimitives/runtimes/python/test/internaldafny/test_dafny_wrapper.py @@ -0,0 +1,22 @@ +# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 +""" +Wrapper file for executing Dafny tests from pytest. +This allows us to import modules required by Dafny-generated tests +before executing Dafny-generated tests. +pytest will find and execute the `test_dafny` method below, +which will execute the `internaldafny_test_executor.py` file in the `dafny` directory. +""" + +import sys + +internaldafny_dir = '/'.join(__file__.split("/")[:-1]) + +sys.path.append(internaldafny_dir + "/extern") +sys.path.append(internaldafny_dir + "/generated") + +from . import extern + + +def test_dafny(): + from .generated import __main__ diff --git a/AwsCryptographyPrimitives/runtimes/python/tox.ini b/AwsCryptographyPrimitives/runtimes/python/tox.ini new file mode 100644 index 000000000..929b2ed44 --- /dev/null +++ b/AwsCryptographyPrimitives/runtimes/python/tox.ini @@ -0,0 +1,87 @@ +[tox] +isolated_build = True +envlist = + py{311,312}-{dafnytests,functional} + +[testenv:base-command] +commands = poetry run pytest -l {posargs} + +[testenv] +skip_install = True +allowlist_externals = poetry +passenv = AWS_* +commands_pre = + poetry lock + poetry install --with test +commands = + dafnytests: {[testenv:base-command]commands} test/internaldafny -s -v + functional: {[testenv:base-command]commands} test/functional + +# Release tooling +[testenv:build] +basepython = python3 +skip_install = True +allowlist_externals = poetry +commands = + poetry install --no-root --with release + poetry build + +[testenv:release-base] +basepython = python3 +skip_install = True +allowlist_externals = poetry +comands_pre = + poetry install --no-root --with release +passenv = + # Intentionally omit TWINE_REPOSITORY_URL from the passenv list, + # as this overrides other ways of setting the repository and could + # unexpectedly result in releasing to the wrong repo + {[testenv]passenv} \ + TWINE_USERNAME \ + TWINE_PASSWORD +commands = + {[testenv:build]commands} + +[testenv:release-private] +basepython = python3 +skip_install = True +allowlist_externals = poetry +comands_pre = + poetry install --no-root --with release +passenv = + {[testenv:release-base]passenv} \ + TWINE_REPOSITORY_URL +setenv = + # Explicitly set the URL as the env variable value, which will cause us to + # throw an error if the variable is not set. Otherwise, omission of the + # env variable could cause us to unintentionally upload to the wrong repo + TWINE_REPOSITORY_URL = {env:TWINE_REPOSITORY_URL} +commands = + {[testenv:release-base]commands} + # Omitting an explicit repository will cause twine to use the repository + # specified in the environment variable + poetry run twine upload --skip-existing {toxinidir}/dist/* + +[testenv:test-release] +basepython = python3 +skip_install = True +allowlist_externals = poetry +comands_pre = + poetry install --no-root --with release +passenv = + {[testenv:release-base]passenv} +commands = + {[testenv:release-base]commands} + poetry run twine upload --skip-existing --repository testpypi {toxinidir}/dist/* + +[testenv:release] +basepython = python3 +skip_install = True +allowlist_externals = poetry +comands_pre = + poetry install --no-root --with release +passenv = + {[testenv:release-base]passenv} +commands = + {[testenv:release-base]commands} + poetry run twine upload --skip-existing --repository pypi {toxinidir}/dist/* diff --git a/AwsCryptographyPrimitives/test/TestECDH.dfy b/AwsCryptographyPrimitives/test/TestECDH.dfy index 2b4bf852c..054277231 100644 --- a/AwsCryptographyPrimitives/test/TestECDH.dfy +++ b/AwsCryptographyPrimitives/test/TestECDH.dfy @@ -128,10 +128,12 @@ module TestECDH { const INFINITY_POINT_ERR_MSG_JAVA := "encoded key spec not recognized: Point at infinity" const INFINITY_POINT_ERR_MSG_NET6 := "Point at infinity (Parameter 'q')" const INFINITY_POINT_ERR_MSG_NET48 := "Point at infinity\r\nParameter name: q" + const INFINITY_POINT_ERR_MSG_PYTHON := "Unable to load EC key" const OUT_OF_BOUNDS_ERR_MSG_JAVA := "encoded key spec not recognized: x value invalid for" const OUT_OF_BOUNDS_ERR_MSG_NET6 := "value invalid for Fp field element (Parameter 'x')" const OUT_OF_BOUNDS_ERR_MSG_NE48 := "value invalid for Fp field element\r\nParameter name: x" + const OUT_OF_BOUNDS_ERR_MSG_PYTHON := "Could not deserialize key data. The data may be in an incorrect format" // Rust does not provide a separate error message for infinity or out of bounds const BAD_X509_KEY_ERR_MSG_RUST := "Invalid X509 Public Key." @@ -300,7 +302,8 @@ module TestECDH { errMsg == BAD_X509_KEY_ERR_MSG_RUST || errMsg == INFINITY_POINT_ERR_MSG_JAVA || errMsg == INFINITY_POINT_ERR_MSG_NET6 || - errMsg == INFINITY_POINT_ERR_MSG_NET48 + errMsg == INFINITY_POINT_ERR_MSG_NET48 || + seq_contains(errMsg, INFINITY_POINT_ERR_MSG_PYTHON) ); } } @@ -349,7 +352,8 @@ module TestECDH { seq_contains(errMsg, OUT_OF_BOUNDS_ERR_MSG_JAVA) || errMsg == BAD_X509_KEY_ERR_MSG_RUST || errMsg == OUT_OF_BOUNDS_ERR_MSG_NET6 || - errMsg == OUT_OF_BOUNDS_ERR_MSG_NE48 + errMsg == OUT_OF_BOUNDS_ERR_MSG_NE48 || + seq_contains(errMsg, OUT_OF_BOUNDS_ERR_MSG_PYTHON) ); } } @@ -517,7 +521,8 @@ module TestECDH { errMsg == INFINITY_POINT_ERR_MSG_JAVA || errMsg == BAD_X509_KEY_ERR_MSG_RUST || errMsg == INFINITY_POINT_ERR_MSG_NET6 || - errMsg == INFINITY_POINT_ERR_MSG_NET48 + errMsg == INFINITY_POINT_ERR_MSG_NET48 || + seq_contains(errMsg, INFINITY_POINT_ERR_MSG_PYTHON) ); } } @@ -544,7 +549,8 @@ module TestECDH { seq_contains(errMsg, OUT_OF_BOUNDS_ERR_MSG_JAVA) || errMsg == BAD_X509_KEY_ERR_MSG_RUST || errMsg == OUT_OF_BOUNDS_ERR_MSG_NET6 || - errMsg == OUT_OF_BOUNDS_ERR_MSG_NE48 + errMsg == OUT_OF_BOUNDS_ERR_MSG_NE48 || + seq_contains(errMsg, OUT_OF_BOUNDS_ERR_MSG_PYTHON) ); } diff --git a/ComAmazonawsDynamodb/Makefile b/ComAmazonawsDynamodb/Makefile index d1aa246f2..8e4da8bf0 100644 --- a/ComAmazonawsDynamodb/Makefile +++ b/ComAmazonawsDynamodb/Makefile @@ -3,6 +3,8 @@ CORES=2 +ENABLE_EXTERN_PROCESSING=1 + include ../SharedMakefileV2.mk PROJECT_SERVICES := \ @@ -14,3 +16,19 @@ AWS_SDK_CMD := --aws-sdk STD_LIBRARY=StandardLibrary SMITHY_DEPS=model +# Constants for languages that drop extern names (Python, Go) + +TYPES_FILE_PATH=Model/ComAmazonawsDynamodbTypes.dfy +TYPES_FILE_WITH_EXTERN_STRING="module {:extern \"software.amazon.cryptography.services.dynamodb.internaldafny.types\" } ComAmazonawsDynamodbTypes" +TYPES_FILE_WITHOUT_EXTERN_STRING="module ComAmazonawsDynamodbTypes" + +INDEX_FILE_PATH=src/Index.dfy +INDEX_FILE_WITH_EXTERN_STRING="module {:extern \"software.amazon.cryptography.services.dynamodb.internaldafny\"} Com.Amazonaws.Dynamodb refines AbstractComAmazonawsDynamodbService {" +INDEX_FILE_WITHOUT_EXTERN_STRING="module Com.Amazonaws.Dynamodb refines AbstractComAmazonawsDynamodbService {" + +# Python + +PYTHON_MODULE_NAME=aws_cryptography_internal_dynamodb + +TRANSLATION_RECORD_PYTHON := \ + --translation-record ../StandardLibrary/runtimes/python/src/smithy_dafny_standard_library/internaldafny/generated/dafny_src-py.dtr diff --git a/ComAmazonawsDynamodb/codebuild/release-python/prod-release.yml b/ComAmazonawsDynamodb/codebuild/release-python/prod-release.yml new file mode 100644 index 000000000..a3f42787f --- /dev/null +++ b/ComAmazonawsDynamodb/codebuild/release-python/prod-release.yml @@ -0,0 +1,65 @@ +version: 0.2 + +env: + variables: + BRANCH: "main" + secrets-manager: + TWINE_USERNAME: PyPiAPIToken:username + TWINE_PASSWORD: PyPiAPIToken:password + +phases: + install: + commands: + - pip install "tox < 4.0" + - pip install --upgrade pip + runtime-versions: + python: latest + pre_build: + commands: + # Get Dafny + - export dafnyVersion=$(grep '^dafnyVersion=' project.properties | cut -d '=' -f 2) + - cd .. + - curl https://github.com/dafny-lang/dafny/releases/download/v$dafnyVersion/dafny-$dafnyVersion-x64-ubuntu-20.04.zip -L -o dafny.zip + - unzip -qq dafny.zip && rm dafny.zip + - export PATH="$PWD/dafny:$PATH" + # Switch back to the main directory + - cd aws-cryptographic-material-providers-library + # Assert that project version is the expected released version + - git checkout $COMMIT_ID + - FOUND_VERSION=$(sed -n 's/version = "\(.*\)"/\1/p' ComAmazonawsDynamodb/runtimes/python/pyproject.toml) + - | + if expr ${FOUND_VERSION} != ${VERSION}; then + echo "pyproject.toml version (${FOUND_VERSION}) does not match expected version (${VERSION}), stopping" + exit 1; + fi + - cd ComAmazonawsDynamodb + # Build Dafny test source code + - make transpile_only_test_python + build: + commands: + - cd runtimes/python/ + # Install poetry + # https://python-poetry.org/docs/#installing-manually + - pip install poetry + # Add test PyPI as a supplemental repo for installing previously published test packages + - poetry source add --priority=supplemental test https://test.pypi.org/simple/ + # Install project dependencies with release dependencies + - poetry install --with release + # Build whl/sdist, upload to PyPI + # TODO: When ready to prod release, uncomment this line + # tox -e release + +batch: + fast-fail: true + build-graph: + - identifier: release_to_staging + env: + image: aws/codebuild/standard:7.0 + - identifier: validate_staging_release + depend-on: + - release_to_staging + buildspec: ComAmazonawsDynamodb/codebuild/release-python/validate.yml + env: + variables: + PIP_INDEX_URL: https://pypi.python.org/simple/ + image: aws/codebuild/standard:7.0 diff --git a/ComAmazonawsDynamodb/codebuild/release-python/test-release.yml b/ComAmazonawsDynamodb/codebuild/release-python/test-release.yml new file mode 100644 index 000000000..3f8b44912 --- /dev/null +++ b/ComAmazonawsDynamodb/codebuild/release-python/test-release.yml @@ -0,0 +1,65 @@ +version: 0.2 + +env: + variables: + BRANCH: "main" + secrets-manager: + TWINE_USERNAME: TestPyPiAPIToken:username + TWINE_PASSWORD: TestPyPiAPIToken:password + +phases: + install: + commands: + - pip install "tox < 4.0" + - pip install --upgrade pip + runtime-versions: + python: latest + pre_build: + commands: + # Get Dafny + - export dafnyVersion=$(grep '^dafnyVersion=' project.properties | cut -d '=' -f 2) + - cd .. + - curl https://github.com/dafny-lang/dafny/releases/download/v$dafnyVersion/dafny-$dafnyVersion-x64-ubuntu-20.04.zip -L -o dafny.zip + - unzip -qq dafny.zip && rm dafny.zip + - export PATH="$PWD/dafny:$PATH" + # Switch back to the main directory + - cd aws-cryptographic-material-providers-library + # Assert that project version is the expected released version + - git checkout $COMMIT_ID + - FOUND_VERSION=$(sed -n 's/version = "\(.*\)"/\1/p' ComAmazonawsDynamodb/runtimes/python/pyproject.toml) + - | + if expr ${FOUND_VERSION} != ${VERSION}; then + echo "pyproject.toml version (${FOUND_VERSION}) does not match expected version (${VERSION}), stopping" + exit 1; + fi + - cd ComAmazonawsDynamodb + # Build Dafny test source code + - make transpile_only_test_python + build: + commands: + - cd runtimes/python/ + # Install poetry + # https://python-poetry.org/docs/#installing-manually + - pip install poetry + # Add test PyPI as a supplemental repo for installing previously published test packages + - poetry source add --priority=supplemental test https://test.pypi.org/simple/ + # Install project dependencies with release dependencies + - poetry install --with release + # Build whl/sdist, upload to test PyPI + - tox -e test-release + +batch: + fast-fail: true + build-graph: + - identifier: release_to_staging + env: + image: aws/codebuild/standard:7.0 + - identifier: validate_staging_release + depend-on: + - release_to_staging + buildspec: ComAmazonawsDynamodb/codebuild/release-python/validate.yml + env: + variables: + PIP_INDEX_URL: https://test.pypi.org/simple/ + PIP_EXTRA_INDEX_URL: https://pypi.python.org/simple/ + image: aws/codebuild/standard:7.0 diff --git a/ComAmazonawsDynamodb/codebuild/release-python/validate.yml b/ComAmazonawsDynamodb/codebuild/release-python/validate.yml new file mode 100644 index 000000000..c7095d85e --- /dev/null +++ b/ComAmazonawsDynamodb/codebuild/release-python/validate.yml @@ -0,0 +1,46 @@ +version: 0.2 + +# Validate that the released artifact is usable +# by installing it from PyPI +# then running tests from source against the published artifact. + +phases: + install: + commands: + - pip install "tox < 4.0" + runtime-versions: + python: latest + pre_build: + commands: + # Get Dafny + - export dafnyVersion=$(grep '^dafnyVersion=' project.properties | cut -d '=' -f 2) + - cd .. + - curl https://github.com/dafny-lang/dafny/releases/download/v$dafnyVersion/dafny-$dafnyVersion-x64-ubuntu-20.04.zip -L -o dafny.zip + - unzip -qq dafny.zip && rm dafny.zip + - export PATH="$PWD/dafny:$PATH" + # Switch back to the main directory + - cd aws-cryptographic-material-providers-library + # Install test dependencies + - pyenv install --skip-existing 3.11 + - pyenv local 3.11 + - pip install "tox < 4.0" + - pip install pytest + # Install the published artifact from PyPI. + # The tests will use the installed package, not the local code. + # The actual test code must be from local, since we don't publish tests. + - pip install aws-cryptography-internal-dynamodb==$VERSION + # Get CI Creds to be able to call DDB + - TMP_ROLE=$(aws sts assume-role --role-arn "arn:aws:iam::370957321024:role/GitHub-CI-MPL-Dafny-Role-us-west-2" --role-session-name "MPL-Python-Release") + - export TMP_ROLE + - export AWS_ACCESS_KEY_ID=$(echo "${TMP_ROLE}" | jq -r '.Credentials.AccessKeyId') + - export AWS_SECRET_ACCESS_KEY=$(echo "${TMP_ROLE}" | jq -r '.Credentials.SecretAccessKey') + - export AWS_SESSION_TOKEN=$(echo "${TMP_ROLE}" | jq -r '.Credentials.SessionToken') + - aws sts get-caller-identity + build: + commands: + - NUM_RETRIES=3 + - cd ComAmazonawsDynamodb + # Transpile code (for tests) + - make transpile_python + - cd runtimes/python + - python -m pytest test/ -s -v diff --git a/ComAmazonawsDynamodb/runtimes/python/.gitignore b/ComAmazonawsDynamodb/runtimes/python/.gitignore new file mode 100644 index 000000000..9cb72dcab --- /dev/null +++ b/ComAmazonawsDynamodb/runtimes/python/.gitignore @@ -0,0 +1,16 @@ +# Python build artifacts +__pycache__ +**/__pycache__ +*.pyc +src/**.egg-info/ +build +poetry.lock +**/poetry.lock +dist + +# Dafny-generated Python +**/internaldafny/generated/*.py + +# Python test artifacts +.tox +.pytest_cache diff --git a/ComAmazonawsDynamodb/runtimes/python/pyproject.toml b/ComAmazonawsDynamodb/runtimes/python/pyproject.toml new file mode 100644 index 000000000..9e36ffaba --- /dev/null +++ b/ComAmazonawsDynamodb/runtimes/python/pyproject.toml @@ -0,0 +1,38 @@ +[tool.poetry] +name = "aws-cryptography-internal-dynamodb" +version = "0.1.0" +description = "" +authors = ["AWS Crypto Tools "] +packages = [ + { include = "aws_cryptography_internal_dynamodb", from = "src" } +] +# Include generated internaldafny files in package distributions, +# even though they are not included in version control +include = ["**/internaldafny/generated/*.py"] + +[tool.poetry.dependencies] +python = "^3.11.0" +boto3 = "^1.28.38" +aws-cryptography-internal-standard-library = {path = "../../../StandardLibrary/runtimes/python"} + +# Package testing + +[tool.poetry.group.test] +optional = true + +[tool.poetry.group.test.dependencies] +pytest = "^7.4.0" + +# Package release + +[tool.poetry.group.release] +optional = true + +[tool.poetry.group.release.dependencies] +poetry = "1.8.3" +twine = "5.1.1" +wheel = "0.38.4" + +[build-system] +requires = ["poetry-core"] +build-backend = "poetry.core.masonry.api" diff --git a/ComAmazonawsDynamodb/runtimes/python/src/aws_cryptography_internal_dynamodb/__init__.py b/ComAmazonawsDynamodb/runtimes/python/src/aws_cryptography_internal_dynamodb/__init__.py new file mode 100644 index 000000000..b9427e19d --- /dev/null +++ b/ComAmazonawsDynamodb/runtimes/python/src/aws_cryptography_internal_dynamodb/__init__.py @@ -0,0 +1,8 @@ +# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 + +# Initialize generated Dafny +from .internaldafny.generated import module_ + +# Initialize externs +from .internaldafny import extern diff --git a/ComAmazonawsDynamodb/runtimes/python/src/aws_cryptography_internal_dynamodb/internaldafny/extern/Com_Amazonaws_Dynamodb.py b/ComAmazonawsDynamodb/runtimes/python/src/aws_cryptography_internal_dynamodb/internaldafny/extern/Com_Amazonaws_Dynamodb.py new file mode 100644 index 000000000..612bc5fa6 --- /dev/null +++ b/ComAmazonawsDynamodb/runtimes/python/src/aws_cryptography_internal_dynamodb/internaldafny/extern/Com_Amazonaws_Dynamodb.py @@ -0,0 +1,60 @@ +import boto3 +import _dafny + +from botocore.config import Config +from boto3.session import Session + +from smithy_dafny_standard_library.internaldafny.generated.Wrappers import Option_Some +from aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.shim import DynamoDBClientShim +from aws_cryptography_internal_dynamodb.internaldafny.generated.Com_Amazonaws_Dynamodb import * +import aws_cryptography_internal_dynamodb.internaldafny.generated.Com_Amazonaws_Dynamodb + + +# Persist this across calls; this doesn't change +available_aws_regions: list[str] = None + +def get_available_aws_regions(): + global available_aws_regions + if available_aws_regions is not None: + return available_aws_regions + available_aws_regions = Session().get_available_regions("dynamodb") + return available_aws_regions + +class default__(aws_cryptography_internal_dynamodb.internaldafny.generated.Com_Amazonaws_Dynamodb.default__): + @staticmethod + def DynamoDBClient(boto_client = None, region = None): + if boto_client is None: + if region is not None and region in get_available_aws_regions(): + boto_config = Config( + region_name=region + ) + boto_client = boto3.client("dynamodb", config=boto_config) + else: + # If no region is provided, + # boto_client will use the default region provided by boto3 + boto_client = boto3.client("dynamodb") + region = boto_client.meta.region_name + wrapped_client = DynamoDBClientShim(boto_client, region) + return Wrappers.Result_Success(wrapped_client) + + @staticmethod + def DDBClientForRegion(region: _dafny.Seq): + region_string = _dafny.string_of(region) + return default__.DynamoDBClient(region=region_string) + + @staticmethod + def RegionMatch(client, region): + # We should never be passing anything other than Shim as the 'client'. + # If this assertion fails, that indicates that there is something wrong with + # our code generation. + try: + assert isinstance(client, DynamoDBClientShim) + except AssertionError: + raise TypeError("Client provided to RegionMatch is not a DynamoDBClientShim: " + client) + + # Since client is a DynamoDBClientShim, we can reach into its _impl, which is a boto3 client, + # then into the client's .meta.region_name attribute + client_region_name = client._impl.meta.region_name + return Option_Some(region.VerbatimString(False) == client_region_name) + +aws_cryptography_internal_dynamodb.internaldafny.generated.Com_Amazonaws_Dynamodb.default__ = default__ diff --git a/ComAmazonawsDynamodb/runtimes/python/src/aws_cryptography_internal_dynamodb/internaldafny/extern/__init__.py b/ComAmazonawsDynamodb/runtimes/python/src/aws_cryptography_internal_dynamodb/internaldafny/extern/__init__.py new file mode 100644 index 000000000..07f158115 --- /dev/null +++ b/ComAmazonawsDynamodb/runtimes/python/src/aws_cryptography_internal_dynamodb/internaldafny/extern/__init__.py @@ -0,0 +1,3 @@ +from . import ( + Com_Amazonaws_Dynamodb, +) \ No newline at end of file diff --git a/ComAmazonawsDynamodb/runtimes/python/src/aws_cryptography_internal_dynamodb/internaldafny/generated/dafny_src-py.dtr b/ComAmazonawsDynamodb/runtimes/python/src/aws_cryptography_internal_dynamodb/internaldafny/generated/dafny_src-py.dtr new file mode 100644 index 000000000..c512ff4c0 --- /dev/null +++ b/ComAmazonawsDynamodb/runtimes/python/src/aws_cryptography_internal_dynamodb/internaldafny/generated/dafny_src-py.dtr @@ -0,0 +1,14 @@ +file_format_version = "1.0" +dafny_version = "4.8.0.0" +[options_by_module.ComAmazonawsDynamodbTypes] +legacy-module-names = false +python-module-name = "aws_cryptography_internal_dynamodb.internaldafny.generated" +[options_by_module.AbstractComAmazonawsDynamodbService] +legacy-module-names = false +python-module-name = "aws_cryptography_internal_dynamodb.internaldafny.generated" +[options_by_module.AbstractComAmazonawsDynamodbOperations] +legacy-module-names = false +python-module-name = "aws_cryptography_internal_dynamodb.internaldafny.generated" +[options_by_module."Com.Amazonaws.Dynamodb"] +legacy-module-names = false +python-module-name = "aws_cryptography_internal_dynamodb.internaldafny.generated" diff --git a/ComAmazonawsDynamodb/runtimes/python/src/aws_cryptography_internal_dynamodb/smithygenerated/com_amazonaws_dynamodb/__init__.py b/ComAmazonawsDynamodb/runtimes/python/src/aws_cryptography_internal_dynamodb/smithygenerated/com_amazonaws_dynamodb/__init__.py new file mode 100644 index 000000000..09be6133b --- /dev/null +++ b/ComAmazonawsDynamodb/runtimes/python/src/aws_cryptography_internal_dynamodb/smithygenerated/com_amazonaws_dynamodb/__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/ComAmazonawsDynamodb/runtimes/python/src/aws_cryptography_internal_dynamodb/smithygenerated/com_amazonaws_dynamodb/aws_sdk_to_dafny.py b/ComAmazonawsDynamodb/runtimes/python/src/aws_cryptography_internal_dynamodb/smithygenerated/com_amazonaws_dynamodb/aws_sdk_to_dafny.py new file mode 100644 index 000000000..1b27a3c35 --- /dev/null +++ b/ComAmazonawsDynamodb/runtimes/python/src/aws_cryptography_internal_dynamodb/smithygenerated/com_amazonaws_dynamodb/aws_sdk_to_dafny.py @@ -0,0 +1,11279 @@ +# 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 _dafny import Map, Seq +from aws_cryptography_internal_dynamodb.internaldafny.generated.ComAmazonawsDynamodbTypes import ( + ArchivalSummary_ArchivalSummary as DafnyArchivalSummary, + AttributeAction_ADD, + AttributeAction_DELETE, + AttributeAction_PUT, + AttributeDefinition_AttributeDefinition as DafnyAttributeDefinition, + AttributeValueUpdate_AttributeValueUpdate as DafnyAttributeValueUpdate, + AttributeValue_B, + AttributeValue_BOOL, + AttributeValue_BS, + AttributeValue_L, + AttributeValue_M, + AttributeValue_N, + AttributeValue_NS, + AttributeValue_NULL, + AttributeValue_S, + AttributeValue_SS, + AutoScalingPolicyDescription_AutoScalingPolicyDescription as DafnyAutoScalingPolicyDescription, + AutoScalingPolicyUpdate_AutoScalingPolicyUpdate as DafnyAutoScalingPolicyUpdate, + AutoScalingSettingsDescription_AutoScalingSettingsDescription as DafnyAutoScalingSettingsDescription, + AutoScalingSettingsUpdate_AutoScalingSettingsUpdate as DafnyAutoScalingSettingsUpdate, + AutoScalingTargetTrackingScalingPolicyConfigurationDescription_AutoScalingTargetTrackingScalingPolicyConfigurationDescription as DafnyAutoScalingTargetTrackingScalingPolicyConfigurationDescription, + AutoScalingTargetTrackingScalingPolicyConfigurationUpdate_AutoScalingTargetTrackingScalingPolicyConfigurationUpdate as DafnyAutoScalingTargetTrackingScalingPolicyConfigurationUpdate, + BackupDescription_BackupDescription as DafnyBackupDescription, + BackupDetails_BackupDetails as DafnyBackupDetails, + BackupStatus_AVAILABLE, + BackupStatus_CREATING, + BackupStatus_DELETED, + BackupSummary_BackupSummary as DafnyBackupSummary, + BackupTypeFilter_ALL, + BackupTypeFilter_AWS__BACKUP, + BackupTypeFilter_SYSTEM, + BackupTypeFilter_USER, + BackupType_AWS__BACKUP, + BackupType_SYSTEM, + BackupType_USER, + BatchExecuteStatementInput_BatchExecuteStatementInput as DafnyBatchExecuteStatementInput, + BatchExecuteStatementOutput_BatchExecuteStatementOutput as DafnyBatchExecuteStatementOutput, + BatchGetItemInput_BatchGetItemInput as DafnyBatchGetItemInput, + BatchGetItemOutput_BatchGetItemOutput as DafnyBatchGetItemOutput, + BatchStatementErrorCodeEnum_AccessDenied, + BatchStatementErrorCodeEnum_ConditionalCheckFailed, + BatchStatementErrorCodeEnum_DuplicateItem, + BatchStatementErrorCodeEnum_InternalServerError, + BatchStatementErrorCodeEnum_ItemCollectionSizeLimitExceeded, + BatchStatementErrorCodeEnum_ProvisionedThroughputExceeded, + BatchStatementErrorCodeEnum_RequestLimitExceeded, + BatchStatementErrorCodeEnum_ResourceNotFound, + BatchStatementErrorCodeEnum_ThrottlingError, + BatchStatementErrorCodeEnum_TransactionConflict, + BatchStatementErrorCodeEnum_ValidationError, + BatchStatementError_BatchStatementError as DafnyBatchStatementError, + BatchStatementRequest_BatchStatementRequest as DafnyBatchStatementRequest, + BatchStatementResponse_BatchStatementResponse as DafnyBatchStatementResponse, + BatchWriteItemInput_BatchWriteItemInput as DafnyBatchWriteItemInput, + BatchWriteItemOutput_BatchWriteItemOutput as DafnyBatchWriteItemOutput, + BillingModeSummary_BillingModeSummary as DafnyBillingModeSummary, + BillingMode_PAY__PER__REQUEST, + BillingMode_PROVISIONED, + CancellationReason_CancellationReason as DafnyCancellationReason, + Capacity_Capacity as DafnyCapacity, + ComparisonOperator_BEGINS__WITH, + ComparisonOperator_BETWEEN, + ComparisonOperator_CONTAINS, + ComparisonOperator_EQ, + ComparisonOperator_GE, + ComparisonOperator_GT, + ComparisonOperator_IN, + ComparisonOperator_LE, + ComparisonOperator_LT, + ComparisonOperator_NE, + ComparisonOperator_NOT__CONTAINS, + ComparisonOperator_NOT__NULL, + ComparisonOperator_NULL, + ConditionCheck_ConditionCheck as DafnyConditionCheck, + Condition_Condition as DafnyCondition, + ConditionalOperator_AND, + ConditionalOperator_OR, + ConsumedCapacity_ConsumedCapacity as DafnyConsumedCapacity, + ContinuousBackupsDescription_ContinuousBackupsDescription as DafnyContinuousBackupsDescription, + ContinuousBackupsStatus_DISABLED, + ContinuousBackupsStatus_ENABLED, + ContributorInsightsAction_DISABLE, + ContributorInsightsAction_ENABLE, + ContributorInsightsStatus_DISABLED, + ContributorInsightsStatus_DISABLING, + ContributorInsightsStatus_ENABLED, + ContributorInsightsStatus_ENABLING, + ContributorInsightsStatus_FAILED, + ContributorInsightsSummary_ContributorInsightsSummary as DafnyContributorInsightsSummary, + CreateBackupInput_CreateBackupInput as DafnyCreateBackupInput, + CreateBackupOutput_CreateBackupOutput as DafnyCreateBackupOutput, + CreateGlobalSecondaryIndexAction_CreateGlobalSecondaryIndexAction as DafnyCreateGlobalSecondaryIndexAction, + CreateGlobalTableInput_CreateGlobalTableInput as DafnyCreateGlobalTableInput, + CreateGlobalTableOutput_CreateGlobalTableOutput as DafnyCreateGlobalTableOutput, + CreateReplicaAction_CreateReplicaAction as DafnyCreateReplicaAction, + CreateReplicationGroupMemberAction_CreateReplicationGroupMemberAction as DafnyCreateReplicationGroupMemberAction, + CreateTableInput_CreateTableInput as DafnyCreateTableInput, + CreateTableOutput_CreateTableOutput as DafnyCreateTableOutput, + CsvOptions_CsvOptions as DafnyCsvOptions, + DeleteBackupInput_DeleteBackupInput as DafnyDeleteBackupInput, + DeleteBackupOutput_DeleteBackupOutput as DafnyDeleteBackupOutput, + DeleteGlobalSecondaryIndexAction_DeleteGlobalSecondaryIndexAction as DafnyDeleteGlobalSecondaryIndexAction, + DeleteItemInput_DeleteItemInput as DafnyDeleteItemInput, + DeleteItemOutput_DeleteItemOutput as DafnyDeleteItemOutput, + DeleteReplicaAction_DeleteReplicaAction as DafnyDeleteReplicaAction, + DeleteReplicationGroupMemberAction_DeleteReplicationGroupMemberAction as DafnyDeleteReplicationGroupMemberAction, + DeleteRequest_DeleteRequest as DafnyDeleteRequest, + DeleteTableInput_DeleteTableInput as DafnyDeleteTableInput, + DeleteTableOutput_DeleteTableOutput as DafnyDeleteTableOutput, + Delete_Delete as DafnyDelete, + DescribeBackupInput_DescribeBackupInput as DafnyDescribeBackupInput, + DescribeBackupOutput_DescribeBackupOutput as DafnyDescribeBackupOutput, + DescribeContinuousBackupsInput_DescribeContinuousBackupsInput as DafnyDescribeContinuousBackupsInput, + DescribeContinuousBackupsOutput_DescribeContinuousBackupsOutput as DafnyDescribeContinuousBackupsOutput, + DescribeContributorInsightsInput_DescribeContributorInsightsInput as DafnyDescribeContributorInsightsInput, + DescribeContributorInsightsOutput_DescribeContributorInsightsOutput as DafnyDescribeContributorInsightsOutput, + DescribeEndpointsRequest_DescribeEndpointsRequest as DafnyDescribeEndpointsRequest, + DescribeEndpointsResponse_DescribeEndpointsResponse as DafnyDescribeEndpointsResponse, + DescribeExportInput_DescribeExportInput as DafnyDescribeExportInput, + DescribeExportOutput_DescribeExportOutput as DafnyDescribeExportOutput, + DescribeGlobalTableInput_DescribeGlobalTableInput as DafnyDescribeGlobalTableInput, + DescribeGlobalTableOutput_DescribeGlobalTableOutput as DafnyDescribeGlobalTableOutput, + DescribeGlobalTableSettingsInput_DescribeGlobalTableSettingsInput as DafnyDescribeGlobalTableSettingsInput, + DescribeGlobalTableSettingsOutput_DescribeGlobalTableSettingsOutput as DafnyDescribeGlobalTableSettingsOutput, + DescribeImportInput_DescribeImportInput as DafnyDescribeImportInput, + DescribeImportOutput_DescribeImportOutput as DafnyDescribeImportOutput, + DescribeKinesisStreamingDestinationInput_DescribeKinesisStreamingDestinationInput as DafnyDescribeKinesisStreamingDestinationInput, + DescribeKinesisStreamingDestinationOutput_DescribeKinesisStreamingDestinationOutput as DafnyDescribeKinesisStreamingDestinationOutput, + DescribeLimitsInput_DescribeLimitsInput as DafnyDescribeLimitsInput, + DescribeLimitsOutput_DescribeLimitsOutput as DafnyDescribeLimitsOutput, + DescribeTableInput_DescribeTableInput as DafnyDescribeTableInput, + DescribeTableOutput_DescribeTableOutput as DafnyDescribeTableOutput, + DescribeTableReplicaAutoScalingInput_DescribeTableReplicaAutoScalingInput as DafnyDescribeTableReplicaAutoScalingInput, + DescribeTableReplicaAutoScalingOutput_DescribeTableReplicaAutoScalingOutput as DafnyDescribeTableReplicaAutoScalingOutput, + DescribeTimeToLiveInput_DescribeTimeToLiveInput as DafnyDescribeTimeToLiveInput, + DescribeTimeToLiveOutput_DescribeTimeToLiveOutput as DafnyDescribeTimeToLiveOutput, + DestinationStatus_ACTIVE, + DestinationStatus_DISABLED, + DestinationStatus_DISABLING, + DestinationStatus_ENABLE__FAILED, + DestinationStatus_ENABLING, + DisableKinesisStreamingDestinationInput_DisableKinesisStreamingDestinationInput as DafnyDisableKinesisStreamingDestinationInput, + DisableKinesisStreamingDestinationOutput_DisableKinesisStreamingDestinationOutput as DafnyDisableKinesisStreamingDestinationOutput, + EnableKinesisStreamingDestinationInput_EnableKinesisStreamingDestinationInput as DafnyEnableKinesisStreamingDestinationInput, + EnableKinesisStreamingDestinationOutput_EnableKinesisStreamingDestinationOutput as DafnyEnableKinesisStreamingDestinationOutput, + Endpoint_Endpoint as DafnyEndpoint, + Error_BackupInUseException, + Error_BackupNotFoundException, + Error_ConditionalCheckFailedException, + Error_ContinuousBackupsUnavailableException, + Error_DuplicateItemException, + Error_ExportConflictException, + Error_ExportNotFoundException, + Error_GlobalTableAlreadyExistsException, + Error_GlobalTableNotFoundException, + Error_IdempotentParameterMismatchException, + Error_ImportConflictException, + Error_ImportNotFoundException, + Error_IndexNotFoundException, + Error_InternalServerError, + Error_InvalidEndpointException, + Error_InvalidExportTimeException, + Error_InvalidRestoreTimeException, + Error_ItemCollectionSizeLimitExceededException, + Error_LimitExceededException, + Error_PointInTimeRecoveryUnavailableException, + Error_ProvisionedThroughputExceededException, + Error_ReplicaAlreadyExistsException, + Error_ReplicaNotFoundException, + Error_RequestLimitExceeded, + Error_ResourceInUseException, + Error_ResourceNotFoundException, + Error_TableAlreadyExistsException, + Error_TableInUseException, + Error_TableNotFoundException, + Error_TransactionCanceledException, + Error_TransactionConflictException, + Error_TransactionInProgressException, + ExecuteStatementInput_ExecuteStatementInput as DafnyExecuteStatementInput, + ExecuteStatementOutput_ExecuteStatementOutput as DafnyExecuteStatementOutput, + ExecuteTransactionInput_ExecuteTransactionInput as DafnyExecuteTransactionInput, + ExecuteTransactionOutput_ExecuteTransactionOutput as DafnyExecuteTransactionOutput, + ExpectedAttributeValue_ExpectedAttributeValue as DafnyExpectedAttributeValue, + ExportDescription_ExportDescription as DafnyExportDescription, + ExportFormat_DYNAMODB__JSON, + ExportFormat_ION, + ExportStatus_COMPLETED, + ExportStatus_FAILED, + ExportStatus_IN__PROGRESS, + ExportSummary_ExportSummary as DafnyExportSummary, + ExportTableToPointInTimeInput_ExportTableToPointInTimeInput as DafnyExportTableToPointInTimeInput, + ExportTableToPointInTimeOutput_ExportTableToPointInTimeOutput as DafnyExportTableToPointInTimeOutput, + FailureException_FailureException as DafnyFailureException, + GetItemInput_GetItemInput as DafnyGetItemInput, + GetItemOutput_GetItemOutput as DafnyGetItemOutput, + Get_Get as DafnyGet, + GlobalSecondaryIndexAutoScalingUpdate_GlobalSecondaryIndexAutoScalingUpdate as DafnyGlobalSecondaryIndexAutoScalingUpdate, + GlobalSecondaryIndexDescription_GlobalSecondaryIndexDescription as DafnyGlobalSecondaryIndexDescription, + GlobalSecondaryIndexInfo_GlobalSecondaryIndexInfo as DafnyGlobalSecondaryIndexInfo, + GlobalSecondaryIndexUpdate_GlobalSecondaryIndexUpdate as DafnyGlobalSecondaryIndexUpdate, + GlobalSecondaryIndex_GlobalSecondaryIndex as DafnyGlobalSecondaryIndex, + GlobalTableDescription_GlobalTableDescription as DafnyGlobalTableDescription, + GlobalTableGlobalSecondaryIndexSettingsUpdate_GlobalTableGlobalSecondaryIndexSettingsUpdate as DafnyGlobalTableGlobalSecondaryIndexSettingsUpdate, + GlobalTableStatus_ACTIVE, + GlobalTableStatus_CREATING, + GlobalTableStatus_DELETING, + GlobalTableStatus_UPDATING, + GlobalTable_GlobalTable as DafnyGlobalTable, + ImportStatus_CANCELLED, + ImportStatus_CANCELLING, + ImportStatus_COMPLETED, + ImportStatus_FAILED, + ImportStatus_IN__PROGRESS, + ImportSummary_ImportSummary as DafnyImportSummary, + ImportTableDescription_ImportTableDescription as DafnyImportTableDescription, + ImportTableInput_ImportTableInput as DafnyImportTableInput, + ImportTableOutput_ImportTableOutput as DafnyImportTableOutput, + IndexStatus_ACTIVE, + IndexStatus_CREATING, + IndexStatus_DELETING, + IndexStatus_UPDATING, + InputCompressionType_GZIP, + InputCompressionType_NONE, + InputCompressionType_ZSTD, + InputFormatOptions_InputFormatOptions as DafnyInputFormatOptions, + InputFormat_CSV, + InputFormat_DYNAMODB__JSON, + InputFormat_ION, + ItemCollectionMetrics_ItemCollectionMetrics as DafnyItemCollectionMetrics, + ItemResponse_ItemResponse as DafnyItemResponse, + KeySchemaElement_KeySchemaElement as DafnyKeySchemaElement, + KeyType_HASH, + KeyType_RANGE, + KeysAndAttributes_KeysAndAttributes as DafnyKeysAndAttributes, + KinesisDataStreamDestination_KinesisDataStreamDestination as DafnyKinesisDataStreamDestination, + ListBackupsInput_ListBackupsInput as DafnyListBackupsInput, + ListBackupsOutput_ListBackupsOutput as DafnyListBackupsOutput, + ListContributorInsightsInput_ListContributorInsightsInput as DafnyListContributorInsightsInput, + ListContributorInsightsOutput_ListContributorInsightsOutput as DafnyListContributorInsightsOutput, + ListExportsInput_ListExportsInput as DafnyListExportsInput, + ListExportsOutput_ListExportsOutput as DafnyListExportsOutput, + ListGlobalTablesInput_ListGlobalTablesInput as DafnyListGlobalTablesInput, + ListGlobalTablesOutput_ListGlobalTablesOutput as DafnyListGlobalTablesOutput, + ListImportsInput_ListImportsInput as DafnyListImportsInput, + ListImportsOutput_ListImportsOutput as DafnyListImportsOutput, + ListTablesInput_ListTablesInput as DafnyListTablesInput, + ListTablesOutput_ListTablesOutput as DafnyListTablesOutput, + ListTagsOfResourceInput_ListTagsOfResourceInput as DafnyListTagsOfResourceInput, + ListTagsOfResourceOutput_ListTagsOfResourceOutput as DafnyListTagsOfResourceOutput, + LocalSecondaryIndexDescription_LocalSecondaryIndexDescription as DafnyLocalSecondaryIndexDescription, + LocalSecondaryIndexInfo_LocalSecondaryIndexInfo as DafnyLocalSecondaryIndexInfo, + LocalSecondaryIndex_LocalSecondaryIndex as DafnyLocalSecondaryIndex, + ParameterizedStatement_ParameterizedStatement as DafnyParameterizedStatement, + PointInTimeRecoveryDescription_PointInTimeRecoveryDescription as DafnyPointInTimeRecoveryDescription, + PointInTimeRecoverySpecification_PointInTimeRecoverySpecification as DafnyPointInTimeRecoverySpecification, + PointInTimeRecoveryStatus_DISABLED, + PointInTimeRecoveryStatus_ENABLED, + ProjectionType_ALL, + ProjectionType_INCLUDE, + ProjectionType_KEYS__ONLY, + Projection_Projection as DafnyProjection, + ProvisionedThroughputDescription_ProvisionedThroughputDescription as DafnyProvisionedThroughputDescription, + ProvisionedThroughputOverride_ProvisionedThroughputOverride as DafnyProvisionedThroughputOverride, + ProvisionedThroughput_ProvisionedThroughput as DafnyProvisionedThroughput, + PutItemInput_PutItemInput as DafnyPutItemInput, + PutItemOutput_PutItemOutput as DafnyPutItemOutput, + PutRequest_PutRequest as DafnyPutRequest, + Put_Put as DafnyPut, + QueryInput_QueryInput as DafnyQueryInput, + QueryOutput_QueryOutput as DafnyQueryOutput, + ReplicaAutoScalingDescription_ReplicaAutoScalingDescription as DafnyReplicaAutoScalingDescription, + ReplicaAutoScalingUpdate_ReplicaAutoScalingUpdate as DafnyReplicaAutoScalingUpdate, + ReplicaDescription_ReplicaDescription as DafnyReplicaDescription, + ReplicaGlobalSecondaryIndexAutoScalingDescription_ReplicaGlobalSecondaryIndexAutoScalingDescription as DafnyReplicaGlobalSecondaryIndexAutoScalingDescription, + ReplicaGlobalSecondaryIndexAutoScalingUpdate_ReplicaGlobalSecondaryIndexAutoScalingUpdate as DafnyReplicaGlobalSecondaryIndexAutoScalingUpdate, + ReplicaGlobalSecondaryIndexDescription_ReplicaGlobalSecondaryIndexDescription as DafnyReplicaGlobalSecondaryIndexDescription, + ReplicaGlobalSecondaryIndexSettingsDescription_ReplicaGlobalSecondaryIndexSettingsDescription as DafnyReplicaGlobalSecondaryIndexSettingsDescription, + ReplicaGlobalSecondaryIndexSettingsUpdate_ReplicaGlobalSecondaryIndexSettingsUpdate as DafnyReplicaGlobalSecondaryIndexSettingsUpdate, + ReplicaGlobalSecondaryIndex_ReplicaGlobalSecondaryIndex as DafnyReplicaGlobalSecondaryIndex, + ReplicaSettingsDescription_ReplicaSettingsDescription as DafnyReplicaSettingsDescription, + ReplicaSettingsUpdate_ReplicaSettingsUpdate as DafnyReplicaSettingsUpdate, + ReplicaStatus_ACTIVE, + ReplicaStatus_CREATING, + ReplicaStatus_CREATION__FAILED, + ReplicaStatus_DELETING, + ReplicaStatus_INACCESSIBLE__ENCRYPTION__CREDENTIALS, + ReplicaStatus_REGION__DISABLED, + ReplicaStatus_UPDATING, + ReplicaUpdate_ReplicaUpdate as DafnyReplicaUpdate, + Replica_Replica as DafnyReplica, + ReplicationGroupUpdate_ReplicationGroupUpdate as DafnyReplicationGroupUpdate, + RestoreSummary_RestoreSummary as DafnyRestoreSummary, + RestoreTableFromBackupInput_RestoreTableFromBackupInput as DafnyRestoreTableFromBackupInput, + RestoreTableFromBackupOutput_RestoreTableFromBackupOutput as DafnyRestoreTableFromBackupOutput, + RestoreTableToPointInTimeInput_RestoreTableToPointInTimeInput as DafnyRestoreTableToPointInTimeInput, + RestoreTableToPointInTimeOutput_RestoreTableToPointInTimeOutput as DafnyRestoreTableToPointInTimeOutput, + ReturnConsumedCapacity_INDEXES, + ReturnConsumedCapacity_NONE, + ReturnConsumedCapacity_TOTAL, + ReturnItemCollectionMetrics_NONE, + ReturnItemCollectionMetrics_SIZE, + ReturnValue_ALL__NEW, + ReturnValue_ALL__OLD, + ReturnValue_NONE, + ReturnValue_UPDATED__NEW, + ReturnValue_UPDATED__OLD, + ReturnValuesOnConditionCheckFailure_ALL__OLD, + ReturnValuesOnConditionCheckFailure_NONE, + S3BucketSource_S3BucketSource as DafnyS3BucketSource, + S3SseAlgorithm_AES256, + S3SseAlgorithm_KMS, + SSEDescription_SSEDescription as DafnySSEDescription, + SSESpecification_SSESpecification as DafnySSESpecification, + SSEStatus_DISABLED, + SSEStatus_DISABLING, + SSEStatus_ENABLED, + SSEStatus_ENABLING, + SSEStatus_UPDATING, + SSEType_AES256, + SSEType_KMS, + ScalarAttributeType_B, + ScalarAttributeType_N, + ScalarAttributeType_S, + ScanInput_ScanInput as DafnyScanInput, + ScanOutput_ScanOutput as DafnyScanOutput, + Select_ALL__ATTRIBUTES, + Select_ALL__PROJECTED__ATTRIBUTES, + Select_COUNT, + Select_SPECIFIC__ATTRIBUTES, + SourceTableDetails_SourceTableDetails as DafnySourceTableDetails, + SourceTableFeatureDetails_SourceTableFeatureDetails as DafnySourceTableFeatureDetails, + StreamSpecification_StreamSpecification as DafnyStreamSpecification, + StreamViewType_KEYS__ONLY, + StreamViewType_NEW__AND__OLD__IMAGES, + StreamViewType_NEW__IMAGE, + StreamViewType_OLD__IMAGE, + TableAutoScalingDescription_TableAutoScalingDescription as DafnyTableAutoScalingDescription, + TableClassSummary_TableClassSummary as DafnyTableClassSummary, + TableClass_STANDARD, + TableClass_STANDARD__INFREQUENT__ACCESS, + TableCreationParameters_TableCreationParameters as DafnyTableCreationParameters, + TableDescription_TableDescription as DafnyTableDescription, + TableStatus_ACTIVE, + TableStatus_ARCHIVED, + TableStatus_ARCHIVING, + TableStatus_CREATING, + TableStatus_DELETING, + TableStatus_INACCESSIBLE__ENCRYPTION__CREDENTIALS, + TableStatus_UPDATING, + TagResourceInput_TagResourceInput as DafnyTagResourceInput, + Tag_Tag as DafnyTag, + TimeToLiveDescription_TimeToLiveDescription as DafnyTimeToLiveDescription, + TimeToLiveSpecification_TimeToLiveSpecification as DafnyTimeToLiveSpecification, + TimeToLiveStatus_DISABLED, + TimeToLiveStatus_DISABLING, + TimeToLiveStatus_ENABLED, + TimeToLiveStatus_ENABLING, + TransactGetItem_TransactGetItem as DafnyTransactGetItem, + TransactGetItemsInput_TransactGetItemsInput as DafnyTransactGetItemsInput, + TransactGetItemsOutput_TransactGetItemsOutput as DafnyTransactGetItemsOutput, + TransactWriteItem_TransactWriteItem as DafnyTransactWriteItem, + TransactWriteItemsInput_TransactWriteItemsInput as DafnyTransactWriteItemsInput, + TransactWriteItemsOutput_TransactWriteItemsOutput as DafnyTransactWriteItemsOutput, + UntagResourceInput_UntagResourceInput as DafnyUntagResourceInput, + UpdateContinuousBackupsInput_UpdateContinuousBackupsInput as DafnyUpdateContinuousBackupsInput, + UpdateContinuousBackupsOutput_UpdateContinuousBackupsOutput as DafnyUpdateContinuousBackupsOutput, + UpdateContributorInsightsInput_UpdateContributorInsightsInput as DafnyUpdateContributorInsightsInput, + UpdateContributorInsightsOutput_UpdateContributorInsightsOutput as DafnyUpdateContributorInsightsOutput, + UpdateGlobalSecondaryIndexAction_UpdateGlobalSecondaryIndexAction as DafnyUpdateGlobalSecondaryIndexAction, + UpdateGlobalTableInput_UpdateGlobalTableInput as DafnyUpdateGlobalTableInput, + UpdateGlobalTableOutput_UpdateGlobalTableOutput as DafnyUpdateGlobalTableOutput, + UpdateGlobalTableSettingsInput_UpdateGlobalTableSettingsInput as DafnyUpdateGlobalTableSettingsInput, + UpdateGlobalTableSettingsOutput_UpdateGlobalTableSettingsOutput as DafnyUpdateGlobalTableSettingsOutput, + UpdateItemInput_UpdateItemInput as DafnyUpdateItemInput, + UpdateItemOutput_UpdateItemOutput as DafnyUpdateItemOutput, + UpdateReplicationGroupMemberAction_UpdateReplicationGroupMemberAction as DafnyUpdateReplicationGroupMemberAction, + UpdateTableInput_UpdateTableInput as DafnyUpdateTableInput, + UpdateTableOutput_UpdateTableOutput as DafnyUpdateTableOutput, + UpdateTableReplicaAutoScalingInput_UpdateTableReplicaAutoScalingInput as DafnyUpdateTableReplicaAutoScalingInput, + UpdateTableReplicaAutoScalingOutput_UpdateTableReplicaAutoScalingOutput as DafnyUpdateTableReplicaAutoScalingOutput, + UpdateTimeToLiveInput_UpdateTimeToLiveInput as DafnyUpdateTimeToLiveInput, + UpdateTimeToLiveOutput_UpdateTimeToLiveOutput as DafnyUpdateTimeToLiveOutput, + Update_Update as DafnyUpdate, + WriteRequest_WriteRequest as DafnyWriteRequest, +) +import aws_cryptography_internal_dynamodb.internaldafny.generated.module_ +import aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny +from smithy_dafny_standard_library.internaldafny.generated.Wrappers import ( + Option_None, + Option_Some, +) + + +def com_amazonaws_dynamodb_BackupInUseException(native_input): + return Error_BackupInUseException( + message=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Error"]["Message"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_dynamodb_BackupNotFoundException(native_input): + return Error_BackupNotFoundException( + message=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Error"]["Message"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_dynamodb_ConditionalCheckFailedException(native_input): + return Error_ConditionalCheckFailedException( + message=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Error"]["Message"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_dynamodb_ContinuousBackupsUnavailableException(native_input): + return Error_ContinuousBackupsUnavailableException( + message=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Error"]["Message"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_dynamodb_DuplicateItemException(native_input): + return Error_DuplicateItemException( + message=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Error"]["Message"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_dynamodb_ExportConflictException(native_input): + return Error_ExportConflictException( + message=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Error"]["Message"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_dynamodb_ExportNotFoundException(native_input): + return Error_ExportNotFoundException( + message=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Error"]["Message"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_dynamodb_GlobalTableAlreadyExistsException(native_input): + return Error_GlobalTableAlreadyExistsException( + message=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Error"]["Message"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_dynamodb_GlobalTableNotFoundException(native_input): + return Error_GlobalTableNotFoundException( + message=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Error"]["Message"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_dynamodb_IdempotentParameterMismatchException(native_input): + return Error_IdempotentParameterMismatchException( + Message=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Error"]["Message"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_dynamodb_ImportConflictException(native_input): + return Error_ImportConflictException( + message=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Error"]["Message"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_dynamodb_ImportNotFoundException(native_input): + return Error_ImportNotFoundException( + message=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Error"]["Message"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_dynamodb_IndexNotFoundException(native_input): + return Error_IndexNotFoundException( + message=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Error"]["Message"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_dynamodb_InternalServerError(native_input): + return Error_InternalServerError( + message=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Error"]["Message"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_dynamodb_InvalidEndpointException(native_input): + return Error_InvalidEndpointException( + Message=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Error"]["Message"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_dynamodb_InvalidExportTimeException(native_input): + return Error_InvalidExportTimeException( + message=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Error"]["Message"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_dynamodb_InvalidRestoreTimeException(native_input): + return Error_InvalidRestoreTimeException( + message=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Error"]["Message"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_dynamodb_ItemCollectionSizeLimitExceededException(native_input): + return Error_ItemCollectionSizeLimitExceededException( + message=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Error"]["Message"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_dynamodb_LimitExceededException(native_input): + return Error_LimitExceededException( + message=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Error"]["Message"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_dynamodb_PointInTimeRecoveryUnavailableException(native_input): + return Error_PointInTimeRecoveryUnavailableException( + message=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Error"]["Message"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_dynamodb_ProvisionedThroughputExceededException(native_input): + return Error_ProvisionedThroughputExceededException( + message=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Error"]["Message"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_dynamodb_ReplicaAlreadyExistsException(native_input): + return Error_ReplicaAlreadyExistsException( + message=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Error"]["Message"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_dynamodb_ReplicaNotFoundException(native_input): + return Error_ReplicaNotFoundException( + message=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Error"]["Message"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_dynamodb_RequestLimitExceeded(native_input): + return Error_RequestLimitExceeded( + message=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Error"]["Message"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_dynamodb_ResourceInUseException(native_input): + return Error_ResourceInUseException( + message=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Error"]["Message"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_dynamodb_ResourceNotFoundException(native_input): + return Error_ResourceNotFoundException( + message=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Error"]["Message"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_dynamodb_TableAlreadyExistsException(native_input): + return Error_TableAlreadyExistsException( + message=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Error"]["Message"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_dynamodb_TableInUseException(native_input): + return Error_TableInUseException( + message=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Error"]["Message"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_dynamodb_TableNotFoundException(native_input): + return Error_TableNotFoundException( + message=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Error"]["Message"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_dynamodb_TransactionCanceledException(native_input): + return Error_TransactionCanceledException( + Message=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Error"]["Message"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ), + CancellationReasons=Seq( + [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_CancellationReason( + list_element + ) + for list_element in native_input["CancellationReasons"] + ] + ), + ) + + +def com_amazonaws_dynamodb_CancellationReason(native_input): + return DafnyCancellationReason( + Item=( + Option_Some( + Map( + { + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(key.encode("utf-16-be"))] * 2 + ) + ] + ) + ): aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_AttributeValue( + value + ) + for (key, value) in native_input["Item"].items() + } + ) + ) + if "Item" in native_input.keys() + else Option_None() + ), + Code=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Code"].encode("utf-16-be"))] * 2 + ) + ] + ) + ) + ) + if "Code" in native_input.keys() + else Option_None() + ), + Message=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Message"].encode("utf-16-be"))] * 2 + ) + ] + ) + ) + ) + if "Message" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_AttributeValue(native_input): + if "S" in native_input.keys(): + AttributeValue_union_value = AttributeValue_S( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["S"].encode("utf-16-be"))] * 2 + ) + ] + ) + ) + ) + elif "N" in native_input.keys(): + AttributeValue_union_value = AttributeValue_N( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["N"].encode("utf-16-be"))] * 2 + ) + ] + ) + ) + ) + elif "B" in native_input.keys(): + AttributeValue_union_value = AttributeValue_B(Seq(native_input["B"])) + elif "SS" in native_input.keys(): + AttributeValue_union_value = AttributeValue_SS( + 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["SS"] + ] + ) + ) + elif "NS" in native_input.keys(): + AttributeValue_union_value = AttributeValue_NS( + 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["NS"] + ] + ) + ) + elif "BS" in native_input.keys(): + AttributeValue_union_value = AttributeValue_BS( + Seq([Seq(list_element) for list_element in native_input["BS"]]) + ) + elif "M" in native_input.keys(): + AttributeValue_union_value = AttributeValue_M( + Map( + { + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip(*[iter(key.encode("utf-16-be"))] * 2) + ] + ) + ): aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_AttributeValue( + value + ) + for (key, value) in native_input["M"].items() + } + ) + ) + elif "L" in native_input.keys(): + AttributeValue_union_value = AttributeValue_L( + Seq( + [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_AttributeValue( + list_element + ) + for list_element in native_input["L"] + ] + ) + ) + elif "NULL" in native_input.keys(): + AttributeValue_union_value = AttributeValue_NULL(native_input["NULL"]) + elif "BOOL" in native_input.keys(): + AttributeValue_union_value = AttributeValue_BOOL(native_input["BOOL"]) + else: + raise ValueError( + "No recognized union value in union type: " + str(native_input) + ) + + return AttributeValue_union_value + + +def com_amazonaws_dynamodb_TransactionConflictException(native_input): + return Error_TransactionConflictException( + message=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Error"]["Message"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_dynamodb_TransactionInProgressException(native_input): + return Error_TransactionInProgressException( + Message=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Error"]["Message"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_dynamodb_BatchExecuteStatementInput(native_input): + return DafnyBatchExecuteStatementInput( + Statements=Seq( + [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_BatchStatementRequest( + list_element + ) + for list_element in native_input["Statements"] + ] + ), + ReturnConsumedCapacity=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ReturnConsumedCapacity( + native_input["ReturnConsumedCapacity"] + ) + ) + if "ReturnConsumedCapacity" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_BatchStatementRequest(native_input): + return DafnyBatchStatementRequest( + Statement=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Statement"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + Parameters=( + Option_Some( + Seq( + [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_AttributeValue( + list_element + ) + for list_element in native_input["Parameters"] + ] + ) + ) + if "Parameters" in native_input.keys() + else Option_None() + ), + ConsistentRead=( + Option_Some(native_input["ConsistentRead"]) + if "ConsistentRead" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_ReturnConsumedCapacity(native_input): + # Convert ReturnConsumedCapacity + if native_input == "INDEXES": + return ReturnConsumedCapacity_INDEXES() + elif native_input == "TOTAL": + return ReturnConsumedCapacity_TOTAL() + elif native_input == "NONE": + return ReturnConsumedCapacity_NONE() + else: + raise ValueError("No recognized enum value in enum type: " + native_input) + + +def com_amazonaws_dynamodb_BatchExecuteStatementOutput(native_input): + return DafnyBatchExecuteStatementOutput( + Responses=( + Option_Some( + Seq( + [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_BatchStatementResponse( + list_element + ) + for list_element in native_input["Responses"] + ] + ) + ) + if "Responses" in native_input.keys() + else Option_None() + ), + ConsumedCapacity=( + Option_Some( + Seq( + [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ConsumedCapacity( + list_element + ) + for list_element in native_input["ConsumedCapacity"] + ] + ) + ) + if "ConsumedCapacity" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_BatchStatementResponse(native_input): + return DafnyBatchStatementResponse( + Error=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_BatchStatementError( + native_input["Error"] + ) + ) + if "Error" in native_input.keys() + else Option_None() + ), + TableName=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["TableName"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ) + ) + if "TableName" in native_input.keys() + else Option_None() + ), + Item=( + Option_Some( + Map( + { + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(key.encode("utf-16-be"))] * 2 + ) + ] + ) + ): aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_AttributeValue( + value + ) + for (key, value) in native_input["Item"].items() + } + ) + ) + if "Item" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_BatchStatementError(native_input): + return DafnyBatchStatementError( + Code=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_BatchStatementErrorCodeEnum( + native_input["Code"] + ) + ) + if "Code" in native_input.keys() + else Option_None() + ), + Message=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Message"].encode("utf-16-be"))] * 2 + ) + ] + ) + ) + ) + if "Message" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_BatchStatementErrorCodeEnum(native_input): + # Convert BatchStatementErrorCodeEnum + if native_input == "ConditionalCheckFailed": + return BatchStatementErrorCodeEnum_ConditionalCheckFailed() + elif native_input == "ItemCollectionSizeLimitExceeded": + return BatchStatementErrorCodeEnum_ItemCollectionSizeLimitExceeded() + elif native_input == "RequestLimitExceeded": + return BatchStatementErrorCodeEnum_RequestLimitExceeded() + elif native_input == "ValidationError": + return BatchStatementErrorCodeEnum_ValidationError() + elif native_input == "ProvisionedThroughputExceeded": + return BatchStatementErrorCodeEnum_ProvisionedThroughputExceeded() + elif native_input == "TransactionConflict": + return BatchStatementErrorCodeEnum_TransactionConflict() + elif native_input == "ThrottlingError": + return BatchStatementErrorCodeEnum_ThrottlingError() + elif native_input == "InternalServerError": + return BatchStatementErrorCodeEnum_InternalServerError() + elif native_input == "ResourceNotFound": + return BatchStatementErrorCodeEnum_ResourceNotFound() + elif native_input == "AccessDenied": + return BatchStatementErrorCodeEnum_AccessDenied() + elif native_input == "DuplicateItem": + return BatchStatementErrorCodeEnum_DuplicateItem() + else: + raise ValueError("No recognized enum value in enum type: " + native_input) + + +def com_amazonaws_dynamodb_ConsumedCapacity(native_input): + return DafnyConsumedCapacity( + TableName=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["TableName"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ) + ) + if "TableName" in native_input.keys() + else Option_None() + ), + CapacityUnits=( + Option_Some(native_input["CapacityUnits"]) + if "CapacityUnits" in native_input.keys() + else Option_None() + ), + ReadCapacityUnits=( + Option_Some(native_input["ReadCapacityUnits"]) + if "ReadCapacityUnits" in native_input.keys() + else Option_None() + ), + WriteCapacityUnits=( + Option_Some(native_input["WriteCapacityUnits"]) + if "WriteCapacityUnits" in native_input.keys() + else Option_None() + ), + Table=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_Capacity( + native_input["Table"] + ) + ) + if "Table" in native_input.keys() + else Option_None() + ), + LocalSecondaryIndexes=( + Option_Some( + Map( + { + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(key.encode("utf-16-be"))] * 2 + ) + ] + ) + ): aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_Capacity( + value + ) + for (key, value) in native_input[ + "LocalSecondaryIndexes" + ].items() + } + ) + ) + if "LocalSecondaryIndexes" in native_input.keys() + else Option_None() + ), + GlobalSecondaryIndexes=( + Option_Some( + Map( + { + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(key.encode("utf-16-be"))] * 2 + ) + ] + ) + ): aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_Capacity( + value + ) + for (key, value) in native_input[ + "GlobalSecondaryIndexes" + ].items() + } + ) + ) + if "GlobalSecondaryIndexes" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_Capacity(native_input): + return DafnyCapacity( + ReadCapacityUnits=( + Option_Some(native_input["ReadCapacityUnits"]) + if "ReadCapacityUnits" in native_input.keys() + else Option_None() + ), + WriteCapacityUnits=( + Option_Some(native_input["WriteCapacityUnits"]) + if "WriteCapacityUnits" in native_input.keys() + else Option_None() + ), + CapacityUnits=( + Option_Some(native_input["CapacityUnits"]) + if "CapacityUnits" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_BatchGetItemInput(native_input): + return DafnyBatchGetItemInput( + RequestItems=Map( + { + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip(*[iter(key.encode("utf-16-be"))] * 2) + ] + ) + ): aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_KeysAndAttributes( + value + ) + for (key, value) in native_input["RequestItems"].items() + } + ), + ReturnConsumedCapacity=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ReturnConsumedCapacity( + native_input["ReturnConsumedCapacity"] + ) + ) + if "ReturnConsumedCapacity" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_KeysAndAttributes(native_input): + return DafnyKeysAndAttributes( + Keys=Seq( + [ + Map( + { + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(key.encode("utf-16-be"))] * 2 + ) + ] + ) + ): aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_AttributeValue( + value + ) + for (key, value) in list_element.items() + } + ) + for list_element in native_input["Keys"] + ] + ), + AttributesToGet=( + 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["AttributesToGet"] + ] + ) + ) + if "AttributesToGet" in native_input.keys() + else Option_None() + ), + ConsistentRead=( + Option_Some(native_input["ConsistentRead"]) + if "ConsistentRead" in native_input.keys() + else Option_None() + ), + ProjectionExpression=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[ + iter( + native_input["ProjectionExpression"].encode( + "utf-16-be" + ) + ) + ] + * 2 + ) + ] + ) + ) + ) + if "ProjectionExpression" in native_input.keys() + else Option_None() + ), + ExpressionAttributeNames=( + 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[ + "ExpressionAttributeNames" + ].items() + } + ) + ) + if "ExpressionAttributeNames" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_BatchGetItemOutput(native_input): + return DafnyBatchGetItemOutput( + Responses=( + Option_Some( + Map( + { + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(key.encode("utf-16-be"))] * 2 + ) + ] + ) + ): Seq( + [ + Map( + { + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(key.encode("utf-16-be"))] + * 2 + ) + ] + ) + ): aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_AttributeValue( + value + ) + for (key, value) in list_element.items() + } + ) + for list_element in value + ] + ) + for (key, value) in native_input["Responses"].items() + } + ) + ) + if "Responses" in native_input.keys() + else Option_None() + ), + UnprocessedKeys=( + Option_Some( + Map( + { + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(key.encode("utf-16-be"))] * 2 + ) + ] + ) + ): aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_KeysAndAttributes( + value + ) + for (key, value) in native_input["UnprocessedKeys"].items() + } + ) + ) + if "UnprocessedKeys" in native_input.keys() + else Option_None() + ), + ConsumedCapacity=( + Option_Some( + Seq( + [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ConsumedCapacity( + list_element + ) + for list_element in native_input["ConsumedCapacity"] + ] + ) + ) + if "ConsumedCapacity" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_BatchWriteItemInput(native_input): + return DafnyBatchWriteItemInput( + RequestItems=Map( + { + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip(*[iter(key.encode("utf-16-be"))] * 2) + ] + ) + ): Seq( + [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_WriteRequest( + list_element + ) + for list_element in value + ] + ) + for (key, value) in native_input["RequestItems"].items() + } + ), + ReturnConsumedCapacity=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ReturnConsumedCapacity( + native_input["ReturnConsumedCapacity"] + ) + ) + if "ReturnConsumedCapacity" in native_input.keys() + else Option_None() + ), + ReturnItemCollectionMetrics=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ReturnItemCollectionMetrics( + native_input["ReturnItemCollectionMetrics"] + ) + ) + if "ReturnItemCollectionMetrics" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_WriteRequest(native_input): + return DafnyWriteRequest( + PutRequest=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_PutRequest( + native_input["PutRequest"] + ) + ) + if "PutRequest" in native_input.keys() + else Option_None() + ), + DeleteRequest=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_DeleteRequest( + native_input["DeleteRequest"] + ) + ) + if "DeleteRequest" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_PutRequest(native_input): + return DafnyPutRequest( + Item=Map( + { + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip(*[iter(key.encode("utf-16-be"))] * 2) + ] + ) + ): aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_AttributeValue( + value + ) + for (key, value) in native_input["Item"].items() + } + ), + ) + + +def com_amazonaws_dynamodb_DeleteRequest(native_input): + return DafnyDeleteRequest( + Key=Map( + { + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip(*[iter(key.encode("utf-16-be"))] * 2) + ] + ) + ): aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_AttributeValue( + value + ) + for (key, value) in native_input["Key"].items() + } + ), + ) + + +def com_amazonaws_dynamodb_ReturnItemCollectionMetrics(native_input): + # Convert ReturnItemCollectionMetrics + if native_input == "SIZE": + return ReturnItemCollectionMetrics_SIZE() + elif native_input == "NONE": + return ReturnItemCollectionMetrics_NONE() + else: + raise ValueError("No recognized enum value in enum type: " + native_input) + + +def com_amazonaws_dynamodb_BatchWriteItemOutput(native_input): + return DafnyBatchWriteItemOutput( + UnprocessedItems=( + Option_Some( + Map( + { + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(key.encode("utf-16-be"))] * 2 + ) + ] + ) + ): Seq( + [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_WriteRequest( + list_element + ) + for list_element in value + ] + ) + for (key, value) in native_input["UnprocessedItems"].items() + } + ) + ) + if "UnprocessedItems" in native_input.keys() + else Option_None() + ), + ItemCollectionMetrics=( + Option_Some( + Map( + { + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(key.encode("utf-16-be"))] * 2 + ) + ] + ) + ): Seq( + [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ItemCollectionMetrics( + list_element + ) + for list_element in value + ] + ) + for (key, value) in native_input[ + "ItemCollectionMetrics" + ].items() + } + ) + ) + if "ItemCollectionMetrics" in native_input.keys() + else Option_None() + ), + ConsumedCapacity=( + Option_Some( + Seq( + [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ConsumedCapacity( + list_element + ) + for list_element in native_input["ConsumedCapacity"] + ] + ) + ) + if "ConsumedCapacity" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_ItemCollectionMetrics(native_input): + return DafnyItemCollectionMetrics( + ItemCollectionKey=( + Option_Some( + Map( + { + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(key.encode("utf-16-be"))] * 2 + ) + ] + ) + ): aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_AttributeValue( + value + ) + for (key, value) in native_input["ItemCollectionKey"].items() + } + ) + ) + if "ItemCollectionKey" in native_input.keys() + else Option_None() + ), + SizeEstimateRangeGB=( + Option_Some( + Seq( + [ + list_element + for list_element in native_input["SizeEstimateRangeGB"] + ] + ) + ) + if "SizeEstimateRangeGB" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_CreateBackupInput(native_input): + return DafnyCreateBackupInput( + TableName=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["TableName"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + BackupName=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["BackupName"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_dynamodb_CreateBackupOutput(native_input): + return DafnyCreateBackupOutput( + BackupDetails=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_BackupDetails( + native_input["BackupDetails"] + ) + ) + if "BackupDetails" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_BackupDetails(native_input): + return DafnyBackupDetails( + BackupArn=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["BackupArn"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + BackupName=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["BackupName"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + BackupSizeBytes=( + Option_Some(native_input["BackupSizeBytes"]) + if "BackupSizeBytes" in native_input.keys() + else Option_None() + ), + BackupStatus=aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_BackupStatus( + native_input["BackupStatus"] + ), + BackupType=aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_BackupType( + native_input["BackupType"] + ), + BackupCreationDateTime=_dafny.Seq( + native_input["BackupCreationDateTime"].isoformat() + ), + BackupExpiryDateTime=( + Option_Some(_dafny.Seq(native_input["BackupExpiryDateTime"].isoformat())) + if "BackupExpiryDateTime" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_BackupStatus(native_input): + # Convert BackupStatus + if native_input == "CREATING": + return BackupStatus_CREATING() + elif native_input == "DELETED": + return BackupStatus_DELETED() + elif native_input == "AVAILABLE": + return BackupStatus_AVAILABLE() + else: + raise ValueError("No recognized enum value in enum type: " + native_input) + + +def com_amazonaws_dynamodb_BackupType(native_input): + # Convert BackupType + if native_input == "USER": + return BackupType_USER() + elif native_input == "SYSTEM": + return BackupType_SYSTEM() + elif native_input == "AWS_BACKUP": + return BackupType_AWS__BACKUP() + else: + raise ValueError("No recognized enum value in enum type: " + native_input) + + +def com_amazonaws_dynamodb_CreateGlobalTableInput(native_input): + return DafnyCreateGlobalTableInput( + GlobalTableName=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["GlobalTableName"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + ReplicationGroup=Seq( + [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_Replica( + list_element + ) + for list_element in native_input["ReplicationGroup"] + ] + ), + ) + + +def com_amazonaws_dynamodb_Replica(native_input): + return DafnyReplica( + RegionName=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["RegionName"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ) + ) + if "RegionName" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_CreateGlobalTableOutput(native_input): + return DafnyCreateGlobalTableOutput( + GlobalTableDescription=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_GlobalTableDescription( + native_input["GlobalTableDescription"] + ) + ) + if "GlobalTableDescription" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_GlobalTableDescription(native_input): + return DafnyGlobalTableDescription( + ReplicationGroup=( + Option_Some( + Seq( + [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ReplicaDescription( + list_element + ) + for list_element in native_input["ReplicationGroup"] + ] + ) + ) + if "ReplicationGroup" in native_input.keys() + else Option_None() + ), + GlobalTableArn=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[ + iter( + native_input["GlobalTableArn"].encode( + "utf-16-be" + ) + ) + ] + * 2 + ) + ] + ) + ) + ) + if "GlobalTableArn" in native_input.keys() + else Option_None() + ), + CreationDateTime=( + Option_Some(_dafny.Seq(native_input["CreationDateTime"].isoformat())) + if "CreationDateTime" in native_input.keys() + else Option_None() + ), + GlobalTableStatus=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_GlobalTableStatus( + native_input["GlobalTableStatus"] + ) + ) + if "GlobalTableStatus" in native_input.keys() + else Option_None() + ), + GlobalTableName=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[ + iter( + native_input["GlobalTableName"].encode( + "utf-16-be" + ) + ) + ] + * 2 + ) + ] + ) + ) + ) + if "GlobalTableName" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_ReplicaDescription(native_input): + return DafnyReplicaDescription( + RegionName=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["RegionName"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ) + ) + if "RegionName" in native_input.keys() + else Option_None() + ), + ReplicaStatus=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ReplicaStatus( + native_input["ReplicaStatus"] + ) + ) + if "ReplicaStatus" in native_input.keys() + else Option_None() + ), + ReplicaStatusDescription=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[ + iter( + native_input["ReplicaStatusDescription"].encode( + "utf-16-be" + ) + ) + ] + * 2 + ) + ] + ) + ) + ) + if "ReplicaStatusDescription" in native_input.keys() + else Option_None() + ), + ReplicaStatusPercentProgress=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[ + iter( + native_input[ + "ReplicaStatusPercentProgress" + ].encode("utf-16-be") + ) + ] + * 2 + ) + ] + ) + ) + ) + if "ReplicaStatusPercentProgress" in native_input.keys() + else Option_None() + ), + KMSMasterKeyId=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[ + iter( + native_input["KMSMasterKeyId"].encode( + "utf-16-be" + ) + ) + ] + * 2 + ) + ] + ) + ) + ) + if "KMSMasterKeyId" in native_input.keys() + else Option_None() + ), + ProvisionedThroughputOverride=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ProvisionedThroughputOverride( + native_input["ProvisionedThroughputOverride"] + ) + ) + if "ProvisionedThroughputOverride" in native_input.keys() + else Option_None() + ), + GlobalSecondaryIndexes=( + Option_Some( + Seq( + [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ReplicaGlobalSecondaryIndexDescription( + list_element + ) + for list_element in native_input["GlobalSecondaryIndexes"] + ] + ) + ) + if "GlobalSecondaryIndexes" in native_input.keys() + else Option_None() + ), + ReplicaInaccessibleDateTime=( + Option_Some( + _dafny.Seq(native_input["ReplicaInaccessibleDateTime"].isoformat()) + ) + if "ReplicaInaccessibleDateTime" in native_input.keys() + else Option_None() + ), + ReplicaTableClassSummary=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_TableClassSummary( + native_input["ReplicaTableClassSummary"] + ) + ) + if "ReplicaTableClassSummary" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_GlobalTableStatus(native_input): + # Convert GlobalTableStatus + if native_input == "CREATING": + return GlobalTableStatus_CREATING() + elif native_input == "ACTIVE": + return GlobalTableStatus_ACTIVE() + elif native_input == "DELETING": + return GlobalTableStatus_DELETING() + elif native_input == "UPDATING": + return GlobalTableStatus_UPDATING() + else: + raise ValueError("No recognized enum value in enum type: " + native_input) + + +def com_amazonaws_dynamodb_ReplicaStatus(native_input): + # Convert ReplicaStatus + if native_input == "CREATING": + return ReplicaStatus_CREATING() + elif native_input == "CREATION_FAILED": + return ReplicaStatus_CREATION__FAILED() + elif native_input == "UPDATING": + return ReplicaStatus_UPDATING() + elif native_input == "DELETING": + return ReplicaStatus_DELETING() + elif native_input == "ACTIVE": + return ReplicaStatus_ACTIVE() + elif native_input == "REGION_DISABLED": + return ReplicaStatus_REGION__DISABLED() + elif native_input == "INACCESSIBLE_ENCRYPTION_CREDENTIALS": + return ReplicaStatus_INACCESSIBLE__ENCRYPTION__CREDENTIALS() + else: + raise ValueError("No recognized enum value in enum type: " + native_input) + + +def com_amazonaws_dynamodb_ProvisionedThroughputOverride(native_input): + return DafnyProvisionedThroughputOverride( + ReadCapacityUnits=( + Option_Some(native_input["ReadCapacityUnits"]) + if "ReadCapacityUnits" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_ReplicaGlobalSecondaryIndexDescription(native_input): + return DafnyReplicaGlobalSecondaryIndexDescription( + IndexName=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["IndexName"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ) + ) + if "IndexName" in native_input.keys() + else Option_None() + ), + ProvisionedThroughputOverride=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ProvisionedThroughputOverride( + native_input["ProvisionedThroughputOverride"] + ) + ) + if "ProvisionedThroughputOverride" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_TableClassSummary(native_input): + return DafnyTableClassSummary( + TableClass=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_TableClass( + native_input["TableClass"] + ) + ) + if "TableClass" in native_input.keys() + else Option_None() + ), + LastUpdateDateTime=( + Option_Some(_dafny.Seq(native_input["LastUpdateDateTime"].isoformat())) + if "LastUpdateDateTime" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_TableClass(native_input): + # Convert TableClass + if native_input == "STANDARD": + return TableClass_STANDARD() + elif native_input == "STANDARD_INFREQUENT_ACCESS": + return TableClass_STANDARD__INFREQUENT__ACCESS() + else: + raise ValueError("No recognized enum value in enum type: " + native_input) + + +def com_amazonaws_dynamodb_CreateTableInput(native_input): + return DafnyCreateTableInput( + AttributeDefinitions=Seq( + [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_AttributeDefinition( + list_element + ) + for list_element in native_input["AttributeDefinitions"] + ] + ), + TableName=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["TableName"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + KeySchema=Seq( + [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_KeySchemaElement( + list_element + ) + for list_element in native_input["KeySchema"] + ] + ), + LocalSecondaryIndexes=( + Option_Some( + Seq( + [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_LocalSecondaryIndex( + list_element + ) + for list_element in native_input["LocalSecondaryIndexes"] + ] + ) + ) + if "LocalSecondaryIndexes" in native_input.keys() + else Option_None() + ), + GlobalSecondaryIndexes=( + Option_Some( + Seq( + [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_GlobalSecondaryIndex( + list_element + ) + for list_element in native_input["GlobalSecondaryIndexes"] + ] + ) + ) + if "GlobalSecondaryIndexes" in native_input.keys() + else Option_None() + ), + BillingMode=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_BillingMode( + native_input["BillingMode"] + ) + ) + if "BillingMode" in native_input.keys() + else Option_None() + ), + ProvisionedThroughput=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ProvisionedThroughput( + native_input["ProvisionedThroughput"] + ) + ) + if "ProvisionedThroughput" in native_input.keys() + else Option_None() + ), + StreamSpecification=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_StreamSpecification( + native_input["StreamSpecification"] + ) + ) + if "StreamSpecification" in native_input.keys() + else Option_None() + ), + SSESpecification=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_SSESpecification( + native_input["SSESpecification"] + ) + ) + if "SSESpecification" in native_input.keys() + else Option_None() + ), + Tags=( + Option_Some( + Seq( + [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_Tag( + list_element + ) + for list_element in native_input["Tags"] + ] + ) + ) + if "Tags" in native_input.keys() + else Option_None() + ), + TableClass=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_TableClass( + native_input["TableClass"] + ) + ) + if "TableClass" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_AttributeDefinition(native_input): + return DafnyAttributeDefinition( + AttributeName=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["AttributeName"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + AttributeType=aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ScalarAttributeType( + native_input["AttributeType"] + ), + ) + + +def com_amazonaws_dynamodb_ScalarAttributeType(native_input): + # Convert ScalarAttributeType + if native_input == "S": + return ScalarAttributeType_S() + elif native_input == "N": + return ScalarAttributeType_N() + elif native_input == "B": + return ScalarAttributeType_B() + else: + raise ValueError("No recognized enum value in enum type: " + native_input) + + +def com_amazonaws_dynamodb_KeySchemaElement(native_input): + return DafnyKeySchemaElement( + AttributeName=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["AttributeName"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + KeyType=aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_KeyType( + native_input["KeyType"] + ), + ) + + +def com_amazonaws_dynamodb_KeyType(native_input): + # Convert KeyType + if native_input == "HASH": + return KeyType_HASH() + elif native_input == "RANGE": + return KeyType_RANGE() + else: + raise ValueError("No recognized enum value in enum type: " + native_input) + + +def com_amazonaws_dynamodb_LocalSecondaryIndex(native_input): + return DafnyLocalSecondaryIndex( + IndexName=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["IndexName"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + KeySchema=Seq( + [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_KeySchemaElement( + list_element + ) + for list_element in native_input["KeySchema"] + ] + ), + Projection=aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_Projection( + native_input["Projection"] + ), + ) + + +def com_amazonaws_dynamodb_Projection(native_input): + return DafnyProjection( + ProjectionType=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ProjectionType( + native_input["ProjectionType"] + ) + ) + if "ProjectionType" in native_input.keys() + else Option_None() + ), + NonKeyAttributes=( + 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["NonKeyAttributes"] + ] + ) + ) + if "NonKeyAttributes" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_ProjectionType(native_input): + # Convert ProjectionType + if native_input == "ALL": + return ProjectionType_ALL() + elif native_input == "KEYS_ONLY": + return ProjectionType_KEYS__ONLY() + elif native_input == "INCLUDE": + return ProjectionType_INCLUDE() + else: + raise ValueError("No recognized enum value in enum type: " + native_input) + + +def com_amazonaws_dynamodb_GlobalSecondaryIndex(native_input): + return DafnyGlobalSecondaryIndex( + IndexName=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["IndexName"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + KeySchema=Seq( + [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_KeySchemaElement( + list_element + ) + for list_element in native_input["KeySchema"] + ] + ), + Projection=aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_Projection( + native_input["Projection"] + ), + ProvisionedThroughput=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ProvisionedThroughput( + native_input["ProvisionedThroughput"] + ) + ) + if "ProvisionedThroughput" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_ProvisionedThroughput(native_input): + return DafnyProvisionedThroughput( + ReadCapacityUnits=native_input["ReadCapacityUnits"], + WriteCapacityUnits=native_input["WriteCapacityUnits"], + ) + + +def com_amazonaws_dynamodb_BillingMode(native_input): + # Convert BillingMode + if native_input == "PROVISIONED": + return BillingMode_PROVISIONED() + elif native_input == "PAY_PER_REQUEST": + return BillingMode_PAY__PER__REQUEST() + else: + raise ValueError("No recognized enum value in enum type: " + native_input) + + +def com_amazonaws_dynamodb_StreamSpecification(native_input): + return DafnyStreamSpecification( + StreamEnabled=native_input["StreamEnabled"], + StreamViewType=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_StreamViewType( + native_input["StreamViewType"] + ) + ) + if "StreamViewType" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_StreamViewType(native_input): + # Convert StreamViewType + if native_input == "NEW_IMAGE": + return StreamViewType_NEW__IMAGE() + elif native_input == "OLD_IMAGE": + return StreamViewType_OLD__IMAGE() + elif native_input == "NEW_AND_OLD_IMAGES": + return StreamViewType_NEW__AND__OLD__IMAGES() + elif native_input == "KEYS_ONLY": + return StreamViewType_KEYS__ONLY() + else: + raise ValueError("No recognized enum value in enum type: " + native_input) + + +def com_amazonaws_dynamodb_SSESpecification(native_input): + return DafnySSESpecification( + Enabled=( + Option_Some(native_input["Enabled"]) + if "Enabled" in native_input.keys() + else Option_None() + ), + SSEType=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_SSEType( + native_input["SSEType"] + ) + ) + if "SSEType" in native_input.keys() + else Option_None() + ), + KMSMasterKeyId=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[ + iter( + native_input["KMSMasterKeyId"].encode( + "utf-16-be" + ) + ) + ] + * 2 + ) + ] + ) + ) + ) + if "KMSMasterKeyId" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_SSEType(native_input): + # Convert SSEType + if native_input == "AES256": + return SSEType_AES256() + elif native_input == "KMS": + return SSEType_KMS() + else: + raise ValueError("No recognized enum value in enum type: " + native_input) + + +def com_amazonaws_dynamodb_Tag(native_input): + return DafnyTag( + Key=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Key"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + Value=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Value"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_dynamodb_CreateTableOutput(native_input): + return DafnyCreateTableOutput( + TableDescription=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_TableDescription( + native_input["TableDescription"] + ) + ) + if "TableDescription" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_TableDescription(native_input): + return DafnyTableDescription( + AttributeDefinitions=( + Option_Some( + Seq( + [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_AttributeDefinition( + list_element + ) + for list_element in native_input["AttributeDefinitions"] + ] + ) + ) + if "AttributeDefinitions" in native_input.keys() + else Option_None() + ), + TableName=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["TableName"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ) + ) + if "TableName" in native_input.keys() + else Option_None() + ), + KeySchema=( + Option_Some( + Seq( + [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_KeySchemaElement( + list_element + ) + for list_element in native_input["KeySchema"] + ] + ) + ) + if "KeySchema" in native_input.keys() + else Option_None() + ), + TableStatus=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_TableStatus( + native_input["TableStatus"] + ) + ) + if "TableStatus" in native_input.keys() + else Option_None() + ), + CreationDateTime=( + Option_Some(_dafny.Seq(native_input["CreationDateTime"].isoformat())) + if "CreationDateTime" in native_input.keys() + else Option_None() + ), + ProvisionedThroughput=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ProvisionedThroughputDescription( + native_input["ProvisionedThroughput"] + ) + ) + if "ProvisionedThroughput" in native_input.keys() + else Option_None() + ), + TableSizeBytes=( + Option_Some(native_input["TableSizeBytes"]) + if "TableSizeBytes" in native_input.keys() + else Option_None() + ), + ItemCount=( + Option_Some(native_input["ItemCount"]) + if "ItemCount" in native_input.keys() + else Option_None() + ), + TableArn=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["TableArn"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ) + ) + if "TableArn" in native_input.keys() + else Option_None() + ), + TableId=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["TableId"].encode("utf-16-be"))] * 2 + ) + ] + ) + ) + ) + if "TableId" in native_input.keys() + else Option_None() + ), + BillingModeSummary=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_BillingModeSummary( + native_input["BillingModeSummary"] + ) + ) + if "BillingModeSummary" in native_input.keys() + else Option_None() + ), + LocalSecondaryIndexes=( + Option_Some( + Seq( + [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_LocalSecondaryIndexDescription( + list_element + ) + for list_element in native_input["LocalSecondaryIndexes"] + ] + ) + ) + if "LocalSecondaryIndexes" in native_input.keys() + else Option_None() + ), + GlobalSecondaryIndexes=( + Option_Some( + Seq( + [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_GlobalSecondaryIndexDescription( + list_element + ) + for list_element in native_input["GlobalSecondaryIndexes"] + ] + ) + ) + if "GlobalSecondaryIndexes" in native_input.keys() + else Option_None() + ), + StreamSpecification=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_StreamSpecification( + native_input["StreamSpecification"] + ) + ) + if "StreamSpecification" in native_input.keys() + else Option_None() + ), + LatestStreamLabel=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[ + iter( + native_input["LatestStreamLabel"].encode( + "utf-16-be" + ) + ) + ] + * 2 + ) + ] + ) + ) + ) + if "LatestStreamLabel" in native_input.keys() + else Option_None() + ), + LatestStreamArn=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[ + iter( + native_input["LatestStreamArn"].encode( + "utf-16-be" + ) + ) + ] + * 2 + ) + ] + ) + ) + ) + if "LatestStreamArn" in native_input.keys() + else Option_None() + ), + GlobalTableVersion=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[ + iter( + native_input["GlobalTableVersion"].encode( + "utf-16-be" + ) + ) + ] + * 2 + ) + ] + ) + ) + ) + if "GlobalTableVersion" in native_input.keys() + else Option_None() + ), + Replicas=( + Option_Some( + Seq( + [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ReplicaDescription( + list_element + ) + for list_element in native_input["Replicas"] + ] + ) + ) + if "Replicas" in native_input.keys() + else Option_None() + ), + RestoreSummary=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_RestoreSummary( + native_input["RestoreSummary"] + ) + ) + if "RestoreSummary" in native_input.keys() + else Option_None() + ), + SSEDescription=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_SSEDescription( + native_input["SSEDescription"] + ) + ) + if "SSEDescription" in native_input.keys() + else Option_None() + ), + ArchivalSummary=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ArchivalSummary( + native_input["ArchivalSummary"] + ) + ) + if "ArchivalSummary" in native_input.keys() + else Option_None() + ), + TableClassSummary=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_TableClassSummary( + native_input["TableClassSummary"] + ) + ) + if "TableClassSummary" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_TableStatus(native_input): + # Convert TableStatus + if native_input == "CREATING": + return TableStatus_CREATING() + elif native_input == "UPDATING": + return TableStatus_UPDATING() + elif native_input == "DELETING": + return TableStatus_DELETING() + elif native_input == "ACTIVE": + return TableStatus_ACTIVE() + elif native_input == "INACCESSIBLE_ENCRYPTION_CREDENTIALS": + return TableStatus_INACCESSIBLE__ENCRYPTION__CREDENTIALS() + elif native_input == "ARCHIVING": + return TableStatus_ARCHIVING() + elif native_input == "ARCHIVED": + return TableStatus_ARCHIVED() + else: + raise ValueError("No recognized enum value in enum type: " + native_input) + + +def com_amazonaws_dynamodb_ProvisionedThroughputDescription(native_input): + return DafnyProvisionedThroughputDescription( + LastIncreaseDateTime=( + Option_Some(_dafny.Seq(native_input["LastIncreaseDateTime"].isoformat())) + if "LastIncreaseDateTime" in native_input.keys() + else Option_None() + ), + LastDecreaseDateTime=( + Option_Some(_dafny.Seq(native_input["LastDecreaseDateTime"].isoformat())) + if "LastDecreaseDateTime" in native_input.keys() + else Option_None() + ), + NumberOfDecreasesToday=( + Option_Some(native_input["NumberOfDecreasesToday"]) + if "NumberOfDecreasesToday" in native_input.keys() + else Option_None() + ), + ReadCapacityUnits=( + Option_Some(native_input["ReadCapacityUnits"]) + if "ReadCapacityUnits" in native_input.keys() + else Option_None() + ), + WriteCapacityUnits=( + Option_Some(native_input["WriteCapacityUnits"]) + if "WriteCapacityUnits" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_BillingModeSummary(native_input): + return DafnyBillingModeSummary( + BillingMode=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_BillingMode( + native_input["BillingMode"] + ) + ) + if "BillingMode" in native_input.keys() + else Option_None() + ), + LastUpdateToPayPerRequestDateTime=( + Option_Some( + _dafny.Seq( + native_input["LastUpdateToPayPerRequestDateTime"].isoformat() + ) + ) + if "LastUpdateToPayPerRequestDateTime" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_LocalSecondaryIndexDescription(native_input): + return DafnyLocalSecondaryIndexDescription( + IndexName=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["IndexName"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ) + ) + if "IndexName" in native_input.keys() + else Option_None() + ), + KeySchema=( + Option_Some( + Seq( + [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_KeySchemaElement( + list_element + ) + for list_element in native_input["KeySchema"] + ] + ) + ) + if "KeySchema" in native_input.keys() + else Option_None() + ), + Projection=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_Projection( + native_input["Projection"] + ) + ) + if "Projection" in native_input.keys() + else Option_None() + ), + IndexSizeBytes=( + Option_Some(native_input["IndexSizeBytes"]) + if "IndexSizeBytes" in native_input.keys() + else Option_None() + ), + ItemCount=( + Option_Some(native_input["ItemCount"]) + if "ItemCount" in native_input.keys() + else Option_None() + ), + IndexArn=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["IndexArn"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ) + ) + if "IndexArn" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_GlobalSecondaryIndexDescription(native_input): + return DafnyGlobalSecondaryIndexDescription( + IndexName=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["IndexName"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ) + ) + if "IndexName" in native_input.keys() + else Option_None() + ), + KeySchema=( + Option_Some( + Seq( + [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_KeySchemaElement( + list_element + ) + for list_element in native_input["KeySchema"] + ] + ) + ) + if "KeySchema" in native_input.keys() + else Option_None() + ), + Projection=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_Projection( + native_input["Projection"] + ) + ) + if "Projection" in native_input.keys() + else Option_None() + ), + IndexStatus=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_IndexStatus( + native_input["IndexStatus"] + ) + ) + if "IndexStatus" in native_input.keys() + else Option_None() + ), + Backfilling=( + Option_Some(native_input["Backfilling"]) + if "Backfilling" in native_input.keys() + else Option_None() + ), + ProvisionedThroughput=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ProvisionedThroughputDescription( + native_input["ProvisionedThroughput"] + ) + ) + if "ProvisionedThroughput" in native_input.keys() + else Option_None() + ), + IndexSizeBytes=( + Option_Some(native_input["IndexSizeBytes"]) + if "IndexSizeBytes" in native_input.keys() + else Option_None() + ), + ItemCount=( + Option_Some(native_input["ItemCount"]) + if "ItemCount" in native_input.keys() + else Option_None() + ), + IndexArn=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["IndexArn"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ) + ) + if "IndexArn" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_RestoreSummary(native_input): + return DafnyRestoreSummary( + SourceBackupArn=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[ + iter( + native_input["SourceBackupArn"].encode( + "utf-16-be" + ) + ) + ] + * 2 + ) + ] + ) + ) + ) + if "SourceBackupArn" in native_input.keys() + else Option_None() + ), + SourceTableArn=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[ + iter( + native_input["SourceTableArn"].encode( + "utf-16-be" + ) + ) + ] + * 2 + ) + ] + ) + ) + ) + if "SourceTableArn" in native_input.keys() + else Option_None() + ), + RestoreDateTime=_dafny.Seq(native_input["RestoreDateTime"].isoformat()), + RestoreInProgress=native_input["RestoreInProgress"], + ) + + +def com_amazonaws_dynamodb_SSEDescription(native_input): + return DafnySSEDescription( + Status=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_SSEStatus( + native_input["Status"] + ) + ) + if "Status" in native_input.keys() + else Option_None() + ), + SSEType=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_SSEType( + native_input["SSEType"] + ) + ) + if "SSEType" in native_input.keys() + else Option_None() + ), + KMSMasterKeyArn=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[ + iter( + native_input["KMSMasterKeyArn"].encode( + "utf-16-be" + ) + ) + ] + * 2 + ) + ] + ) + ) + ) + if "KMSMasterKeyArn" in native_input.keys() + else Option_None() + ), + InaccessibleEncryptionDateTime=( + Option_Some( + _dafny.Seq(native_input["InaccessibleEncryptionDateTime"].isoformat()) + ) + if "InaccessibleEncryptionDateTime" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_ArchivalSummary(native_input): + return DafnyArchivalSummary( + ArchivalDateTime=( + Option_Some(_dafny.Seq(native_input["ArchivalDateTime"].isoformat())) + if "ArchivalDateTime" in native_input.keys() + else Option_None() + ), + ArchivalReason=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[ + iter( + native_input["ArchivalReason"].encode( + "utf-16-be" + ) + ) + ] + * 2 + ) + ] + ) + ) + ) + if "ArchivalReason" in native_input.keys() + else Option_None() + ), + ArchivalBackupArn=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[ + iter( + native_input["ArchivalBackupArn"].encode( + "utf-16-be" + ) + ) + ] + * 2 + ) + ] + ) + ) + ) + if "ArchivalBackupArn" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_IndexStatus(native_input): + # Convert IndexStatus + if native_input == "CREATING": + return IndexStatus_CREATING() + elif native_input == "UPDATING": + return IndexStatus_UPDATING() + elif native_input == "DELETING": + return IndexStatus_DELETING() + elif native_input == "ACTIVE": + return IndexStatus_ACTIVE() + else: + raise ValueError("No recognized enum value in enum type: " + native_input) + + +def com_amazonaws_dynamodb_SSEStatus(native_input): + # Convert SSEStatus + if native_input == "ENABLING": + return SSEStatus_ENABLING() + elif native_input == "ENABLED": + return SSEStatus_ENABLED() + elif native_input == "DISABLING": + return SSEStatus_DISABLING() + elif native_input == "DISABLED": + return SSEStatus_DISABLED() + elif native_input == "UPDATING": + return SSEStatus_UPDATING() + else: + raise ValueError("No recognized enum value in enum type: " + native_input) + + +def com_amazonaws_dynamodb_DeleteBackupInput(native_input): + return DafnyDeleteBackupInput( + BackupArn=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["BackupArn"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_dynamodb_DeleteBackupOutput(native_input): + return DafnyDeleteBackupOutput( + BackupDescription=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_BackupDescription( + native_input["BackupDescription"] + ) + ) + if "BackupDescription" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_BackupDescription(native_input): + return DafnyBackupDescription( + BackupDetails=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_BackupDetails( + native_input["BackupDetails"] + ) + ) + if "BackupDetails" in native_input.keys() + else Option_None() + ), + SourceTableDetails=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_SourceTableDetails( + native_input["SourceTableDetails"] + ) + ) + if "SourceTableDetails" in native_input.keys() + else Option_None() + ), + SourceTableFeatureDetails=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_SourceTableFeatureDetails( + native_input["SourceTableFeatureDetails"] + ) + ) + if "SourceTableFeatureDetails" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_SourceTableDetails(native_input): + return DafnySourceTableDetails( + TableName=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["TableName"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + TableId=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["TableId"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + TableArn=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["TableArn"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ) + ) + if "TableArn" in native_input.keys() + else Option_None() + ), + TableSizeBytes=( + Option_Some(native_input["TableSizeBytes"]) + if "TableSizeBytes" in native_input.keys() + else Option_None() + ), + KeySchema=Seq( + [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_KeySchemaElement( + list_element + ) + for list_element in native_input["KeySchema"] + ] + ), + TableCreationDateTime=_dafny.Seq( + native_input["TableCreationDateTime"].isoformat() + ), + ProvisionedThroughput=aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ProvisionedThroughput( + native_input["ProvisionedThroughput"] + ), + ItemCount=( + Option_Some(native_input["ItemCount"]) + if "ItemCount" in native_input.keys() + else Option_None() + ), + BillingMode=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_BillingMode( + native_input["BillingMode"] + ) + ) + if "BillingMode" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_SourceTableFeatureDetails(native_input): + return DafnySourceTableFeatureDetails( + LocalSecondaryIndexes=( + Option_Some( + Seq( + [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_LocalSecondaryIndexInfo( + list_element + ) + for list_element in native_input["LocalSecondaryIndexes"] + ] + ) + ) + if "LocalSecondaryIndexes" in native_input.keys() + else Option_None() + ), + GlobalSecondaryIndexes=( + Option_Some( + Seq( + [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_GlobalSecondaryIndexInfo( + list_element + ) + for list_element in native_input["GlobalSecondaryIndexes"] + ] + ) + ) + if "GlobalSecondaryIndexes" in native_input.keys() + else Option_None() + ), + StreamDescription=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_StreamSpecification( + native_input["StreamDescription"] + ) + ) + if "StreamDescription" in native_input.keys() + else Option_None() + ), + TimeToLiveDescription=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_TimeToLiveDescription( + native_input["TimeToLiveDescription"] + ) + ) + if "TimeToLiveDescription" in native_input.keys() + else Option_None() + ), + SSEDescription=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_SSEDescription( + native_input["SSEDescription"] + ) + ) + if "SSEDescription" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_LocalSecondaryIndexInfo(native_input): + return DafnyLocalSecondaryIndexInfo( + IndexName=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["IndexName"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ) + ) + if "IndexName" in native_input.keys() + else Option_None() + ), + KeySchema=( + Option_Some( + Seq( + [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_KeySchemaElement( + list_element + ) + for list_element in native_input["KeySchema"] + ] + ) + ) + if "KeySchema" in native_input.keys() + else Option_None() + ), + Projection=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_Projection( + native_input["Projection"] + ) + ) + if "Projection" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_GlobalSecondaryIndexInfo(native_input): + return DafnyGlobalSecondaryIndexInfo( + IndexName=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["IndexName"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ) + ) + if "IndexName" in native_input.keys() + else Option_None() + ), + KeySchema=( + Option_Some( + Seq( + [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_KeySchemaElement( + list_element + ) + for list_element in native_input["KeySchema"] + ] + ) + ) + if "KeySchema" in native_input.keys() + else Option_None() + ), + Projection=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_Projection( + native_input["Projection"] + ) + ) + if "Projection" in native_input.keys() + else Option_None() + ), + ProvisionedThroughput=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ProvisionedThroughput( + native_input["ProvisionedThroughput"] + ) + ) + if "ProvisionedThroughput" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_TimeToLiveDescription(native_input): + return DafnyTimeToLiveDescription( + TimeToLiveStatus=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_TimeToLiveStatus( + native_input["TimeToLiveStatus"] + ) + ) + if "TimeToLiveStatus" in native_input.keys() + else Option_None() + ), + AttributeName=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[ + iter( + native_input["AttributeName"].encode( + "utf-16-be" + ) + ) + ] + * 2 + ) + ] + ) + ) + ) + if "AttributeName" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_TimeToLiveStatus(native_input): + # Convert TimeToLiveStatus + if native_input == "ENABLING": + return TimeToLiveStatus_ENABLING() + elif native_input == "DISABLING": + return TimeToLiveStatus_DISABLING() + elif native_input == "ENABLED": + return TimeToLiveStatus_ENABLED() + elif native_input == "DISABLED": + return TimeToLiveStatus_DISABLED() + else: + raise ValueError("No recognized enum value in enum type: " + native_input) + + +def com_amazonaws_dynamodb_DeleteItemInput(native_input): + return DafnyDeleteItemInput( + TableName=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["TableName"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + Key=Map( + { + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip(*[iter(key.encode("utf-16-be"))] * 2) + ] + ) + ): aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_AttributeValue( + value + ) + for (key, value) in native_input["Key"].items() + } + ), + Expected=( + Option_Some( + Map( + { + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(key.encode("utf-16-be"))] * 2 + ) + ] + ) + ): aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ExpectedAttributeValue( + value + ) + for (key, value) in native_input["Expected"].items() + } + ) + ) + if "Expected" in native_input.keys() + else Option_None() + ), + ConditionalOperator=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ConditionalOperator( + native_input["ConditionalOperator"] + ) + ) + if "ConditionalOperator" in native_input.keys() + else Option_None() + ), + ReturnValues=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ReturnValue( + native_input["ReturnValues"] + ) + ) + if "ReturnValues" in native_input.keys() + else Option_None() + ), + ReturnConsumedCapacity=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ReturnConsumedCapacity( + native_input["ReturnConsumedCapacity"] + ) + ) + if "ReturnConsumedCapacity" in native_input.keys() + else Option_None() + ), + ReturnItemCollectionMetrics=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ReturnItemCollectionMetrics( + native_input["ReturnItemCollectionMetrics"] + ) + ) + if "ReturnItemCollectionMetrics" in native_input.keys() + else Option_None() + ), + ConditionExpression=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[ + iter( + native_input["ConditionExpression"].encode( + "utf-16-be" + ) + ) + ] + * 2 + ) + ] + ) + ) + ) + if "ConditionExpression" in native_input.keys() + else Option_None() + ), + ExpressionAttributeNames=( + 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[ + "ExpressionAttributeNames" + ].items() + } + ) + ) + if "ExpressionAttributeNames" in native_input.keys() + else Option_None() + ), + ExpressionAttributeValues=( + Option_Some( + Map( + { + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(key.encode("utf-16-be"))] * 2 + ) + ] + ) + ): aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_AttributeValue( + value + ) + for (key, value) in native_input[ + "ExpressionAttributeValues" + ].items() + } + ) + ) + if "ExpressionAttributeValues" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_ExpectedAttributeValue(native_input): + return DafnyExpectedAttributeValue( + Value=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_AttributeValue( + native_input["Value"] + ) + ) + if "Value" in native_input.keys() + else Option_None() + ), + Exists=( + Option_Some(native_input["Exists"]) + if "Exists" in native_input.keys() + else Option_None() + ), + ComparisonOperator=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ComparisonOperator( + native_input["ComparisonOperator"] + ) + ) + if "ComparisonOperator" in native_input.keys() + else Option_None() + ), + AttributeValueList=( + Option_Some( + Seq( + [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_AttributeValue( + list_element + ) + for list_element in native_input["AttributeValueList"] + ] + ) + ) + if "AttributeValueList" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_ComparisonOperator(native_input): + # Convert ComparisonOperator + if native_input == "EQ": + return ComparisonOperator_EQ() + elif native_input == "NE": + return ComparisonOperator_NE() + elif native_input == "IN": + return ComparisonOperator_IN() + elif native_input == "LE": + return ComparisonOperator_LE() + elif native_input == "LT": + return ComparisonOperator_LT() + elif native_input == "GE": + return ComparisonOperator_GE() + elif native_input == "GT": + return ComparisonOperator_GT() + elif native_input == "BETWEEN": + return ComparisonOperator_BETWEEN() + elif native_input == "NOT_NULL": + return ComparisonOperator_NOT__NULL() + elif native_input == "NULL": + return ComparisonOperator_NULL() + elif native_input == "CONTAINS": + return ComparisonOperator_CONTAINS() + elif native_input == "NOT_CONTAINS": + return ComparisonOperator_NOT__CONTAINS() + elif native_input == "BEGINS_WITH": + return ComparisonOperator_BEGINS__WITH() + else: + raise ValueError("No recognized enum value in enum type: " + native_input) + + +def com_amazonaws_dynamodb_ConditionalOperator(native_input): + # Convert ConditionalOperator + if native_input == "AND": + return ConditionalOperator_AND() + elif native_input == "OR": + return ConditionalOperator_OR() + else: + raise ValueError("No recognized enum value in enum type: " + native_input) + + +def com_amazonaws_dynamodb_ReturnValue(native_input): + # Convert ReturnValue + if native_input == "NONE": + return ReturnValue_NONE() + elif native_input == "ALL_OLD": + return ReturnValue_ALL__OLD() + elif native_input == "UPDATED_OLD": + return ReturnValue_UPDATED__OLD() + elif native_input == "ALL_NEW": + return ReturnValue_ALL__NEW() + elif native_input == "UPDATED_NEW": + return ReturnValue_UPDATED__NEW() + else: + raise ValueError("No recognized enum value in enum type: " + native_input) + + +def com_amazonaws_dynamodb_DeleteItemOutput(native_input): + return DafnyDeleteItemOutput( + Attributes=( + Option_Some( + Map( + { + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(key.encode("utf-16-be"))] * 2 + ) + ] + ) + ): aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_AttributeValue( + value + ) + for (key, value) in native_input["Attributes"].items() + } + ) + ) + if "Attributes" in native_input.keys() + else Option_None() + ), + ConsumedCapacity=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ConsumedCapacity( + native_input["ConsumedCapacity"] + ) + ) + if "ConsumedCapacity" in native_input.keys() + else Option_None() + ), + ItemCollectionMetrics=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ItemCollectionMetrics( + native_input["ItemCollectionMetrics"] + ) + ) + if "ItemCollectionMetrics" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_DeleteTableInput(native_input): + return DafnyDeleteTableInput( + TableName=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["TableName"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_dynamodb_DeleteTableOutput(native_input): + return DafnyDeleteTableOutput( + TableDescription=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_TableDescription( + native_input["TableDescription"] + ) + ) + if "TableDescription" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_DescribeBackupInput(native_input): + return DafnyDescribeBackupInput( + BackupArn=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["BackupArn"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_dynamodb_DescribeBackupOutput(native_input): + return DafnyDescribeBackupOutput( + BackupDescription=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_BackupDescription( + native_input["BackupDescription"] + ) + ) + if "BackupDescription" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_DescribeContinuousBackupsInput(native_input): + return DafnyDescribeContinuousBackupsInput( + TableName=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["TableName"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_dynamodb_DescribeContinuousBackupsOutput(native_input): + return DafnyDescribeContinuousBackupsOutput( + ContinuousBackupsDescription=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ContinuousBackupsDescription( + native_input["ContinuousBackupsDescription"] + ) + ) + if "ContinuousBackupsDescription" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_ContinuousBackupsDescription(native_input): + return DafnyContinuousBackupsDescription( + ContinuousBackupsStatus=aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ContinuousBackupsStatus( + native_input["ContinuousBackupsStatus"] + ), + PointInTimeRecoveryDescription=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_PointInTimeRecoveryDescription( + native_input["PointInTimeRecoveryDescription"] + ) + ) + if "PointInTimeRecoveryDescription" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_ContinuousBackupsStatus(native_input): + # Convert ContinuousBackupsStatus + if native_input == "ENABLED": + return ContinuousBackupsStatus_ENABLED() + elif native_input == "DISABLED": + return ContinuousBackupsStatus_DISABLED() + else: + raise ValueError("No recognized enum value in enum type: " + native_input) + + +def com_amazonaws_dynamodb_PointInTimeRecoveryDescription(native_input): + return DafnyPointInTimeRecoveryDescription( + PointInTimeRecoveryStatus=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_PointInTimeRecoveryStatus( + native_input["PointInTimeRecoveryStatus"] + ) + ) + if "PointInTimeRecoveryStatus" in native_input.keys() + else Option_None() + ), + EarliestRestorableDateTime=( + Option_Some( + _dafny.Seq(native_input["EarliestRestorableDateTime"].isoformat()) + ) + if "EarliestRestorableDateTime" in native_input.keys() + else Option_None() + ), + LatestRestorableDateTime=( + Option_Some( + _dafny.Seq(native_input["LatestRestorableDateTime"].isoformat()) + ) + if "LatestRestorableDateTime" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_PointInTimeRecoveryStatus(native_input): + # Convert PointInTimeRecoveryStatus + if native_input == "ENABLED": + return PointInTimeRecoveryStatus_ENABLED() + elif native_input == "DISABLED": + return PointInTimeRecoveryStatus_DISABLED() + else: + raise ValueError("No recognized enum value in enum type: " + native_input) + + +def com_amazonaws_dynamodb_DescribeContributorInsightsInput(native_input): + return DafnyDescribeContributorInsightsInput( + TableName=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["TableName"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + IndexName=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["IndexName"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ) + ) + if "IndexName" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_DescribeContributorInsightsOutput(native_input): + return DafnyDescribeContributorInsightsOutput( + TableName=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["TableName"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ) + ) + if "TableName" in native_input.keys() + else Option_None() + ), + IndexName=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["IndexName"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ) + ) + if "IndexName" in native_input.keys() + else Option_None() + ), + ContributorInsightsRuleList=( + 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["ContributorInsightsRuleList"] + ] + ) + ) + if "ContributorInsightsRuleList" in native_input.keys() + else Option_None() + ), + ContributorInsightsStatus=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ContributorInsightsStatus( + native_input["ContributorInsightsStatus"] + ) + ) + if "ContributorInsightsStatus" in native_input.keys() + else Option_None() + ), + LastUpdateDateTime=( + Option_Some(_dafny.Seq(native_input["LastUpdateDateTime"].isoformat())) + if "LastUpdateDateTime" in native_input.keys() + else Option_None() + ), + FailureException=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_FailureException( + native_input["FailureException"] + ) + ) + if "FailureException" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_ContributorInsightsStatus(native_input): + # Convert ContributorInsightsStatus + if native_input == "ENABLING": + return ContributorInsightsStatus_ENABLING() + elif native_input == "ENABLED": + return ContributorInsightsStatus_ENABLED() + elif native_input == "DISABLING": + return ContributorInsightsStatus_DISABLING() + elif native_input == "DISABLED": + return ContributorInsightsStatus_DISABLED() + elif native_input == "FAILED": + return ContributorInsightsStatus_FAILED() + else: + raise ValueError("No recognized enum value in enum type: " + native_input) + + +def com_amazonaws_dynamodb_FailureException(native_input): + return DafnyFailureException( + ExceptionName=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[ + iter( + native_input["ExceptionName"].encode( + "utf-16-be" + ) + ) + ] + * 2 + ) + ] + ) + ) + ) + if "ExceptionName" in native_input.keys() + else Option_None() + ), + ExceptionDescription=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[ + iter( + native_input["ExceptionDescription"].encode( + "utf-16-be" + ) + ) + ] + * 2 + ) + ] + ) + ) + ) + if "ExceptionDescription" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_DescribeEndpointsRequest(native_input): + return DafnyDescribeEndpointsRequest() + + +def com_amazonaws_dynamodb_DescribeEndpointsResponse(native_input): + return DafnyDescribeEndpointsResponse( + Endpoints=Seq( + [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_Endpoint( + list_element + ) + for list_element in native_input["Endpoints"] + ] + ), + ) + + +def com_amazonaws_dynamodb_Endpoint(native_input): + return DafnyEndpoint( + Address=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Address"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + CachePeriodInMinutes=native_input["CachePeriodInMinutes"], + ) + + +def com_amazonaws_dynamodb_DescribeExportInput(native_input): + return DafnyDescribeExportInput( + ExportArn=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["ExportArn"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_dynamodb_DescribeExportOutput(native_input): + return DafnyDescribeExportOutput( + ExportDescription=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ExportDescription( + native_input["ExportDescription"] + ) + ) + if "ExportDescription" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_ExportDescription(native_input): + return DafnyExportDescription( + ExportArn=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["ExportArn"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ) + ) + if "ExportArn" in native_input.keys() + else Option_None() + ), + ExportStatus=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ExportStatus( + native_input["ExportStatus"] + ) + ) + if "ExportStatus" in native_input.keys() + else Option_None() + ), + StartTime=( + Option_Some(_dafny.Seq(native_input["StartTime"].isoformat())) + if "StartTime" in native_input.keys() + else Option_None() + ), + EndTime=( + Option_Some(_dafny.Seq(native_input["EndTime"].isoformat())) + if "EndTime" in native_input.keys() + else Option_None() + ), + ExportManifest=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[ + iter( + native_input["ExportManifest"].encode( + "utf-16-be" + ) + ) + ] + * 2 + ) + ] + ) + ) + ) + if "ExportManifest" in native_input.keys() + else Option_None() + ), + TableArn=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["TableArn"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ) + ) + if "TableArn" in native_input.keys() + else Option_None() + ), + TableId=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["TableId"].encode("utf-16-be"))] * 2 + ) + ] + ) + ) + ) + if "TableId" in native_input.keys() + else Option_None() + ), + ExportTime=( + Option_Some(_dafny.Seq(native_input["ExportTime"].isoformat())) + if "ExportTime" in native_input.keys() + else Option_None() + ), + ClientToken=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["ClientToken"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ) + ) + if "ClientToken" in native_input.keys() + else Option_None() + ), + S3Bucket=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["S3Bucket"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ) + ) + if "S3Bucket" in native_input.keys() + else Option_None() + ), + S3BucketOwner=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[ + iter( + native_input["S3BucketOwner"].encode( + "utf-16-be" + ) + ) + ] + * 2 + ) + ] + ) + ) + ) + if "S3BucketOwner" in native_input.keys() + else Option_None() + ), + S3Prefix=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["S3Prefix"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ) + ) + if "S3Prefix" in native_input.keys() + else Option_None() + ), + S3SseAlgorithm=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_S3SseAlgorithm( + native_input["S3SseAlgorithm"] + ) + ) + if "S3SseAlgorithm" in native_input.keys() + else Option_None() + ), + S3SseKmsKeyId=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[ + iter( + native_input["S3SseKmsKeyId"].encode( + "utf-16-be" + ) + ) + ] + * 2 + ) + ] + ) + ) + ) + if "S3SseKmsKeyId" in native_input.keys() + else Option_None() + ), + FailureCode=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["FailureCode"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ) + ) + if "FailureCode" in native_input.keys() + else Option_None() + ), + FailureMessage=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[ + iter( + native_input["FailureMessage"].encode( + "utf-16-be" + ) + ) + ] + * 2 + ) + ] + ) + ) + ) + if "FailureMessage" in native_input.keys() + else Option_None() + ), + ExportFormat=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ExportFormat( + native_input["ExportFormat"] + ) + ) + if "ExportFormat" in native_input.keys() + else Option_None() + ), + BilledSizeBytes=( + Option_Some(native_input["BilledSizeBytes"]) + if "BilledSizeBytes" in native_input.keys() + else Option_None() + ), + ItemCount=( + Option_Some(native_input["ItemCount"]) + if "ItemCount" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_ExportStatus(native_input): + # Convert ExportStatus + if native_input == "IN_PROGRESS": + return ExportStatus_IN__PROGRESS() + elif native_input == "COMPLETED": + return ExportStatus_COMPLETED() + elif native_input == "FAILED": + return ExportStatus_FAILED() + else: + raise ValueError("No recognized enum value in enum type: " + native_input) + + +def com_amazonaws_dynamodb_S3SseAlgorithm(native_input): + # Convert S3SseAlgorithm + if native_input == "AES256": + return S3SseAlgorithm_AES256() + elif native_input == "KMS": + return S3SseAlgorithm_KMS() + else: + raise ValueError("No recognized enum value in enum type: " + native_input) + + +def com_amazonaws_dynamodb_ExportFormat(native_input): + # Convert ExportFormat + if native_input == "DYNAMODB_JSON": + return ExportFormat_DYNAMODB__JSON() + elif native_input == "ION": + return ExportFormat_ION() + else: + raise ValueError("No recognized enum value in enum type: " + native_input) + + +def com_amazonaws_dynamodb_DescribeGlobalTableInput(native_input): + return DafnyDescribeGlobalTableInput( + GlobalTableName=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["GlobalTableName"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_dynamodb_DescribeGlobalTableOutput(native_input): + return DafnyDescribeGlobalTableOutput( + GlobalTableDescription=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_GlobalTableDescription( + native_input["GlobalTableDescription"] + ) + ) + if "GlobalTableDescription" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_DescribeGlobalTableSettingsInput(native_input): + return DafnyDescribeGlobalTableSettingsInput( + GlobalTableName=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["GlobalTableName"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_dynamodb_DescribeGlobalTableSettingsOutput(native_input): + return DafnyDescribeGlobalTableSettingsOutput( + GlobalTableName=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[ + iter( + native_input["GlobalTableName"].encode( + "utf-16-be" + ) + ) + ] + * 2 + ) + ] + ) + ) + ) + if "GlobalTableName" in native_input.keys() + else Option_None() + ), + ReplicaSettings=( + Option_Some( + Seq( + [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ReplicaSettingsDescription( + list_element + ) + for list_element in native_input["ReplicaSettings"] + ] + ) + ) + if "ReplicaSettings" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_ReplicaSettingsDescription(native_input): + return DafnyReplicaSettingsDescription( + RegionName=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["RegionName"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + ReplicaStatus=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ReplicaStatus( + native_input["ReplicaStatus"] + ) + ) + if "ReplicaStatus" in native_input.keys() + else Option_None() + ), + ReplicaBillingModeSummary=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_BillingModeSummary( + native_input["ReplicaBillingModeSummary"] + ) + ) + if "ReplicaBillingModeSummary" in native_input.keys() + else Option_None() + ), + ReplicaProvisionedReadCapacityUnits=( + Option_Some(native_input["ReplicaProvisionedReadCapacityUnits"]) + if "ReplicaProvisionedReadCapacityUnits" in native_input.keys() + else Option_None() + ), + ReplicaProvisionedReadCapacityAutoScalingSettings=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_AutoScalingSettingsDescription( + native_input["ReplicaProvisionedReadCapacityAutoScalingSettings"] + ) + ) + if "ReplicaProvisionedReadCapacityAutoScalingSettings" + in native_input.keys() + else Option_None() + ), + ReplicaProvisionedWriteCapacityUnits=( + Option_Some(native_input["ReplicaProvisionedWriteCapacityUnits"]) + if "ReplicaProvisionedWriteCapacityUnits" in native_input.keys() + else Option_None() + ), + ReplicaProvisionedWriteCapacityAutoScalingSettings=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_AutoScalingSettingsDescription( + native_input["ReplicaProvisionedWriteCapacityAutoScalingSettings"] + ) + ) + if "ReplicaProvisionedWriteCapacityAutoScalingSettings" + in native_input.keys() + else Option_None() + ), + ReplicaGlobalSecondaryIndexSettings=( + Option_Some( + Seq( + [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ReplicaGlobalSecondaryIndexSettingsDescription( + list_element + ) + for list_element in native_input[ + "ReplicaGlobalSecondaryIndexSettings" + ] + ] + ) + ) + if "ReplicaGlobalSecondaryIndexSettings" in native_input.keys() + else Option_None() + ), + ReplicaTableClassSummary=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_TableClassSummary( + native_input["ReplicaTableClassSummary"] + ) + ) + if "ReplicaTableClassSummary" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_AutoScalingSettingsDescription(native_input): + return DafnyAutoScalingSettingsDescription( + MinimumUnits=( + Option_Some(native_input["MinimumUnits"]) + if "MinimumUnits" in native_input.keys() + else Option_None() + ), + MaximumUnits=( + Option_Some(native_input["MaximumUnits"]) + if "MaximumUnits" in native_input.keys() + else Option_None() + ), + AutoScalingDisabled=( + Option_Some(native_input["AutoScalingDisabled"]) + if "AutoScalingDisabled" in native_input.keys() + else Option_None() + ), + AutoScalingRoleArn=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[ + iter( + native_input["AutoScalingRoleArn"].encode( + "utf-16-be" + ) + ) + ] + * 2 + ) + ] + ) + ) + ) + if "AutoScalingRoleArn" in native_input.keys() + else Option_None() + ), + ScalingPolicies=( + Option_Some( + Seq( + [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_AutoScalingPolicyDescription( + list_element + ) + for list_element in native_input["ScalingPolicies"] + ] + ) + ) + if "ScalingPolicies" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_ReplicaGlobalSecondaryIndexSettingsDescription(native_input): + return DafnyReplicaGlobalSecondaryIndexSettingsDescription( + IndexName=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["IndexName"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + IndexStatus=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_IndexStatus( + native_input["IndexStatus"] + ) + ) + if "IndexStatus" in native_input.keys() + else Option_None() + ), + ProvisionedReadCapacityUnits=( + Option_Some(native_input["ProvisionedReadCapacityUnits"]) + if "ProvisionedReadCapacityUnits" in native_input.keys() + else Option_None() + ), + ProvisionedReadCapacityAutoScalingSettings=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_AutoScalingSettingsDescription( + native_input["ProvisionedReadCapacityAutoScalingSettings"] + ) + ) + if "ProvisionedReadCapacityAutoScalingSettings" in native_input.keys() + else Option_None() + ), + ProvisionedWriteCapacityUnits=( + Option_Some(native_input["ProvisionedWriteCapacityUnits"]) + if "ProvisionedWriteCapacityUnits" in native_input.keys() + else Option_None() + ), + ProvisionedWriteCapacityAutoScalingSettings=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_AutoScalingSettingsDescription( + native_input["ProvisionedWriteCapacityAutoScalingSettings"] + ) + ) + if "ProvisionedWriteCapacityAutoScalingSettings" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_AutoScalingPolicyDescription(native_input): + return DafnyAutoScalingPolicyDescription( + PolicyName=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["PolicyName"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ) + ) + if "PolicyName" in native_input.keys() + else Option_None() + ), + TargetTrackingScalingPolicyConfiguration=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_AutoScalingTargetTrackingScalingPolicyConfigurationDescription( + native_input["TargetTrackingScalingPolicyConfiguration"] + ) + ) + if "TargetTrackingScalingPolicyConfiguration" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_AutoScalingTargetTrackingScalingPolicyConfigurationDescription( + native_input, +): + return DafnyAutoScalingTargetTrackingScalingPolicyConfigurationDescription( + DisableScaleIn=( + Option_Some(native_input["DisableScaleIn"]) + if "DisableScaleIn" in native_input.keys() + else Option_None() + ), + ScaleInCooldown=( + Option_Some(native_input["ScaleInCooldown"]) + if "ScaleInCooldown" in native_input.keys() + else Option_None() + ), + ScaleOutCooldown=( + Option_Some(native_input["ScaleOutCooldown"]) + if "ScaleOutCooldown" in native_input.keys() + else Option_None() + ), + TargetValue=native_input["TargetValue"], + ) + + +def com_amazonaws_dynamodb_DescribeImportInput(native_input): + return DafnyDescribeImportInput( + ImportArn=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["ImportArn"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_dynamodb_DescribeImportOutput(native_input): + return DafnyDescribeImportOutput( + ImportTableDescription=aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ImportTableDescription( + native_input["ImportTableDescription"] + ), + ) + + +def com_amazonaws_dynamodb_ImportTableDescription(native_input): + return DafnyImportTableDescription( + ImportArn=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["ImportArn"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ) + ) + if "ImportArn" in native_input.keys() + else Option_None() + ), + ImportStatus=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ImportStatus( + native_input["ImportStatus"] + ) + ) + if "ImportStatus" in native_input.keys() + else Option_None() + ), + TableArn=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["TableArn"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ) + ) + if "TableArn" in native_input.keys() + else Option_None() + ), + TableId=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["TableId"].encode("utf-16-be"))] * 2 + ) + ] + ) + ) + ) + if "TableId" in native_input.keys() + else Option_None() + ), + ClientToken=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["ClientToken"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ) + ) + if "ClientToken" in native_input.keys() + else Option_None() + ), + S3BucketSource=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_S3BucketSource( + native_input["S3BucketSource"] + ) + ) + if "S3BucketSource" in native_input.keys() + else Option_None() + ), + ErrorCount=( + Option_Some(native_input["ErrorCount"]) + if "ErrorCount" in native_input.keys() + else Option_None() + ), + CloudWatchLogGroupArn=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[ + iter( + native_input["CloudWatchLogGroupArn"].encode( + "utf-16-be" + ) + ) + ] + * 2 + ) + ] + ) + ) + ) + if "CloudWatchLogGroupArn" in native_input.keys() + else Option_None() + ), + InputFormat=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_InputFormat( + native_input["InputFormat"] + ) + ) + if "InputFormat" in native_input.keys() + else Option_None() + ), + InputFormatOptions=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_InputFormatOptions( + native_input["InputFormatOptions"] + ) + ) + if "InputFormatOptions" in native_input.keys() + else Option_None() + ), + InputCompressionType=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_InputCompressionType( + native_input["InputCompressionType"] + ) + ) + if "InputCompressionType" in native_input.keys() + else Option_None() + ), + TableCreationParameters=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_TableCreationParameters( + native_input["TableCreationParameters"] + ) + ) + if "TableCreationParameters" in native_input.keys() + else Option_None() + ), + StartTime=( + Option_Some(_dafny.Seq(native_input["StartTime"].isoformat())) + if "StartTime" in native_input.keys() + else Option_None() + ), + EndTime=( + Option_Some(_dafny.Seq(native_input["EndTime"].isoformat())) + if "EndTime" in native_input.keys() + else Option_None() + ), + ProcessedSizeBytes=( + Option_Some(native_input["ProcessedSizeBytes"]) + if "ProcessedSizeBytes" in native_input.keys() + else Option_None() + ), + ProcessedItemCount=( + Option_Some(native_input["ProcessedItemCount"]) + if "ProcessedItemCount" in native_input.keys() + else Option_None() + ), + ImportedItemCount=( + Option_Some(native_input["ImportedItemCount"]) + if "ImportedItemCount" in native_input.keys() + else Option_None() + ), + FailureCode=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["FailureCode"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ) + ) + if "FailureCode" in native_input.keys() + else Option_None() + ), + FailureMessage=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[ + iter( + native_input["FailureMessage"].encode( + "utf-16-be" + ) + ) + ] + * 2 + ) + ] + ) + ) + ) + if "FailureMessage" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_ImportStatus(native_input): + # Convert ImportStatus + if native_input == "IN_PROGRESS": + return ImportStatus_IN__PROGRESS() + elif native_input == "COMPLETED": + return ImportStatus_COMPLETED() + elif native_input == "CANCELLING": + return ImportStatus_CANCELLING() + elif native_input == "CANCELLED": + return ImportStatus_CANCELLED() + elif native_input == "FAILED": + return ImportStatus_FAILED() + else: + raise ValueError("No recognized enum value in enum type: " + native_input) + + +def com_amazonaws_dynamodb_S3BucketSource(native_input): + return DafnyS3BucketSource( + S3BucketOwner=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[ + iter( + native_input["S3BucketOwner"].encode( + "utf-16-be" + ) + ) + ] + * 2 + ) + ] + ) + ) + ) + if "S3BucketOwner" in native_input.keys() + else Option_None() + ), + S3Bucket=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["S3Bucket"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + S3KeyPrefix=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["S3KeyPrefix"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ) + ) + if "S3KeyPrefix" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_InputFormat(native_input): + # Convert InputFormat + if native_input == "DYNAMODB_JSON": + return InputFormat_DYNAMODB__JSON() + elif native_input == "ION": + return InputFormat_ION() + elif native_input == "CSV": + return InputFormat_CSV() + else: + raise ValueError("No recognized enum value in enum type: " + native_input) + + +def com_amazonaws_dynamodb_InputFormatOptions(native_input): + return DafnyInputFormatOptions( + Csv=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_CsvOptions( + native_input["Csv"] + ) + ) + if "Csv" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_InputCompressionType(native_input): + # Convert InputCompressionType + if native_input == "GZIP": + return InputCompressionType_GZIP() + elif native_input == "ZSTD": + return InputCompressionType_ZSTD() + elif native_input == "NONE": + return InputCompressionType_NONE() + else: + raise ValueError("No recognized enum value in enum type: " + native_input) + + +def com_amazonaws_dynamodb_TableCreationParameters(native_input): + return DafnyTableCreationParameters( + TableName=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["TableName"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + AttributeDefinitions=Seq( + [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_AttributeDefinition( + list_element + ) + for list_element in native_input["AttributeDefinitions"] + ] + ), + KeySchema=Seq( + [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_KeySchemaElement( + list_element + ) + for list_element in native_input["KeySchema"] + ] + ), + BillingMode=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_BillingMode( + native_input["BillingMode"] + ) + ) + if "BillingMode" in native_input.keys() + else Option_None() + ), + ProvisionedThroughput=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ProvisionedThroughput( + native_input["ProvisionedThroughput"] + ) + ) + if "ProvisionedThroughput" in native_input.keys() + else Option_None() + ), + SSESpecification=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_SSESpecification( + native_input["SSESpecification"] + ) + ) + if "SSESpecification" in native_input.keys() + else Option_None() + ), + GlobalSecondaryIndexes=( + Option_Some( + Seq( + [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_GlobalSecondaryIndex( + list_element + ) + for list_element in native_input["GlobalSecondaryIndexes"] + ] + ) + ) + if "GlobalSecondaryIndexes" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_CsvOptions(native_input): + return DafnyCsvOptions( + Delimiter=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Delimiter"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ) + ) + if "Delimiter" in native_input.keys() + else Option_None() + ), + HeaderList=( + 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["HeaderList"] + ] + ) + ) + if "HeaderList" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_DescribeKinesisStreamingDestinationInput(native_input): + return DafnyDescribeKinesisStreamingDestinationInput( + TableName=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["TableName"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_dynamodb_DescribeKinesisStreamingDestinationOutput(native_input): + return DafnyDescribeKinesisStreamingDestinationOutput( + TableName=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["TableName"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ) + ) + if "TableName" in native_input.keys() + else Option_None() + ), + KinesisDataStreamDestinations=( + Option_Some( + Seq( + [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_KinesisDataStreamDestination( + list_element + ) + for list_element in native_input[ + "KinesisDataStreamDestinations" + ] + ] + ) + ) + if "KinesisDataStreamDestinations" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_KinesisDataStreamDestination(native_input): + return DafnyKinesisDataStreamDestination( + StreamArn=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["StreamArn"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ) + ) + if "StreamArn" in native_input.keys() + else Option_None() + ), + DestinationStatus=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_DestinationStatus( + native_input["DestinationStatus"] + ) + ) + if "DestinationStatus" in native_input.keys() + else Option_None() + ), + DestinationStatusDescription=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[ + iter( + native_input[ + "DestinationStatusDescription" + ].encode("utf-16-be") + ) + ] + * 2 + ) + ] + ) + ) + ) + if "DestinationStatusDescription" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_DestinationStatus(native_input): + # Convert DestinationStatus + if native_input == "ENABLING": + return DestinationStatus_ENABLING() + elif native_input == "ACTIVE": + return DestinationStatus_ACTIVE() + elif native_input == "DISABLING": + return DestinationStatus_DISABLING() + elif native_input == "DISABLED": + return DestinationStatus_DISABLED() + elif native_input == "ENABLE_FAILED": + return DestinationStatus_ENABLE__FAILED() + else: + raise ValueError("No recognized enum value in enum type: " + native_input) + + +def com_amazonaws_dynamodb_DescribeLimitsInput(native_input): + return DafnyDescribeLimitsInput() + + +def com_amazonaws_dynamodb_DescribeLimitsOutput(native_input): + return DafnyDescribeLimitsOutput( + AccountMaxReadCapacityUnits=( + Option_Some(native_input["AccountMaxReadCapacityUnits"]) + if "AccountMaxReadCapacityUnits" in native_input.keys() + else Option_None() + ), + AccountMaxWriteCapacityUnits=( + Option_Some(native_input["AccountMaxWriteCapacityUnits"]) + if "AccountMaxWriteCapacityUnits" in native_input.keys() + else Option_None() + ), + TableMaxReadCapacityUnits=( + Option_Some(native_input["TableMaxReadCapacityUnits"]) + if "TableMaxReadCapacityUnits" in native_input.keys() + else Option_None() + ), + TableMaxWriteCapacityUnits=( + Option_Some(native_input["TableMaxWriteCapacityUnits"]) + if "TableMaxWriteCapacityUnits" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_DescribeTableInput(native_input): + return DafnyDescribeTableInput( + TableName=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["TableName"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_dynamodb_DescribeTableOutput(native_input): + return DafnyDescribeTableOutput( + Table=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_TableDescription( + native_input["Table"] + ) + ) + if "Table" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_DescribeTableReplicaAutoScalingInput(native_input): + return DafnyDescribeTableReplicaAutoScalingInput( + TableName=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["TableName"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_dynamodb_DescribeTableReplicaAutoScalingOutput(native_input): + return DafnyDescribeTableReplicaAutoScalingOutput( + TableAutoScalingDescription=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_TableAutoScalingDescription( + native_input["TableAutoScalingDescription"] + ) + ) + if "TableAutoScalingDescription" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_TableAutoScalingDescription(native_input): + return DafnyTableAutoScalingDescription( + TableName=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["TableName"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ) + ) + if "TableName" in native_input.keys() + else Option_None() + ), + TableStatus=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_TableStatus( + native_input["TableStatus"] + ) + ) + if "TableStatus" in native_input.keys() + else Option_None() + ), + Replicas=( + Option_Some( + Seq( + [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ReplicaAutoScalingDescription( + list_element + ) + for list_element in native_input["Replicas"] + ] + ) + ) + if "Replicas" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_ReplicaAutoScalingDescription(native_input): + return DafnyReplicaAutoScalingDescription( + RegionName=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["RegionName"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ) + ) + if "RegionName" in native_input.keys() + else Option_None() + ), + GlobalSecondaryIndexes=( + Option_Some( + Seq( + [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ReplicaGlobalSecondaryIndexAutoScalingDescription( + list_element + ) + for list_element in native_input["GlobalSecondaryIndexes"] + ] + ) + ) + if "GlobalSecondaryIndexes" in native_input.keys() + else Option_None() + ), + ReplicaProvisionedReadCapacityAutoScalingSettings=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_AutoScalingSettingsDescription( + native_input["ReplicaProvisionedReadCapacityAutoScalingSettings"] + ) + ) + if "ReplicaProvisionedReadCapacityAutoScalingSettings" + in native_input.keys() + else Option_None() + ), + ReplicaProvisionedWriteCapacityAutoScalingSettings=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_AutoScalingSettingsDescription( + native_input["ReplicaProvisionedWriteCapacityAutoScalingSettings"] + ) + ) + if "ReplicaProvisionedWriteCapacityAutoScalingSettings" + in native_input.keys() + else Option_None() + ), + ReplicaStatus=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ReplicaStatus( + native_input["ReplicaStatus"] + ) + ) + if "ReplicaStatus" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_ReplicaGlobalSecondaryIndexAutoScalingDescription( + native_input, +): + return DafnyReplicaGlobalSecondaryIndexAutoScalingDescription( + IndexName=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["IndexName"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ) + ) + if "IndexName" in native_input.keys() + else Option_None() + ), + IndexStatus=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_IndexStatus( + native_input["IndexStatus"] + ) + ) + if "IndexStatus" in native_input.keys() + else Option_None() + ), + ProvisionedReadCapacityAutoScalingSettings=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_AutoScalingSettingsDescription( + native_input["ProvisionedReadCapacityAutoScalingSettings"] + ) + ) + if "ProvisionedReadCapacityAutoScalingSettings" in native_input.keys() + else Option_None() + ), + ProvisionedWriteCapacityAutoScalingSettings=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_AutoScalingSettingsDescription( + native_input["ProvisionedWriteCapacityAutoScalingSettings"] + ) + ) + if "ProvisionedWriteCapacityAutoScalingSettings" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_DescribeTimeToLiveInput(native_input): + return DafnyDescribeTimeToLiveInput( + TableName=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["TableName"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_dynamodb_DescribeTimeToLiveOutput(native_input): + return DafnyDescribeTimeToLiveOutput( + TimeToLiveDescription=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_TimeToLiveDescription( + native_input["TimeToLiveDescription"] + ) + ) + if "TimeToLiveDescription" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_DisableKinesisStreamingDestinationInput(native_input): + return DafnyDisableKinesisStreamingDestinationInput( + TableName=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["TableName"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + StreamArn=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["StreamArn"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_dynamodb_DisableKinesisStreamingDestinationOutput(native_input): + return DafnyDisableKinesisStreamingDestinationOutput( + TableName=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["TableName"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ) + ) + if "TableName" in native_input.keys() + else Option_None() + ), + StreamArn=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["StreamArn"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ) + ) + if "StreamArn" in native_input.keys() + else Option_None() + ), + DestinationStatus=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_DestinationStatus( + native_input["DestinationStatus"] + ) + ) + if "DestinationStatus" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_EnableKinesisStreamingDestinationInput(native_input): + return DafnyEnableKinesisStreamingDestinationInput( + TableName=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["TableName"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + StreamArn=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["StreamArn"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_dynamodb_EnableKinesisStreamingDestinationOutput(native_input): + return DafnyEnableKinesisStreamingDestinationOutput( + TableName=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["TableName"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ) + ) + if "TableName" in native_input.keys() + else Option_None() + ), + StreamArn=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["StreamArn"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ) + ) + if "StreamArn" in native_input.keys() + else Option_None() + ), + DestinationStatus=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_DestinationStatus( + native_input["DestinationStatus"] + ) + ) + if "DestinationStatus" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_ExecuteStatementInput(native_input): + return DafnyExecuteStatementInput( + Statement=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Statement"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + Parameters=( + Option_Some( + Seq( + [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_AttributeValue( + list_element + ) + for list_element in native_input["Parameters"] + ] + ) + ) + if "Parameters" in native_input.keys() + else Option_None() + ), + ConsistentRead=( + Option_Some(native_input["ConsistentRead"]) + if "ConsistentRead" in native_input.keys() + else Option_None() + ), + NextToken=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["NextToken"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ) + ) + if "NextToken" in native_input.keys() + else Option_None() + ), + ReturnConsumedCapacity=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ReturnConsumedCapacity( + native_input["ReturnConsumedCapacity"] + ) + ) + if "ReturnConsumedCapacity" in native_input.keys() + else Option_None() + ), + Limit=( + Option_Some(native_input["Limit"]) + if "Limit" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_ExecuteStatementOutput(native_input): + return DafnyExecuteStatementOutput( + Items=( + Option_Some( + Seq( + [ + Map( + { + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(key.encode("utf-16-be"))] * 2 + ) + ] + ) + ): aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_AttributeValue( + value + ) + for (key, value) in list_element.items() + } + ) + for list_element in native_input["Items"] + ] + ) + ) + if "Items" in native_input.keys() + else Option_None() + ), + NextToken=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["NextToken"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ) + ) + if "NextToken" in native_input.keys() + else Option_None() + ), + ConsumedCapacity=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ConsumedCapacity( + native_input["ConsumedCapacity"] + ) + ) + if "ConsumedCapacity" in native_input.keys() + else Option_None() + ), + LastEvaluatedKey=( + Option_Some( + Map( + { + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(key.encode("utf-16-be"))] * 2 + ) + ] + ) + ): aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_AttributeValue( + value + ) + for (key, value) in native_input["LastEvaluatedKey"].items() + } + ) + ) + if "LastEvaluatedKey" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_ExecuteTransactionInput(native_input): + return DafnyExecuteTransactionInput( + TransactStatements=Seq( + [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ParameterizedStatement( + list_element + ) + for list_element in native_input["TransactStatements"] + ] + ), + ClientRequestToken=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[ + iter( + native_input["ClientRequestToken"].encode( + "utf-16-be" + ) + ) + ] + * 2 + ) + ] + ) + ) + ) + if "ClientRequestToken" in native_input.keys() + else Option_None() + ), + ReturnConsumedCapacity=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ReturnConsumedCapacity( + native_input["ReturnConsumedCapacity"] + ) + ) + if "ReturnConsumedCapacity" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_ParameterizedStatement(native_input): + return DafnyParameterizedStatement( + Statement=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Statement"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + Parameters=( + Option_Some( + Seq( + [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_AttributeValue( + list_element + ) + for list_element in native_input["Parameters"] + ] + ) + ) + if "Parameters" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_ExecuteTransactionOutput(native_input): + return DafnyExecuteTransactionOutput( + Responses=( + Option_Some( + Seq( + [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ItemResponse( + list_element + ) + for list_element in native_input["Responses"] + ] + ) + ) + if "Responses" in native_input.keys() + else Option_None() + ), + ConsumedCapacity=( + Option_Some( + Seq( + [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ConsumedCapacity( + list_element + ) + for list_element in native_input["ConsumedCapacity"] + ] + ) + ) + if "ConsumedCapacity" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_ItemResponse(native_input): + return DafnyItemResponse( + Item=( + Option_Some( + Map( + { + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(key.encode("utf-16-be"))] * 2 + ) + ] + ) + ): aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_AttributeValue( + value + ) + for (key, value) in native_input["Item"].items() + } + ) + ) + if "Item" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_ExportTableToPointInTimeInput(native_input): + return DafnyExportTableToPointInTimeInput( + TableArn=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["TableArn"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + ExportTime=( + Option_Some(_dafny.Seq(native_input["ExportTime"].isoformat())) + if "ExportTime" in native_input.keys() + else Option_None() + ), + ClientToken=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["ClientToken"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ) + ) + if "ClientToken" in native_input.keys() + else Option_None() + ), + S3Bucket=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["S3Bucket"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + S3BucketOwner=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[ + iter( + native_input["S3BucketOwner"].encode( + "utf-16-be" + ) + ) + ] + * 2 + ) + ] + ) + ) + ) + if "S3BucketOwner" in native_input.keys() + else Option_None() + ), + S3Prefix=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["S3Prefix"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ) + ) + if "S3Prefix" in native_input.keys() + else Option_None() + ), + S3SseAlgorithm=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_S3SseAlgorithm( + native_input["S3SseAlgorithm"] + ) + ) + if "S3SseAlgorithm" in native_input.keys() + else Option_None() + ), + S3SseKmsKeyId=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[ + iter( + native_input["S3SseKmsKeyId"].encode( + "utf-16-be" + ) + ) + ] + * 2 + ) + ] + ) + ) + ) + if "S3SseKmsKeyId" in native_input.keys() + else Option_None() + ), + ExportFormat=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ExportFormat( + native_input["ExportFormat"] + ) + ) + if "ExportFormat" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_ExportTableToPointInTimeOutput(native_input): + return DafnyExportTableToPointInTimeOutput( + ExportDescription=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ExportDescription( + native_input["ExportDescription"] + ) + ) + if "ExportDescription" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_GetItemInput(native_input): + return DafnyGetItemInput( + TableName=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["TableName"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + Key=Map( + { + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip(*[iter(key.encode("utf-16-be"))] * 2) + ] + ) + ): aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_AttributeValue( + value + ) + for (key, value) in native_input["Key"].items() + } + ), + AttributesToGet=( + 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["AttributesToGet"] + ] + ) + ) + if "AttributesToGet" in native_input.keys() + else Option_None() + ), + ConsistentRead=( + Option_Some(native_input["ConsistentRead"]) + if "ConsistentRead" in native_input.keys() + else Option_None() + ), + ReturnConsumedCapacity=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ReturnConsumedCapacity( + native_input["ReturnConsumedCapacity"] + ) + ) + if "ReturnConsumedCapacity" in native_input.keys() + else Option_None() + ), + ProjectionExpression=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[ + iter( + native_input["ProjectionExpression"].encode( + "utf-16-be" + ) + ) + ] + * 2 + ) + ] + ) + ) + ) + if "ProjectionExpression" in native_input.keys() + else Option_None() + ), + ExpressionAttributeNames=( + 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[ + "ExpressionAttributeNames" + ].items() + } + ) + ) + if "ExpressionAttributeNames" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_GetItemOutput(native_input): + return DafnyGetItemOutput( + Item=( + Option_Some( + Map( + { + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(key.encode("utf-16-be"))] * 2 + ) + ] + ) + ): aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_AttributeValue( + value + ) + for (key, value) in native_input["Item"].items() + } + ) + ) + if "Item" in native_input.keys() + else Option_None() + ), + ConsumedCapacity=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ConsumedCapacity( + native_input["ConsumedCapacity"] + ) + ) + if "ConsumedCapacity" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_ImportTableInput(native_input): + return DafnyImportTableInput( + ClientToken=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["ClientToken"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ) + ) + if "ClientToken" in native_input.keys() + else Option_None() + ), + S3BucketSource=aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_S3BucketSource( + native_input["S3BucketSource"] + ), + InputFormat=aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_InputFormat( + native_input["InputFormat"] + ), + InputFormatOptions=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_InputFormatOptions( + native_input["InputFormatOptions"] + ) + ) + if "InputFormatOptions" in native_input.keys() + else Option_None() + ), + InputCompressionType=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_InputCompressionType( + native_input["InputCompressionType"] + ) + ) + if "InputCompressionType" in native_input.keys() + else Option_None() + ), + TableCreationParameters=aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_TableCreationParameters( + native_input["TableCreationParameters"] + ), + ) + + +def com_amazonaws_dynamodb_ImportTableOutput(native_input): + return DafnyImportTableOutput( + ImportTableDescription=aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ImportTableDescription( + native_input["ImportTableDescription"] + ), + ) + + +def com_amazonaws_dynamodb_ListBackupsInput(native_input): + return DafnyListBackupsInput( + TableName=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["TableName"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ) + ) + if "TableName" in native_input.keys() + else Option_None() + ), + Limit=( + Option_Some(native_input["Limit"]) + if "Limit" in native_input.keys() + else Option_None() + ), + TimeRangeLowerBound=( + Option_Some(_dafny.Seq(native_input["TimeRangeLowerBound"].isoformat())) + if "TimeRangeLowerBound" in native_input.keys() + else Option_None() + ), + TimeRangeUpperBound=( + Option_Some(_dafny.Seq(native_input["TimeRangeUpperBound"].isoformat())) + if "TimeRangeUpperBound" in native_input.keys() + else Option_None() + ), + ExclusiveStartBackupArn=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[ + iter( + native_input["ExclusiveStartBackupArn"].encode( + "utf-16-be" + ) + ) + ] + * 2 + ) + ] + ) + ) + ) + if "ExclusiveStartBackupArn" in native_input.keys() + else Option_None() + ), + BackupType=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_BackupTypeFilter( + native_input["BackupType"] + ) + ) + if "BackupType" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_BackupTypeFilter(native_input): + # Convert BackupTypeFilter + if native_input == "USER": + return BackupTypeFilter_USER() + elif native_input == "SYSTEM": + return BackupTypeFilter_SYSTEM() + elif native_input == "AWS_BACKUP": + return BackupTypeFilter_AWS__BACKUP() + elif native_input == "ALL": + return BackupTypeFilter_ALL() + else: + raise ValueError("No recognized enum value in enum type: " + native_input) + + +def com_amazonaws_dynamodb_ListBackupsOutput(native_input): + return DafnyListBackupsOutput( + BackupSummaries=( + Option_Some( + Seq( + [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_BackupSummary( + list_element + ) + for list_element in native_input["BackupSummaries"] + ] + ) + ) + if "BackupSummaries" in native_input.keys() + else Option_None() + ), + LastEvaluatedBackupArn=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[ + iter( + native_input["LastEvaluatedBackupArn"].encode( + "utf-16-be" + ) + ) + ] + * 2 + ) + ] + ) + ) + ) + if "LastEvaluatedBackupArn" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_BackupSummary(native_input): + return DafnyBackupSummary( + TableName=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["TableName"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ) + ) + if "TableName" in native_input.keys() + else Option_None() + ), + TableId=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["TableId"].encode("utf-16-be"))] * 2 + ) + ] + ) + ) + ) + if "TableId" in native_input.keys() + else Option_None() + ), + TableArn=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["TableArn"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ) + ) + if "TableArn" in native_input.keys() + else Option_None() + ), + BackupArn=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["BackupArn"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ) + ) + if "BackupArn" in native_input.keys() + else Option_None() + ), + BackupName=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["BackupName"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ) + ) + if "BackupName" in native_input.keys() + else Option_None() + ), + BackupCreationDateTime=( + Option_Some(_dafny.Seq(native_input["BackupCreationDateTime"].isoformat())) + if "BackupCreationDateTime" in native_input.keys() + else Option_None() + ), + BackupExpiryDateTime=( + Option_Some(_dafny.Seq(native_input["BackupExpiryDateTime"].isoformat())) + if "BackupExpiryDateTime" in native_input.keys() + else Option_None() + ), + BackupStatus=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_BackupStatus( + native_input["BackupStatus"] + ) + ) + if "BackupStatus" in native_input.keys() + else Option_None() + ), + BackupType=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_BackupType( + native_input["BackupType"] + ) + ) + if "BackupType" in native_input.keys() + else Option_None() + ), + BackupSizeBytes=( + Option_Some(native_input["BackupSizeBytes"]) + if "BackupSizeBytes" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_ListContributorInsightsInput(native_input): + return DafnyListContributorInsightsInput( + TableName=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["TableName"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ) + ) + if "TableName" in native_input.keys() + else Option_None() + ), + NextToken=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["NextToken"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ) + ) + if "NextToken" in native_input.keys() + else Option_None() + ), + MaxResults=( + Option_Some(native_input["MaxResults"]) + if "MaxResults" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_ListContributorInsightsOutput(native_input): + return DafnyListContributorInsightsOutput( + ContributorInsightsSummaries=( + Option_Some( + Seq( + [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ContributorInsightsSummary( + list_element + ) + for list_element in native_input["ContributorInsightsSummaries"] + ] + ) + ) + if "ContributorInsightsSummaries" in native_input.keys() + else Option_None() + ), + NextToken=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["NextToken"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ) + ) + if "NextToken" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_ContributorInsightsSummary(native_input): + return DafnyContributorInsightsSummary( + TableName=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["TableName"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ) + ) + if "TableName" in native_input.keys() + else Option_None() + ), + IndexName=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["IndexName"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ) + ) + if "IndexName" in native_input.keys() + else Option_None() + ), + ContributorInsightsStatus=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ContributorInsightsStatus( + native_input["ContributorInsightsStatus"] + ) + ) + if "ContributorInsightsStatus" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_ListExportsInput(native_input): + return DafnyListExportsInput( + TableArn=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["TableArn"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ) + ) + if "TableArn" in native_input.keys() + else Option_None() + ), + MaxResults=( + Option_Some(native_input["MaxResults"]) + if "MaxResults" in native_input.keys() + else Option_None() + ), + NextToken=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["NextToken"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ) + ) + if "NextToken" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_ListExportsOutput(native_input): + return DafnyListExportsOutput( + ExportSummaries=( + Option_Some( + Seq( + [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ExportSummary( + list_element + ) + for list_element in native_input["ExportSummaries"] + ] + ) + ) + if "ExportSummaries" in native_input.keys() + else Option_None() + ), + NextToken=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["NextToken"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ) + ) + if "NextToken" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_ExportSummary(native_input): + return DafnyExportSummary( + ExportArn=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["ExportArn"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ) + ) + if "ExportArn" in native_input.keys() + else Option_None() + ), + ExportStatus=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ExportStatus( + native_input["ExportStatus"] + ) + ) + if "ExportStatus" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_ListGlobalTablesInput(native_input): + return DafnyListGlobalTablesInput( + ExclusiveStartGlobalTableName=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[ + iter( + native_input[ + "ExclusiveStartGlobalTableName" + ].encode("utf-16-be") + ) + ] + * 2 + ) + ] + ) + ) + ) + if "ExclusiveStartGlobalTableName" in native_input.keys() + else Option_None() + ), + Limit=( + Option_Some(native_input["Limit"]) + if "Limit" in native_input.keys() + else Option_None() + ), + RegionName=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["RegionName"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ) + ) + if "RegionName" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_ListGlobalTablesOutput(native_input): + return DafnyListGlobalTablesOutput( + GlobalTables=( + Option_Some( + Seq( + [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_GlobalTable( + list_element + ) + for list_element in native_input["GlobalTables"] + ] + ) + ) + if "GlobalTables" in native_input.keys() + else Option_None() + ), + LastEvaluatedGlobalTableName=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[ + iter( + native_input[ + "LastEvaluatedGlobalTableName" + ].encode("utf-16-be") + ) + ] + * 2 + ) + ] + ) + ) + ) + if "LastEvaluatedGlobalTableName" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_GlobalTable(native_input): + return DafnyGlobalTable( + GlobalTableName=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[ + iter( + native_input["GlobalTableName"].encode( + "utf-16-be" + ) + ) + ] + * 2 + ) + ] + ) + ) + ) + if "GlobalTableName" in native_input.keys() + else Option_None() + ), + ReplicationGroup=( + Option_Some( + Seq( + [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_Replica( + list_element + ) + for list_element in native_input["ReplicationGroup"] + ] + ) + ) + if "ReplicationGroup" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_ListImportsInput(native_input): + return DafnyListImportsInput( + TableArn=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["TableArn"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ) + ) + if "TableArn" in native_input.keys() + else Option_None() + ), + PageSize=( + Option_Some(native_input["PageSize"]) + if "PageSize" in native_input.keys() + else Option_None() + ), + NextToken=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["NextToken"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ) + ) + if "NextToken" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_ListImportsOutput(native_input): + return DafnyListImportsOutput( + ImportSummaryList=( + Option_Some( + Seq( + [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ImportSummary( + list_element + ) + for list_element in native_input["ImportSummaryList"] + ] + ) + ) + if "ImportSummaryList" in native_input.keys() + else Option_None() + ), + NextToken=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["NextToken"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ) + ) + if "NextToken" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_ImportSummary(native_input): + return DafnyImportSummary( + ImportArn=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["ImportArn"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ) + ) + if "ImportArn" in native_input.keys() + else Option_None() + ), + ImportStatus=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ImportStatus( + native_input["ImportStatus"] + ) + ) + if "ImportStatus" in native_input.keys() + else Option_None() + ), + TableArn=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["TableArn"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ) + ) + if "TableArn" in native_input.keys() + else Option_None() + ), + S3BucketSource=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_S3BucketSource( + native_input["S3BucketSource"] + ) + ) + if "S3BucketSource" in native_input.keys() + else Option_None() + ), + CloudWatchLogGroupArn=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[ + iter( + native_input["CloudWatchLogGroupArn"].encode( + "utf-16-be" + ) + ) + ] + * 2 + ) + ] + ) + ) + ) + if "CloudWatchLogGroupArn" in native_input.keys() + else Option_None() + ), + InputFormat=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_InputFormat( + native_input["InputFormat"] + ) + ) + if "InputFormat" in native_input.keys() + else Option_None() + ), + StartTime=( + Option_Some(_dafny.Seq(native_input["StartTime"].isoformat())) + if "StartTime" in native_input.keys() + else Option_None() + ), + EndTime=( + Option_Some(_dafny.Seq(native_input["EndTime"].isoformat())) + if "EndTime" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_ListTablesInput(native_input): + return DafnyListTablesInput( + ExclusiveStartTableName=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[ + iter( + native_input["ExclusiveStartTableName"].encode( + "utf-16-be" + ) + ) + ] + * 2 + ) + ] + ) + ) + ) + if "ExclusiveStartTableName" in native_input.keys() + else Option_None() + ), + Limit=( + Option_Some(native_input["Limit"]) + if "Limit" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_ListTablesOutput(native_input): + return DafnyListTablesOutput( + TableNames=( + 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["TableNames"] + ] + ) + ) + if "TableNames" in native_input.keys() + else Option_None() + ), + LastEvaluatedTableName=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[ + iter( + native_input["LastEvaluatedTableName"].encode( + "utf-16-be" + ) + ) + ] + * 2 + ) + ] + ) + ) + ) + if "LastEvaluatedTableName" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_ListTagsOfResourceInput(native_input): + return DafnyListTagsOfResourceInput( + ResourceArn=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["ResourceArn"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + NextToken=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["NextToken"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ) + ) + if "NextToken" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_ListTagsOfResourceOutput(native_input): + return DafnyListTagsOfResourceOutput( + Tags=( + Option_Some( + Seq( + [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_Tag( + list_element + ) + for list_element in native_input["Tags"] + ] + ) + ) + if "Tags" in native_input.keys() + else Option_None() + ), + NextToken=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["NextToken"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ) + ) + if "NextToken" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_PutItemInput(native_input): + return DafnyPutItemInput( + TableName=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["TableName"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + Item=Map( + { + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip(*[iter(key.encode("utf-16-be"))] * 2) + ] + ) + ): aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_AttributeValue( + value + ) + for (key, value) in native_input["Item"].items() + } + ), + Expected=( + Option_Some( + Map( + { + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(key.encode("utf-16-be"))] * 2 + ) + ] + ) + ): aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ExpectedAttributeValue( + value + ) + for (key, value) in native_input["Expected"].items() + } + ) + ) + if "Expected" in native_input.keys() + else Option_None() + ), + ReturnValues=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ReturnValue( + native_input["ReturnValues"] + ) + ) + if "ReturnValues" in native_input.keys() + else Option_None() + ), + ReturnConsumedCapacity=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ReturnConsumedCapacity( + native_input["ReturnConsumedCapacity"] + ) + ) + if "ReturnConsumedCapacity" in native_input.keys() + else Option_None() + ), + ReturnItemCollectionMetrics=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ReturnItemCollectionMetrics( + native_input["ReturnItemCollectionMetrics"] + ) + ) + if "ReturnItemCollectionMetrics" in native_input.keys() + else Option_None() + ), + ConditionalOperator=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ConditionalOperator( + native_input["ConditionalOperator"] + ) + ) + if "ConditionalOperator" in native_input.keys() + else Option_None() + ), + ConditionExpression=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[ + iter( + native_input["ConditionExpression"].encode( + "utf-16-be" + ) + ) + ] + * 2 + ) + ] + ) + ) + ) + if "ConditionExpression" in native_input.keys() + else Option_None() + ), + ExpressionAttributeNames=( + 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[ + "ExpressionAttributeNames" + ].items() + } + ) + ) + if "ExpressionAttributeNames" in native_input.keys() + else Option_None() + ), + ExpressionAttributeValues=( + Option_Some( + Map( + { + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(key.encode("utf-16-be"))] * 2 + ) + ] + ) + ): aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_AttributeValue( + value + ) + for (key, value) in native_input[ + "ExpressionAttributeValues" + ].items() + } + ) + ) + if "ExpressionAttributeValues" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_PutItemOutput(native_input): + return DafnyPutItemOutput( + Attributes=( + Option_Some( + Map( + { + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(key.encode("utf-16-be"))] * 2 + ) + ] + ) + ): aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_AttributeValue( + value + ) + for (key, value) in native_input["Attributes"].items() + } + ) + ) + if "Attributes" in native_input.keys() + else Option_None() + ), + ConsumedCapacity=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ConsumedCapacity( + native_input["ConsumedCapacity"] + ) + ) + if "ConsumedCapacity" in native_input.keys() + else Option_None() + ), + ItemCollectionMetrics=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ItemCollectionMetrics( + native_input["ItemCollectionMetrics"] + ) + ) + if "ItemCollectionMetrics" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_QueryInput(native_input): + return DafnyQueryInput( + TableName=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["TableName"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + IndexName=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["IndexName"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ) + ) + if "IndexName" in native_input.keys() + else Option_None() + ), + Select=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_Select( + native_input["Select"] + ) + ) + if "Select" in native_input.keys() + else Option_None() + ), + AttributesToGet=( + 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["AttributesToGet"] + ] + ) + ) + if "AttributesToGet" in native_input.keys() + else Option_None() + ), + Limit=( + Option_Some(native_input["Limit"]) + if "Limit" in native_input.keys() + else Option_None() + ), + ConsistentRead=( + Option_Some(native_input["ConsistentRead"]) + if "ConsistentRead" in native_input.keys() + else Option_None() + ), + KeyConditions=( + Option_Some( + Map( + { + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(key.encode("utf-16-be"))] * 2 + ) + ] + ) + ): aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_Condition( + value + ) + for (key, value) in native_input["KeyConditions"].items() + } + ) + ) + if "KeyConditions" in native_input.keys() + else Option_None() + ), + QueryFilter=( + Option_Some( + Map( + { + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(key.encode("utf-16-be"))] * 2 + ) + ] + ) + ): aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_Condition( + value + ) + for (key, value) in native_input["QueryFilter"].items() + } + ) + ) + if "QueryFilter" in native_input.keys() + else Option_None() + ), + ConditionalOperator=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ConditionalOperator( + native_input["ConditionalOperator"] + ) + ) + if "ConditionalOperator" in native_input.keys() + else Option_None() + ), + ScanIndexForward=( + Option_Some(native_input["ScanIndexForward"]) + if "ScanIndexForward" in native_input.keys() + else Option_None() + ), + ExclusiveStartKey=( + Option_Some( + Map( + { + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(key.encode("utf-16-be"))] * 2 + ) + ] + ) + ): aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_AttributeValue( + value + ) + for (key, value) in native_input["ExclusiveStartKey"].items() + } + ) + ) + if "ExclusiveStartKey" in native_input.keys() + else Option_None() + ), + ReturnConsumedCapacity=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ReturnConsumedCapacity( + native_input["ReturnConsumedCapacity"] + ) + ) + if "ReturnConsumedCapacity" in native_input.keys() + else Option_None() + ), + ProjectionExpression=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[ + iter( + native_input["ProjectionExpression"].encode( + "utf-16-be" + ) + ) + ] + * 2 + ) + ] + ) + ) + ) + if "ProjectionExpression" in native_input.keys() + else Option_None() + ), + FilterExpression=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[ + iter( + native_input["FilterExpression"].encode( + "utf-16-be" + ) + ) + ] + * 2 + ) + ] + ) + ) + ) + if "FilterExpression" in native_input.keys() + else Option_None() + ), + KeyConditionExpression=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[ + iter( + native_input["KeyConditionExpression"].encode( + "utf-16-be" + ) + ) + ] + * 2 + ) + ] + ) + ) + ) + if "KeyConditionExpression" in native_input.keys() + else Option_None() + ), + ExpressionAttributeNames=( + 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[ + "ExpressionAttributeNames" + ].items() + } + ) + ) + if "ExpressionAttributeNames" in native_input.keys() + else Option_None() + ), + ExpressionAttributeValues=( + Option_Some( + Map( + { + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(key.encode("utf-16-be"))] * 2 + ) + ] + ) + ): aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_AttributeValue( + value + ) + for (key, value) in native_input[ + "ExpressionAttributeValues" + ].items() + } + ) + ) + if "ExpressionAttributeValues" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_Select(native_input): + # Convert Select + if native_input == "ALL_ATTRIBUTES": + return Select_ALL__ATTRIBUTES() + elif native_input == "ALL_PROJECTED_ATTRIBUTES": + return Select_ALL__PROJECTED__ATTRIBUTES() + elif native_input == "SPECIFIC_ATTRIBUTES": + return Select_SPECIFIC__ATTRIBUTES() + elif native_input == "COUNT": + return Select_COUNT() + else: + raise ValueError("No recognized enum value in enum type: " + native_input) + + +def com_amazonaws_dynamodb_Condition(native_input): + return DafnyCondition( + AttributeValueList=( + Option_Some( + Seq( + [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_AttributeValue( + list_element + ) + for list_element in native_input["AttributeValueList"] + ] + ) + ) + if "AttributeValueList" in native_input.keys() + else Option_None() + ), + ComparisonOperator=aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ComparisonOperator( + native_input["ComparisonOperator"] + ), + ) + + +def com_amazonaws_dynamodb_QueryOutput(native_input): + return DafnyQueryOutput( + Items=( + Option_Some( + Seq( + [ + Map( + { + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(key.encode("utf-16-be"))] * 2 + ) + ] + ) + ): aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_AttributeValue( + value + ) + for (key, value) in list_element.items() + } + ) + for list_element in native_input["Items"] + ] + ) + ) + if "Items" in native_input.keys() + else Option_None() + ), + Count=( + Option_Some(native_input["Count"]) + if "Count" in native_input.keys() + else Option_None() + ), + ScannedCount=( + Option_Some(native_input["ScannedCount"]) + if "ScannedCount" in native_input.keys() + else Option_None() + ), + LastEvaluatedKey=( + Option_Some( + Map( + { + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(key.encode("utf-16-be"))] * 2 + ) + ] + ) + ): aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_AttributeValue( + value + ) + for (key, value) in native_input["LastEvaluatedKey"].items() + } + ) + ) + if "LastEvaluatedKey" in native_input.keys() + else Option_None() + ), + ConsumedCapacity=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ConsumedCapacity( + native_input["ConsumedCapacity"] + ) + ) + if "ConsumedCapacity" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_RestoreTableFromBackupInput(native_input): + return DafnyRestoreTableFromBackupInput( + TargetTableName=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["TargetTableName"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + BackupArn=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["BackupArn"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + BillingModeOverride=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_BillingMode( + native_input["BillingModeOverride"] + ) + ) + if "BillingModeOverride" in native_input.keys() + else Option_None() + ), + GlobalSecondaryIndexOverride=( + Option_Some( + Seq( + [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_GlobalSecondaryIndex( + list_element + ) + for list_element in native_input["GlobalSecondaryIndexOverride"] + ] + ) + ) + if "GlobalSecondaryIndexOverride" in native_input.keys() + else Option_None() + ), + LocalSecondaryIndexOverride=( + Option_Some( + Seq( + [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_LocalSecondaryIndex( + list_element + ) + for list_element in native_input["LocalSecondaryIndexOverride"] + ] + ) + ) + if "LocalSecondaryIndexOverride" in native_input.keys() + else Option_None() + ), + ProvisionedThroughputOverride=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ProvisionedThroughput( + native_input["ProvisionedThroughputOverride"] + ) + ) + if "ProvisionedThroughputOverride" in native_input.keys() + else Option_None() + ), + SSESpecificationOverride=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_SSESpecification( + native_input["SSESpecificationOverride"] + ) + ) + if "SSESpecificationOverride" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_RestoreTableFromBackupOutput(native_input): + return DafnyRestoreTableFromBackupOutput( + TableDescription=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_TableDescription( + native_input["TableDescription"] + ) + ) + if "TableDescription" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_RestoreTableToPointInTimeInput(native_input): + return DafnyRestoreTableToPointInTimeInput( + SourceTableArn=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[ + iter( + native_input["SourceTableArn"].encode( + "utf-16-be" + ) + ) + ] + * 2 + ) + ] + ) + ) + ) + if "SourceTableArn" in native_input.keys() + else Option_None() + ), + SourceTableName=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[ + iter( + native_input["SourceTableName"].encode( + "utf-16-be" + ) + ) + ] + * 2 + ) + ] + ) + ) + ) + if "SourceTableName" in native_input.keys() + else Option_None() + ), + TargetTableName=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["TargetTableName"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + UseLatestRestorableTime=( + Option_Some(native_input["UseLatestRestorableTime"]) + if "UseLatestRestorableTime" in native_input.keys() + else Option_None() + ), + RestoreDateTime=( + Option_Some(_dafny.Seq(native_input["RestoreDateTime"].isoformat())) + if "RestoreDateTime" in native_input.keys() + else Option_None() + ), + BillingModeOverride=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_BillingMode( + native_input["BillingModeOverride"] + ) + ) + if "BillingModeOverride" in native_input.keys() + else Option_None() + ), + GlobalSecondaryIndexOverride=( + Option_Some( + Seq( + [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_GlobalSecondaryIndex( + list_element + ) + for list_element in native_input["GlobalSecondaryIndexOverride"] + ] + ) + ) + if "GlobalSecondaryIndexOverride" in native_input.keys() + else Option_None() + ), + LocalSecondaryIndexOverride=( + Option_Some( + Seq( + [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_LocalSecondaryIndex( + list_element + ) + for list_element in native_input["LocalSecondaryIndexOverride"] + ] + ) + ) + if "LocalSecondaryIndexOverride" in native_input.keys() + else Option_None() + ), + ProvisionedThroughputOverride=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ProvisionedThroughput( + native_input["ProvisionedThroughputOverride"] + ) + ) + if "ProvisionedThroughputOverride" in native_input.keys() + else Option_None() + ), + SSESpecificationOverride=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_SSESpecification( + native_input["SSESpecificationOverride"] + ) + ) + if "SSESpecificationOverride" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_RestoreTableToPointInTimeOutput(native_input): + return DafnyRestoreTableToPointInTimeOutput( + TableDescription=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_TableDescription( + native_input["TableDescription"] + ) + ) + if "TableDescription" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_ScanInput(native_input): + return DafnyScanInput( + TableName=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["TableName"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + IndexName=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["IndexName"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ) + ) + if "IndexName" in native_input.keys() + else Option_None() + ), + AttributesToGet=( + 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["AttributesToGet"] + ] + ) + ) + if "AttributesToGet" in native_input.keys() + else Option_None() + ), + Limit=( + Option_Some(native_input["Limit"]) + if "Limit" in native_input.keys() + else Option_None() + ), + Select=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_Select( + native_input["Select"] + ) + ) + if "Select" in native_input.keys() + else Option_None() + ), + ScanFilter=( + Option_Some( + Map( + { + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(key.encode("utf-16-be"))] * 2 + ) + ] + ) + ): aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_Condition( + value + ) + for (key, value) in native_input["ScanFilter"].items() + } + ) + ) + if "ScanFilter" in native_input.keys() + else Option_None() + ), + ConditionalOperator=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ConditionalOperator( + native_input["ConditionalOperator"] + ) + ) + if "ConditionalOperator" in native_input.keys() + else Option_None() + ), + ExclusiveStartKey=( + Option_Some( + Map( + { + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(key.encode("utf-16-be"))] * 2 + ) + ] + ) + ): aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_AttributeValue( + value + ) + for (key, value) in native_input["ExclusiveStartKey"].items() + } + ) + ) + if "ExclusiveStartKey" in native_input.keys() + else Option_None() + ), + ReturnConsumedCapacity=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ReturnConsumedCapacity( + native_input["ReturnConsumedCapacity"] + ) + ) + if "ReturnConsumedCapacity" in native_input.keys() + else Option_None() + ), + TotalSegments=( + Option_Some(native_input["TotalSegments"]) + if "TotalSegments" in native_input.keys() + else Option_None() + ), + Segment=( + Option_Some(native_input["Segment"]) + if "Segment" in native_input.keys() + else Option_None() + ), + ProjectionExpression=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[ + iter( + native_input["ProjectionExpression"].encode( + "utf-16-be" + ) + ) + ] + * 2 + ) + ] + ) + ) + ) + if "ProjectionExpression" in native_input.keys() + else Option_None() + ), + FilterExpression=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[ + iter( + native_input["FilterExpression"].encode( + "utf-16-be" + ) + ) + ] + * 2 + ) + ] + ) + ) + ) + if "FilterExpression" in native_input.keys() + else Option_None() + ), + ExpressionAttributeNames=( + 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[ + "ExpressionAttributeNames" + ].items() + } + ) + ) + if "ExpressionAttributeNames" in native_input.keys() + else Option_None() + ), + ExpressionAttributeValues=( + Option_Some( + Map( + { + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(key.encode("utf-16-be"))] * 2 + ) + ] + ) + ): aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_AttributeValue( + value + ) + for (key, value) in native_input[ + "ExpressionAttributeValues" + ].items() + } + ) + ) + if "ExpressionAttributeValues" in native_input.keys() + else Option_None() + ), + ConsistentRead=( + Option_Some(native_input["ConsistentRead"]) + if "ConsistentRead" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_ScanOutput(native_input): + return DafnyScanOutput( + Items=( + Option_Some( + Seq( + [ + Map( + { + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(key.encode("utf-16-be"))] * 2 + ) + ] + ) + ): aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_AttributeValue( + value + ) + for (key, value) in list_element.items() + } + ) + for list_element in native_input["Items"] + ] + ) + ) + if "Items" in native_input.keys() + else Option_None() + ), + Count=( + Option_Some(native_input["Count"]) + if "Count" in native_input.keys() + else Option_None() + ), + ScannedCount=( + Option_Some(native_input["ScannedCount"]) + if "ScannedCount" in native_input.keys() + else Option_None() + ), + LastEvaluatedKey=( + Option_Some( + Map( + { + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(key.encode("utf-16-be"))] * 2 + ) + ] + ) + ): aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_AttributeValue( + value + ) + for (key, value) in native_input["LastEvaluatedKey"].items() + } + ) + ) + if "LastEvaluatedKey" in native_input.keys() + else Option_None() + ), + ConsumedCapacity=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ConsumedCapacity( + native_input["ConsumedCapacity"] + ) + ) + if "ConsumedCapacity" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_TagResourceInput(native_input): + return DafnyTagResourceInput( + ResourceArn=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["ResourceArn"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + Tags=Seq( + [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_Tag( + list_element + ) + for list_element in native_input["Tags"] + ] + ), + ) + + +def com_amazonaws_dynamodb_TransactGetItemsInput(native_input): + return DafnyTransactGetItemsInput( + TransactItems=Seq( + [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_TransactGetItem( + list_element + ) + for list_element in native_input["TransactItems"] + ] + ), + ReturnConsumedCapacity=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ReturnConsumedCapacity( + native_input["ReturnConsumedCapacity"] + ) + ) + if "ReturnConsumedCapacity" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_TransactGetItem(native_input): + return DafnyTransactGetItem( + Get=aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_Get( + native_input["Get"] + ), + ) + + +def com_amazonaws_dynamodb_Get(native_input): + return DafnyGet( + Key=Map( + { + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip(*[iter(key.encode("utf-16-be"))] * 2) + ] + ) + ): aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_AttributeValue( + value + ) + for (key, value) in native_input["Key"].items() + } + ), + TableName=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["TableName"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + ProjectionExpression=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[ + iter( + native_input["ProjectionExpression"].encode( + "utf-16-be" + ) + ) + ] + * 2 + ) + ] + ) + ) + ) + if "ProjectionExpression" in native_input.keys() + else Option_None() + ), + ExpressionAttributeNames=( + 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[ + "ExpressionAttributeNames" + ].items() + } + ) + ) + if "ExpressionAttributeNames" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_TransactGetItemsOutput(native_input): + return DafnyTransactGetItemsOutput( + ConsumedCapacity=( + Option_Some( + Seq( + [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ConsumedCapacity( + list_element + ) + for list_element in native_input["ConsumedCapacity"] + ] + ) + ) + if "ConsumedCapacity" in native_input.keys() + else Option_None() + ), + Responses=( + Option_Some( + Seq( + [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ItemResponse( + list_element + ) + for list_element in native_input["Responses"] + ] + ) + ) + if "Responses" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_TransactWriteItemsInput(native_input): + return DafnyTransactWriteItemsInput( + TransactItems=Seq( + [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_TransactWriteItem( + list_element + ) + for list_element in native_input["TransactItems"] + ] + ), + ReturnConsumedCapacity=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ReturnConsumedCapacity( + native_input["ReturnConsumedCapacity"] + ) + ) + if "ReturnConsumedCapacity" in native_input.keys() + else Option_None() + ), + ReturnItemCollectionMetrics=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ReturnItemCollectionMetrics( + native_input["ReturnItemCollectionMetrics"] + ) + ) + if "ReturnItemCollectionMetrics" in native_input.keys() + else Option_None() + ), + ClientRequestToken=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[ + iter( + native_input["ClientRequestToken"].encode( + "utf-16-be" + ) + ) + ] + * 2 + ) + ] + ) + ) + ) + if "ClientRequestToken" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_TransactWriteItem(native_input): + return DafnyTransactWriteItem( + ConditionCheck=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ConditionCheck( + native_input["ConditionCheck"] + ) + ) + if "ConditionCheck" in native_input.keys() + else Option_None() + ), + Put=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_Put( + native_input["Put"] + ) + ) + if "Put" in native_input.keys() + else Option_None() + ), + Delete=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_Delete( + native_input["Delete"] + ) + ) + if "Delete" in native_input.keys() + else Option_None() + ), + Update=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_Update( + native_input["Update"] + ) + ) + if "Update" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_ConditionCheck(native_input): + return DafnyConditionCheck( + Key=Map( + { + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip(*[iter(key.encode("utf-16-be"))] * 2) + ] + ) + ): aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_AttributeValue( + value + ) + for (key, value) in native_input["Key"].items() + } + ), + TableName=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["TableName"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + ConditionExpression=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["ConditionExpression"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ), + ExpressionAttributeNames=( + 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[ + "ExpressionAttributeNames" + ].items() + } + ) + ) + if "ExpressionAttributeNames" in native_input.keys() + else Option_None() + ), + ExpressionAttributeValues=( + Option_Some( + Map( + { + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(key.encode("utf-16-be"))] * 2 + ) + ] + ) + ): aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_AttributeValue( + value + ) + for (key, value) in native_input[ + "ExpressionAttributeValues" + ].items() + } + ) + ) + if "ExpressionAttributeValues" in native_input.keys() + else Option_None() + ), + ReturnValuesOnConditionCheckFailure=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ReturnValuesOnConditionCheckFailure( + native_input["ReturnValuesOnConditionCheckFailure"] + ) + ) + if "ReturnValuesOnConditionCheckFailure" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_Put(native_input): + return DafnyPut( + Item=Map( + { + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip(*[iter(key.encode("utf-16-be"))] * 2) + ] + ) + ): aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_AttributeValue( + value + ) + for (key, value) in native_input["Item"].items() + } + ), + TableName=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["TableName"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + ConditionExpression=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[ + iter( + native_input["ConditionExpression"].encode( + "utf-16-be" + ) + ) + ] + * 2 + ) + ] + ) + ) + ) + if "ConditionExpression" in native_input.keys() + else Option_None() + ), + ExpressionAttributeNames=( + 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[ + "ExpressionAttributeNames" + ].items() + } + ) + ) + if "ExpressionAttributeNames" in native_input.keys() + else Option_None() + ), + ExpressionAttributeValues=( + Option_Some( + Map( + { + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(key.encode("utf-16-be"))] * 2 + ) + ] + ) + ): aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_AttributeValue( + value + ) + for (key, value) in native_input[ + "ExpressionAttributeValues" + ].items() + } + ) + ) + if "ExpressionAttributeValues" in native_input.keys() + else Option_None() + ), + ReturnValuesOnConditionCheckFailure=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ReturnValuesOnConditionCheckFailure( + native_input["ReturnValuesOnConditionCheckFailure"] + ) + ) + if "ReturnValuesOnConditionCheckFailure" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_Delete(native_input): + return DafnyDelete( + Key=Map( + { + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip(*[iter(key.encode("utf-16-be"))] * 2) + ] + ) + ): aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_AttributeValue( + value + ) + for (key, value) in native_input["Key"].items() + } + ), + TableName=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["TableName"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + ConditionExpression=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[ + iter( + native_input["ConditionExpression"].encode( + "utf-16-be" + ) + ) + ] + * 2 + ) + ] + ) + ) + ) + if "ConditionExpression" in native_input.keys() + else Option_None() + ), + ExpressionAttributeNames=( + 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[ + "ExpressionAttributeNames" + ].items() + } + ) + ) + if "ExpressionAttributeNames" in native_input.keys() + else Option_None() + ), + ExpressionAttributeValues=( + Option_Some( + Map( + { + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(key.encode("utf-16-be"))] * 2 + ) + ] + ) + ): aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_AttributeValue( + value + ) + for (key, value) in native_input[ + "ExpressionAttributeValues" + ].items() + } + ) + ) + if "ExpressionAttributeValues" in native_input.keys() + else Option_None() + ), + ReturnValuesOnConditionCheckFailure=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ReturnValuesOnConditionCheckFailure( + native_input["ReturnValuesOnConditionCheckFailure"] + ) + ) + if "ReturnValuesOnConditionCheckFailure" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_Update(native_input): + return DafnyUpdate( + Key=Map( + { + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip(*[iter(key.encode("utf-16-be"))] * 2) + ] + ) + ): aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_AttributeValue( + value + ) + for (key, value) in native_input["Key"].items() + } + ), + UpdateExpression=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["UpdateExpression"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ), + TableName=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["TableName"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + ConditionExpression=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[ + iter( + native_input["ConditionExpression"].encode( + "utf-16-be" + ) + ) + ] + * 2 + ) + ] + ) + ) + ) + if "ConditionExpression" in native_input.keys() + else Option_None() + ), + ExpressionAttributeNames=( + 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[ + "ExpressionAttributeNames" + ].items() + } + ) + ) + if "ExpressionAttributeNames" in native_input.keys() + else Option_None() + ), + ExpressionAttributeValues=( + Option_Some( + Map( + { + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(key.encode("utf-16-be"))] * 2 + ) + ] + ) + ): aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_AttributeValue( + value + ) + for (key, value) in native_input[ + "ExpressionAttributeValues" + ].items() + } + ) + ) + if "ExpressionAttributeValues" in native_input.keys() + else Option_None() + ), + ReturnValuesOnConditionCheckFailure=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ReturnValuesOnConditionCheckFailure( + native_input["ReturnValuesOnConditionCheckFailure"] + ) + ) + if "ReturnValuesOnConditionCheckFailure" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_ReturnValuesOnConditionCheckFailure(native_input): + # Convert ReturnValuesOnConditionCheckFailure + if native_input == "ALL_OLD": + return ReturnValuesOnConditionCheckFailure_ALL__OLD() + elif native_input == "NONE": + return ReturnValuesOnConditionCheckFailure_NONE() + else: + raise ValueError("No recognized enum value in enum type: " + native_input) + + +def com_amazonaws_dynamodb_TransactWriteItemsOutput(native_input): + return DafnyTransactWriteItemsOutput( + ConsumedCapacity=( + Option_Some( + Seq( + [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ConsumedCapacity( + list_element + ) + for list_element in native_input["ConsumedCapacity"] + ] + ) + ) + if "ConsumedCapacity" in native_input.keys() + else Option_None() + ), + ItemCollectionMetrics=( + Option_Some( + Map( + { + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(key.encode("utf-16-be"))] * 2 + ) + ] + ) + ): Seq( + [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ItemCollectionMetrics( + list_element + ) + for list_element in value + ] + ) + for (key, value) in native_input[ + "ItemCollectionMetrics" + ].items() + } + ) + ) + if "ItemCollectionMetrics" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_UntagResourceInput(native_input): + return DafnyUntagResourceInput( + ResourceArn=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["ResourceArn"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + TagKeys=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["TagKeys"] + ] + ), + ) + + +def com_amazonaws_dynamodb_UpdateContinuousBackupsInput(native_input): + return DafnyUpdateContinuousBackupsInput( + TableName=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["TableName"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + PointInTimeRecoverySpecification=aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_PointInTimeRecoverySpecification( + native_input["PointInTimeRecoverySpecification"] + ), + ) + + +def com_amazonaws_dynamodb_PointInTimeRecoverySpecification(native_input): + return DafnyPointInTimeRecoverySpecification( + PointInTimeRecoveryEnabled=native_input["PointInTimeRecoveryEnabled"], + ) + + +def com_amazonaws_dynamodb_UpdateContinuousBackupsOutput(native_input): + return DafnyUpdateContinuousBackupsOutput( + ContinuousBackupsDescription=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ContinuousBackupsDescription( + native_input["ContinuousBackupsDescription"] + ) + ) + if "ContinuousBackupsDescription" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_UpdateContributorInsightsInput(native_input): + return DafnyUpdateContributorInsightsInput( + TableName=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["TableName"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + IndexName=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["IndexName"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ) + ) + if "IndexName" in native_input.keys() + else Option_None() + ), + ContributorInsightsAction=aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ContributorInsightsAction( + native_input["ContributorInsightsAction"] + ), + ) + + +def com_amazonaws_dynamodb_ContributorInsightsAction(native_input): + # Convert ContributorInsightsAction + if native_input == "ENABLE": + return ContributorInsightsAction_ENABLE() + elif native_input == "DISABLE": + return ContributorInsightsAction_DISABLE() + else: + raise ValueError("No recognized enum value in enum type: " + native_input) + + +def com_amazonaws_dynamodb_UpdateContributorInsightsOutput(native_input): + return DafnyUpdateContributorInsightsOutput( + TableName=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["TableName"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ) + ) + if "TableName" in native_input.keys() + else Option_None() + ), + IndexName=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["IndexName"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ) + ) + if "IndexName" in native_input.keys() + else Option_None() + ), + ContributorInsightsStatus=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ContributorInsightsStatus( + native_input["ContributorInsightsStatus"] + ) + ) + if "ContributorInsightsStatus" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_UpdateGlobalTableInput(native_input): + return DafnyUpdateGlobalTableInput( + GlobalTableName=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["GlobalTableName"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + ReplicaUpdates=Seq( + [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ReplicaUpdate( + list_element + ) + for list_element in native_input["ReplicaUpdates"] + ] + ), + ) + + +def com_amazonaws_dynamodb_ReplicaUpdate(native_input): + return DafnyReplicaUpdate( + Create=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_CreateReplicaAction( + native_input["Create"] + ) + ) + if "Create" in native_input.keys() + else Option_None() + ), + Delete=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_DeleteReplicaAction( + native_input["Delete"] + ) + ) + if "Delete" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_CreateReplicaAction(native_input): + return DafnyCreateReplicaAction( + RegionName=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["RegionName"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_dynamodb_DeleteReplicaAction(native_input): + return DafnyDeleteReplicaAction( + RegionName=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["RegionName"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_dynamodb_UpdateGlobalTableOutput(native_input): + return DafnyUpdateGlobalTableOutput( + GlobalTableDescription=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_GlobalTableDescription( + native_input["GlobalTableDescription"] + ) + ) + if "GlobalTableDescription" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_UpdateGlobalTableSettingsInput(native_input): + return DafnyUpdateGlobalTableSettingsInput( + GlobalTableName=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["GlobalTableName"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + GlobalTableBillingMode=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_BillingMode( + native_input["GlobalTableBillingMode"] + ) + ) + if "GlobalTableBillingMode" in native_input.keys() + else Option_None() + ), + GlobalTableProvisionedWriteCapacityUnits=( + Option_Some(native_input["GlobalTableProvisionedWriteCapacityUnits"]) + if "GlobalTableProvisionedWriteCapacityUnits" in native_input.keys() + else Option_None() + ), + GlobalTableProvisionedWriteCapacityAutoScalingSettingsUpdate=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_AutoScalingSettingsUpdate( + native_input[ + "GlobalTableProvisionedWriteCapacityAutoScalingSettingsUpdate" + ] + ) + ) + if "GlobalTableProvisionedWriteCapacityAutoScalingSettingsUpdate" + in native_input.keys() + else Option_None() + ), + GlobalTableGlobalSecondaryIndexSettingsUpdate=( + Option_Some( + Seq( + [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_GlobalTableGlobalSecondaryIndexSettingsUpdate( + list_element + ) + for list_element in native_input[ + "GlobalTableGlobalSecondaryIndexSettingsUpdate" + ] + ] + ) + ) + if "GlobalTableGlobalSecondaryIndexSettingsUpdate" in native_input.keys() + else Option_None() + ), + ReplicaSettingsUpdate=( + Option_Some( + Seq( + [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ReplicaSettingsUpdate( + list_element + ) + for list_element in native_input["ReplicaSettingsUpdate"] + ] + ) + ) + if "ReplicaSettingsUpdate" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_AutoScalingSettingsUpdate(native_input): + return DafnyAutoScalingSettingsUpdate( + MinimumUnits=( + Option_Some(native_input["MinimumUnits"]) + if "MinimumUnits" in native_input.keys() + else Option_None() + ), + MaximumUnits=( + Option_Some(native_input["MaximumUnits"]) + if "MaximumUnits" in native_input.keys() + else Option_None() + ), + AutoScalingDisabled=( + Option_Some(native_input["AutoScalingDisabled"]) + if "AutoScalingDisabled" in native_input.keys() + else Option_None() + ), + AutoScalingRoleArn=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[ + iter( + native_input["AutoScalingRoleArn"].encode( + "utf-16-be" + ) + ) + ] + * 2 + ) + ] + ) + ) + ) + if "AutoScalingRoleArn" in native_input.keys() + else Option_None() + ), + ScalingPolicyUpdate=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_AutoScalingPolicyUpdate( + native_input["ScalingPolicyUpdate"] + ) + ) + if "ScalingPolicyUpdate" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_AutoScalingPolicyUpdate(native_input): + return DafnyAutoScalingPolicyUpdate( + PolicyName=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["PolicyName"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ) + ) + if "PolicyName" in native_input.keys() + else Option_None() + ), + TargetTrackingScalingPolicyConfiguration=aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_AutoScalingTargetTrackingScalingPolicyConfigurationUpdate( + native_input["TargetTrackingScalingPolicyConfiguration"] + ), + ) + + +def com_amazonaws_dynamodb_AutoScalingTargetTrackingScalingPolicyConfigurationUpdate( + native_input, +): + return DafnyAutoScalingTargetTrackingScalingPolicyConfigurationUpdate( + DisableScaleIn=( + Option_Some(native_input["DisableScaleIn"]) + if "DisableScaleIn" in native_input.keys() + else Option_None() + ), + ScaleInCooldown=( + Option_Some(native_input["ScaleInCooldown"]) + if "ScaleInCooldown" in native_input.keys() + else Option_None() + ), + ScaleOutCooldown=( + Option_Some(native_input["ScaleOutCooldown"]) + if "ScaleOutCooldown" in native_input.keys() + else Option_None() + ), + TargetValue=native_input["TargetValue"], + ) + + +def com_amazonaws_dynamodb_GlobalTableGlobalSecondaryIndexSettingsUpdate(native_input): + return DafnyGlobalTableGlobalSecondaryIndexSettingsUpdate( + IndexName=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["IndexName"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + ProvisionedWriteCapacityUnits=( + Option_Some(native_input["ProvisionedWriteCapacityUnits"]) + if "ProvisionedWriteCapacityUnits" in native_input.keys() + else Option_None() + ), + ProvisionedWriteCapacityAutoScalingSettingsUpdate=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_AutoScalingSettingsUpdate( + native_input["ProvisionedWriteCapacityAutoScalingSettingsUpdate"] + ) + ) + if "ProvisionedWriteCapacityAutoScalingSettingsUpdate" + in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_ReplicaSettingsUpdate(native_input): + return DafnyReplicaSettingsUpdate( + RegionName=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["RegionName"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + ReplicaProvisionedReadCapacityUnits=( + Option_Some(native_input["ReplicaProvisionedReadCapacityUnits"]) + if "ReplicaProvisionedReadCapacityUnits" in native_input.keys() + else Option_None() + ), + ReplicaProvisionedReadCapacityAutoScalingSettingsUpdate=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_AutoScalingSettingsUpdate( + native_input[ + "ReplicaProvisionedReadCapacityAutoScalingSettingsUpdate" + ] + ) + ) + if "ReplicaProvisionedReadCapacityAutoScalingSettingsUpdate" + in native_input.keys() + else Option_None() + ), + ReplicaGlobalSecondaryIndexSettingsUpdate=( + Option_Some( + Seq( + [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ReplicaGlobalSecondaryIndexSettingsUpdate( + list_element + ) + for list_element in native_input[ + "ReplicaGlobalSecondaryIndexSettingsUpdate" + ] + ] + ) + ) + if "ReplicaGlobalSecondaryIndexSettingsUpdate" in native_input.keys() + else Option_None() + ), + ReplicaTableClass=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_TableClass( + native_input["ReplicaTableClass"] + ) + ) + if "ReplicaTableClass" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_ReplicaGlobalSecondaryIndexSettingsUpdate(native_input): + return DafnyReplicaGlobalSecondaryIndexSettingsUpdate( + IndexName=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["IndexName"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + ProvisionedReadCapacityUnits=( + Option_Some(native_input["ProvisionedReadCapacityUnits"]) + if "ProvisionedReadCapacityUnits" in native_input.keys() + else Option_None() + ), + ProvisionedReadCapacityAutoScalingSettingsUpdate=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_AutoScalingSettingsUpdate( + native_input["ProvisionedReadCapacityAutoScalingSettingsUpdate"] + ) + ) + if "ProvisionedReadCapacityAutoScalingSettingsUpdate" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_UpdateGlobalTableSettingsOutput(native_input): + return DafnyUpdateGlobalTableSettingsOutput( + GlobalTableName=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[ + iter( + native_input["GlobalTableName"].encode( + "utf-16-be" + ) + ) + ] + * 2 + ) + ] + ) + ) + ) + if "GlobalTableName" in native_input.keys() + else Option_None() + ), + ReplicaSettings=( + Option_Some( + Seq( + [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ReplicaSettingsDescription( + list_element + ) + for list_element in native_input["ReplicaSettings"] + ] + ) + ) + if "ReplicaSettings" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_UpdateItemInput(native_input): + return DafnyUpdateItemInput( + TableName=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["TableName"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + Key=Map( + { + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip(*[iter(key.encode("utf-16-be"))] * 2) + ] + ) + ): aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_AttributeValue( + value + ) + for (key, value) in native_input["Key"].items() + } + ), + AttributeUpdates=( + Option_Some( + Map( + { + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(key.encode("utf-16-be"))] * 2 + ) + ] + ) + ): aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_AttributeValueUpdate( + value + ) + for (key, value) in native_input["AttributeUpdates"].items() + } + ) + ) + if "AttributeUpdates" in native_input.keys() + else Option_None() + ), + Expected=( + Option_Some( + Map( + { + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(key.encode("utf-16-be"))] * 2 + ) + ] + ) + ): aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ExpectedAttributeValue( + value + ) + for (key, value) in native_input["Expected"].items() + } + ) + ) + if "Expected" in native_input.keys() + else Option_None() + ), + ConditionalOperator=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ConditionalOperator( + native_input["ConditionalOperator"] + ) + ) + if "ConditionalOperator" in native_input.keys() + else Option_None() + ), + ReturnValues=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ReturnValue( + native_input["ReturnValues"] + ) + ) + if "ReturnValues" in native_input.keys() + else Option_None() + ), + ReturnConsumedCapacity=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ReturnConsumedCapacity( + native_input["ReturnConsumedCapacity"] + ) + ) + if "ReturnConsumedCapacity" in native_input.keys() + else Option_None() + ), + ReturnItemCollectionMetrics=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ReturnItemCollectionMetrics( + native_input["ReturnItemCollectionMetrics"] + ) + ) + if "ReturnItemCollectionMetrics" in native_input.keys() + else Option_None() + ), + UpdateExpression=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[ + iter( + native_input["UpdateExpression"].encode( + "utf-16-be" + ) + ) + ] + * 2 + ) + ] + ) + ) + ) + if "UpdateExpression" in native_input.keys() + else Option_None() + ), + ConditionExpression=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[ + iter( + native_input["ConditionExpression"].encode( + "utf-16-be" + ) + ) + ] + * 2 + ) + ] + ) + ) + ) + if "ConditionExpression" in native_input.keys() + else Option_None() + ), + ExpressionAttributeNames=( + 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[ + "ExpressionAttributeNames" + ].items() + } + ) + ) + if "ExpressionAttributeNames" in native_input.keys() + else Option_None() + ), + ExpressionAttributeValues=( + Option_Some( + Map( + { + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(key.encode("utf-16-be"))] * 2 + ) + ] + ) + ): aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_AttributeValue( + value + ) + for (key, value) in native_input[ + "ExpressionAttributeValues" + ].items() + } + ) + ) + if "ExpressionAttributeValues" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_AttributeValueUpdate(native_input): + return DafnyAttributeValueUpdate( + Value=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_AttributeValue( + native_input["Value"] + ) + ) + if "Value" in native_input.keys() + else Option_None() + ), + Action=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_AttributeAction( + native_input["Action"] + ) + ) + if "Action" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_AttributeAction(native_input): + # Convert AttributeAction + if native_input == "ADD": + return AttributeAction_ADD() + elif native_input == "PUT": + return AttributeAction_PUT() + elif native_input == "DELETE": + return AttributeAction_DELETE() + else: + raise ValueError("No recognized enum value in enum type: " + native_input) + + +def com_amazonaws_dynamodb_UpdateItemOutput(native_input): + return DafnyUpdateItemOutput( + Attributes=( + Option_Some( + Map( + { + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(key.encode("utf-16-be"))] * 2 + ) + ] + ) + ): aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_AttributeValue( + value + ) + for (key, value) in native_input["Attributes"].items() + } + ) + ) + if "Attributes" in native_input.keys() + else Option_None() + ), + ConsumedCapacity=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ConsumedCapacity( + native_input["ConsumedCapacity"] + ) + ) + if "ConsumedCapacity" in native_input.keys() + else Option_None() + ), + ItemCollectionMetrics=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ItemCollectionMetrics( + native_input["ItemCollectionMetrics"] + ) + ) + if "ItemCollectionMetrics" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_UpdateTableInput(native_input): + return DafnyUpdateTableInput( + AttributeDefinitions=( + Option_Some( + Seq( + [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_AttributeDefinition( + list_element + ) + for list_element in native_input["AttributeDefinitions"] + ] + ) + ) + if "AttributeDefinitions" in native_input.keys() + else Option_None() + ), + TableName=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["TableName"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + BillingMode=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_BillingMode( + native_input["BillingMode"] + ) + ) + if "BillingMode" in native_input.keys() + else Option_None() + ), + ProvisionedThroughput=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ProvisionedThroughput( + native_input["ProvisionedThroughput"] + ) + ) + if "ProvisionedThroughput" in native_input.keys() + else Option_None() + ), + GlobalSecondaryIndexUpdates=( + Option_Some( + Seq( + [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_GlobalSecondaryIndexUpdate( + list_element + ) + for list_element in native_input["GlobalSecondaryIndexUpdates"] + ] + ) + ) + if "GlobalSecondaryIndexUpdates" in native_input.keys() + else Option_None() + ), + StreamSpecification=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_StreamSpecification( + native_input["StreamSpecification"] + ) + ) + if "StreamSpecification" in native_input.keys() + else Option_None() + ), + SSESpecification=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_SSESpecification( + native_input["SSESpecification"] + ) + ) + if "SSESpecification" in native_input.keys() + else Option_None() + ), + ReplicaUpdates=( + Option_Some( + Seq( + [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ReplicationGroupUpdate( + list_element + ) + for list_element in native_input["ReplicaUpdates"] + ] + ) + ) + if "ReplicaUpdates" in native_input.keys() + else Option_None() + ), + TableClass=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_TableClass( + native_input["TableClass"] + ) + ) + if "TableClass" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_GlobalSecondaryIndexUpdate(native_input): + return DafnyGlobalSecondaryIndexUpdate( + Update=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_UpdateGlobalSecondaryIndexAction( + native_input["Update"] + ) + ) + if "Update" in native_input.keys() + else Option_None() + ), + Create=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_CreateGlobalSecondaryIndexAction( + native_input["Create"] + ) + ) + if "Create" in native_input.keys() + else Option_None() + ), + Delete=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_DeleteGlobalSecondaryIndexAction( + native_input["Delete"] + ) + ) + if "Delete" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_UpdateGlobalSecondaryIndexAction(native_input): + return DafnyUpdateGlobalSecondaryIndexAction( + IndexName=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["IndexName"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + ProvisionedThroughput=aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ProvisionedThroughput( + native_input["ProvisionedThroughput"] + ), + ) + + +def com_amazonaws_dynamodb_CreateGlobalSecondaryIndexAction(native_input): + return DafnyCreateGlobalSecondaryIndexAction( + IndexName=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["IndexName"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + KeySchema=Seq( + [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_KeySchemaElement( + list_element + ) + for list_element in native_input["KeySchema"] + ] + ), + Projection=aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_Projection( + native_input["Projection"] + ), + ProvisionedThroughput=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ProvisionedThroughput( + native_input["ProvisionedThroughput"] + ) + ) + if "ProvisionedThroughput" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_DeleteGlobalSecondaryIndexAction(native_input): + return DafnyDeleteGlobalSecondaryIndexAction( + IndexName=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["IndexName"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_dynamodb_ReplicationGroupUpdate(native_input): + return DafnyReplicationGroupUpdate( + Create=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_CreateReplicationGroupMemberAction( + native_input["Create"] + ) + ) + if "Create" in native_input.keys() + else Option_None() + ), + Update=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_UpdateReplicationGroupMemberAction( + native_input["Update"] + ) + ) + if "Update" in native_input.keys() + else Option_None() + ), + Delete=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_DeleteReplicationGroupMemberAction( + native_input["Delete"] + ) + ) + if "Delete" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_CreateReplicationGroupMemberAction(native_input): + return DafnyCreateReplicationGroupMemberAction( + RegionName=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["RegionName"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + KMSMasterKeyId=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[ + iter( + native_input["KMSMasterKeyId"].encode( + "utf-16-be" + ) + ) + ] + * 2 + ) + ] + ) + ) + ) + if "KMSMasterKeyId" in native_input.keys() + else Option_None() + ), + ProvisionedThroughputOverride=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ProvisionedThroughputOverride( + native_input["ProvisionedThroughputOverride"] + ) + ) + if "ProvisionedThroughputOverride" in native_input.keys() + else Option_None() + ), + GlobalSecondaryIndexes=( + Option_Some( + Seq( + [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ReplicaGlobalSecondaryIndex( + list_element + ) + for list_element in native_input["GlobalSecondaryIndexes"] + ] + ) + ) + if "GlobalSecondaryIndexes" in native_input.keys() + else Option_None() + ), + TableClassOverride=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_TableClass( + native_input["TableClassOverride"] + ) + ) + if "TableClassOverride" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_UpdateReplicationGroupMemberAction(native_input): + return DafnyUpdateReplicationGroupMemberAction( + RegionName=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["RegionName"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + KMSMasterKeyId=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[ + iter( + native_input["KMSMasterKeyId"].encode( + "utf-16-be" + ) + ) + ] + * 2 + ) + ] + ) + ) + ) + if "KMSMasterKeyId" in native_input.keys() + else Option_None() + ), + ProvisionedThroughputOverride=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ProvisionedThroughputOverride( + native_input["ProvisionedThroughputOverride"] + ) + ) + if "ProvisionedThroughputOverride" in native_input.keys() + else Option_None() + ), + GlobalSecondaryIndexes=( + Option_Some( + Seq( + [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ReplicaGlobalSecondaryIndex( + list_element + ) + for list_element in native_input["GlobalSecondaryIndexes"] + ] + ) + ) + if "GlobalSecondaryIndexes" in native_input.keys() + else Option_None() + ), + TableClassOverride=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_TableClass( + native_input["TableClassOverride"] + ) + ) + if "TableClassOverride" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_DeleteReplicationGroupMemberAction(native_input): + return DafnyDeleteReplicationGroupMemberAction( + RegionName=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["RegionName"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_dynamodb_ReplicaGlobalSecondaryIndex(native_input): + return DafnyReplicaGlobalSecondaryIndex( + IndexName=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["IndexName"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + ProvisionedThroughputOverride=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ProvisionedThroughputOverride( + native_input["ProvisionedThroughputOverride"] + ) + ) + if "ProvisionedThroughputOverride" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_UpdateTableOutput(native_input): + return DafnyUpdateTableOutput( + TableDescription=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_TableDescription( + native_input["TableDescription"] + ) + ) + if "TableDescription" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_UpdateTableReplicaAutoScalingInput(native_input): + return DafnyUpdateTableReplicaAutoScalingInput( + GlobalSecondaryIndexUpdates=( + Option_Some( + Seq( + [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_GlobalSecondaryIndexAutoScalingUpdate( + list_element + ) + for list_element in native_input["GlobalSecondaryIndexUpdates"] + ] + ) + ) + if "GlobalSecondaryIndexUpdates" in native_input.keys() + else Option_None() + ), + TableName=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["TableName"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + ProvisionedWriteCapacityAutoScalingUpdate=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_AutoScalingSettingsUpdate( + native_input["ProvisionedWriteCapacityAutoScalingUpdate"] + ) + ) + if "ProvisionedWriteCapacityAutoScalingUpdate" in native_input.keys() + else Option_None() + ), + ReplicaUpdates=( + Option_Some( + Seq( + [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ReplicaAutoScalingUpdate( + list_element + ) + for list_element in native_input["ReplicaUpdates"] + ] + ) + ) + if "ReplicaUpdates" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_GlobalSecondaryIndexAutoScalingUpdate(native_input): + return DafnyGlobalSecondaryIndexAutoScalingUpdate( + IndexName=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["IndexName"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ) + ) + if "IndexName" in native_input.keys() + else Option_None() + ), + ProvisionedWriteCapacityAutoScalingUpdate=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_AutoScalingSettingsUpdate( + native_input["ProvisionedWriteCapacityAutoScalingUpdate"] + ) + ) + if "ProvisionedWriteCapacityAutoScalingUpdate" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_ReplicaAutoScalingUpdate(native_input): + return DafnyReplicaAutoScalingUpdate( + RegionName=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["RegionName"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + ReplicaGlobalSecondaryIndexUpdates=( + Option_Some( + Seq( + [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ReplicaGlobalSecondaryIndexAutoScalingUpdate( + list_element + ) + for list_element in native_input[ + "ReplicaGlobalSecondaryIndexUpdates" + ] + ] + ) + ) + if "ReplicaGlobalSecondaryIndexUpdates" in native_input.keys() + else Option_None() + ), + ReplicaProvisionedReadCapacityAutoScalingUpdate=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_AutoScalingSettingsUpdate( + native_input["ReplicaProvisionedReadCapacityAutoScalingUpdate"] + ) + ) + if "ReplicaProvisionedReadCapacityAutoScalingUpdate" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_ReplicaGlobalSecondaryIndexAutoScalingUpdate(native_input): + return DafnyReplicaGlobalSecondaryIndexAutoScalingUpdate( + IndexName=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["IndexName"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ) + ) + if "IndexName" in native_input.keys() + else Option_None() + ), + ProvisionedReadCapacityAutoScalingUpdate=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_AutoScalingSettingsUpdate( + native_input["ProvisionedReadCapacityAutoScalingUpdate"] + ) + ) + if "ProvisionedReadCapacityAutoScalingUpdate" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_UpdateTableReplicaAutoScalingOutput(native_input): + return DafnyUpdateTableReplicaAutoScalingOutput( + TableAutoScalingDescription=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_TableAutoScalingDescription( + native_input["TableAutoScalingDescription"] + ) + ) + if "TableAutoScalingDescription" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_dynamodb_UpdateTimeToLiveInput(native_input): + return DafnyUpdateTimeToLiveInput( + TableName=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["TableName"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + TimeToLiveSpecification=aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_TimeToLiveSpecification( + native_input["TimeToLiveSpecification"] + ), + ) + + +def com_amazonaws_dynamodb_TimeToLiveSpecification(native_input): + return DafnyTimeToLiveSpecification( + Enabled=native_input["Enabled"], + AttributeName=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["AttributeName"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_dynamodb_UpdateTimeToLiveOutput(native_input): + return DafnyUpdateTimeToLiveOutput( + TimeToLiveSpecification=( + Option_Some( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_TimeToLiveSpecification( + native_input["TimeToLiveSpecification"] + ) + ) + if "TimeToLiveSpecification" in native_input.keys() + else Option_None() + ), + ) diff --git a/ComAmazonawsDynamodb/runtimes/python/src/aws_cryptography_internal_dynamodb/smithygenerated/com_amazonaws_dynamodb/dafny_to_aws_sdk.py b/ComAmazonawsDynamodb/runtimes/python/src/aws_cryptography_internal_dynamodb/smithygenerated/com_amazonaws_dynamodb/dafny_to_aws_sdk.py new file mode 100644 index 000000000..1b7cfba94 --- /dev/null +++ b/ComAmazonawsDynamodb/runtimes/python/src/aws_cryptography_internal_dynamodb/smithygenerated/com_amazonaws_dynamodb/dafny_to_aws_sdk.py @@ -0,0 +1,6347 @@ +# 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_cryptography_internal_dynamodb.internaldafny.generated.ComAmazonawsDynamodbTypes import ( + AttributeAction_ADD, + AttributeAction_DELETE, + AttributeAction_PUT, + AttributeValue_B, + AttributeValue_BOOL, + AttributeValue_BS, + AttributeValue_L, + AttributeValue_M, + AttributeValue_N, + AttributeValue_NS, + AttributeValue_NULL, + AttributeValue_S, + AttributeValue_SS, + BackupStatus_AVAILABLE, + BackupStatus_CREATING, + BackupStatus_DELETED, + BackupTypeFilter_ALL, + BackupTypeFilter_AWS__BACKUP, + BackupTypeFilter_SYSTEM, + BackupTypeFilter_USER, + BackupType_AWS__BACKUP, + BackupType_SYSTEM, + BackupType_USER, + BatchStatementErrorCodeEnum_AccessDenied, + BatchStatementErrorCodeEnum_ConditionalCheckFailed, + BatchStatementErrorCodeEnum_DuplicateItem, + BatchStatementErrorCodeEnum_InternalServerError, + BatchStatementErrorCodeEnum_ItemCollectionSizeLimitExceeded, + BatchStatementErrorCodeEnum_ProvisionedThroughputExceeded, + BatchStatementErrorCodeEnum_RequestLimitExceeded, + BatchStatementErrorCodeEnum_ResourceNotFound, + BatchStatementErrorCodeEnum_ThrottlingError, + BatchStatementErrorCodeEnum_TransactionConflict, + BatchStatementErrorCodeEnum_ValidationError, + BillingMode_PAY__PER__REQUEST, + BillingMode_PROVISIONED, + ComparisonOperator_BEGINS__WITH, + ComparisonOperator_BETWEEN, + ComparisonOperator_CONTAINS, + ComparisonOperator_EQ, + ComparisonOperator_GE, + ComparisonOperator_GT, + ComparisonOperator_IN, + ComparisonOperator_LE, + ComparisonOperator_LT, + ComparisonOperator_NE, + ComparisonOperator_NOT__CONTAINS, + ComparisonOperator_NOT__NULL, + ComparisonOperator_NULL, + ConditionalOperator_AND, + ConditionalOperator_OR, + ContinuousBackupsStatus_DISABLED, + ContinuousBackupsStatus_ENABLED, + ContributorInsightsAction_DISABLE, + ContributorInsightsAction_ENABLE, + ContributorInsightsStatus_DISABLED, + ContributorInsightsStatus_DISABLING, + ContributorInsightsStatus_ENABLED, + ContributorInsightsStatus_ENABLING, + ContributorInsightsStatus_FAILED, + DestinationStatus_ACTIVE, + DestinationStatus_DISABLED, + DestinationStatus_DISABLING, + DestinationStatus_ENABLE__FAILED, + DestinationStatus_ENABLING, + ExportFormat_DYNAMODB__JSON, + ExportFormat_ION, + ExportStatus_COMPLETED, + ExportStatus_FAILED, + ExportStatus_IN__PROGRESS, + GlobalTableStatus_ACTIVE, + GlobalTableStatus_CREATING, + GlobalTableStatus_DELETING, + GlobalTableStatus_UPDATING, + ImportStatus_CANCELLED, + ImportStatus_CANCELLING, + ImportStatus_COMPLETED, + ImportStatus_FAILED, + ImportStatus_IN__PROGRESS, + IndexStatus_ACTIVE, + IndexStatus_CREATING, + IndexStatus_DELETING, + IndexStatus_UPDATING, + InputCompressionType_GZIP, + InputCompressionType_NONE, + InputCompressionType_ZSTD, + InputFormat_CSV, + InputFormat_DYNAMODB__JSON, + InputFormat_ION, + KeyType_HASH, + KeyType_RANGE, + PointInTimeRecoveryStatus_DISABLED, + PointInTimeRecoveryStatus_ENABLED, + ProjectionType_ALL, + ProjectionType_INCLUDE, + ProjectionType_KEYS__ONLY, + ReplicaStatus_ACTIVE, + ReplicaStatus_CREATING, + ReplicaStatus_CREATION__FAILED, + ReplicaStatus_DELETING, + ReplicaStatus_INACCESSIBLE__ENCRYPTION__CREDENTIALS, + ReplicaStatus_REGION__DISABLED, + ReplicaStatus_UPDATING, + ReturnConsumedCapacity_INDEXES, + ReturnConsumedCapacity_NONE, + ReturnConsumedCapacity_TOTAL, + ReturnItemCollectionMetrics_NONE, + ReturnItemCollectionMetrics_SIZE, + ReturnValue_ALL__NEW, + ReturnValue_ALL__OLD, + ReturnValue_NONE, + ReturnValue_UPDATED__NEW, + ReturnValue_UPDATED__OLD, + ReturnValuesOnConditionCheckFailure_ALL__OLD, + ReturnValuesOnConditionCheckFailure_NONE, + S3SseAlgorithm_AES256, + S3SseAlgorithm_KMS, + SSEStatus_DISABLED, + SSEStatus_DISABLING, + SSEStatus_ENABLED, + SSEStatus_ENABLING, + SSEStatus_UPDATING, + SSEType_AES256, + SSEType_KMS, + ScalarAttributeType_B, + ScalarAttributeType_N, + ScalarAttributeType_S, + Select_ALL__ATTRIBUTES, + Select_ALL__PROJECTED__ATTRIBUTES, + Select_COUNT, + Select_SPECIFIC__ATTRIBUTES, + StreamViewType_KEYS__ONLY, + StreamViewType_NEW__AND__OLD__IMAGES, + StreamViewType_NEW__IMAGE, + StreamViewType_OLD__IMAGE, + TableClass_STANDARD, + TableClass_STANDARD__INFREQUENT__ACCESS, + TableStatus_ACTIVE, + TableStatus_ARCHIVED, + TableStatus_ARCHIVING, + TableStatus_CREATING, + TableStatus_DELETING, + TableStatus_INACCESSIBLE__ENCRYPTION__CREDENTIALS, + TableStatus_UPDATING, + TimeToLiveStatus_DISABLED, + TimeToLiveStatus_DISABLING, + TimeToLiveStatus_ENABLED, + TimeToLiveStatus_ENABLING, +) +import aws_cryptography_internal_dynamodb.internaldafny.generated.module_ +import aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk +from datetime import datetime + + +def com_amazonaws_dynamodb_BackupInUseException(dafny_input): + output = {} + if dafny_input.message.is_Some: + output["message"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.message.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_dynamodb_BackupNotFoundException(dafny_input): + output = {} + if dafny_input.message.is_Some: + output["message"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.message.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_dynamodb_ConditionalCheckFailedException(dafny_input): + output = {} + if dafny_input.message.is_Some: + output["message"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.message.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_dynamodb_ContinuousBackupsUnavailableException(dafny_input): + output = {} + if dafny_input.message.is_Some: + output["message"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.message.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_dynamodb_DuplicateItemException(dafny_input): + output = {} + if dafny_input.message.is_Some: + output["message"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.message.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_dynamodb_ExportConflictException(dafny_input): + output = {} + if dafny_input.message.is_Some: + output["message"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.message.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_dynamodb_ExportNotFoundException(dafny_input): + output = {} + if dafny_input.message.is_Some: + output["message"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.message.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_dynamodb_GlobalTableAlreadyExistsException(dafny_input): + output = {} + if dafny_input.message.is_Some: + output["message"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.message.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_dynamodb_GlobalTableNotFoundException(dafny_input): + output = {} + if dafny_input.message.is_Some: + output["message"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.message.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_dynamodb_IdempotentParameterMismatchException(dafny_input): + output = {} + if dafny_input.Message.is_Some: + output["Message"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.Message.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_dynamodb_ImportConflictException(dafny_input): + output = {} + if dafny_input.message.is_Some: + output["message"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.message.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_dynamodb_ImportNotFoundException(dafny_input): + output = {} + if dafny_input.message.is_Some: + output["message"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.message.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_dynamodb_IndexNotFoundException(dafny_input): + output = {} + if dafny_input.message.is_Some: + output["message"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.message.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_dynamodb_InternalServerError(dafny_input): + output = {} + if dafny_input.message.is_Some: + output["message"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.message.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_dynamodb_InvalidEndpointException(dafny_input): + output = {} + if dafny_input.Message.is_Some: + output["Message"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.Message.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_dynamodb_InvalidExportTimeException(dafny_input): + output = {} + if dafny_input.message.is_Some: + output["message"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.message.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_dynamodb_InvalidRestoreTimeException(dafny_input): + output = {} + if dafny_input.message.is_Some: + output["message"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.message.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_dynamodb_ItemCollectionSizeLimitExceededException(dafny_input): + output = {} + if dafny_input.message.is_Some: + output["message"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.message.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_dynamodb_LimitExceededException(dafny_input): + output = {} + if dafny_input.message.is_Some: + output["message"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.message.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_dynamodb_PointInTimeRecoveryUnavailableException(dafny_input): + output = {} + if dafny_input.message.is_Some: + output["message"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.message.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_dynamodb_ProvisionedThroughputExceededException(dafny_input): + output = {} + if dafny_input.message.is_Some: + output["message"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.message.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_dynamodb_ReplicaAlreadyExistsException(dafny_input): + output = {} + if dafny_input.message.is_Some: + output["message"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.message.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_dynamodb_ReplicaNotFoundException(dafny_input): + output = {} + if dafny_input.message.is_Some: + output["message"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.message.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_dynamodb_RequestLimitExceeded(dafny_input): + output = {} + if dafny_input.message.is_Some: + output["message"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.message.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_dynamodb_ResourceInUseException(dafny_input): + output = {} + if dafny_input.message.is_Some: + output["message"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.message.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_dynamodb_ResourceNotFoundException(dafny_input): + output = {} + if dafny_input.message.is_Some: + output["message"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.message.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_dynamodb_TableAlreadyExistsException(dafny_input): + output = {} + if dafny_input.message.is_Some: + output["message"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.message.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_dynamodb_TableInUseException(dafny_input): + output = {} + if dafny_input.message.is_Some: + output["message"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.message.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_dynamodb_TableNotFoundException(dafny_input): + output = {} + if dafny_input.message.is_Some: + output["message"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.message.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_dynamodb_CancellationReason(dafny_input): + output = {} + if dafny_input.Item.is_Some: + output["Item"] = { + b"".join(ord(c).to_bytes(2, "big") for c in key).decode( + "utf-16-be" + ): aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_AttributeValue( + value + ) + for (key, value) in dafny_input.Item.value.items + } + + if dafny_input.Code.is_Some: + output["Code"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.Code.value + ).decode("utf-16-be") + + if dafny_input.Message.is_Some: + output["Message"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.Message.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_dynamodb_AttributeValue(dafny_input): + # Convert AttributeValue + if isinstance(dafny_input, AttributeValue_S): + AttributeValue_union_value = { + "S": b"".join(ord(c).to_bytes(2, "big") for c in dafny_input.S).decode( + "utf-16-be" + ) + } + elif isinstance(dafny_input, AttributeValue_N): + AttributeValue_union_value = { + "N": b"".join(ord(c).to_bytes(2, "big") for c in dafny_input.N).decode( + "utf-16-be" + ) + } + elif isinstance(dafny_input, AttributeValue_B): + AttributeValue_union_value = {"B": bytes(dafny_input.B)} + elif isinstance(dafny_input, AttributeValue_SS): + AttributeValue_union_value = { + "SS": [ + b"".join(ord(c).to_bytes(2, "big") for c in list_element).decode( + "utf-16-be" + ) + for list_element in dafny_input.SS + ] + } + elif isinstance(dafny_input, AttributeValue_NS): + AttributeValue_union_value = { + "NS": [ + b"".join(ord(c).to_bytes(2, "big") for c in list_element).decode( + "utf-16-be" + ) + for list_element in dafny_input.NS + ] + } + elif isinstance(dafny_input, AttributeValue_BS): + AttributeValue_union_value = { + "BS": [bytes(list_element) for list_element in dafny_input.BS] + } + elif isinstance(dafny_input, AttributeValue_M): + AttributeValue_union_value = { + "M": { + b"".join(ord(c).to_bytes(2, "big") for c in key).decode( + "utf-16-be" + ): aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_AttributeValue( + value + ) + for (key, value) in dafny_input.M.items + } + } + elif isinstance(dafny_input, AttributeValue_L): + AttributeValue_union_value = { + "L": [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_AttributeValue( + list_element + ) + for list_element in dafny_input.L + ] + } + elif isinstance(dafny_input, AttributeValue_NULL): + AttributeValue_union_value = {"NULL": dafny_input.NULL} + elif isinstance(dafny_input, AttributeValue_BOOL): + AttributeValue_union_value = {"BOOL": dafny_input.BOOL} + else: + raise ValueError("No recognized union value in union type: " + str(dafny_input)) + + return AttributeValue_union_value + + +def com_amazonaws_dynamodb_TransactionCanceledException(dafny_input): + output = {} + if dafny_input.Message.is_Some: + output["Message"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.Message.value + ).decode("utf-16-be") + + if dafny_input.CancellationReasons.is_Some: + output["CancellationReasons"] = [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_CancellationReason( + list_element + ) + for list_element in dafny_input.CancellationReasons.value + ] + + return output + + +def com_amazonaws_dynamodb_TransactionConflictException(dafny_input): + output = {} + if dafny_input.message.is_Some: + output["message"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.message.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_dynamodb_TransactionInProgressException(dafny_input): + output = {} + if dafny_input.Message.is_Some: + output["Message"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.Message.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_dynamodb_BatchStatementRequest(dafny_input): + output = {} + output["Statement"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.Statement + ).decode("utf-16-be") + if dafny_input.Parameters.is_Some: + output["Parameters"] = [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_AttributeValue( + list_element + ) + for list_element in dafny_input.Parameters.value + ] + + if dafny_input.ConsistentRead.is_Some: + output["ConsistentRead"] = dafny_input.ConsistentRead.value + + return output + + +def com_amazonaws_dynamodb_ReturnConsumedCapacity(dafny_input): + # Convert ReturnConsumedCapacity + if isinstance(dafny_input, ReturnConsumedCapacity_INDEXES): + return "INDEXES" + + elif isinstance(dafny_input, ReturnConsumedCapacity_TOTAL): + return "TOTAL" + + elif isinstance(dafny_input, ReturnConsumedCapacity_NONE): + return "NONE" + + else: + raise ValueError("No recognized enum value in enum type: " + dafny_input) + + +def com_amazonaws_dynamodb_BatchExecuteStatementInput(dafny_input): + output = {} + output["Statements"] = [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_BatchStatementRequest( + list_element + ) + for list_element in dafny_input.Statements + ] + if dafny_input.ReturnConsumedCapacity.is_Some: + output["ReturnConsumedCapacity"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ReturnConsumedCapacity( + dafny_input.ReturnConsumedCapacity.value + ) + ) + + return output + + +def com_amazonaws_dynamodb_BatchStatementResponse(dafny_input): + output = {} + if dafny_input.Error.is_Some: + output["Error"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_BatchStatementError( + dafny_input.Error.value + ) + ) + + if dafny_input.TableName.is_Some: + output["TableName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.TableName.value + ).decode("utf-16-be") + + if dafny_input.Item.is_Some: + output["Item"] = { + b"".join(ord(c).to_bytes(2, "big") for c in key).decode( + "utf-16-be" + ): aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_AttributeValue( + value + ) + for (key, value) in dafny_input.Item.value.items + } + + return output + + +def com_amazonaws_dynamodb_BatchStatementError(dafny_input): + output = {} + if dafny_input.Code.is_Some: + output["Code"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_BatchStatementErrorCodeEnum( + dafny_input.Code.value + ) + ) + + if dafny_input.Message.is_Some: + output["Message"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.Message.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_dynamodb_BatchStatementErrorCodeEnum(dafny_input): + # Convert BatchStatementErrorCodeEnum + if isinstance(dafny_input, BatchStatementErrorCodeEnum_ConditionalCheckFailed): + return "ConditionalCheckFailed" + + elif isinstance( + dafny_input, BatchStatementErrorCodeEnum_ItemCollectionSizeLimitExceeded + ): + return "ItemCollectionSizeLimitExceeded" + + elif isinstance(dafny_input, BatchStatementErrorCodeEnum_RequestLimitExceeded): + return "RequestLimitExceeded" + + elif isinstance(dafny_input, BatchStatementErrorCodeEnum_ValidationError): + return "ValidationError" + + elif isinstance( + dafny_input, BatchStatementErrorCodeEnum_ProvisionedThroughputExceeded + ): + return "ProvisionedThroughputExceeded" + + elif isinstance(dafny_input, BatchStatementErrorCodeEnum_TransactionConflict): + return "TransactionConflict" + + elif isinstance(dafny_input, BatchStatementErrorCodeEnum_ThrottlingError): + return "ThrottlingError" + + elif isinstance(dafny_input, BatchStatementErrorCodeEnum_InternalServerError): + return "InternalServerError" + + elif isinstance(dafny_input, BatchStatementErrorCodeEnum_ResourceNotFound): + return "ResourceNotFound" + + elif isinstance(dafny_input, BatchStatementErrorCodeEnum_AccessDenied): + return "AccessDenied" + + elif isinstance(dafny_input, BatchStatementErrorCodeEnum_DuplicateItem): + return "DuplicateItem" + + else: + raise ValueError("No recognized enum value in enum type: " + dafny_input) + + +def com_amazonaws_dynamodb_ConsumedCapacity(dafny_input): + output = {} + if dafny_input.TableName.is_Some: + output["TableName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.TableName.value + ).decode("utf-16-be") + + if dafny_input.CapacityUnits.is_Some: + output["CapacityUnits"] = dafny_input.CapacityUnits.value + + if dafny_input.ReadCapacityUnits.is_Some: + output["ReadCapacityUnits"] = dafny_input.ReadCapacityUnits.value + + if dafny_input.WriteCapacityUnits.is_Some: + output["WriteCapacityUnits"] = dafny_input.WriteCapacityUnits.value + + if dafny_input.Table.is_Some: + output["Table"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_Capacity( + dafny_input.Table.value + ) + ) + + if dafny_input.LocalSecondaryIndexes.is_Some: + output["LocalSecondaryIndexes"] = { + b"".join(ord(c).to_bytes(2, "big") for c in key).decode( + "utf-16-be" + ): aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_Capacity( + value + ) + for (key, value) in dafny_input.LocalSecondaryIndexes.value.items + } + + if dafny_input.GlobalSecondaryIndexes.is_Some: + output["GlobalSecondaryIndexes"] = { + b"".join(ord(c).to_bytes(2, "big") for c in key).decode( + "utf-16-be" + ): aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_Capacity( + value + ) + for (key, value) in dafny_input.GlobalSecondaryIndexes.value.items + } + + return output + + +def com_amazonaws_dynamodb_Capacity(dafny_input): + output = {} + if dafny_input.ReadCapacityUnits.is_Some: + output["ReadCapacityUnits"] = dafny_input.ReadCapacityUnits.value + + if dafny_input.WriteCapacityUnits.is_Some: + output["WriteCapacityUnits"] = dafny_input.WriteCapacityUnits.value + + if dafny_input.CapacityUnits.is_Some: + output["CapacityUnits"] = dafny_input.CapacityUnits.value + + return output + + +def com_amazonaws_dynamodb_BatchExecuteStatementOutput(dafny_input): + output = {} + if dafny_input.Responses.is_Some: + output["Responses"] = [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_BatchStatementResponse( + list_element + ) + for list_element in dafny_input.Responses.value + ] + + if dafny_input.ConsumedCapacity.is_Some: + output["ConsumedCapacity"] = [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ConsumedCapacity( + list_element + ) + for list_element in dafny_input.ConsumedCapacity.value + ] + + return output + + +def com_amazonaws_dynamodb_KeysAndAttributes(dafny_input): + output = {} + output["Keys"] = [ + { + b"".join(ord(c).to_bytes(2, "big") for c in key).decode( + "utf-16-be" + ): aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_AttributeValue( + value + ) + for (key, value) in list_element.items + } + for list_element in dafny_input.Keys + ] + if dafny_input.AttributesToGet.is_Some: + output["AttributesToGet"] = [ + b"".join(ord(c).to_bytes(2, "big") for c in list_element).decode( + "utf-16-be" + ) + for list_element in dafny_input.AttributesToGet.value + ] + + if dafny_input.ConsistentRead.is_Some: + output["ConsistentRead"] = dafny_input.ConsistentRead.value + + if dafny_input.ProjectionExpression.is_Some: + output["ProjectionExpression"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.ProjectionExpression.value + ).decode("utf-16-be") + + if dafny_input.ExpressionAttributeNames.is_Some: + output["ExpressionAttributeNames"] = { + 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.ExpressionAttributeNames.value.items + } + + return output + + +def com_amazonaws_dynamodb_BatchGetItemInput(dafny_input): + output = {} + output["RequestItems"] = { + b"".join(ord(c).to_bytes(2, "big") for c in key).decode( + "utf-16-be" + ): aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_KeysAndAttributes( + value + ) + for (key, value) in dafny_input.RequestItems.items + } + if dafny_input.ReturnConsumedCapacity.is_Some: + output["ReturnConsumedCapacity"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ReturnConsumedCapacity( + dafny_input.ReturnConsumedCapacity.value + ) + ) + + return output + + +def com_amazonaws_dynamodb_BatchGetItemOutput(dafny_input): + output = {} + if dafny_input.Responses.is_Some: + output["Responses"] = { + 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 key).decode( + "utf-16-be" + ): aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_AttributeValue( + value + ) + for (key, value) in list_element.items + } + for list_element in value + ] + for (key, value) in dafny_input.Responses.value.items + } + + if dafny_input.UnprocessedKeys.is_Some: + output["UnprocessedKeys"] = { + b"".join(ord(c).to_bytes(2, "big") for c in key).decode( + "utf-16-be" + ): aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_KeysAndAttributes( + value + ) + for (key, value) in dafny_input.UnprocessedKeys.value.items + } + + if dafny_input.ConsumedCapacity.is_Some: + output["ConsumedCapacity"] = [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ConsumedCapacity( + list_element + ) + for list_element in dafny_input.ConsumedCapacity.value + ] + + return output + + +def com_amazonaws_dynamodb_WriteRequest(dafny_input): + output = {} + if dafny_input.PutRequest.is_Some: + output["PutRequest"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_PutRequest( + dafny_input.PutRequest.value + ) + ) + + if dafny_input.DeleteRequest.is_Some: + output["DeleteRequest"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_DeleteRequest( + dafny_input.DeleteRequest.value + ) + ) + + return output + + +def com_amazonaws_dynamodb_PutRequest(dafny_input): + output = {} + output["Item"] = { + b"".join(ord(c).to_bytes(2, "big") for c in key).decode( + "utf-16-be" + ): aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_AttributeValue( + value + ) + for (key, value) in dafny_input.Item.items + } + return output + + +def com_amazonaws_dynamodb_DeleteRequest(dafny_input): + output = {} + output["Key"] = { + b"".join(ord(c).to_bytes(2, "big") for c in key).decode( + "utf-16-be" + ): aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_AttributeValue( + value + ) + for (key, value) in dafny_input.Key.items + } + return output + + +def com_amazonaws_dynamodb_ReturnItemCollectionMetrics(dafny_input): + # Convert ReturnItemCollectionMetrics + if isinstance(dafny_input, ReturnItemCollectionMetrics_SIZE): + return "SIZE" + + elif isinstance(dafny_input, ReturnItemCollectionMetrics_NONE): + return "NONE" + + else: + raise ValueError("No recognized enum value in enum type: " + dafny_input) + + +def com_amazonaws_dynamodb_BatchWriteItemInput(dafny_input): + output = {} + output["RequestItems"] = { + b"".join(ord(c).to_bytes(2, "big") for c in key).decode("utf-16-be"): [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_WriteRequest( + list_element + ) + for list_element in value + ] + for (key, value) in dafny_input.RequestItems.items + } + if dafny_input.ReturnConsumedCapacity.is_Some: + output["ReturnConsumedCapacity"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ReturnConsumedCapacity( + dafny_input.ReturnConsumedCapacity.value + ) + ) + + if dafny_input.ReturnItemCollectionMetrics.is_Some: + output["ReturnItemCollectionMetrics"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ReturnItemCollectionMetrics( + dafny_input.ReturnItemCollectionMetrics.value + ) + ) + + return output + + +def com_amazonaws_dynamodb_ItemCollectionMetrics(dafny_input): + output = {} + if dafny_input.ItemCollectionKey.is_Some: + output["ItemCollectionKey"] = { + b"".join(ord(c).to_bytes(2, "big") for c in key).decode( + "utf-16-be" + ): aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_AttributeValue( + value + ) + for (key, value) in dafny_input.ItemCollectionKey.value.items + } + + if dafny_input.SizeEstimateRangeGB.is_Some: + output["SizeEstimateRangeGB"] = [ + list_element for list_element in dafny_input.SizeEstimateRangeGB.value + ] + + return output + + +def com_amazonaws_dynamodb_BatchWriteItemOutput(dafny_input): + output = {} + if dafny_input.UnprocessedItems.is_Some: + output["UnprocessedItems"] = { + b"".join(ord(c).to_bytes(2, "big") for c in key).decode("utf-16-be"): [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_WriteRequest( + list_element + ) + for list_element in value + ] + for (key, value) in dafny_input.UnprocessedItems.value.items + } + + if dafny_input.ItemCollectionMetrics.is_Some: + output["ItemCollectionMetrics"] = { + b"".join(ord(c).to_bytes(2, "big") for c in key).decode("utf-16-be"): [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ItemCollectionMetrics( + list_element + ) + for list_element in value + ] + for (key, value) in dafny_input.ItemCollectionMetrics.value.items + } + + if dafny_input.ConsumedCapacity.is_Some: + output["ConsumedCapacity"] = [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ConsumedCapacity( + list_element + ) + for list_element in dafny_input.ConsumedCapacity.value + ] + + return output + + +def com_amazonaws_dynamodb_CreateBackupInput(dafny_input): + output = {} + output["TableName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.TableName + ).decode("utf-16-be") + output["BackupName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.BackupName + ).decode("utf-16-be") + return output + + +def com_amazonaws_dynamodb_BackupDetails(dafny_input): + output = {} + output["BackupArn"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.BackupArn + ).decode("utf-16-be") + output["BackupName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.BackupName + ).decode("utf-16-be") + if dafny_input.BackupSizeBytes.is_Some: + output["BackupSizeBytes"] = dafny_input.BackupSizeBytes.value + + output["BackupStatus"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_BackupStatus( + dafny_input.BackupStatus + ) + ) + output["BackupType"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_BackupType( + dafny_input.BackupType + ) + ) + output["BackupCreationDateTime"] = datetime.fromisoformat( + dafny_input.BackupCreationDateTime.VerbatimString(False) + ) + if dafny_input.BackupExpiryDateTime.is_Some: + output["BackupExpiryDateTime"] = datetime.fromisoformat( + dafny_input.BackupExpiryDateTime.value.VerbatimString(False) + ) + + return output + + +def com_amazonaws_dynamodb_BackupStatus(dafny_input): + # Convert BackupStatus + if isinstance(dafny_input, BackupStatus_CREATING): + return "CREATING" + + elif isinstance(dafny_input, BackupStatus_DELETED): + return "DELETED" + + elif isinstance(dafny_input, BackupStatus_AVAILABLE): + return "AVAILABLE" + + else: + raise ValueError("No recognized enum value in enum type: " + dafny_input) + + +def com_amazonaws_dynamodb_BackupType(dafny_input): + # Convert BackupType + if isinstance(dafny_input, BackupType_USER): + return "USER" + + elif isinstance(dafny_input, BackupType_SYSTEM): + return "SYSTEM" + + elif isinstance(dafny_input, BackupType_AWS__BACKUP): + return "AWS_BACKUP" + + else: + raise ValueError("No recognized enum value in enum type: " + dafny_input) + + +def com_amazonaws_dynamodb_CreateBackupOutput(dafny_input): + output = {} + if dafny_input.BackupDetails.is_Some: + output["BackupDetails"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_BackupDetails( + dafny_input.BackupDetails.value + ) + ) + + return output + + +def com_amazonaws_dynamodb_Replica(dafny_input): + output = {} + if dafny_input.RegionName.is_Some: + output["RegionName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.RegionName.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_dynamodb_CreateGlobalTableInput(dafny_input): + output = {} + output["GlobalTableName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.GlobalTableName + ).decode("utf-16-be") + output["ReplicationGroup"] = [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_Replica( + list_element + ) + for list_element in dafny_input.ReplicationGroup + ] + return output + + +def com_amazonaws_dynamodb_GlobalTableDescription(dafny_input): + output = {} + if dafny_input.ReplicationGroup.is_Some: + output["ReplicationGroup"] = [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ReplicaDescription( + list_element + ) + for list_element in dafny_input.ReplicationGroup.value + ] + + if dafny_input.GlobalTableArn.is_Some: + output["GlobalTableArn"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.GlobalTableArn.value + ).decode("utf-16-be") + + if dafny_input.CreationDateTime.is_Some: + output["CreationDateTime"] = datetime.fromisoformat( + dafny_input.CreationDateTime.value.VerbatimString(False) + ) + + if dafny_input.GlobalTableStatus.is_Some: + output["GlobalTableStatus"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_GlobalTableStatus( + dafny_input.GlobalTableStatus.value + ) + ) + + if dafny_input.GlobalTableName.is_Some: + output["GlobalTableName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.GlobalTableName.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_dynamodb_ReplicaDescription(dafny_input): + output = {} + if dafny_input.RegionName.is_Some: + output["RegionName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.RegionName.value + ).decode("utf-16-be") + + if dafny_input.ReplicaStatus.is_Some: + output["ReplicaStatus"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ReplicaStatus( + dafny_input.ReplicaStatus.value + ) + ) + + if dafny_input.ReplicaStatusDescription.is_Some: + output["ReplicaStatusDescription"] = b"".join( + ord(c).to_bytes(2, "big") + for c in dafny_input.ReplicaStatusDescription.value + ).decode("utf-16-be") + + if dafny_input.ReplicaStatusPercentProgress.is_Some: + output["ReplicaStatusPercentProgress"] = b"".join( + ord(c).to_bytes(2, "big") + for c in dafny_input.ReplicaStatusPercentProgress.value + ).decode("utf-16-be") + + if dafny_input.KMSMasterKeyId.is_Some: + output["KMSMasterKeyId"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.KMSMasterKeyId.value + ).decode("utf-16-be") + + if dafny_input.ProvisionedThroughputOverride.is_Some: + output["ProvisionedThroughputOverride"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ProvisionedThroughputOverride( + dafny_input.ProvisionedThroughputOverride.value + ) + ) + + if dafny_input.GlobalSecondaryIndexes.is_Some: + output["GlobalSecondaryIndexes"] = [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ReplicaGlobalSecondaryIndexDescription( + list_element + ) + for list_element in dafny_input.GlobalSecondaryIndexes.value + ] + + if dafny_input.ReplicaInaccessibleDateTime.is_Some: + output["ReplicaInaccessibleDateTime"] = datetime.fromisoformat( + dafny_input.ReplicaInaccessibleDateTime.value.VerbatimString(False) + ) + + if dafny_input.ReplicaTableClassSummary.is_Some: + output["ReplicaTableClassSummary"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_TableClassSummary( + dafny_input.ReplicaTableClassSummary.value + ) + ) + + return output + + +def com_amazonaws_dynamodb_GlobalTableStatus(dafny_input): + # Convert GlobalTableStatus + if isinstance(dafny_input, GlobalTableStatus_CREATING): + return "CREATING" + + elif isinstance(dafny_input, GlobalTableStatus_ACTIVE): + return "ACTIVE" + + elif isinstance(dafny_input, GlobalTableStatus_DELETING): + return "DELETING" + + elif isinstance(dafny_input, GlobalTableStatus_UPDATING): + return "UPDATING" + + else: + raise ValueError("No recognized enum value in enum type: " + dafny_input) + + +def com_amazonaws_dynamodb_ReplicaStatus(dafny_input): + # Convert ReplicaStatus + if isinstance(dafny_input, ReplicaStatus_CREATING): + return "CREATING" + + elif isinstance(dafny_input, ReplicaStatus_CREATION__FAILED): + return "CREATION_FAILED" + + elif isinstance(dafny_input, ReplicaStatus_UPDATING): + return "UPDATING" + + elif isinstance(dafny_input, ReplicaStatus_DELETING): + return "DELETING" + + elif isinstance(dafny_input, ReplicaStatus_ACTIVE): + return "ACTIVE" + + elif isinstance(dafny_input, ReplicaStatus_REGION__DISABLED): + return "REGION_DISABLED" + + elif isinstance(dafny_input, ReplicaStatus_INACCESSIBLE__ENCRYPTION__CREDENTIALS): + return "INACCESSIBLE_ENCRYPTION_CREDENTIALS" + + else: + raise ValueError("No recognized enum value in enum type: " + dafny_input) + + +def com_amazonaws_dynamodb_ProvisionedThroughputOverride(dafny_input): + output = {} + if dafny_input.ReadCapacityUnits.is_Some: + output["ReadCapacityUnits"] = dafny_input.ReadCapacityUnits.value + + return output + + +def com_amazonaws_dynamodb_ReplicaGlobalSecondaryIndexDescription(dafny_input): + output = {} + if dafny_input.IndexName.is_Some: + output["IndexName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.IndexName.value + ).decode("utf-16-be") + + if dafny_input.ProvisionedThroughputOverride.is_Some: + output["ProvisionedThroughputOverride"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ProvisionedThroughputOverride( + dafny_input.ProvisionedThroughputOverride.value + ) + ) + + return output + + +def com_amazonaws_dynamodb_TableClassSummary(dafny_input): + output = {} + if dafny_input.TableClass.is_Some: + output["TableClass"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_TableClass( + dafny_input.TableClass.value + ) + ) + + if dafny_input.LastUpdateDateTime.is_Some: + output["LastUpdateDateTime"] = datetime.fromisoformat( + dafny_input.LastUpdateDateTime.value.VerbatimString(False) + ) + + return output + + +def com_amazonaws_dynamodb_TableClass(dafny_input): + # Convert TableClass + if isinstance(dafny_input, TableClass_STANDARD): + return "STANDARD" + + elif isinstance(dafny_input, TableClass_STANDARD__INFREQUENT__ACCESS): + return "STANDARD_INFREQUENT_ACCESS" + + else: + raise ValueError("No recognized enum value in enum type: " + dafny_input) + + +def com_amazonaws_dynamodb_CreateGlobalTableOutput(dafny_input): + output = {} + if dafny_input.GlobalTableDescription.is_Some: + output["GlobalTableDescription"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_GlobalTableDescription( + dafny_input.GlobalTableDescription.value + ) + ) + + return output + + +def com_amazonaws_dynamodb_AttributeDefinition(dafny_input): + output = {} + output["AttributeName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.AttributeName + ).decode("utf-16-be") + output["AttributeType"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ScalarAttributeType( + dafny_input.AttributeType + ) + ) + return output + + +def com_amazonaws_dynamodb_ScalarAttributeType(dafny_input): + # Convert ScalarAttributeType + if isinstance(dafny_input, ScalarAttributeType_S): + return "S" + + elif isinstance(dafny_input, ScalarAttributeType_N): + return "N" + + elif isinstance(dafny_input, ScalarAttributeType_B): + return "B" + + else: + raise ValueError("No recognized enum value in enum type: " + dafny_input) + + +def com_amazonaws_dynamodb_KeySchemaElement(dafny_input): + output = {} + output["AttributeName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.AttributeName + ).decode("utf-16-be") + output["KeyType"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_KeyType( + dafny_input.KeyType + ) + ) + return output + + +def com_amazonaws_dynamodb_KeyType(dafny_input): + # Convert KeyType + if isinstance(dafny_input, KeyType_HASH): + return "HASH" + + elif isinstance(dafny_input, KeyType_RANGE): + return "RANGE" + + else: + raise ValueError("No recognized enum value in enum type: " + dafny_input) + + +def com_amazonaws_dynamodb_LocalSecondaryIndex(dafny_input): + output = {} + output["IndexName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.IndexName + ).decode("utf-16-be") + output["KeySchema"] = [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_KeySchemaElement( + list_element + ) + for list_element in dafny_input.KeySchema + ] + output["Projection"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_Projection( + dafny_input.Projection + ) + ) + return output + + +def com_amazonaws_dynamodb_Projection(dafny_input): + output = {} + if dafny_input.ProjectionType.is_Some: + output["ProjectionType"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ProjectionType( + dafny_input.ProjectionType.value + ) + ) + + if dafny_input.NonKeyAttributes.is_Some: + output["NonKeyAttributes"] = [ + b"".join(ord(c).to_bytes(2, "big") for c in list_element).decode( + "utf-16-be" + ) + for list_element in dafny_input.NonKeyAttributes.value + ] + + return output + + +def com_amazonaws_dynamodb_ProjectionType(dafny_input): + # Convert ProjectionType + if isinstance(dafny_input, ProjectionType_ALL): + return "ALL" + + elif isinstance(dafny_input, ProjectionType_KEYS__ONLY): + return "KEYS_ONLY" + + elif isinstance(dafny_input, ProjectionType_INCLUDE): + return "INCLUDE" + + else: + raise ValueError("No recognized enum value in enum type: " + dafny_input) + + +def com_amazonaws_dynamodb_GlobalSecondaryIndex(dafny_input): + output = {} + output["IndexName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.IndexName + ).decode("utf-16-be") + output["KeySchema"] = [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_KeySchemaElement( + list_element + ) + for list_element in dafny_input.KeySchema + ] + output["Projection"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_Projection( + dafny_input.Projection + ) + ) + if dafny_input.ProvisionedThroughput.is_Some: + output["ProvisionedThroughput"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ProvisionedThroughput( + dafny_input.ProvisionedThroughput.value + ) + ) + + return output + + +def com_amazonaws_dynamodb_ProvisionedThroughput(dafny_input): + output = {} + output["ReadCapacityUnits"] = dafny_input.ReadCapacityUnits + output["WriteCapacityUnits"] = dafny_input.WriteCapacityUnits + return output + + +def com_amazonaws_dynamodb_BillingMode(dafny_input): + # Convert BillingMode + if isinstance(dafny_input, BillingMode_PROVISIONED): + return "PROVISIONED" + + elif isinstance(dafny_input, BillingMode_PAY__PER__REQUEST): + return "PAY_PER_REQUEST" + + else: + raise ValueError("No recognized enum value in enum type: " + dafny_input) + + +def com_amazonaws_dynamodb_StreamSpecification(dafny_input): + output = {} + output["StreamEnabled"] = dafny_input.StreamEnabled + if dafny_input.StreamViewType.is_Some: + output["StreamViewType"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_StreamViewType( + dafny_input.StreamViewType.value + ) + ) + + return output + + +def com_amazonaws_dynamodb_StreamViewType(dafny_input): + # Convert StreamViewType + if isinstance(dafny_input, StreamViewType_NEW__IMAGE): + return "NEW_IMAGE" + + elif isinstance(dafny_input, StreamViewType_OLD__IMAGE): + return "OLD_IMAGE" + + elif isinstance(dafny_input, StreamViewType_NEW__AND__OLD__IMAGES): + return "NEW_AND_OLD_IMAGES" + + elif isinstance(dafny_input, StreamViewType_KEYS__ONLY): + return "KEYS_ONLY" + + else: + raise ValueError("No recognized enum value in enum type: " + dafny_input) + + +def com_amazonaws_dynamodb_SSESpecification(dafny_input): + output = {} + if dafny_input.Enabled.is_Some: + output["Enabled"] = dafny_input.Enabled.value + + if dafny_input.SSEType.is_Some: + output["SSEType"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_SSEType( + dafny_input.SSEType.value + ) + ) + + if dafny_input.KMSMasterKeyId.is_Some: + output["KMSMasterKeyId"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.KMSMasterKeyId.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_dynamodb_SSEType(dafny_input): + # Convert SSEType + if isinstance(dafny_input, SSEType_AES256): + return "AES256" + + elif isinstance(dafny_input, SSEType_KMS): + return "KMS" + + else: + raise ValueError("No recognized enum value in enum type: " + dafny_input) + + +def com_amazonaws_dynamodb_Tag(dafny_input): + output = {} + output["Key"] = b"".join(ord(c).to_bytes(2, "big") for c in dafny_input.Key).decode( + "utf-16-be" + ) + output["Value"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.Value + ).decode("utf-16-be") + return output + + +def com_amazonaws_dynamodb_CreateTableInput(dafny_input): + output = {} + output["AttributeDefinitions"] = [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_AttributeDefinition( + list_element + ) + for list_element in dafny_input.AttributeDefinitions + ] + output["TableName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.TableName + ).decode("utf-16-be") + output["KeySchema"] = [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_KeySchemaElement( + list_element + ) + for list_element in dafny_input.KeySchema + ] + if dafny_input.LocalSecondaryIndexes.is_Some: + output["LocalSecondaryIndexes"] = [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_LocalSecondaryIndex( + list_element + ) + for list_element in dafny_input.LocalSecondaryIndexes.value + ] + + if dafny_input.GlobalSecondaryIndexes.is_Some: + output["GlobalSecondaryIndexes"] = [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_GlobalSecondaryIndex( + list_element + ) + for list_element in dafny_input.GlobalSecondaryIndexes.value + ] + + if dafny_input.BillingMode.is_Some: + output["BillingMode"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_BillingMode( + dafny_input.BillingMode.value + ) + ) + + if dafny_input.ProvisionedThroughput.is_Some: + output["ProvisionedThroughput"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ProvisionedThroughput( + dafny_input.ProvisionedThroughput.value + ) + ) + + if dafny_input.StreamSpecification.is_Some: + output["StreamSpecification"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_StreamSpecification( + dafny_input.StreamSpecification.value + ) + ) + + if dafny_input.SSESpecification.is_Some: + output["SSESpecification"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_SSESpecification( + dafny_input.SSESpecification.value + ) + ) + + if dafny_input.Tags.is_Some: + output["Tags"] = [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_Tag( + list_element + ) + for list_element in dafny_input.Tags.value + ] + + if dafny_input.TableClass.is_Some: + output["TableClass"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_TableClass( + dafny_input.TableClass.value + ) + ) + + return output + + +def com_amazonaws_dynamodb_TableDescription(dafny_input): + output = {} + if dafny_input.AttributeDefinitions.is_Some: + output["AttributeDefinitions"] = [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_AttributeDefinition( + list_element + ) + for list_element in dafny_input.AttributeDefinitions.value + ] + + if dafny_input.TableName.is_Some: + output["TableName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.TableName.value + ).decode("utf-16-be") + + if dafny_input.KeySchema.is_Some: + output["KeySchema"] = [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_KeySchemaElement( + list_element + ) + for list_element in dafny_input.KeySchema.value + ] + + if dafny_input.TableStatus.is_Some: + output["TableStatus"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_TableStatus( + dafny_input.TableStatus.value + ) + ) + + if dafny_input.CreationDateTime.is_Some: + output["CreationDateTime"] = datetime.fromisoformat( + dafny_input.CreationDateTime.value.VerbatimString(False) + ) + + if dafny_input.ProvisionedThroughput.is_Some: + output["ProvisionedThroughput"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ProvisionedThroughputDescription( + dafny_input.ProvisionedThroughput.value + ) + ) + + if dafny_input.TableSizeBytes.is_Some: + output["TableSizeBytes"] = dafny_input.TableSizeBytes.value + + if dafny_input.ItemCount.is_Some: + output["ItemCount"] = dafny_input.ItemCount.value + + if dafny_input.TableArn.is_Some: + output["TableArn"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.TableArn.value + ).decode("utf-16-be") + + if dafny_input.TableId.is_Some: + output["TableId"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.TableId.value + ).decode("utf-16-be") + + if dafny_input.BillingModeSummary.is_Some: + output["BillingModeSummary"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_BillingModeSummary( + dafny_input.BillingModeSummary.value + ) + ) + + if dafny_input.LocalSecondaryIndexes.is_Some: + output["LocalSecondaryIndexes"] = [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_LocalSecondaryIndexDescription( + list_element + ) + for list_element in dafny_input.LocalSecondaryIndexes.value + ] + + if dafny_input.GlobalSecondaryIndexes.is_Some: + output["GlobalSecondaryIndexes"] = [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_GlobalSecondaryIndexDescription( + list_element + ) + for list_element in dafny_input.GlobalSecondaryIndexes.value + ] + + if dafny_input.StreamSpecification.is_Some: + output["StreamSpecification"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_StreamSpecification( + dafny_input.StreamSpecification.value + ) + ) + + if dafny_input.LatestStreamLabel.is_Some: + output["LatestStreamLabel"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.LatestStreamLabel.value + ).decode("utf-16-be") + + if dafny_input.LatestStreamArn.is_Some: + output["LatestStreamArn"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.LatestStreamArn.value + ).decode("utf-16-be") + + if dafny_input.GlobalTableVersion.is_Some: + output["GlobalTableVersion"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.GlobalTableVersion.value + ).decode("utf-16-be") + + if dafny_input.Replicas.is_Some: + output["Replicas"] = [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ReplicaDescription( + list_element + ) + for list_element in dafny_input.Replicas.value + ] + + if dafny_input.RestoreSummary.is_Some: + output["RestoreSummary"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_RestoreSummary( + dafny_input.RestoreSummary.value + ) + ) + + if dafny_input.SSEDescription.is_Some: + output["SSEDescription"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_SSEDescription( + dafny_input.SSEDescription.value + ) + ) + + if dafny_input.ArchivalSummary.is_Some: + output["ArchivalSummary"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ArchivalSummary( + dafny_input.ArchivalSummary.value + ) + ) + + if dafny_input.TableClassSummary.is_Some: + output["TableClassSummary"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_TableClassSummary( + dafny_input.TableClassSummary.value + ) + ) + + return output + + +def com_amazonaws_dynamodb_TableStatus(dafny_input): + # Convert TableStatus + if isinstance(dafny_input, TableStatus_CREATING): + return "CREATING" + + elif isinstance(dafny_input, TableStatus_UPDATING): + return "UPDATING" + + elif isinstance(dafny_input, TableStatus_DELETING): + return "DELETING" + + elif isinstance(dafny_input, TableStatus_ACTIVE): + return "ACTIVE" + + elif isinstance(dafny_input, TableStatus_INACCESSIBLE__ENCRYPTION__CREDENTIALS): + return "INACCESSIBLE_ENCRYPTION_CREDENTIALS" + + elif isinstance(dafny_input, TableStatus_ARCHIVING): + return "ARCHIVING" + + elif isinstance(dafny_input, TableStatus_ARCHIVED): + return "ARCHIVED" + + else: + raise ValueError("No recognized enum value in enum type: " + dafny_input) + + +def com_amazonaws_dynamodb_ProvisionedThroughputDescription(dafny_input): + output = {} + if dafny_input.LastIncreaseDateTime.is_Some: + output["LastIncreaseDateTime"] = datetime.fromisoformat( + dafny_input.LastIncreaseDateTime.value.VerbatimString(False) + ) + + if dafny_input.LastDecreaseDateTime.is_Some: + output["LastDecreaseDateTime"] = datetime.fromisoformat( + dafny_input.LastDecreaseDateTime.value.VerbatimString(False) + ) + + if dafny_input.NumberOfDecreasesToday.is_Some: + output["NumberOfDecreasesToday"] = dafny_input.NumberOfDecreasesToday.value + + if dafny_input.ReadCapacityUnits.is_Some: + output["ReadCapacityUnits"] = dafny_input.ReadCapacityUnits.value + + if dafny_input.WriteCapacityUnits.is_Some: + output["WriteCapacityUnits"] = dafny_input.WriteCapacityUnits.value + + return output + + +def com_amazonaws_dynamodb_BillingModeSummary(dafny_input): + output = {} + if dafny_input.BillingMode.is_Some: + output["BillingMode"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_BillingMode( + dafny_input.BillingMode.value + ) + ) + + if dafny_input.LastUpdateToPayPerRequestDateTime.is_Some: + output["LastUpdateToPayPerRequestDateTime"] = datetime.fromisoformat( + dafny_input.LastUpdateToPayPerRequestDateTime.value.VerbatimString(False) + ) + + return output + + +def com_amazonaws_dynamodb_LocalSecondaryIndexDescription(dafny_input): + output = {} + if dafny_input.IndexName.is_Some: + output["IndexName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.IndexName.value + ).decode("utf-16-be") + + if dafny_input.KeySchema.is_Some: + output["KeySchema"] = [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_KeySchemaElement( + list_element + ) + for list_element in dafny_input.KeySchema.value + ] + + if dafny_input.Projection.is_Some: + output["Projection"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_Projection( + dafny_input.Projection.value + ) + ) + + if dafny_input.IndexSizeBytes.is_Some: + output["IndexSizeBytes"] = dafny_input.IndexSizeBytes.value + + if dafny_input.ItemCount.is_Some: + output["ItemCount"] = dafny_input.ItemCount.value + + if dafny_input.IndexArn.is_Some: + output["IndexArn"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.IndexArn.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_dynamodb_GlobalSecondaryIndexDescription(dafny_input): + output = {} + if dafny_input.IndexName.is_Some: + output["IndexName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.IndexName.value + ).decode("utf-16-be") + + if dafny_input.KeySchema.is_Some: + output["KeySchema"] = [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_KeySchemaElement( + list_element + ) + for list_element in dafny_input.KeySchema.value + ] + + if dafny_input.Projection.is_Some: + output["Projection"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_Projection( + dafny_input.Projection.value + ) + ) + + if dafny_input.IndexStatus.is_Some: + output["IndexStatus"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_IndexStatus( + dafny_input.IndexStatus.value + ) + ) + + if dafny_input.Backfilling.is_Some: + output["Backfilling"] = dafny_input.Backfilling.value + + if dafny_input.ProvisionedThroughput.is_Some: + output["ProvisionedThroughput"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ProvisionedThroughputDescription( + dafny_input.ProvisionedThroughput.value + ) + ) + + if dafny_input.IndexSizeBytes.is_Some: + output["IndexSizeBytes"] = dafny_input.IndexSizeBytes.value + + if dafny_input.ItemCount.is_Some: + output["ItemCount"] = dafny_input.ItemCount.value + + if dafny_input.IndexArn.is_Some: + output["IndexArn"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.IndexArn.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_dynamodb_RestoreSummary(dafny_input): + output = {} + if dafny_input.SourceBackupArn.is_Some: + output["SourceBackupArn"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.SourceBackupArn.value + ).decode("utf-16-be") + + if dafny_input.SourceTableArn.is_Some: + output["SourceTableArn"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.SourceTableArn.value + ).decode("utf-16-be") + + output["RestoreDateTime"] = datetime.fromisoformat( + dafny_input.RestoreDateTime.VerbatimString(False) + ) + output["RestoreInProgress"] = dafny_input.RestoreInProgress + return output + + +def com_amazonaws_dynamodb_SSEDescription(dafny_input): + output = {} + if dafny_input.Status.is_Some: + output["Status"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_SSEStatus( + dafny_input.Status.value + ) + ) + + if dafny_input.SSEType.is_Some: + output["SSEType"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_SSEType( + dafny_input.SSEType.value + ) + ) + + if dafny_input.KMSMasterKeyArn.is_Some: + output["KMSMasterKeyArn"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.KMSMasterKeyArn.value + ).decode("utf-16-be") + + if dafny_input.InaccessibleEncryptionDateTime.is_Some: + output["InaccessibleEncryptionDateTime"] = datetime.fromisoformat( + dafny_input.InaccessibleEncryptionDateTime.value.VerbatimString(False) + ) + + return output + + +def com_amazonaws_dynamodb_ArchivalSummary(dafny_input): + output = {} + if dafny_input.ArchivalDateTime.is_Some: + output["ArchivalDateTime"] = datetime.fromisoformat( + dafny_input.ArchivalDateTime.value.VerbatimString(False) + ) + + if dafny_input.ArchivalReason.is_Some: + output["ArchivalReason"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.ArchivalReason.value + ).decode("utf-16-be") + + if dafny_input.ArchivalBackupArn.is_Some: + output["ArchivalBackupArn"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.ArchivalBackupArn.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_dynamodb_IndexStatus(dafny_input): + # Convert IndexStatus + if isinstance(dafny_input, IndexStatus_CREATING): + return "CREATING" + + elif isinstance(dafny_input, IndexStatus_UPDATING): + return "UPDATING" + + elif isinstance(dafny_input, IndexStatus_DELETING): + return "DELETING" + + elif isinstance(dafny_input, IndexStatus_ACTIVE): + return "ACTIVE" + + else: + raise ValueError("No recognized enum value in enum type: " + dafny_input) + + +def com_amazonaws_dynamodb_SSEStatus(dafny_input): + # Convert SSEStatus + if isinstance(dafny_input, SSEStatus_ENABLING): + return "ENABLING" + + elif isinstance(dafny_input, SSEStatus_ENABLED): + return "ENABLED" + + elif isinstance(dafny_input, SSEStatus_DISABLING): + return "DISABLING" + + elif isinstance(dafny_input, SSEStatus_DISABLED): + return "DISABLED" + + elif isinstance(dafny_input, SSEStatus_UPDATING): + return "UPDATING" + + else: + raise ValueError("No recognized enum value in enum type: " + dafny_input) + + +def com_amazonaws_dynamodb_CreateTableOutput(dafny_input): + output = {} + if dafny_input.TableDescription.is_Some: + output["TableDescription"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_TableDescription( + dafny_input.TableDescription.value + ) + ) + + return output + + +def com_amazonaws_dynamodb_DeleteBackupInput(dafny_input): + output = {} + output["BackupArn"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.BackupArn + ).decode("utf-16-be") + return output + + +def com_amazonaws_dynamodb_BackupDescription(dafny_input): + output = {} + if dafny_input.BackupDetails.is_Some: + output["BackupDetails"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_BackupDetails( + dafny_input.BackupDetails.value + ) + ) + + if dafny_input.SourceTableDetails.is_Some: + output["SourceTableDetails"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_SourceTableDetails( + dafny_input.SourceTableDetails.value + ) + ) + + if dafny_input.SourceTableFeatureDetails.is_Some: + output["SourceTableFeatureDetails"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_SourceTableFeatureDetails( + dafny_input.SourceTableFeatureDetails.value + ) + ) + + return output + + +def com_amazonaws_dynamodb_SourceTableDetails(dafny_input): + output = {} + output["TableName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.TableName + ).decode("utf-16-be") + output["TableId"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.TableId + ).decode("utf-16-be") + if dafny_input.TableArn.is_Some: + output["TableArn"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.TableArn.value + ).decode("utf-16-be") + + if dafny_input.TableSizeBytes.is_Some: + output["TableSizeBytes"] = dafny_input.TableSizeBytes.value + + output["KeySchema"] = [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_KeySchemaElement( + list_element + ) + for list_element in dafny_input.KeySchema + ] + output["TableCreationDateTime"] = datetime.fromisoformat( + dafny_input.TableCreationDateTime.VerbatimString(False) + ) + output["ProvisionedThroughput"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ProvisionedThroughput( + dafny_input.ProvisionedThroughput + ) + ) + if dafny_input.ItemCount.is_Some: + output["ItemCount"] = dafny_input.ItemCount.value + + if dafny_input.BillingMode.is_Some: + output["BillingMode"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_BillingMode( + dafny_input.BillingMode.value + ) + ) + + return output + + +def com_amazonaws_dynamodb_SourceTableFeatureDetails(dafny_input): + output = {} + if dafny_input.LocalSecondaryIndexes.is_Some: + output["LocalSecondaryIndexes"] = [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_LocalSecondaryIndexInfo( + list_element + ) + for list_element in dafny_input.LocalSecondaryIndexes.value + ] + + if dafny_input.GlobalSecondaryIndexes.is_Some: + output["GlobalSecondaryIndexes"] = [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_GlobalSecondaryIndexInfo( + list_element + ) + for list_element in dafny_input.GlobalSecondaryIndexes.value + ] + + if dafny_input.StreamDescription.is_Some: + output["StreamDescription"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_StreamSpecification( + dafny_input.StreamDescription.value + ) + ) + + if dafny_input.TimeToLiveDescription.is_Some: + output["TimeToLiveDescription"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_TimeToLiveDescription( + dafny_input.TimeToLiveDescription.value + ) + ) + + if dafny_input.SSEDescription.is_Some: + output["SSEDescription"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_SSEDescription( + dafny_input.SSEDescription.value + ) + ) + + return output + + +def com_amazonaws_dynamodb_LocalSecondaryIndexInfo(dafny_input): + output = {} + if dafny_input.IndexName.is_Some: + output["IndexName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.IndexName.value + ).decode("utf-16-be") + + if dafny_input.KeySchema.is_Some: + output["KeySchema"] = [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_KeySchemaElement( + list_element + ) + for list_element in dafny_input.KeySchema.value + ] + + if dafny_input.Projection.is_Some: + output["Projection"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_Projection( + dafny_input.Projection.value + ) + ) + + return output + + +def com_amazonaws_dynamodb_GlobalSecondaryIndexInfo(dafny_input): + output = {} + if dafny_input.IndexName.is_Some: + output["IndexName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.IndexName.value + ).decode("utf-16-be") + + if dafny_input.KeySchema.is_Some: + output["KeySchema"] = [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_KeySchemaElement( + list_element + ) + for list_element in dafny_input.KeySchema.value + ] + + if dafny_input.Projection.is_Some: + output["Projection"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_Projection( + dafny_input.Projection.value + ) + ) + + if dafny_input.ProvisionedThroughput.is_Some: + output["ProvisionedThroughput"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ProvisionedThroughput( + dafny_input.ProvisionedThroughput.value + ) + ) + + return output + + +def com_amazonaws_dynamodb_TimeToLiveDescription(dafny_input): + output = {} + if dafny_input.TimeToLiveStatus.is_Some: + output["TimeToLiveStatus"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_TimeToLiveStatus( + dafny_input.TimeToLiveStatus.value + ) + ) + + if dafny_input.AttributeName.is_Some: + output["AttributeName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.AttributeName.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_dynamodb_TimeToLiveStatus(dafny_input): + # Convert TimeToLiveStatus + if isinstance(dafny_input, TimeToLiveStatus_ENABLING): + return "ENABLING" + + elif isinstance(dafny_input, TimeToLiveStatus_DISABLING): + return "DISABLING" + + elif isinstance(dafny_input, TimeToLiveStatus_ENABLED): + return "ENABLED" + + elif isinstance(dafny_input, TimeToLiveStatus_DISABLED): + return "DISABLED" + + else: + raise ValueError("No recognized enum value in enum type: " + dafny_input) + + +def com_amazonaws_dynamodb_DeleteBackupOutput(dafny_input): + output = {} + if dafny_input.BackupDescription.is_Some: + output["BackupDescription"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_BackupDescription( + dafny_input.BackupDescription.value + ) + ) + + return output + + +def com_amazonaws_dynamodb_ExpectedAttributeValue(dafny_input): + output = {} + if dafny_input.Value.is_Some: + output["Value"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_AttributeValue( + dafny_input.Value.value + ) + ) + + if dafny_input.Exists.is_Some: + output["Exists"] = dafny_input.Exists.value + + if dafny_input.ComparisonOperator.is_Some: + output["ComparisonOperator"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ComparisonOperator( + dafny_input.ComparisonOperator.value + ) + ) + + if dafny_input.AttributeValueList.is_Some: + output["AttributeValueList"] = [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_AttributeValue( + list_element + ) + for list_element in dafny_input.AttributeValueList.value + ] + + return output + + +def com_amazonaws_dynamodb_ComparisonOperator(dafny_input): + # Convert ComparisonOperator + if isinstance(dafny_input, ComparisonOperator_EQ): + return "EQ" + + elif isinstance(dafny_input, ComparisonOperator_NE): + return "NE" + + elif isinstance(dafny_input, ComparisonOperator_IN): + return "IN" + + elif isinstance(dafny_input, ComparisonOperator_LE): + return "LE" + + elif isinstance(dafny_input, ComparisonOperator_LT): + return "LT" + + elif isinstance(dafny_input, ComparisonOperator_GE): + return "GE" + + elif isinstance(dafny_input, ComparisonOperator_GT): + return "GT" + + elif isinstance(dafny_input, ComparisonOperator_BETWEEN): + return "BETWEEN" + + elif isinstance(dafny_input, ComparisonOperator_NOT__NULL): + return "NOT_NULL" + + elif isinstance(dafny_input, ComparisonOperator_NULL): + return "NULL" + + elif isinstance(dafny_input, ComparisonOperator_CONTAINS): + return "CONTAINS" + + elif isinstance(dafny_input, ComparisonOperator_NOT__CONTAINS): + return "NOT_CONTAINS" + + elif isinstance(dafny_input, ComparisonOperator_BEGINS__WITH): + return "BEGINS_WITH" + + else: + raise ValueError("No recognized enum value in enum type: " + dafny_input) + + +def com_amazonaws_dynamodb_ConditionalOperator(dafny_input): + # Convert ConditionalOperator + if isinstance(dafny_input, ConditionalOperator_AND): + return "AND" + + elif isinstance(dafny_input, ConditionalOperator_OR): + return "OR" + + else: + raise ValueError("No recognized enum value in enum type: " + dafny_input) + + +def com_amazonaws_dynamodb_ReturnValue(dafny_input): + # Convert ReturnValue + if isinstance(dafny_input, ReturnValue_NONE): + return "NONE" + + elif isinstance(dafny_input, ReturnValue_ALL__OLD): + return "ALL_OLD" + + elif isinstance(dafny_input, ReturnValue_UPDATED__OLD): + return "UPDATED_OLD" + + elif isinstance(dafny_input, ReturnValue_ALL__NEW): + return "ALL_NEW" + + elif isinstance(dafny_input, ReturnValue_UPDATED__NEW): + return "UPDATED_NEW" + + else: + raise ValueError("No recognized enum value in enum type: " + dafny_input) + + +def com_amazonaws_dynamodb_DeleteItemInput(dafny_input): + output = {} + output["TableName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.TableName + ).decode("utf-16-be") + output["Key"] = { + b"".join(ord(c).to_bytes(2, "big") for c in key).decode( + "utf-16-be" + ): aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_AttributeValue( + value + ) + for (key, value) in dafny_input.Key.items + } + if dafny_input.Expected.is_Some: + output["Expected"] = { + b"".join(ord(c).to_bytes(2, "big") for c in key).decode( + "utf-16-be" + ): aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ExpectedAttributeValue( + value + ) + for (key, value) in dafny_input.Expected.value.items + } + + if dafny_input.ConditionalOperator.is_Some: + output["ConditionalOperator"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ConditionalOperator( + dafny_input.ConditionalOperator.value + ) + ) + + if dafny_input.ReturnValues.is_Some: + output["ReturnValues"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ReturnValue( + dafny_input.ReturnValues.value + ) + ) + + if dafny_input.ReturnConsumedCapacity.is_Some: + output["ReturnConsumedCapacity"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ReturnConsumedCapacity( + dafny_input.ReturnConsumedCapacity.value + ) + ) + + if dafny_input.ReturnItemCollectionMetrics.is_Some: + output["ReturnItemCollectionMetrics"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ReturnItemCollectionMetrics( + dafny_input.ReturnItemCollectionMetrics.value + ) + ) + + if dafny_input.ConditionExpression.is_Some: + output["ConditionExpression"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.ConditionExpression.value + ).decode("utf-16-be") + + if dafny_input.ExpressionAttributeNames.is_Some: + output["ExpressionAttributeNames"] = { + 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.ExpressionAttributeNames.value.items + } + + if dafny_input.ExpressionAttributeValues.is_Some: + output["ExpressionAttributeValues"] = { + b"".join(ord(c).to_bytes(2, "big") for c in key).decode( + "utf-16-be" + ): aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_AttributeValue( + value + ) + for (key, value) in dafny_input.ExpressionAttributeValues.value.items + } + + return output + + +def com_amazonaws_dynamodb_DeleteItemOutput(dafny_input): + output = {} + if dafny_input.Attributes.is_Some: + output["Attributes"] = { + b"".join(ord(c).to_bytes(2, "big") for c in key).decode( + "utf-16-be" + ): aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_AttributeValue( + value + ) + for (key, value) in dafny_input.Attributes.value.items + } + + if dafny_input.ConsumedCapacity.is_Some: + output["ConsumedCapacity"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ConsumedCapacity( + dafny_input.ConsumedCapacity.value + ) + ) + + if dafny_input.ItemCollectionMetrics.is_Some: + output["ItemCollectionMetrics"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ItemCollectionMetrics( + dafny_input.ItemCollectionMetrics.value + ) + ) + + return output + + +def com_amazonaws_dynamodb_DeleteTableInput(dafny_input): + output = {} + output["TableName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.TableName + ).decode("utf-16-be") + return output + + +def com_amazonaws_dynamodb_DeleteTableOutput(dafny_input): + output = {} + if dafny_input.TableDescription.is_Some: + output["TableDescription"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_TableDescription( + dafny_input.TableDescription.value + ) + ) + + return output + + +def com_amazonaws_dynamodb_DescribeBackupInput(dafny_input): + output = {} + output["BackupArn"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.BackupArn + ).decode("utf-16-be") + return output + + +def com_amazonaws_dynamodb_DescribeBackupOutput(dafny_input): + output = {} + if dafny_input.BackupDescription.is_Some: + output["BackupDescription"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_BackupDescription( + dafny_input.BackupDescription.value + ) + ) + + return output + + +def com_amazonaws_dynamodb_DescribeContinuousBackupsInput(dafny_input): + output = {} + output["TableName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.TableName + ).decode("utf-16-be") + return output + + +def com_amazonaws_dynamodb_ContinuousBackupsDescription(dafny_input): + output = {} + output["ContinuousBackupsStatus"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ContinuousBackupsStatus( + dafny_input.ContinuousBackupsStatus + ) + ) + if dafny_input.PointInTimeRecoveryDescription.is_Some: + output["PointInTimeRecoveryDescription"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_PointInTimeRecoveryDescription( + dafny_input.PointInTimeRecoveryDescription.value + ) + ) + + return output + + +def com_amazonaws_dynamodb_ContinuousBackupsStatus(dafny_input): + # Convert ContinuousBackupsStatus + if isinstance(dafny_input, ContinuousBackupsStatus_ENABLED): + return "ENABLED" + + elif isinstance(dafny_input, ContinuousBackupsStatus_DISABLED): + return "DISABLED" + + else: + raise ValueError("No recognized enum value in enum type: " + dafny_input) + + +def com_amazonaws_dynamodb_PointInTimeRecoveryDescription(dafny_input): + output = {} + if dafny_input.PointInTimeRecoveryStatus.is_Some: + output["PointInTimeRecoveryStatus"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_PointInTimeRecoveryStatus( + dafny_input.PointInTimeRecoveryStatus.value + ) + ) + + if dafny_input.EarliestRestorableDateTime.is_Some: + output["EarliestRestorableDateTime"] = datetime.fromisoformat( + dafny_input.EarliestRestorableDateTime.value.VerbatimString(False) + ) + + if dafny_input.LatestRestorableDateTime.is_Some: + output["LatestRestorableDateTime"] = datetime.fromisoformat( + dafny_input.LatestRestorableDateTime.value.VerbatimString(False) + ) + + return output + + +def com_amazonaws_dynamodb_PointInTimeRecoveryStatus(dafny_input): + # Convert PointInTimeRecoveryStatus + if isinstance(dafny_input, PointInTimeRecoveryStatus_ENABLED): + return "ENABLED" + + elif isinstance(dafny_input, PointInTimeRecoveryStatus_DISABLED): + return "DISABLED" + + else: + raise ValueError("No recognized enum value in enum type: " + dafny_input) + + +def com_amazonaws_dynamodb_DescribeContinuousBackupsOutput(dafny_input): + output = {} + if dafny_input.ContinuousBackupsDescription.is_Some: + output["ContinuousBackupsDescription"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ContinuousBackupsDescription( + dafny_input.ContinuousBackupsDescription.value + ) + ) + + return output + + +def com_amazonaws_dynamodb_DescribeContributorInsightsInput(dafny_input): + output = {} + output["TableName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.TableName + ).decode("utf-16-be") + if dafny_input.IndexName.is_Some: + output["IndexName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.IndexName.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_dynamodb_ContributorInsightsStatus(dafny_input): + # Convert ContributorInsightsStatus + if isinstance(dafny_input, ContributorInsightsStatus_ENABLING): + return "ENABLING" + + elif isinstance(dafny_input, ContributorInsightsStatus_ENABLED): + return "ENABLED" + + elif isinstance(dafny_input, ContributorInsightsStatus_DISABLING): + return "DISABLING" + + elif isinstance(dafny_input, ContributorInsightsStatus_DISABLED): + return "DISABLED" + + elif isinstance(dafny_input, ContributorInsightsStatus_FAILED): + return "FAILED" + + else: + raise ValueError("No recognized enum value in enum type: " + dafny_input) + + +def com_amazonaws_dynamodb_FailureException(dafny_input): + output = {} + if dafny_input.ExceptionName.is_Some: + output["ExceptionName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.ExceptionName.value + ).decode("utf-16-be") + + if dafny_input.ExceptionDescription.is_Some: + output["ExceptionDescription"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.ExceptionDescription.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_dynamodb_DescribeContributorInsightsOutput(dafny_input): + output = {} + if dafny_input.TableName.is_Some: + output["TableName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.TableName.value + ).decode("utf-16-be") + + if dafny_input.IndexName.is_Some: + output["IndexName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.IndexName.value + ).decode("utf-16-be") + + if dafny_input.ContributorInsightsRuleList.is_Some: + output["ContributorInsightsRuleList"] = [ + b"".join(ord(c).to_bytes(2, "big") for c in list_element).decode( + "utf-16-be" + ) + for list_element in dafny_input.ContributorInsightsRuleList.value + ] + + if dafny_input.ContributorInsightsStatus.is_Some: + output["ContributorInsightsStatus"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ContributorInsightsStatus( + dafny_input.ContributorInsightsStatus.value + ) + ) + + if dafny_input.LastUpdateDateTime.is_Some: + output["LastUpdateDateTime"] = datetime.fromisoformat( + dafny_input.LastUpdateDateTime.value.VerbatimString(False) + ) + + if dafny_input.FailureException.is_Some: + output["FailureException"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_FailureException( + dafny_input.FailureException.value + ) + ) + + return output + + +def com_amazonaws_dynamodb_DescribeEndpointsRequest(dafny_input): + output = {} + return output + + +def com_amazonaws_dynamodb_Endpoint(dafny_input): + output = {} + output["Address"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.Address + ).decode("utf-16-be") + output["CachePeriodInMinutes"] = dafny_input.CachePeriodInMinutes + return output + + +def com_amazonaws_dynamodb_DescribeEndpointsResponse(dafny_input): + output = {} + output["Endpoints"] = [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_Endpoint( + list_element + ) + for list_element in dafny_input.Endpoints + ] + return output + + +def com_amazonaws_dynamodb_DescribeExportInput(dafny_input): + output = {} + output["ExportArn"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.ExportArn + ).decode("utf-16-be") + return output + + +def com_amazonaws_dynamodb_ExportDescription(dafny_input): + output = {} + if dafny_input.ExportArn.is_Some: + output["ExportArn"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.ExportArn.value + ).decode("utf-16-be") + + if dafny_input.ExportStatus.is_Some: + output["ExportStatus"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ExportStatus( + dafny_input.ExportStatus.value + ) + ) + + if dafny_input.StartTime.is_Some: + output["StartTime"] = datetime.fromisoformat( + dafny_input.StartTime.value.VerbatimString(False) + ) + + if dafny_input.EndTime.is_Some: + output["EndTime"] = datetime.fromisoformat( + dafny_input.EndTime.value.VerbatimString(False) + ) + + if dafny_input.ExportManifest.is_Some: + output["ExportManifest"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.ExportManifest.value + ).decode("utf-16-be") + + if dafny_input.TableArn.is_Some: + output["TableArn"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.TableArn.value + ).decode("utf-16-be") + + if dafny_input.TableId.is_Some: + output["TableId"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.TableId.value + ).decode("utf-16-be") + + if dafny_input.ExportTime.is_Some: + output["ExportTime"] = datetime.fromisoformat( + dafny_input.ExportTime.value.VerbatimString(False) + ) + + if dafny_input.ClientToken.is_Some: + output["ClientToken"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.ClientToken.value + ).decode("utf-16-be") + + if dafny_input.S3Bucket.is_Some: + output["S3Bucket"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.S3Bucket.value + ).decode("utf-16-be") + + if dafny_input.S3BucketOwner.is_Some: + output["S3BucketOwner"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.S3BucketOwner.value + ).decode("utf-16-be") + + if dafny_input.S3Prefix.is_Some: + output["S3Prefix"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.S3Prefix.value + ).decode("utf-16-be") + + if dafny_input.S3SseAlgorithm.is_Some: + output["S3SseAlgorithm"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_S3SseAlgorithm( + dafny_input.S3SseAlgorithm.value + ) + ) + + if dafny_input.S3SseKmsKeyId.is_Some: + output["S3SseKmsKeyId"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.S3SseKmsKeyId.value + ).decode("utf-16-be") + + if dafny_input.FailureCode.is_Some: + output["FailureCode"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.FailureCode.value + ).decode("utf-16-be") + + if dafny_input.FailureMessage.is_Some: + output["FailureMessage"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.FailureMessage.value + ).decode("utf-16-be") + + if dafny_input.ExportFormat.is_Some: + output["ExportFormat"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ExportFormat( + dafny_input.ExportFormat.value + ) + ) + + if dafny_input.BilledSizeBytes.is_Some: + output["BilledSizeBytes"] = dafny_input.BilledSizeBytes.value + + if dafny_input.ItemCount.is_Some: + output["ItemCount"] = dafny_input.ItemCount.value + + return output + + +def com_amazonaws_dynamodb_ExportStatus(dafny_input): + # Convert ExportStatus + if isinstance(dafny_input, ExportStatus_IN__PROGRESS): + return "IN_PROGRESS" + + elif isinstance(dafny_input, ExportStatus_COMPLETED): + return "COMPLETED" + + elif isinstance(dafny_input, ExportStatus_FAILED): + return "FAILED" + + else: + raise ValueError("No recognized enum value in enum type: " + dafny_input) + + +def com_amazonaws_dynamodb_S3SseAlgorithm(dafny_input): + # Convert S3SseAlgorithm + if isinstance(dafny_input, S3SseAlgorithm_AES256): + return "AES256" + + elif isinstance(dafny_input, S3SseAlgorithm_KMS): + return "KMS" + + else: + raise ValueError("No recognized enum value in enum type: " + dafny_input) + + +def com_amazonaws_dynamodb_ExportFormat(dafny_input): + # Convert ExportFormat + if isinstance(dafny_input, ExportFormat_DYNAMODB__JSON): + return "DYNAMODB_JSON" + + elif isinstance(dafny_input, ExportFormat_ION): + return "ION" + + else: + raise ValueError("No recognized enum value in enum type: " + dafny_input) + + +def com_amazonaws_dynamodb_DescribeExportOutput(dafny_input): + output = {} + if dafny_input.ExportDescription.is_Some: + output["ExportDescription"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ExportDescription( + dafny_input.ExportDescription.value + ) + ) + + return output + + +def com_amazonaws_dynamodb_DescribeGlobalTableInput(dafny_input): + output = {} + output["GlobalTableName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.GlobalTableName + ).decode("utf-16-be") + return output + + +def com_amazonaws_dynamodb_DescribeGlobalTableOutput(dafny_input): + output = {} + if dafny_input.GlobalTableDescription.is_Some: + output["GlobalTableDescription"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_GlobalTableDescription( + dafny_input.GlobalTableDescription.value + ) + ) + + return output + + +def com_amazonaws_dynamodb_DescribeGlobalTableSettingsInput(dafny_input): + output = {} + output["GlobalTableName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.GlobalTableName + ).decode("utf-16-be") + return output + + +def com_amazonaws_dynamodb_ReplicaSettingsDescription(dafny_input): + output = {} + output["RegionName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.RegionName + ).decode("utf-16-be") + if dafny_input.ReplicaStatus.is_Some: + output["ReplicaStatus"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ReplicaStatus( + dafny_input.ReplicaStatus.value + ) + ) + + if dafny_input.ReplicaBillingModeSummary.is_Some: + output["ReplicaBillingModeSummary"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_BillingModeSummary( + dafny_input.ReplicaBillingModeSummary.value + ) + ) + + if dafny_input.ReplicaProvisionedReadCapacityUnits.is_Some: + output["ReplicaProvisionedReadCapacityUnits"] = ( + dafny_input.ReplicaProvisionedReadCapacityUnits.value + ) + + if dafny_input.ReplicaProvisionedReadCapacityAutoScalingSettings.is_Some: + output["ReplicaProvisionedReadCapacityAutoScalingSettings"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_AutoScalingSettingsDescription( + dafny_input.ReplicaProvisionedReadCapacityAutoScalingSettings.value + ) + ) + + if dafny_input.ReplicaProvisionedWriteCapacityUnits.is_Some: + output["ReplicaProvisionedWriteCapacityUnits"] = ( + dafny_input.ReplicaProvisionedWriteCapacityUnits.value + ) + + if dafny_input.ReplicaProvisionedWriteCapacityAutoScalingSettings.is_Some: + output["ReplicaProvisionedWriteCapacityAutoScalingSettings"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_AutoScalingSettingsDescription( + dafny_input.ReplicaProvisionedWriteCapacityAutoScalingSettings.value + ) + ) + + if dafny_input.ReplicaGlobalSecondaryIndexSettings.is_Some: + output["ReplicaGlobalSecondaryIndexSettings"] = [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ReplicaGlobalSecondaryIndexSettingsDescription( + list_element + ) + for list_element in dafny_input.ReplicaGlobalSecondaryIndexSettings.value + ] + + if dafny_input.ReplicaTableClassSummary.is_Some: + output["ReplicaTableClassSummary"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_TableClassSummary( + dafny_input.ReplicaTableClassSummary.value + ) + ) + + return output + + +def com_amazonaws_dynamodb_AutoScalingSettingsDescription(dafny_input): + output = {} + if dafny_input.MinimumUnits.is_Some: + output["MinimumUnits"] = dafny_input.MinimumUnits.value + + if dafny_input.MaximumUnits.is_Some: + output["MaximumUnits"] = dafny_input.MaximumUnits.value + + if dafny_input.AutoScalingDisabled.is_Some: + output["AutoScalingDisabled"] = dafny_input.AutoScalingDisabled.value + + if dafny_input.AutoScalingRoleArn.is_Some: + output["AutoScalingRoleArn"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.AutoScalingRoleArn.value + ).decode("utf-16-be") + + if dafny_input.ScalingPolicies.is_Some: + output["ScalingPolicies"] = [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_AutoScalingPolicyDescription( + list_element + ) + for list_element in dafny_input.ScalingPolicies.value + ] + + return output + + +def com_amazonaws_dynamodb_ReplicaGlobalSecondaryIndexSettingsDescription(dafny_input): + output = {} + output["IndexName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.IndexName + ).decode("utf-16-be") + if dafny_input.IndexStatus.is_Some: + output["IndexStatus"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_IndexStatus( + dafny_input.IndexStatus.value + ) + ) + + if dafny_input.ProvisionedReadCapacityUnits.is_Some: + output["ProvisionedReadCapacityUnits"] = ( + dafny_input.ProvisionedReadCapacityUnits.value + ) + + if dafny_input.ProvisionedReadCapacityAutoScalingSettings.is_Some: + output["ProvisionedReadCapacityAutoScalingSettings"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_AutoScalingSettingsDescription( + dafny_input.ProvisionedReadCapacityAutoScalingSettings.value + ) + ) + + if dafny_input.ProvisionedWriteCapacityUnits.is_Some: + output["ProvisionedWriteCapacityUnits"] = ( + dafny_input.ProvisionedWriteCapacityUnits.value + ) + + if dafny_input.ProvisionedWriteCapacityAutoScalingSettings.is_Some: + output["ProvisionedWriteCapacityAutoScalingSettings"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_AutoScalingSettingsDescription( + dafny_input.ProvisionedWriteCapacityAutoScalingSettings.value + ) + ) + + return output + + +def com_amazonaws_dynamodb_AutoScalingPolicyDescription(dafny_input): + output = {} + if dafny_input.PolicyName.is_Some: + output["PolicyName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.PolicyName.value + ).decode("utf-16-be") + + if dafny_input.TargetTrackingScalingPolicyConfiguration.is_Some: + output["TargetTrackingScalingPolicyConfiguration"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_AutoScalingTargetTrackingScalingPolicyConfigurationDescription( + dafny_input.TargetTrackingScalingPolicyConfiguration.value + ) + ) + + return output + + +def com_amazonaws_dynamodb_AutoScalingTargetTrackingScalingPolicyConfigurationDescription( + dafny_input, +): + output = {} + if dafny_input.DisableScaleIn.is_Some: + output["DisableScaleIn"] = dafny_input.DisableScaleIn.value + + if dafny_input.ScaleInCooldown.is_Some: + output["ScaleInCooldown"] = dafny_input.ScaleInCooldown.value + + if dafny_input.ScaleOutCooldown.is_Some: + output["ScaleOutCooldown"] = dafny_input.ScaleOutCooldown.value + + output["TargetValue"] = dafny_input.TargetValue + return output + + +def com_amazonaws_dynamodb_DescribeGlobalTableSettingsOutput(dafny_input): + output = {} + if dafny_input.GlobalTableName.is_Some: + output["GlobalTableName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.GlobalTableName.value + ).decode("utf-16-be") + + if dafny_input.ReplicaSettings.is_Some: + output["ReplicaSettings"] = [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ReplicaSettingsDescription( + list_element + ) + for list_element in dafny_input.ReplicaSettings.value + ] + + return output + + +def com_amazonaws_dynamodb_DescribeImportInput(dafny_input): + output = {} + output["ImportArn"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.ImportArn + ).decode("utf-16-be") + return output + + +def com_amazonaws_dynamodb_ImportTableDescription(dafny_input): + output = {} + if dafny_input.ImportArn.is_Some: + output["ImportArn"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.ImportArn.value + ).decode("utf-16-be") + + if dafny_input.ImportStatus.is_Some: + output["ImportStatus"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ImportStatus( + dafny_input.ImportStatus.value + ) + ) + + if dafny_input.TableArn.is_Some: + output["TableArn"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.TableArn.value + ).decode("utf-16-be") + + if dafny_input.TableId.is_Some: + output["TableId"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.TableId.value + ).decode("utf-16-be") + + if dafny_input.ClientToken.is_Some: + output["ClientToken"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.ClientToken.value + ).decode("utf-16-be") + + if dafny_input.S3BucketSource.is_Some: + output["S3BucketSource"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_S3BucketSource( + dafny_input.S3BucketSource.value + ) + ) + + if dafny_input.ErrorCount.is_Some: + output["ErrorCount"] = dafny_input.ErrorCount.value + + if dafny_input.CloudWatchLogGroupArn.is_Some: + output["CloudWatchLogGroupArn"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.CloudWatchLogGroupArn.value + ).decode("utf-16-be") + + if dafny_input.InputFormat.is_Some: + output["InputFormat"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_InputFormat( + dafny_input.InputFormat.value + ) + ) + + if dafny_input.InputFormatOptions.is_Some: + output["InputFormatOptions"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_InputFormatOptions( + dafny_input.InputFormatOptions.value + ) + ) + + if dafny_input.InputCompressionType.is_Some: + output["InputCompressionType"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_InputCompressionType( + dafny_input.InputCompressionType.value + ) + ) + + if dafny_input.TableCreationParameters.is_Some: + output["TableCreationParameters"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_TableCreationParameters( + dafny_input.TableCreationParameters.value + ) + ) + + if dafny_input.StartTime.is_Some: + output["StartTime"] = datetime.fromisoformat( + dafny_input.StartTime.value.VerbatimString(False) + ) + + if dafny_input.EndTime.is_Some: + output["EndTime"] = datetime.fromisoformat( + dafny_input.EndTime.value.VerbatimString(False) + ) + + if dafny_input.ProcessedSizeBytes.is_Some: + output["ProcessedSizeBytes"] = dafny_input.ProcessedSizeBytes.value + + if dafny_input.ProcessedItemCount.is_Some: + output["ProcessedItemCount"] = dafny_input.ProcessedItemCount.value + + if dafny_input.ImportedItemCount.is_Some: + output["ImportedItemCount"] = dafny_input.ImportedItemCount.value + + if dafny_input.FailureCode.is_Some: + output["FailureCode"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.FailureCode.value + ).decode("utf-16-be") + + if dafny_input.FailureMessage.is_Some: + output["FailureMessage"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.FailureMessage.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_dynamodb_ImportStatus(dafny_input): + # Convert ImportStatus + if isinstance(dafny_input, ImportStatus_IN__PROGRESS): + return "IN_PROGRESS" + + elif isinstance(dafny_input, ImportStatus_COMPLETED): + return "COMPLETED" + + elif isinstance(dafny_input, ImportStatus_CANCELLING): + return "CANCELLING" + + elif isinstance(dafny_input, ImportStatus_CANCELLED): + return "CANCELLED" + + elif isinstance(dafny_input, ImportStatus_FAILED): + return "FAILED" + + else: + raise ValueError("No recognized enum value in enum type: " + dafny_input) + + +def com_amazonaws_dynamodb_S3BucketSource(dafny_input): + output = {} + if dafny_input.S3BucketOwner.is_Some: + output["S3BucketOwner"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.S3BucketOwner.value + ).decode("utf-16-be") + + output["S3Bucket"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.S3Bucket + ).decode("utf-16-be") + if dafny_input.S3KeyPrefix.is_Some: + output["S3KeyPrefix"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.S3KeyPrefix.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_dynamodb_InputFormat(dafny_input): + # Convert InputFormat + if isinstance(dafny_input, InputFormat_DYNAMODB__JSON): + return "DYNAMODB_JSON" + + elif isinstance(dafny_input, InputFormat_ION): + return "ION" + + elif isinstance(dafny_input, InputFormat_CSV): + return "CSV" + + else: + raise ValueError("No recognized enum value in enum type: " + dafny_input) + + +def com_amazonaws_dynamodb_InputFormatOptions(dafny_input): + output = {} + if dafny_input.Csv.is_Some: + output["Csv"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_CsvOptions( + dafny_input.Csv.value + ) + ) + + return output + + +def com_amazonaws_dynamodb_InputCompressionType(dafny_input): + # Convert InputCompressionType + if isinstance(dafny_input, InputCompressionType_GZIP): + return "GZIP" + + elif isinstance(dafny_input, InputCompressionType_ZSTD): + return "ZSTD" + + elif isinstance(dafny_input, InputCompressionType_NONE): + return "NONE" + + else: + raise ValueError("No recognized enum value in enum type: " + dafny_input) + + +def com_amazonaws_dynamodb_TableCreationParameters(dafny_input): + output = {} + output["TableName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.TableName + ).decode("utf-16-be") + output["AttributeDefinitions"] = [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_AttributeDefinition( + list_element + ) + for list_element in dafny_input.AttributeDefinitions + ] + output["KeySchema"] = [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_KeySchemaElement( + list_element + ) + for list_element in dafny_input.KeySchema + ] + if dafny_input.BillingMode.is_Some: + output["BillingMode"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_BillingMode( + dafny_input.BillingMode.value + ) + ) + + if dafny_input.ProvisionedThroughput.is_Some: + output["ProvisionedThroughput"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ProvisionedThroughput( + dafny_input.ProvisionedThroughput.value + ) + ) + + if dafny_input.SSESpecification.is_Some: + output["SSESpecification"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_SSESpecification( + dafny_input.SSESpecification.value + ) + ) + + if dafny_input.GlobalSecondaryIndexes.is_Some: + output["GlobalSecondaryIndexes"] = [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_GlobalSecondaryIndex( + list_element + ) + for list_element in dafny_input.GlobalSecondaryIndexes.value + ] + + return output + + +def com_amazonaws_dynamodb_CsvOptions(dafny_input): + output = {} + if dafny_input.Delimiter.is_Some: + output["Delimiter"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.Delimiter.value + ).decode("utf-16-be") + + if dafny_input.HeaderList.is_Some: + output["HeaderList"] = [ + b"".join(ord(c).to_bytes(2, "big") for c in list_element).decode( + "utf-16-be" + ) + for list_element in dafny_input.HeaderList.value + ] + + return output + + +def com_amazonaws_dynamodb_DescribeImportOutput(dafny_input): + output = {} + output["ImportTableDescription"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ImportTableDescription( + dafny_input.ImportTableDescription + ) + ) + return output + + +def com_amazonaws_dynamodb_DescribeKinesisStreamingDestinationInput(dafny_input): + output = {} + output["TableName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.TableName + ).decode("utf-16-be") + return output + + +def com_amazonaws_dynamodb_KinesisDataStreamDestination(dafny_input): + output = {} + if dafny_input.StreamArn.is_Some: + output["StreamArn"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.StreamArn.value + ).decode("utf-16-be") + + if dafny_input.DestinationStatus.is_Some: + output["DestinationStatus"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_DestinationStatus( + dafny_input.DestinationStatus.value + ) + ) + + if dafny_input.DestinationStatusDescription.is_Some: + output["DestinationStatusDescription"] = b"".join( + ord(c).to_bytes(2, "big") + for c in dafny_input.DestinationStatusDescription.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_dynamodb_DestinationStatus(dafny_input): + # Convert DestinationStatus + if isinstance(dafny_input, DestinationStatus_ENABLING): + return "ENABLING" + + elif isinstance(dafny_input, DestinationStatus_ACTIVE): + return "ACTIVE" + + elif isinstance(dafny_input, DestinationStatus_DISABLING): + return "DISABLING" + + elif isinstance(dafny_input, DestinationStatus_DISABLED): + return "DISABLED" + + elif isinstance(dafny_input, DestinationStatus_ENABLE__FAILED): + return "ENABLE_FAILED" + + else: + raise ValueError("No recognized enum value in enum type: " + dafny_input) + + +def com_amazonaws_dynamodb_DescribeKinesisStreamingDestinationOutput(dafny_input): + output = {} + if dafny_input.TableName.is_Some: + output["TableName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.TableName.value + ).decode("utf-16-be") + + if dafny_input.KinesisDataStreamDestinations.is_Some: + output["KinesisDataStreamDestinations"] = [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_KinesisDataStreamDestination( + list_element + ) + for list_element in dafny_input.KinesisDataStreamDestinations.value + ] + + return output + + +def com_amazonaws_dynamodb_DescribeLimitsInput(dafny_input): + output = {} + return output + + +def com_amazonaws_dynamodb_DescribeLimitsOutput(dafny_input): + output = {} + if dafny_input.AccountMaxReadCapacityUnits.is_Some: + output["AccountMaxReadCapacityUnits"] = ( + dafny_input.AccountMaxReadCapacityUnits.value + ) + + if dafny_input.AccountMaxWriteCapacityUnits.is_Some: + output["AccountMaxWriteCapacityUnits"] = ( + dafny_input.AccountMaxWriteCapacityUnits.value + ) + + if dafny_input.TableMaxReadCapacityUnits.is_Some: + output["TableMaxReadCapacityUnits"] = ( + dafny_input.TableMaxReadCapacityUnits.value + ) + + if dafny_input.TableMaxWriteCapacityUnits.is_Some: + output["TableMaxWriteCapacityUnits"] = ( + dafny_input.TableMaxWriteCapacityUnits.value + ) + + return output + + +def com_amazonaws_dynamodb_DescribeTableInput(dafny_input): + output = {} + output["TableName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.TableName + ).decode("utf-16-be") + return output + + +def com_amazonaws_dynamodb_DescribeTableOutput(dafny_input): + output = {} + if dafny_input.Table.is_Some: + output["Table"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_TableDescription( + dafny_input.Table.value + ) + ) + + return output + + +def com_amazonaws_dynamodb_DescribeTableReplicaAutoScalingInput(dafny_input): + output = {} + output["TableName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.TableName + ).decode("utf-16-be") + return output + + +def com_amazonaws_dynamodb_TableAutoScalingDescription(dafny_input): + output = {} + if dafny_input.TableName.is_Some: + output["TableName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.TableName.value + ).decode("utf-16-be") + + if dafny_input.TableStatus.is_Some: + output["TableStatus"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_TableStatus( + dafny_input.TableStatus.value + ) + ) + + if dafny_input.Replicas.is_Some: + output["Replicas"] = [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ReplicaAutoScalingDescription( + list_element + ) + for list_element in dafny_input.Replicas.value + ] + + return output + + +def com_amazonaws_dynamodb_ReplicaAutoScalingDescription(dafny_input): + output = {} + if dafny_input.RegionName.is_Some: + output["RegionName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.RegionName.value + ).decode("utf-16-be") + + if dafny_input.GlobalSecondaryIndexes.is_Some: + output["GlobalSecondaryIndexes"] = [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ReplicaGlobalSecondaryIndexAutoScalingDescription( + list_element + ) + for list_element in dafny_input.GlobalSecondaryIndexes.value + ] + + if dafny_input.ReplicaProvisionedReadCapacityAutoScalingSettings.is_Some: + output["ReplicaProvisionedReadCapacityAutoScalingSettings"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_AutoScalingSettingsDescription( + dafny_input.ReplicaProvisionedReadCapacityAutoScalingSettings.value + ) + ) + + if dafny_input.ReplicaProvisionedWriteCapacityAutoScalingSettings.is_Some: + output["ReplicaProvisionedWriteCapacityAutoScalingSettings"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_AutoScalingSettingsDescription( + dafny_input.ReplicaProvisionedWriteCapacityAutoScalingSettings.value + ) + ) + + if dafny_input.ReplicaStatus.is_Some: + output["ReplicaStatus"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ReplicaStatus( + dafny_input.ReplicaStatus.value + ) + ) + + return output + + +def com_amazonaws_dynamodb_ReplicaGlobalSecondaryIndexAutoScalingDescription( + dafny_input, +): + output = {} + if dafny_input.IndexName.is_Some: + output["IndexName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.IndexName.value + ).decode("utf-16-be") + + if dafny_input.IndexStatus.is_Some: + output["IndexStatus"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_IndexStatus( + dafny_input.IndexStatus.value + ) + ) + + if dafny_input.ProvisionedReadCapacityAutoScalingSettings.is_Some: + output["ProvisionedReadCapacityAutoScalingSettings"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_AutoScalingSettingsDescription( + dafny_input.ProvisionedReadCapacityAutoScalingSettings.value + ) + ) + + if dafny_input.ProvisionedWriteCapacityAutoScalingSettings.is_Some: + output["ProvisionedWriteCapacityAutoScalingSettings"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_AutoScalingSettingsDescription( + dafny_input.ProvisionedWriteCapacityAutoScalingSettings.value + ) + ) + + return output + + +def com_amazonaws_dynamodb_DescribeTableReplicaAutoScalingOutput(dafny_input): + output = {} + if dafny_input.TableAutoScalingDescription.is_Some: + output["TableAutoScalingDescription"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_TableAutoScalingDescription( + dafny_input.TableAutoScalingDescription.value + ) + ) + + return output + + +def com_amazonaws_dynamodb_DescribeTimeToLiveInput(dafny_input): + output = {} + output["TableName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.TableName + ).decode("utf-16-be") + return output + + +def com_amazonaws_dynamodb_DescribeTimeToLiveOutput(dafny_input): + output = {} + if dafny_input.TimeToLiveDescription.is_Some: + output["TimeToLiveDescription"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_TimeToLiveDescription( + dafny_input.TimeToLiveDescription.value + ) + ) + + return output + + +def com_amazonaws_dynamodb_DisableKinesisStreamingDestinationInput(dafny_input): + output = {} + output["TableName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.TableName + ).decode("utf-16-be") + output["StreamArn"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.StreamArn + ).decode("utf-16-be") + return output + + +def com_amazonaws_dynamodb_DisableKinesisStreamingDestinationOutput(dafny_input): + output = {} + if dafny_input.TableName.is_Some: + output["TableName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.TableName.value + ).decode("utf-16-be") + + if dafny_input.StreamArn.is_Some: + output["StreamArn"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.StreamArn.value + ).decode("utf-16-be") + + if dafny_input.DestinationStatus.is_Some: + output["DestinationStatus"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_DestinationStatus( + dafny_input.DestinationStatus.value + ) + ) + + return output + + +def com_amazonaws_dynamodb_EnableKinesisStreamingDestinationInput(dafny_input): + output = {} + output["TableName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.TableName + ).decode("utf-16-be") + output["StreamArn"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.StreamArn + ).decode("utf-16-be") + return output + + +def com_amazonaws_dynamodb_EnableKinesisStreamingDestinationOutput(dafny_input): + output = {} + if dafny_input.TableName.is_Some: + output["TableName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.TableName.value + ).decode("utf-16-be") + + if dafny_input.StreamArn.is_Some: + output["StreamArn"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.StreamArn.value + ).decode("utf-16-be") + + if dafny_input.DestinationStatus.is_Some: + output["DestinationStatus"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_DestinationStatus( + dafny_input.DestinationStatus.value + ) + ) + + return output + + +def com_amazonaws_dynamodb_ExecuteStatementInput(dafny_input): + output = {} + output["Statement"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.Statement + ).decode("utf-16-be") + if dafny_input.Parameters.is_Some: + output["Parameters"] = [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_AttributeValue( + list_element + ) + for list_element in dafny_input.Parameters.value + ] + + if dafny_input.ConsistentRead.is_Some: + output["ConsistentRead"] = dafny_input.ConsistentRead.value + + if dafny_input.NextToken.is_Some: + output["NextToken"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.NextToken.value + ).decode("utf-16-be") + + if dafny_input.ReturnConsumedCapacity.is_Some: + output["ReturnConsumedCapacity"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ReturnConsumedCapacity( + dafny_input.ReturnConsumedCapacity.value + ) + ) + + if dafny_input.Limit.is_Some: + output["Limit"] = dafny_input.Limit.value + + return output + + +def com_amazonaws_dynamodb_ExecuteStatementOutput(dafny_input): + output = {} + if dafny_input.Items.is_Some: + output["Items"] = [ + { + b"".join(ord(c).to_bytes(2, "big") for c in key).decode( + "utf-16-be" + ): aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_AttributeValue( + value + ) + for (key, value) in list_element.items + } + for list_element in dafny_input.Items.value + ] + + if dafny_input.NextToken.is_Some: + output["NextToken"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.NextToken.value + ).decode("utf-16-be") + + if dafny_input.ConsumedCapacity.is_Some: + output["ConsumedCapacity"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ConsumedCapacity( + dafny_input.ConsumedCapacity.value + ) + ) + + if dafny_input.LastEvaluatedKey.is_Some: + output["LastEvaluatedKey"] = { + b"".join(ord(c).to_bytes(2, "big") for c in key).decode( + "utf-16-be" + ): aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_AttributeValue( + value + ) + for (key, value) in dafny_input.LastEvaluatedKey.value.items + } + + return output + + +def com_amazonaws_dynamodb_ParameterizedStatement(dafny_input): + output = {} + output["Statement"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.Statement + ).decode("utf-16-be") + if dafny_input.Parameters.is_Some: + output["Parameters"] = [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_AttributeValue( + list_element + ) + for list_element in dafny_input.Parameters.value + ] + + return output + + +def com_amazonaws_dynamodb_ExecuteTransactionInput(dafny_input): + output = {} + output["TransactStatements"] = [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ParameterizedStatement( + list_element + ) + for list_element in dafny_input.TransactStatements + ] + if dafny_input.ClientRequestToken.is_Some: + output["ClientRequestToken"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.ClientRequestToken.value + ).decode("utf-16-be") + + if dafny_input.ReturnConsumedCapacity.is_Some: + output["ReturnConsumedCapacity"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ReturnConsumedCapacity( + dafny_input.ReturnConsumedCapacity.value + ) + ) + + return output + + +def com_amazonaws_dynamodb_ItemResponse(dafny_input): + output = {} + if dafny_input.Item.is_Some: + output["Item"] = { + b"".join(ord(c).to_bytes(2, "big") for c in key).decode( + "utf-16-be" + ): aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_AttributeValue( + value + ) + for (key, value) in dafny_input.Item.value.items + } + + return output + + +def com_amazonaws_dynamodb_ExecuteTransactionOutput(dafny_input): + output = {} + if dafny_input.Responses.is_Some: + output["Responses"] = [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ItemResponse( + list_element + ) + for list_element in dafny_input.Responses.value + ] + + if dafny_input.ConsumedCapacity.is_Some: + output["ConsumedCapacity"] = [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ConsumedCapacity( + list_element + ) + for list_element in dafny_input.ConsumedCapacity.value + ] + + return output + + +def com_amazonaws_dynamodb_ExportTableToPointInTimeInput(dafny_input): + output = {} + output["TableArn"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.TableArn + ).decode("utf-16-be") + if dafny_input.ExportTime.is_Some: + output["ExportTime"] = datetime.fromisoformat( + dafny_input.ExportTime.value.VerbatimString(False) + ) + + if dafny_input.ClientToken.is_Some: + output["ClientToken"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.ClientToken.value + ).decode("utf-16-be") + + output["S3Bucket"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.S3Bucket + ).decode("utf-16-be") + if dafny_input.S3BucketOwner.is_Some: + output["S3BucketOwner"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.S3BucketOwner.value + ).decode("utf-16-be") + + if dafny_input.S3Prefix.is_Some: + output["S3Prefix"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.S3Prefix.value + ).decode("utf-16-be") + + if dafny_input.S3SseAlgorithm.is_Some: + output["S3SseAlgorithm"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_S3SseAlgorithm( + dafny_input.S3SseAlgorithm.value + ) + ) + + if dafny_input.S3SseKmsKeyId.is_Some: + output["S3SseKmsKeyId"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.S3SseKmsKeyId.value + ).decode("utf-16-be") + + if dafny_input.ExportFormat.is_Some: + output["ExportFormat"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ExportFormat( + dafny_input.ExportFormat.value + ) + ) + + return output + + +def com_amazonaws_dynamodb_ExportTableToPointInTimeOutput(dafny_input): + output = {} + if dafny_input.ExportDescription.is_Some: + output["ExportDescription"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ExportDescription( + dafny_input.ExportDescription.value + ) + ) + + return output + + +def com_amazonaws_dynamodb_GetItemInput(dafny_input): + output = {} + output["TableName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.TableName + ).decode("utf-16-be") + output["Key"] = { + b"".join(ord(c).to_bytes(2, "big") for c in key).decode( + "utf-16-be" + ): aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_AttributeValue( + value + ) + for (key, value) in dafny_input.Key.items + } + if dafny_input.AttributesToGet.is_Some: + output["AttributesToGet"] = [ + b"".join(ord(c).to_bytes(2, "big") for c in list_element).decode( + "utf-16-be" + ) + for list_element in dafny_input.AttributesToGet.value + ] + + if dafny_input.ConsistentRead.is_Some: + output["ConsistentRead"] = dafny_input.ConsistentRead.value + + if dafny_input.ReturnConsumedCapacity.is_Some: + output["ReturnConsumedCapacity"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ReturnConsumedCapacity( + dafny_input.ReturnConsumedCapacity.value + ) + ) + + if dafny_input.ProjectionExpression.is_Some: + output["ProjectionExpression"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.ProjectionExpression.value + ).decode("utf-16-be") + + if dafny_input.ExpressionAttributeNames.is_Some: + output["ExpressionAttributeNames"] = { + 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.ExpressionAttributeNames.value.items + } + + return output + + +def com_amazonaws_dynamodb_GetItemOutput(dafny_input): + output = {} + if dafny_input.Item.is_Some: + output["Item"] = { + b"".join(ord(c).to_bytes(2, "big") for c in key).decode( + "utf-16-be" + ): aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_AttributeValue( + value + ) + for (key, value) in dafny_input.Item.value.items + } + + if dafny_input.ConsumedCapacity.is_Some: + output["ConsumedCapacity"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ConsumedCapacity( + dafny_input.ConsumedCapacity.value + ) + ) + + return output + + +def com_amazonaws_dynamodb_ImportTableInput(dafny_input): + output = {} + if dafny_input.ClientToken.is_Some: + output["ClientToken"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.ClientToken.value + ).decode("utf-16-be") + + output["S3BucketSource"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_S3BucketSource( + dafny_input.S3BucketSource + ) + ) + output["InputFormat"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_InputFormat( + dafny_input.InputFormat + ) + ) + if dafny_input.InputFormatOptions.is_Some: + output["InputFormatOptions"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_InputFormatOptions( + dafny_input.InputFormatOptions.value + ) + ) + + if dafny_input.InputCompressionType.is_Some: + output["InputCompressionType"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_InputCompressionType( + dafny_input.InputCompressionType.value + ) + ) + + output["TableCreationParameters"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_TableCreationParameters( + dafny_input.TableCreationParameters + ) + ) + return output + + +def com_amazonaws_dynamodb_ImportTableOutput(dafny_input): + output = {} + output["ImportTableDescription"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ImportTableDescription( + dafny_input.ImportTableDescription + ) + ) + return output + + +def com_amazonaws_dynamodb_BackupTypeFilter(dafny_input): + # Convert BackupTypeFilter + if isinstance(dafny_input, BackupTypeFilter_USER): + return "USER" + + elif isinstance(dafny_input, BackupTypeFilter_SYSTEM): + return "SYSTEM" + + elif isinstance(dafny_input, BackupTypeFilter_AWS__BACKUP): + return "AWS_BACKUP" + + elif isinstance(dafny_input, BackupTypeFilter_ALL): + return "ALL" + + else: + raise ValueError("No recognized enum value in enum type: " + dafny_input) + + +def com_amazonaws_dynamodb_ListBackupsInput(dafny_input): + output = {} + if dafny_input.TableName.is_Some: + output["TableName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.TableName.value + ).decode("utf-16-be") + + if dafny_input.Limit.is_Some: + output["Limit"] = dafny_input.Limit.value + + if dafny_input.TimeRangeLowerBound.is_Some: + output["TimeRangeLowerBound"] = datetime.fromisoformat( + dafny_input.TimeRangeLowerBound.value.VerbatimString(False) + ) + + if dafny_input.TimeRangeUpperBound.is_Some: + output["TimeRangeUpperBound"] = datetime.fromisoformat( + dafny_input.TimeRangeUpperBound.value.VerbatimString(False) + ) + + if dafny_input.ExclusiveStartBackupArn.is_Some: + output["ExclusiveStartBackupArn"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.ExclusiveStartBackupArn.value + ).decode("utf-16-be") + + if dafny_input.BackupType.is_Some: + output["BackupType"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_BackupTypeFilter( + dafny_input.BackupType.value + ) + ) + + return output + + +def com_amazonaws_dynamodb_BackupSummary(dafny_input): + output = {} + if dafny_input.TableName.is_Some: + output["TableName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.TableName.value + ).decode("utf-16-be") + + if dafny_input.TableId.is_Some: + output["TableId"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.TableId.value + ).decode("utf-16-be") + + if dafny_input.TableArn.is_Some: + output["TableArn"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.TableArn.value + ).decode("utf-16-be") + + if dafny_input.BackupArn.is_Some: + output["BackupArn"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.BackupArn.value + ).decode("utf-16-be") + + if dafny_input.BackupName.is_Some: + output["BackupName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.BackupName.value + ).decode("utf-16-be") + + if dafny_input.BackupCreationDateTime.is_Some: + output["BackupCreationDateTime"] = datetime.fromisoformat( + dafny_input.BackupCreationDateTime.value.VerbatimString(False) + ) + + if dafny_input.BackupExpiryDateTime.is_Some: + output["BackupExpiryDateTime"] = datetime.fromisoformat( + dafny_input.BackupExpiryDateTime.value.VerbatimString(False) + ) + + if dafny_input.BackupStatus.is_Some: + output["BackupStatus"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_BackupStatus( + dafny_input.BackupStatus.value + ) + ) + + if dafny_input.BackupType.is_Some: + output["BackupType"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_BackupType( + dafny_input.BackupType.value + ) + ) + + if dafny_input.BackupSizeBytes.is_Some: + output["BackupSizeBytes"] = dafny_input.BackupSizeBytes.value + + return output + + +def com_amazonaws_dynamodb_ListBackupsOutput(dafny_input): + output = {} + if dafny_input.BackupSummaries.is_Some: + output["BackupSummaries"] = [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_BackupSummary( + list_element + ) + for list_element in dafny_input.BackupSummaries.value + ] + + if dafny_input.LastEvaluatedBackupArn.is_Some: + output["LastEvaluatedBackupArn"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.LastEvaluatedBackupArn.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_dynamodb_ListContributorInsightsInput(dafny_input): + output = {} + if dafny_input.TableName.is_Some: + output["TableName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.TableName.value + ).decode("utf-16-be") + + if dafny_input.NextToken.is_Some: + output["NextToken"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.NextToken.value + ).decode("utf-16-be") + + if dafny_input.MaxResults.is_Some: + output["MaxResults"] = dafny_input.MaxResults.value + + return output + + +def com_amazonaws_dynamodb_ContributorInsightsSummary(dafny_input): + output = {} + if dafny_input.TableName.is_Some: + output["TableName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.TableName.value + ).decode("utf-16-be") + + if dafny_input.IndexName.is_Some: + output["IndexName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.IndexName.value + ).decode("utf-16-be") + + if dafny_input.ContributorInsightsStatus.is_Some: + output["ContributorInsightsStatus"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ContributorInsightsStatus( + dafny_input.ContributorInsightsStatus.value + ) + ) + + return output + + +def com_amazonaws_dynamodb_ListContributorInsightsOutput(dafny_input): + output = {} + if dafny_input.ContributorInsightsSummaries.is_Some: + output["ContributorInsightsSummaries"] = [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ContributorInsightsSummary( + list_element + ) + for list_element in dafny_input.ContributorInsightsSummaries.value + ] + + if dafny_input.NextToken.is_Some: + output["NextToken"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.NextToken.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_dynamodb_ListExportsInput(dafny_input): + output = {} + if dafny_input.TableArn.is_Some: + output["TableArn"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.TableArn.value + ).decode("utf-16-be") + + if dafny_input.MaxResults.is_Some: + output["MaxResults"] = dafny_input.MaxResults.value + + if dafny_input.NextToken.is_Some: + output["NextToken"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.NextToken.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_dynamodb_ExportSummary(dafny_input): + output = {} + if dafny_input.ExportArn.is_Some: + output["ExportArn"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.ExportArn.value + ).decode("utf-16-be") + + if dafny_input.ExportStatus.is_Some: + output["ExportStatus"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ExportStatus( + dafny_input.ExportStatus.value + ) + ) + + return output + + +def com_amazonaws_dynamodb_ListExportsOutput(dafny_input): + output = {} + if dafny_input.ExportSummaries.is_Some: + output["ExportSummaries"] = [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ExportSummary( + list_element + ) + for list_element in dafny_input.ExportSummaries.value + ] + + if dafny_input.NextToken.is_Some: + output["NextToken"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.NextToken.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_dynamodb_ListGlobalTablesInput(dafny_input): + output = {} + if dafny_input.ExclusiveStartGlobalTableName.is_Some: + output["ExclusiveStartGlobalTableName"] = b"".join( + ord(c).to_bytes(2, "big") + for c in dafny_input.ExclusiveStartGlobalTableName.value + ).decode("utf-16-be") + + if dafny_input.Limit.is_Some: + output["Limit"] = dafny_input.Limit.value + + if dafny_input.RegionName.is_Some: + output["RegionName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.RegionName.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_dynamodb_GlobalTable(dafny_input): + output = {} + if dafny_input.GlobalTableName.is_Some: + output["GlobalTableName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.GlobalTableName.value + ).decode("utf-16-be") + + if dafny_input.ReplicationGroup.is_Some: + output["ReplicationGroup"] = [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_Replica( + list_element + ) + for list_element in dafny_input.ReplicationGroup.value + ] + + return output + + +def com_amazonaws_dynamodb_ListGlobalTablesOutput(dafny_input): + output = {} + if dafny_input.GlobalTables.is_Some: + output["GlobalTables"] = [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_GlobalTable( + list_element + ) + for list_element in dafny_input.GlobalTables.value + ] + + if dafny_input.LastEvaluatedGlobalTableName.is_Some: + output["LastEvaluatedGlobalTableName"] = b"".join( + ord(c).to_bytes(2, "big") + for c in dafny_input.LastEvaluatedGlobalTableName.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_dynamodb_ListImportsInput(dafny_input): + output = {} + if dafny_input.TableArn.is_Some: + output["TableArn"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.TableArn.value + ).decode("utf-16-be") + + if dafny_input.PageSize.is_Some: + output["PageSize"] = dafny_input.PageSize.value + + if dafny_input.NextToken.is_Some: + output["NextToken"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.NextToken.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_dynamodb_ImportSummary(dafny_input): + output = {} + if dafny_input.ImportArn.is_Some: + output["ImportArn"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.ImportArn.value + ).decode("utf-16-be") + + if dafny_input.ImportStatus.is_Some: + output["ImportStatus"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ImportStatus( + dafny_input.ImportStatus.value + ) + ) + + if dafny_input.TableArn.is_Some: + output["TableArn"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.TableArn.value + ).decode("utf-16-be") + + if dafny_input.S3BucketSource.is_Some: + output["S3BucketSource"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_S3BucketSource( + dafny_input.S3BucketSource.value + ) + ) + + if dafny_input.CloudWatchLogGroupArn.is_Some: + output["CloudWatchLogGroupArn"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.CloudWatchLogGroupArn.value + ).decode("utf-16-be") + + if dafny_input.InputFormat.is_Some: + output["InputFormat"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_InputFormat( + dafny_input.InputFormat.value + ) + ) + + if dafny_input.StartTime.is_Some: + output["StartTime"] = datetime.fromisoformat( + dafny_input.StartTime.value.VerbatimString(False) + ) + + if dafny_input.EndTime.is_Some: + output["EndTime"] = datetime.fromisoformat( + dafny_input.EndTime.value.VerbatimString(False) + ) + + return output + + +def com_amazonaws_dynamodb_ListImportsOutput(dafny_input): + output = {} + if dafny_input.ImportSummaryList.is_Some: + output["ImportSummaryList"] = [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ImportSummary( + list_element + ) + for list_element in dafny_input.ImportSummaryList.value + ] + + if dafny_input.NextToken.is_Some: + output["NextToken"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.NextToken.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_dynamodb_ListTablesInput(dafny_input): + output = {} + if dafny_input.ExclusiveStartTableName.is_Some: + output["ExclusiveStartTableName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.ExclusiveStartTableName.value + ).decode("utf-16-be") + + if dafny_input.Limit.is_Some: + output["Limit"] = dafny_input.Limit.value + + return output + + +def com_amazonaws_dynamodb_ListTablesOutput(dafny_input): + output = {} + if dafny_input.TableNames.is_Some: + output["TableNames"] = [ + b"".join(ord(c).to_bytes(2, "big") for c in list_element).decode( + "utf-16-be" + ) + for list_element in dafny_input.TableNames.value + ] + + if dafny_input.LastEvaluatedTableName.is_Some: + output["LastEvaluatedTableName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.LastEvaluatedTableName.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_dynamodb_ListTagsOfResourceInput(dafny_input): + output = {} + output["ResourceArn"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.ResourceArn + ).decode("utf-16-be") + if dafny_input.NextToken.is_Some: + output["NextToken"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.NextToken.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_dynamodb_ListTagsOfResourceOutput(dafny_input): + output = {} + if dafny_input.Tags.is_Some: + output["Tags"] = [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_Tag( + list_element + ) + for list_element in dafny_input.Tags.value + ] + + if dafny_input.NextToken.is_Some: + output["NextToken"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.NextToken.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_dynamodb_PutItemInput(dafny_input): + output = {} + output["TableName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.TableName + ).decode("utf-16-be") + output["Item"] = { + b"".join(ord(c).to_bytes(2, "big") for c in key).decode( + "utf-16-be" + ): aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_AttributeValue( + value + ) + for (key, value) in dafny_input.Item.items + } + if dafny_input.Expected.is_Some: + output["Expected"] = { + b"".join(ord(c).to_bytes(2, "big") for c in key).decode( + "utf-16-be" + ): aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ExpectedAttributeValue( + value + ) + for (key, value) in dafny_input.Expected.value.items + } + + if dafny_input.ReturnValues.is_Some: + output["ReturnValues"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ReturnValue( + dafny_input.ReturnValues.value + ) + ) + + if dafny_input.ReturnConsumedCapacity.is_Some: + output["ReturnConsumedCapacity"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ReturnConsumedCapacity( + dafny_input.ReturnConsumedCapacity.value + ) + ) + + if dafny_input.ReturnItemCollectionMetrics.is_Some: + output["ReturnItemCollectionMetrics"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ReturnItemCollectionMetrics( + dafny_input.ReturnItemCollectionMetrics.value + ) + ) + + if dafny_input.ConditionalOperator.is_Some: + output["ConditionalOperator"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ConditionalOperator( + dafny_input.ConditionalOperator.value + ) + ) + + if dafny_input.ConditionExpression.is_Some: + output["ConditionExpression"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.ConditionExpression.value + ).decode("utf-16-be") + + if dafny_input.ExpressionAttributeNames.is_Some: + output["ExpressionAttributeNames"] = { + 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.ExpressionAttributeNames.value.items + } + + if dafny_input.ExpressionAttributeValues.is_Some: + output["ExpressionAttributeValues"] = { + b"".join(ord(c).to_bytes(2, "big") for c in key).decode( + "utf-16-be" + ): aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_AttributeValue( + value + ) + for (key, value) in dafny_input.ExpressionAttributeValues.value.items + } + + return output + + +def com_amazonaws_dynamodb_PutItemOutput(dafny_input): + output = {} + if dafny_input.Attributes.is_Some: + output["Attributes"] = { + b"".join(ord(c).to_bytes(2, "big") for c in key).decode( + "utf-16-be" + ): aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_AttributeValue( + value + ) + for (key, value) in dafny_input.Attributes.value.items + } + + if dafny_input.ConsumedCapacity.is_Some: + output["ConsumedCapacity"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ConsumedCapacity( + dafny_input.ConsumedCapacity.value + ) + ) + + if dafny_input.ItemCollectionMetrics.is_Some: + output["ItemCollectionMetrics"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ItemCollectionMetrics( + dafny_input.ItemCollectionMetrics.value + ) + ) + + return output + + +def com_amazonaws_dynamodb_Select(dafny_input): + # Convert Select + if isinstance(dafny_input, Select_ALL__ATTRIBUTES): + return "ALL_ATTRIBUTES" + + elif isinstance(dafny_input, Select_ALL__PROJECTED__ATTRIBUTES): + return "ALL_PROJECTED_ATTRIBUTES" + + elif isinstance(dafny_input, Select_SPECIFIC__ATTRIBUTES): + return "SPECIFIC_ATTRIBUTES" + + elif isinstance(dafny_input, Select_COUNT): + return "COUNT" + + else: + raise ValueError("No recognized enum value in enum type: " + dafny_input) + + +def com_amazonaws_dynamodb_Condition(dafny_input): + output = {} + if dafny_input.AttributeValueList.is_Some: + output["AttributeValueList"] = [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_AttributeValue( + list_element + ) + for list_element in dafny_input.AttributeValueList.value + ] + + output["ComparisonOperator"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ComparisonOperator( + dafny_input.ComparisonOperator + ) + ) + return output + + +def com_amazonaws_dynamodb_QueryInput(dafny_input): + output = {} + output["TableName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.TableName + ).decode("utf-16-be") + if dafny_input.IndexName.is_Some: + output["IndexName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.IndexName.value + ).decode("utf-16-be") + + if dafny_input.Select.is_Some: + output["Select"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_Select( + dafny_input.Select.value + ) + ) + + if dafny_input.AttributesToGet.is_Some: + output["AttributesToGet"] = [ + b"".join(ord(c).to_bytes(2, "big") for c in list_element).decode( + "utf-16-be" + ) + for list_element in dafny_input.AttributesToGet.value + ] + + if dafny_input.Limit.is_Some: + output["Limit"] = dafny_input.Limit.value + + if dafny_input.ConsistentRead.is_Some: + output["ConsistentRead"] = dafny_input.ConsistentRead.value + + if dafny_input.KeyConditions.is_Some: + output["KeyConditions"] = { + b"".join(ord(c).to_bytes(2, "big") for c in key).decode( + "utf-16-be" + ): aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_Condition( + value + ) + for (key, value) in dafny_input.KeyConditions.value.items + } + + if dafny_input.QueryFilter.is_Some: + output["QueryFilter"] = { + b"".join(ord(c).to_bytes(2, "big") for c in key).decode( + "utf-16-be" + ): aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_Condition( + value + ) + for (key, value) in dafny_input.QueryFilter.value.items + } + + if dafny_input.ConditionalOperator.is_Some: + output["ConditionalOperator"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ConditionalOperator( + dafny_input.ConditionalOperator.value + ) + ) + + if dafny_input.ScanIndexForward.is_Some: + output["ScanIndexForward"] = dafny_input.ScanIndexForward.value + + if dafny_input.ExclusiveStartKey.is_Some: + output["ExclusiveStartKey"] = { + b"".join(ord(c).to_bytes(2, "big") for c in key).decode( + "utf-16-be" + ): aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_AttributeValue( + value + ) + for (key, value) in dafny_input.ExclusiveStartKey.value.items + } + + if dafny_input.ReturnConsumedCapacity.is_Some: + output["ReturnConsumedCapacity"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ReturnConsumedCapacity( + dafny_input.ReturnConsumedCapacity.value + ) + ) + + if dafny_input.ProjectionExpression.is_Some: + output["ProjectionExpression"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.ProjectionExpression.value + ).decode("utf-16-be") + + if dafny_input.FilterExpression.is_Some: + output["FilterExpression"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.FilterExpression.value + ).decode("utf-16-be") + + if dafny_input.KeyConditionExpression.is_Some: + output["KeyConditionExpression"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.KeyConditionExpression.value + ).decode("utf-16-be") + + if dafny_input.ExpressionAttributeNames.is_Some: + output["ExpressionAttributeNames"] = { + 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.ExpressionAttributeNames.value.items + } + + if dafny_input.ExpressionAttributeValues.is_Some: + output["ExpressionAttributeValues"] = { + b"".join(ord(c).to_bytes(2, "big") for c in key).decode( + "utf-16-be" + ): aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_AttributeValue( + value + ) + for (key, value) in dafny_input.ExpressionAttributeValues.value.items + } + + return output + + +def com_amazonaws_dynamodb_QueryOutput(dafny_input): + output = {} + if dafny_input.Items.is_Some: + output["Items"] = [ + { + b"".join(ord(c).to_bytes(2, "big") for c in key).decode( + "utf-16-be" + ): aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_AttributeValue( + value + ) + for (key, value) in list_element.items + } + for list_element in dafny_input.Items.value + ] + + if dafny_input.Count.is_Some: + output["Count"] = dafny_input.Count.value + + if dafny_input.ScannedCount.is_Some: + output["ScannedCount"] = dafny_input.ScannedCount.value + + if dafny_input.LastEvaluatedKey.is_Some: + output["LastEvaluatedKey"] = { + b"".join(ord(c).to_bytes(2, "big") for c in key).decode( + "utf-16-be" + ): aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_AttributeValue( + value + ) + for (key, value) in dafny_input.LastEvaluatedKey.value.items + } + + if dafny_input.ConsumedCapacity.is_Some: + output["ConsumedCapacity"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ConsumedCapacity( + dafny_input.ConsumedCapacity.value + ) + ) + + return output + + +def com_amazonaws_dynamodb_RestoreTableFromBackupInput(dafny_input): + output = {} + output["TargetTableName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.TargetTableName + ).decode("utf-16-be") + output["BackupArn"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.BackupArn + ).decode("utf-16-be") + if dafny_input.BillingModeOverride.is_Some: + output["BillingModeOverride"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_BillingMode( + dafny_input.BillingModeOverride.value + ) + ) + + if dafny_input.GlobalSecondaryIndexOverride.is_Some: + output["GlobalSecondaryIndexOverride"] = [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_GlobalSecondaryIndex( + list_element + ) + for list_element in dafny_input.GlobalSecondaryIndexOverride.value + ] + + if dafny_input.LocalSecondaryIndexOverride.is_Some: + output["LocalSecondaryIndexOverride"] = [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_LocalSecondaryIndex( + list_element + ) + for list_element in dafny_input.LocalSecondaryIndexOverride.value + ] + + if dafny_input.ProvisionedThroughputOverride.is_Some: + output["ProvisionedThroughputOverride"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ProvisionedThroughput( + dafny_input.ProvisionedThroughputOverride.value + ) + ) + + if dafny_input.SSESpecificationOverride.is_Some: + output["SSESpecificationOverride"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_SSESpecification( + dafny_input.SSESpecificationOverride.value + ) + ) + + return output + + +def com_amazonaws_dynamodb_RestoreTableFromBackupOutput(dafny_input): + output = {} + if dafny_input.TableDescription.is_Some: + output["TableDescription"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_TableDescription( + dafny_input.TableDescription.value + ) + ) + + return output + + +def com_amazonaws_dynamodb_RestoreTableToPointInTimeInput(dafny_input): + output = {} + if dafny_input.SourceTableArn.is_Some: + output["SourceTableArn"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.SourceTableArn.value + ).decode("utf-16-be") + + if dafny_input.SourceTableName.is_Some: + output["SourceTableName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.SourceTableName.value + ).decode("utf-16-be") + + output["TargetTableName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.TargetTableName + ).decode("utf-16-be") + if dafny_input.UseLatestRestorableTime.is_Some: + output["UseLatestRestorableTime"] = dafny_input.UseLatestRestorableTime.value + + if dafny_input.RestoreDateTime.is_Some: + output["RestoreDateTime"] = datetime.fromisoformat( + dafny_input.RestoreDateTime.value.VerbatimString(False) + ) + + if dafny_input.BillingModeOverride.is_Some: + output["BillingModeOverride"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_BillingMode( + dafny_input.BillingModeOverride.value + ) + ) + + if dafny_input.GlobalSecondaryIndexOverride.is_Some: + output["GlobalSecondaryIndexOverride"] = [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_GlobalSecondaryIndex( + list_element + ) + for list_element in dafny_input.GlobalSecondaryIndexOverride.value + ] + + if dafny_input.LocalSecondaryIndexOverride.is_Some: + output["LocalSecondaryIndexOverride"] = [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_LocalSecondaryIndex( + list_element + ) + for list_element in dafny_input.LocalSecondaryIndexOverride.value + ] + + if dafny_input.ProvisionedThroughputOverride.is_Some: + output["ProvisionedThroughputOverride"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ProvisionedThroughput( + dafny_input.ProvisionedThroughputOverride.value + ) + ) + + if dafny_input.SSESpecificationOverride.is_Some: + output["SSESpecificationOverride"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_SSESpecification( + dafny_input.SSESpecificationOverride.value + ) + ) + + return output + + +def com_amazonaws_dynamodb_RestoreTableToPointInTimeOutput(dafny_input): + output = {} + if dafny_input.TableDescription.is_Some: + output["TableDescription"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_TableDescription( + dafny_input.TableDescription.value + ) + ) + + return output + + +def com_amazonaws_dynamodb_ScanInput(dafny_input): + output = {} + output["TableName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.TableName + ).decode("utf-16-be") + if dafny_input.IndexName.is_Some: + output["IndexName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.IndexName.value + ).decode("utf-16-be") + + if dafny_input.AttributesToGet.is_Some: + output["AttributesToGet"] = [ + b"".join(ord(c).to_bytes(2, "big") for c in list_element).decode( + "utf-16-be" + ) + for list_element in dafny_input.AttributesToGet.value + ] + + if dafny_input.Limit.is_Some: + output["Limit"] = dafny_input.Limit.value + + if dafny_input.Select.is_Some: + output["Select"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_Select( + dafny_input.Select.value + ) + ) + + if dafny_input.ScanFilter.is_Some: + output["ScanFilter"] = { + b"".join(ord(c).to_bytes(2, "big") for c in key).decode( + "utf-16-be" + ): aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_Condition( + value + ) + for (key, value) in dafny_input.ScanFilter.value.items + } + + if dafny_input.ConditionalOperator.is_Some: + output["ConditionalOperator"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ConditionalOperator( + dafny_input.ConditionalOperator.value + ) + ) + + if dafny_input.ExclusiveStartKey.is_Some: + output["ExclusiveStartKey"] = { + b"".join(ord(c).to_bytes(2, "big") for c in key).decode( + "utf-16-be" + ): aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_AttributeValue( + value + ) + for (key, value) in dafny_input.ExclusiveStartKey.value.items + } + + if dafny_input.ReturnConsumedCapacity.is_Some: + output["ReturnConsumedCapacity"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ReturnConsumedCapacity( + dafny_input.ReturnConsumedCapacity.value + ) + ) + + if dafny_input.TotalSegments.is_Some: + output["TotalSegments"] = dafny_input.TotalSegments.value + + if dafny_input.Segment.is_Some: + output["Segment"] = dafny_input.Segment.value + + if dafny_input.ProjectionExpression.is_Some: + output["ProjectionExpression"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.ProjectionExpression.value + ).decode("utf-16-be") + + if dafny_input.FilterExpression.is_Some: + output["FilterExpression"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.FilterExpression.value + ).decode("utf-16-be") + + if dafny_input.ExpressionAttributeNames.is_Some: + output["ExpressionAttributeNames"] = { + 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.ExpressionAttributeNames.value.items + } + + if dafny_input.ExpressionAttributeValues.is_Some: + output["ExpressionAttributeValues"] = { + b"".join(ord(c).to_bytes(2, "big") for c in key).decode( + "utf-16-be" + ): aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_AttributeValue( + value + ) + for (key, value) in dafny_input.ExpressionAttributeValues.value.items + } + + if dafny_input.ConsistentRead.is_Some: + output["ConsistentRead"] = dafny_input.ConsistentRead.value + + return output + + +def com_amazonaws_dynamodb_ScanOutput(dafny_input): + output = {} + if dafny_input.Items.is_Some: + output["Items"] = [ + { + b"".join(ord(c).to_bytes(2, "big") for c in key).decode( + "utf-16-be" + ): aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_AttributeValue( + value + ) + for (key, value) in list_element.items + } + for list_element in dafny_input.Items.value + ] + + if dafny_input.Count.is_Some: + output["Count"] = dafny_input.Count.value + + if dafny_input.ScannedCount.is_Some: + output["ScannedCount"] = dafny_input.ScannedCount.value + + if dafny_input.LastEvaluatedKey.is_Some: + output["LastEvaluatedKey"] = { + b"".join(ord(c).to_bytes(2, "big") for c in key).decode( + "utf-16-be" + ): aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_AttributeValue( + value + ) + for (key, value) in dafny_input.LastEvaluatedKey.value.items + } + + if dafny_input.ConsumedCapacity.is_Some: + output["ConsumedCapacity"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ConsumedCapacity( + dafny_input.ConsumedCapacity.value + ) + ) + + return output + + +def com_amazonaws_dynamodb_TagResourceInput(dafny_input): + output = {} + output["ResourceArn"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.ResourceArn + ).decode("utf-16-be") + output["Tags"] = [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_Tag( + list_element + ) + for list_element in dafny_input.Tags + ] + return output + + +def com_amazonaws_dynamodb_TransactGetItem(dafny_input): + output = {} + output["Get"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_Get( + dafny_input.Get + ) + ) + return output + + +def com_amazonaws_dynamodb_Get(dafny_input): + output = {} + output["Key"] = { + b"".join(ord(c).to_bytes(2, "big") for c in key).decode( + "utf-16-be" + ): aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_AttributeValue( + value + ) + for (key, value) in dafny_input.Key.items + } + output["TableName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.TableName + ).decode("utf-16-be") + if dafny_input.ProjectionExpression.is_Some: + output["ProjectionExpression"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.ProjectionExpression.value + ).decode("utf-16-be") + + if dafny_input.ExpressionAttributeNames.is_Some: + output["ExpressionAttributeNames"] = { + 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.ExpressionAttributeNames.value.items + } + + return output + + +def com_amazonaws_dynamodb_TransactGetItemsInput(dafny_input): + output = {} + output["TransactItems"] = [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_TransactGetItem( + list_element + ) + for list_element in dafny_input.TransactItems + ] + if dafny_input.ReturnConsumedCapacity.is_Some: + output["ReturnConsumedCapacity"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ReturnConsumedCapacity( + dafny_input.ReturnConsumedCapacity.value + ) + ) + + return output + + +def com_amazonaws_dynamodb_TransactGetItemsOutput(dafny_input): + output = {} + if dafny_input.ConsumedCapacity.is_Some: + output["ConsumedCapacity"] = [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ConsumedCapacity( + list_element + ) + for list_element in dafny_input.ConsumedCapacity.value + ] + + if dafny_input.Responses.is_Some: + output["Responses"] = [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ItemResponse( + list_element + ) + for list_element in dafny_input.Responses.value + ] + + return output + + +def com_amazonaws_dynamodb_TransactWriteItem(dafny_input): + output = {} + if dafny_input.ConditionCheck.is_Some: + output["ConditionCheck"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ConditionCheck( + dafny_input.ConditionCheck.value + ) + ) + + if dafny_input.Put.is_Some: + output["Put"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_Put( + dafny_input.Put.value + ) + ) + + if dafny_input.Delete.is_Some: + output["Delete"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_Delete( + dafny_input.Delete.value + ) + ) + + if dafny_input.Update.is_Some: + output["Update"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_Update( + dafny_input.Update.value + ) + ) + + return output + + +def com_amazonaws_dynamodb_ConditionCheck(dafny_input): + output = {} + output["Key"] = { + b"".join(ord(c).to_bytes(2, "big") for c in key).decode( + "utf-16-be" + ): aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_AttributeValue( + value + ) + for (key, value) in dafny_input.Key.items + } + output["TableName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.TableName + ).decode("utf-16-be") + output["ConditionExpression"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.ConditionExpression + ).decode("utf-16-be") + if dafny_input.ExpressionAttributeNames.is_Some: + output["ExpressionAttributeNames"] = { + 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.ExpressionAttributeNames.value.items + } + + if dafny_input.ExpressionAttributeValues.is_Some: + output["ExpressionAttributeValues"] = { + b"".join(ord(c).to_bytes(2, "big") for c in key).decode( + "utf-16-be" + ): aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_AttributeValue( + value + ) + for (key, value) in dafny_input.ExpressionAttributeValues.value.items + } + + if dafny_input.ReturnValuesOnConditionCheckFailure.is_Some: + output["ReturnValuesOnConditionCheckFailure"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ReturnValuesOnConditionCheckFailure( + dafny_input.ReturnValuesOnConditionCheckFailure.value + ) + ) + + return output + + +def com_amazonaws_dynamodb_Put(dafny_input): + output = {} + output["Item"] = { + b"".join(ord(c).to_bytes(2, "big") for c in key).decode( + "utf-16-be" + ): aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_AttributeValue( + value + ) + for (key, value) in dafny_input.Item.items + } + output["TableName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.TableName + ).decode("utf-16-be") + if dafny_input.ConditionExpression.is_Some: + output["ConditionExpression"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.ConditionExpression.value + ).decode("utf-16-be") + + if dafny_input.ExpressionAttributeNames.is_Some: + output["ExpressionAttributeNames"] = { + 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.ExpressionAttributeNames.value.items + } + + if dafny_input.ExpressionAttributeValues.is_Some: + output["ExpressionAttributeValues"] = { + b"".join(ord(c).to_bytes(2, "big") for c in key).decode( + "utf-16-be" + ): aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_AttributeValue( + value + ) + for (key, value) in dafny_input.ExpressionAttributeValues.value.items + } + + if dafny_input.ReturnValuesOnConditionCheckFailure.is_Some: + output["ReturnValuesOnConditionCheckFailure"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ReturnValuesOnConditionCheckFailure( + dafny_input.ReturnValuesOnConditionCheckFailure.value + ) + ) + + return output + + +def com_amazonaws_dynamodb_Delete(dafny_input): + output = {} + output["Key"] = { + b"".join(ord(c).to_bytes(2, "big") for c in key).decode( + "utf-16-be" + ): aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_AttributeValue( + value + ) + for (key, value) in dafny_input.Key.items + } + output["TableName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.TableName + ).decode("utf-16-be") + if dafny_input.ConditionExpression.is_Some: + output["ConditionExpression"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.ConditionExpression.value + ).decode("utf-16-be") + + if dafny_input.ExpressionAttributeNames.is_Some: + output["ExpressionAttributeNames"] = { + 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.ExpressionAttributeNames.value.items + } + + if dafny_input.ExpressionAttributeValues.is_Some: + output["ExpressionAttributeValues"] = { + b"".join(ord(c).to_bytes(2, "big") for c in key).decode( + "utf-16-be" + ): aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_AttributeValue( + value + ) + for (key, value) in dafny_input.ExpressionAttributeValues.value.items + } + + if dafny_input.ReturnValuesOnConditionCheckFailure.is_Some: + output["ReturnValuesOnConditionCheckFailure"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ReturnValuesOnConditionCheckFailure( + dafny_input.ReturnValuesOnConditionCheckFailure.value + ) + ) + + return output + + +def com_amazonaws_dynamodb_Update(dafny_input): + output = {} + output["Key"] = { + b"".join(ord(c).to_bytes(2, "big") for c in key).decode( + "utf-16-be" + ): aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_AttributeValue( + value + ) + for (key, value) in dafny_input.Key.items + } + output["UpdateExpression"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.UpdateExpression + ).decode("utf-16-be") + output["TableName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.TableName + ).decode("utf-16-be") + if dafny_input.ConditionExpression.is_Some: + output["ConditionExpression"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.ConditionExpression.value + ).decode("utf-16-be") + + if dafny_input.ExpressionAttributeNames.is_Some: + output["ExpressionAttributeNames"] = { + 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.ExpressionAttributeNames.value.items + } + + if dafny_input.ExpressionAttributeValues.is_Some: + output["ExpressionAttributeValues"] = { + b"".join(ord(c).to_bytes(2, "big") for c in key).decode( + "utf-16-be" + ): aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_AttributeValue( + value + ) + for (key, value) in dafny_input.ExpressionAttributeValues.value.items + } + + if dafny_input.ReturnValuesOnConditionCheckFailure.is_Some: + output["ReturnValuesOnConditionCheckFailure"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ReturnValuesOnConditionCheckFailure( + dafny_input.ReturnValuesOnConditionCheckFailure.value + ) + ) + + return output + + +def com_amazonaws_dynamodb_ReturnValuesOnConditionCheckFailure(dafny_input): + # Convert ReturnValuesOnConditionCheckFailure + if isinstance(dafny_input, ReturnValuesOnConditionCheckFailure_ALL__OLD): + return "ALL_OLD" + + elif isinstance(dafny_input, ReturnValuesOnConditionCheckFailure_NONE): + return "NONE" + + else: + raise ValueError("No recognized enum value in enum type: " + dafny_input) + + +def com_amazonaws_dynamodb_TransactWriteItemsInput(dafny_input): + output = {} + output["TransactItems"] = [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_TransactWriteItem( + list_element + ) + for list_element in dafny_input.TransactItems + ] + if dafny_input.ReturnConsumedCapacity.is_Some: + output["ReturnConsumedCapacity"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ReturnConsumedCapacity( + dafny_input.ReturnConsumedCapacity.value + ) + ) + + if dafny_input.ReturnItemCollectionMetrics.is_Some: + output["ReturnItemCollectionMetrics"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ReturnItemCollectionMetrics( + dafny_input.ReturnItemCollectionMetrics.value + ) + ) + + if dafny_input.ClientRequestToken.is_Some: + output["ClientRequestToken"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.ClientRequestToken.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_dynamodb_TransactWriteItemsOutput(dafny_input): + output = {} + if dafny_input.ConsumedCapacity.is_Some: + output["ConsumedCapacity"] = [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ConsumedCapacity( + list_element + ) + for list_element in dafny_input.ConsumedCapacity.value + ] + + if dafny_input.ItemCollectionMetrics.is_Some: + output["ItemCollectionMetrics"] = { + b"".join(ord(c).to_bytes(2, "big") for c in key).decode("utf-16-be"): [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ItemCollectionMetrics( + list_element + ) + for list_element in value + ] + for (key, value) in dafny_input.ItemCollectionMetrics.value.items + } + + return output + + +def com_amazonaws_dynamodb_UntagResourceInput(dafny_input): + output = {} + output["ResourceArn"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.ResourceArn + ).decode("utf-16-be") + output["TagKeys"] = [ + b"".join(ord(c).to_bytes(2, "big") for c in list_element).decode("utf-16-be") + for list_element in dafny_input.TagKeys + ] + return output + + +def com_amazonaws_dynamodb_PointInTimeRecoverySpecification(dafny_input): + output = {} + output["PointInTimeRecoveryEnabled"] = dafny_input.PointInTimeRecoveryEnabled + return output + + +def com_amazonaws_dynamodb_UpdateContinuousBackupsInput(dafny_input): + output = {} + output["TableName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.TableName + ).decode("utf-16-be") + output["PointInTimeRecoverySpecification"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_PointInTimeRecoverySpecification( + dafny_input.PointInTimeRecoverySpecification + ) + ) + return output + + +def com_amazonaws_dynamodb_UpdateContinuousBackupsOutput(dafny_input): + output = {} + if dafny_input.ContinuousBackupsDescription.is_Some: + output["ContinuousBackupsDescription"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ContinuousBackupsDescription( + dafny_input.ContinuousBackupsDescription.value + ) + ) + + return output + + +def com_amazonaws_dynamodb_ContributorInsightsAction(dafny_input): + # Convert ContributorInsightsAction + if isinstance(dafny_input, ContributorInsightsAction_ENABLE): + return "ENABLE" + + elif isinstance(dafny_input, ContributorInsightsAction_DISABLE): + return "DISABLE" + + else: + raise ValueError("No recognized enum value in enum type: " + dafny_input) + + +def com_amazonaws_dynamodb_UpdateContributorInsightsInput(dafny_input): + output = {} + output["TableName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.TableName + ).decode("utf-16-be") + if dafny_input.IndexName.is_Some: + output["IndexName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.IndexName.value + ).decode("utf-16-be") + + output["ContributorInsightsAction"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ContributorInsightsAction( + dafny_input.ContributorInsightsAction + ) + ) + return output + + +def com_amazonaws_dynamodb_UpdateContributorInsightsOutput(dafny_input): + output = {} + if dafny_input.TableName.is_Some: + output["TableName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.TableName.value + ).decode("utf-16-be") + + if dafny_input.IndexName.is_Some: + output["IndexName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.IndexName.value + ).decode("utf-16-be") + + if dafny_input.ContributorInsightsStatus.is_Some: + output["ContributorInsightsStatus"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ContributorInsightsStatus( + dafny_input.ContributorInsightsStatus.value + ) + ) + + return output + + +def com_amazonaws_dynamodb_ReplicaUpdate(dafny_input): + output = {} + if dafny_input.Create.is_Some: + output["Create"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_CreateReplicaAction( + dafny_input.Create.value + ) + ) + + if dafny_input.Delete.is_Some: + output["Delete"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_DeleteReplicaAction( + dafny_input.Delete.value + ) + ) + + return output + + +def com_amazonaws_dynamodb_CreateReplicaAction(dafny_input): + output = {} + output["RegionName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.RegionName + ).decode("utf-16-be") + return output + + +def com_amazonaws_dynamodb_DeleteReplicaAction(dafny_input): + output = {} + output["RegionName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.RegionName + ).decode("utf-16-be") + return output + + +def com_amazonaws_dynamodb_UpdateGlobalTableInput(dafny_input): + output = {} + output["GlobalTableName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.GlobalTableName + ).decode("utf-16-be") + output["ReplicaUpdates"] = [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ReplicaUpdate( + list_element + ) + for list_element in dafny_input.ReplicaUpdates + ] + return output + + +def com_amazonaws_dynamodb_UpdateGlobalTableOutput(dafny_input): + output = {} + if dafny_input.GlobalTableDescription.is_Some: + output["GlobalTableDescription"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_GlobalTableDescription( + dafny_input.GlobalTableDescription.value + ) + ) + + return output + + +def com_amazonaws_dynamodb_AutoScalingSettingsUpdate(dafny_input): + output = {} + if dafny_input.MinimumUnits.is_Some: + output["MinimumUnits"] = dafny_input.MinimumUnits.value + + if dafny_input.MaximumUnits.is_Some: + output["MaximumUnits"] = dafny_input.MaximumUnits.value + + if dafny_input.AutoScalingDisabled.is_Some: + output["AutoScalingDisabled"] = dafny_input.AutoScalingDisabled.value + + if dafny_input.AutoScalingRoleArn.is_Some: + output["AutoScalingRoleArn"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.AutoScalingRoleArn.value + ).decode("utf-16-be") + + if dafny_input.ScalingPolicyUpdate.is_Some: + output["ScalingPolicyUpdate"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_AutoScalingPolicyUpdate( + dafny_input.ScalingPolicyUpdate.value + ) + ) + + return output + + +def com_amazonaws_dynamodb_AutoScalingPolicyUpdate(dafny_input): + output = {} + if dafny_input.PolicyName.is_Some: + output["PolicyName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.PolicyName.value + ).decode("utf-16-be") + + output["TargetTrackingScalingPolicyConfiguration"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_AutoScalingTargetTrackingScalingPolicyConfigurationUpdate( + dafny_input.TargetTrackingScalingPolicyConfiguration + ) + ) + return output + + +def com_amazonaws_dynamodb_AutoScalingTargetTrackingScalingPolicyConfigurationUpdate( + dafny_input, +): + output = {} + if dafny_input.DisableScaleIn.is_Some: + output["DisableScaleIn"] = dafny_input.DisableScaleIn.value + + if dafny_input.ScaleInCooldown.is_Some: + output["ScaleInCooldown"] = dafny_input.ScaleInCooldown.value + + if dafny_input.ScaleOutCooldown.is_Some: + output["ScaleOutCooldown"] = dafny_input.ScaleOutCooldown.value + + output["TargetValue"] = dafny_input.TargetValue + return output + + +def com_amazonaws_dynamodb_GlobalTableGlobalSecondaryIndexSettingsUpdate(dafny_input): + output = {} + output["IndexName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.IndexName + ).decode("utf-16-be") + if dafny_input.ProvisionedWriteCapacityUnits.is_Some: + output["ProvisionedWriteCapacityUnits"] = ( + dafny_input.ProvisionedWriteCapacityUnits.value + ) + + if dafny_input.ProvisionedWriteCapacityAutoScalingSettingsUpdate.is_Some: + output["ProvisionedWriteCapacityAutoScalingSettingsUpdate"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_AutoScalingSettingsUpdate( + dafny_input.ProvisionedWriteCapacityAutoScalingSettingsUpdate.value + ) + ) + + return output + + +def com_amazonaws_dynamodb_ReplicaSettingsUpdate(dafny_input): + output = {} + output["RegionName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.RegionName + ).decode("utf-16-be") + if dafny_input.ReplicaProvisionedReadCapacityUnits.is_Some: + output["ReplicaProvisionedReadCapacityUnits"] = ( + dafny_input.ReplicaProvisionedReadCapacityUnits.value + ) + + if dafny_input.ReplicaProvisionedReadCapacityAutoScalingSettingsUpdate.is_Some: + output["ReplicaProvisionedReadCapacityAutoScalingSettingsUpdate"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_AutoScalingSettingsUpdate( + dafny_input.ReplicaProvisionedReadCapacityAutoScalingSettingsUpdate.value + ) + ) + + if dafny_input.ReplicaGlobalSecondaryIndexSettingsUpdate.is_Some: + output["ReplicaGlobalSecondaryIndexSettingsUpdate"] = [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ReplicaGlobalSecondaryIndexSettingsUpdate( + list_element + ) + for list_element in dafny_input.ReplicaGlobalSecondaryIndexSettingsUpdate.value + ] + + if dafny_input.ReplicaTableClass.is_Some: + output["ReplicaTableClass"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_TableClass( + dafny_input.ReplicaTableClass.value + ) + ) + + return output + + +def com_amazonaws_dynamodb_ReplicaGlobalSecondaryIndexSettingsUpdate(dafny_input): + output = {} + output["IndexName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.IndexName + ).decode("utf-16-be") + if dafny_input.ProvisionedReadCapacityUnits.is_Some: + output["ProvisionedReadCapacityUnits"] = ( + dafny_input.ProvisionedReadCapacityUnits.value + ) + + if dafny_input.ProvisionedReadCapacityAutoScalingSettingsUpdate.is_Some: + output["ProvisionedReadCapacityAutoScalingSettingsUpdate"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_AutoScalingSettingsUpdate( + dafny_input.ProvisionedReadCapacityAutoScalingSettingsUpdate.value + ) + ) + + return output + + +def com_amazonaws_dynamodb_UpdateGlobalTableSettingsInput(dafny_input): + output = {} + output["GlobalTableName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.GlobalTableName + ).decode("utf-16-be") + if dafny_input.GlobalTableBillingMode.is_Some: + output["GlobalTableBillingMode"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_BillingMode( + dafny_input.GlobalTableBillingMode.value + ) + ) + + if dafny_input.GlobalTableProvisionedWriteCapacityUnits.is_Some: + output["GlobalTableProvisionedWriteCapacityUnits"] = ( + dafny_input.GlobalTableProvisionedWriteCapacityUnits.value + ) + + if dafny_input.GlobalTableProvisionedWriteCapacityAutoScalingSettingsUpdate.is_Some: + output["GlobalTableProvisionedWriteCapacityAutoScalingSettingsUpdate"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_AutoScalingSettingsUpdate( + dafny_input.GlobalTableProvisionedWriteCapacityAutoScalingSettingsUpdate.value + ) + ) + + if dafny_input.GlobalTableGlobalSecondaryIndexSettingsUpdate.is_Some: + output["GlobalTableGlobalSecondaryIndexSettingsUpdate"] = [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_GlobalTableGlobalSecondaryIndexSettingsUpdate( + list_element + ) + for list_element in dafny_input.GlobalTableGlobalSecondaryIndexSettingsUpdate.value + ] + + if dafny_input.ReplicaSettingsUpdate.is_Some: + output["ReplicaSettingsUpdate"] = [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ReplicaSettingsUpdate( + list_element + ) + for list_element in dafny_input.ReplicaSettingsUpdate.value + ] + + return output + + +def com_amazonaws_dynamodb_UpdateGlobalTableSettingsOutput(dafny_input): + output = {} + if dafny_input.GlobalTableName.is_Some: + output["GlobalTableName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.GlobalTableName.value + ).decode("utf-16-be") + + if dafny_input.ReplicaSettings.is_Some: + output["ReplicaSettings"] = [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ReplicaSettingsDescription( + list_element + ) + for list_element in dafny_input.ReplicaSettings.value + ] + + return output + + +def com_amazonaws_dynamodb_AttributeValueUpdate(dafny_input): + output = {} + if dafny_input.Value.is_Some: + output["Value"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_AttributeValue( + dafny_input.Value.value + ) + ) + + if dafny_input.Action.is_Some: + output["Action"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_AttributeAction( + dafny_input.Action.value + ) + ) + + return output + + +def com_amazonaws_dynamodb_AttributeAction(dafny_input): + # Convert AttributeAction + if isinstance(dafny_input, AttributeAction_ADD): + return "ADD" + + elif isinstance(dafny_input, AttributeAction_PUT): + return "PUT" + + elif isinstance(dafny_input, AttributeAction_DELETE): + return "DELETE" + + else: + raise ValueError("No recognized enum value in enum type: " + dafny_input) + + +def com_amazonaws_dynamodb_UpdateItemInput(dafny_input): + output = {} + output["TableName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.TableName + ).decode("utf-16-be") + output["Key"] = { + b"".join(ord(c).to_bytes(2, "big") for c in key).decode( + "utf-16-be" + ): aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_AttributeValue( + value + ) + for (key, value) in dafny_input.Key.items + } + if dafny_input.AttributeUpdates.is_Some: + output["AttributeUpdates"] = { + b"".join(ord(c).to_bytes(2, "big") for c in key).decode( + "utf-16-be" + ): aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_AttributeValueUpdate( + value + ) + for (key, value) in dafny_input.AttributeUpdates.value.items + } + + if dafny_input.Expected.is_Some: + output["Expected"] = { + b"".join(ord(c).to_bytes(2, "big") for c in key).decode( + "utf-16-be" + ): aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ExpectedAttributeValue( + value + ) + for (key, value) in dafny_input.Expected.value.items + } + + if dafny_input.ConditionalOperator.is_Some: + output["ConditionalOperator"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ConditionalOperator( + dafny_input.ConditionalOperator.value + ) + ) + + if dafny_input.ReturnValues.is_Some: + output["ReturnValues"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ReturnValue( + dafny_input.ReturnValues.value + ) + ) + + if dafny_input.ReturnConsumedCapacity.is_Some: + output["ReturnConsumedCapacity"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ReturnConsumedCapacity( + dafny_input.ReturnConsumedCapacity.value + ) + ) + + if dafny_input.ReturnItemCollectionMetrics.is_Some: + output["ReturnItemCollectionMetrics"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ReturnItemCollectionMetrics( + dafny_input.ReturnItemCollectionMetrics.value + ) + ) + + if dafny_input.UpdateExpression.is_Some: + output["UpdateExpression"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.UpdateExpression.value + ).decode("utf-16-be") + + if dafny_input.ConditionExpression.is_Some: + output["ConditionExpression"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.ConditionExpression.value + ).decode("utf-16-be") + + if dafny_input.ExpressionAttributeNames.is_Some: + output["ExpressionAttributeNames"] = { + 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.ExpressionAttributeNames.value.items + } + + if dafny_input.ExpressionAttributeValues.is_Some: + output["ExpressionAttributeValues"] = { + b"".join(ord(c).to_bytes(2, "big") for c in key).decode( + "utf-16-be" + ): aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_AttributeValue( + value + ) + for (key, value) in dafny_input.ExpressionAttributeValues.value.items + } + + return output + + +def com_amazonaws_dynamodb_UpdateItemOutput(dafny_input): + output = {} + if dafny_input.Attributes.is_Some: + output["Attributes"] = { + b"".join(ord(c).to_bytes(2, "big") for c in key).decode( + "utf-16-be" + ): aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_AttributeValue( + value + ) + for (key, value) in dafny_input.Attributes.value.items + } + + if dafny_input.ConsumedCapacity.is_Some: + output["ConsumedCapacity"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ConsumedCapacity( + dafny_input.ConsumedCapacity.value + ) + ) + + if dafny_input.ItemCollectionMetrics.is_Some: + output["ItemCollectionMetrics"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ItemCollectionMetrics( + dafny_input.ItemCollectionMetrics.value + ) + ) + + return output + + +def com_amazonaws_dynamodb_GlobalSecondaryIndexUpdate(dafny_input): + output = {} + if dafny_input.Update.is_Some: + output["Update"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_UpdateGlobalSecondaryIndexAction( + dafny_input.Update.value + ) + ) + + if dafny_input.Create.is_Some: + output["Create"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_CreateGlobalSecondaryIndexAction( + dafny_input.Create.value + ) + ) + + if dafny_input.Delete.is_Some: + output["Delete"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_DeleteGlobalSecondaryIndexAction( + dafny_input.Delete.value + ) + ) + + return output + + +def com_amazonaws_dynamodb_UpdateGlobalSecondaryIndexAction(dafny_input): + output = {} + output["IndexName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.IndexName + ).decode("utf-16-be") + output["ProvisionedThroughput"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ProvisionedThroughput( + dafny_input.ProvisionedThroughput + ) + ) + return output + + +def com_amazonaws_dynamodb_CreateGlobalSecondaryIndexAction(dafny_input): + output = {} + output["IndexName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.IndexName + ).decode("utf-16-be") + output["KeySchema"] = [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_KeySchemaElement( + list_element + ) + for list_element in dafny_input.KeySchema + ] + output["Projection"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_Projection( + dafny_input.Projection + ) + ) + if dafny_input.ProvisionedThroughput.is_Some: + output["ProvisionedThroughput"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ProvisionedThroughput( + dafny_input.ProvisionedThroughput.value + ) + ) + + return output + + +def com_amazonaws_dynamodb_DeleteGlobalSecondaryIndexAction(dafny_input): + output = {} + output["IndexName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.IndexName + ).decode("utf-16-be") + return output + + +def com_amazonaws_dynamodb_ReplicationGroupUpdate(dafny_input): + output = {} + if dafny_input.Create.is_Some: + output["Create"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_CreateReplicationGroupMemberAction( + dafny_input.Create.value + ) + ) + + if dafny_input.Update.is_Some: + output["Update"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_UpdateReplicationGroupMemberAction( + dafny_input.Update.value + ) + ) + + if dafny_input.Delete.is_Some: + output["Delete"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_DeleteReplicationGroupMemberAction( + dafny_input.Delete.value + ) + ) + + return output + + +def com_amazonaws_dynamodb_CreateReplicationGroupMemberAction(dafny_input): + output = {} + output["RegionName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.RegionName + ).decode("utf-16-be") + if dafny_input.KMSMasterKeyId.is_Some: + output["KMSMasterKeyId"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.KMSMasterKeyId.value + ).decode("utf-16-be") + + if dafny_input.ProvisionedThroughputOverride.is_Some: + output["ProvisionedThroughputOverride"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ProvisionedThroughputOverride( + dafny_input.ProvisionedThroughputOverride.value + ) + ) + + if dafny_input.GlobalSecondaryIndexes.is_Some: + output["GlobalSecondaryIndexes"] = [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ReplicaGlobalSecondaryIndex( + list_element + ) + for list_element in dafny_input.GlobalSecondaryIndexes.value + ] + + if dafny_input.TableClassOverride.is_Some: + output["TableClassOverride"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_TableClass( + dafny_input.TableClassOverride.value + ) + ) + + return output + + +def com_amazonaws_dynamodb_UpdateReplicationGroupMemberAction(dafny_input): + output = {} + output["RegionName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.RegionName + ).decode("utf-16-be") + if dafny_input.KMSMasterKeyId.is_Some: + output["KMSMasterKeyId"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.KMSMasterKeyId.value + ).decode("utf-16-be") + + if dafny_input.ProvisionedThroughputOverride.is_Some: + output["ProvisionedThroughputOverride"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ProvisionedThroughputOverride( + dafny_input.ProvisionedThroughputOverride.value + ) + ) + + if dafny_input.GlobalSecondaryIndexes.is_Some: + output["GlobalSecondaryIndexes"] = [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ReplicaGlobalSecondaryIndex( + list_element + ) + for list_element in dafny_input.GlobalSecondaryIndexes.value + ] + + if dafny_input.TableClassOverride.is_Some: + output["TableClassOverride"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_TableClass( + dafny_input.TableClassOverride.value + ) + ) + + return output + + +def com_amazonaws_dynamodb_DeleteReplicationGroupMemberAction(dafny_input): + output = {} + output["RegionName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.RegionName + ).decode("utf-16-be") + return output + + +def com_amazonaws_dynamodb_ReplicaGlobalSecondaryIndex(dafny_input): + output = {} + output["IndexName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.IndexName + ).decode("utf-16-be") + if dafny_input.ProvisionedThroughputOverride.is_Some: + output["ProvisionedThroughputOverride"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ProvisionedThroughputOverride( + dafny_input.ProvisionedThroughputOverride.value + ) + ) + + return output + + +def com_amazonaws_dynamodb_UpdateTableInput(dafny_input): + output = {} + if dafny_input.AttributeDefinitions.is_Some: + output["AttributeDefinitions"] = [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_AttributeDefinition( + list_element + ) + for list_element in dafny_input.AttributeDefinitions.value + ] + + output["TableName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.TableName + ).decode("utf-16-be") + if dafny_input.BillingMode.is_Some: + output["BillingMode"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_BillingMode( + dafny_input.BillingMode.value + ) + ) + + if dafny_input.ProvisionedThroughput.is_Some: + output["ProvisionedThroughput"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ProvisionedThroughput( + dafny_input.ProvisionedThroughput.value + ) + ) + + if dafny_input.GlobalSecondaryIndexUpdates.is_Some: + output["GlobalSecondaryIndexUpdates"] = [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_GlobalSecondaryIndexUpdate( + list_element + ) + for list_element in dafny_input.GlobalSecondaryIndexUpdates.value + ] + + if dafny_input.StreamSpecification.is_Some: + output["StreamSpecification"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_StreamSpecification( + dafny_input.StreamSpecification.value + ) + ) + + if dafny_input.SSESpecification.is_Some: + output["SSESpecification"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_SSESpecification( + dafny_input.SSESpecification.value + ) + ) + + if dafny_input.ReplicaUpdates.is_Some: + output["ReplicaUpdates"] = [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ReplicationGroupUpdate( + list_element + ) + for list_element in dafny_input.ReplicaUpdates.value + ] + + if dafny_input.TableClass.is_Some: + output["TableClass"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_TableClass( + dafny_input.TableClass.value + ) + ) + + return output + + +def com_amazonaws_dynamodb_UpdateTableOutput(dafny_input): + output = {} + if dafny_input.TableDescription.is_Some: + output["TableDescription"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_TableDescription( + dafny_input.TableDescription.value + ) + ) + + return output + + +def com_amazonaws_dynamodb_GlobalSecondaryIndexAutoScalingUpdate(dafny_input): + output = {} + if dafny_input.IndexName.is_Some: + output["IndexName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.IndexName.value + ).decode("utf-16-be") + + if dafny_input.ProvisionedWriteCapacityAutoScalingUpdate.is_Some: + output["ProvisionedWriteCapacityAutoScalingUpdate"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_AutoScalingSettingsUpdate( + dafny_input.ProvisionedWriteCapacityAutoScalingUpdate.value + ) + ) + + return output + + +def com_amazonaws_dynamodb_ReplicaAutoScalingUpdate(dafny_input): + output = {} + output["RegionName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.RegionName + ).decode("utf-16-be") + if dafny_input.ReplicaGlobalSecondaryIndexUpdates.is_Some: + output["ReplicaGlobalSecondaryIndexUpdates"] = [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ReplicaGlobalSecondaryIndexAutoScalingUpdate( + list_element + ) + for list_element in dafny_input.ReplicaGlobalSecondaryIndexUpdates.value + ] + + if dafny_input.ReplicaProvisionedReadCapacityAutoScalingUpdate.is_Some: + output["ReplicaProvisionedReadCapacityAutoScalingUpdate"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_AutoScalingSettingsUpdate( + dafny_input.ReplicaProvisionedReadCapacityAutoScalingUpdate.value + ) + ) + + return output + + +def com_amazonaws_dynamodb_ReplicaGlobalSecondaryIndexAutoScalingUpdate(dafny_input): + output = {} + if dafny_input.IndexName.is_Some: + output["IndexName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.IndexName.value + ).decode("utf-16-be") + + if dafny_input.ProvisionedReadCapacityAutoScalingUpdate.is_Some: + output["ProvisionedReadCapacityAutoScalingUpdate"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_AutoScalingSettingsUpdate( + dafny_input.ProvisionedReadCapacityAutoScalingUpdate.value + ) + ) + + return output + + +def com_amazonaws_dynamodb_UpdateTableReplicaAutoScalingInput(dafny_input): + output = {} + if dafny_input.GlobalSecondaryIndexUpdates.is_Some: + output["GlobalSecondaryIndexUpdates"] = [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_GlobalSecondaryIndexAutoScalingUpdate( + list_element + ) + for list_element in dafny_input.GlobalSecondaryIndexUpdates.value + ] + + output["TableName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.TableName + ).decode("utf-16-be") + if dafny_input.ProvisionedWriteCapacityAutoScalingUpdate.is_Some: + output["ProvisionedWriteCapacityAutoScalingUpdate"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_AutoScalingSettingsUpdate( + dafny_input.ProvisionedWriteCapacityAutoScalingUpdate.value + ) + ) + + if dafny_input.ReplicaUpdates.is_Some: + output["ReplicaUpdates"] = [ + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ReplicaAutoScalingUpdate( + list_element + ) + for list_element in dafny_input.ReplicaUpdates.value + ] + + return output + + +def com_amazonaws_dynamodb_UpdateTableReplicaAutoScalingOutput(dafny_input): + output = {} + if dafny_input.TableAutoScalingDescription.is_Some: + output["TableAutoScalingDescription"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_TableAutoScalingDescription( + dafny_input.TableAutoScalingDescription.value + ) + ) + + return output + + +def com_amazonaws_dynamodb_TimeToLiveSpecification(dafny_input): + output = {} + output["Enabled"] = dafny_input.Enabled + output["AttributeName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.AttributeName + ).decode("utf-16-be") + return output + + +def com_amazonaws_dynamodb_UpdateTimeToLiveInput(dafny_input): + output = {} + output["TableName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.TableName + ).decode("utf-16-be") + output["TimeToLiveSpecification"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_TimeToLiveSpecification( + dafny_input.TimeToLiveSpecification + ) + ) + return output + + +def com_amazonaws_dynamodb_UpdateTimeToLiveOutput(dafny_input): + output = {} + if dafny_input.TimeToLiveSpecification.is_Some: + output["TimeToLiveSpecification"] = ( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_TimeToLiveSpecification( + dafny_input.TimeToLiveSpecification.value + ) + ) + + return output diff --git a/ComAmazonawsDynamodb/runtimes/python/src/aws_cryptography_internal_dynamodb/smithygenerated/com_amazonaws_dynamodb/shim.py b/ComAmazonawsDynamodb/runtimes/python/src/aws_cryptography_internal_dynamodb/smithygenerated/com_amazonaws_dynamodb/shim.py new file mode 100644 index 000000000..d3d5d47f9 --- /dev/null +++ b/ComAmazonawsDynamodb/runtimes/python/src/aws_cryptography_internal_dynamodb/smithygenerated/com_amazonaws_dynamodb/shim.py @@ -0,0 +1,1177 @@ +# 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_cryptography_internal_dynamodb.internaldafny.generated.ComAmazonawsDynamodbTypes import ( + BatchExecuteStatementInput_BatchExecuteStatementInput as DafnyBatchExecuteStatementInput, + BatchExecuteStatementOutput_BatchExecuteStatementOutput as DafnyBatchExecuteStatementOutput, + BatchGetItemInput_BatchGetItemInput as DafnyBatchGetItemInput, + BatchGetItemOutput_BatchGetItemOutput as DafnyBatchGetItemOutput, + BatchWriteItemInput_BatchWriteItemInput as DafnyBatchWriteItemInput, + BatchWriteItemOutput_BatchWriteItemOutput as DafnyBatchWriteItemOutput, + CreateBackupInput_CreateBackupInput as DafnyCreateBackupInput, + CreateBackupOutput_CreateBackupOutput as DafnyCreateBackupOutput, + CreateGlobalTableInput_CreateGlobalTableInput as DafnyCreateGlobalTableInput, + CreateGlobalTableOutput_CreateGlobalTableOutput as DafnyCreateGlobalTableOutput, + CreateTableInput_CreateTableInput as DafnyCreateTableInput, + CreateTableOutput_CreateTableOutput as DafnyCreateTableOutput, + DeleteBackupInput_DeleteBackupInput as DafnyDeleteBackupInput, + DeleteBackupOutput_DeleteBackupOutput as DafnyDeleteBackupOutput, + DeleteItemInput_DeleteItemInput as DafnyDeleteItemInput, + DeleteItemOutput_DeleteItemOutput as DafnyDeleteItemOutput, + DeleteTableInput_DeleteTableInput as DafnyDeleteTableInput, + DeleteTableOutput_DeleteTableOutput as DafnyDeleteTableOutput, + DescribeBackupInput_DescribeBackupInput as DafnyDescribeBackupInput, + DescribeBackupOutput_DescribeBackupOutput as DafnyDescribeBackupOutput, + DescribeContinuousBackupsInput_DescribeContinuousBackupsInput as DafnyDescribeContinuousBackupsInput, + DescribeContinuousBackupsOutput_DescribeContinuousBackupsOutput as DafnyDescribeContinuousBackupsOutput, + DescribeContributorInsightsInput_DescribeContributorInsightsInput as DafnyDescribeContributorInsightsInput, + DescribeContributorInsightsOutput_DescribeContributorInsightsOutput as DafnyDescribeContributorInsightsOutput, + DescribeEndpointsRequest_DescribeEndpointsRequest as DafnyDescribeEndpointsRequest, + DescribeEndpointsResponse_DescribeEndpointsResponse as DafnyDescribeEndpointsResponse, + DescribeExportInput_DescribeExportInput as DafnyDescribeExportInput, + DescribeExportOutput_DescribeExportOutput as DafnyDescribeExportOutput, + DescribeGlobalTableInput_DescribeGlobalTableInput as DafnyDescribeGlobalTableInput, + DescribeGlobalTableOutput_DescribeGlobalTableOutput as DafnyDescribeGlobalTableOutput, + DescribeGlobalTableSettingsInput_DescribeGlobalTableSettingsInput as DafnyDescribeGlobalTableSettingsInput, + DescribeGlobalTableSettingsOutput_DescribeGlobalTableSettingsOutput as DafnyDescribeGlobalTableSettingsOutput, + DescribeImportInput_DescribeImportInput as DafnyDescribeImportInput, + DescribeImportOutput_DescribeImportOutput as DafnyDescribeImportOutput, + DescribeKinesisStreamingDestinationInput_DescribeKinesisStreamingDestinationInput as DafnyDescribeKinesisStreamingDestinationInput, + DescribeKinesisStreamingDestinationOutput_DescribeKinesisStreamingDestinationOutput as DafnyDescribeKinesisStreamingDestinationOutput, + DescribeLimitsInput_DescribeLimitsInput as DafnyDescribeLimitsInput, + DescribeLimitsOutput_DescribeLimitsOutput as DafnyDescribeLimitsOutput, + DescribeTableInput_DescribeTableInput as DafnyDescribeTableInput, + DescribeTableOutput_DescribeTableOutput as DafnyDescribeTableOutput, + DescribeTableReplicaAutoScalingInput_DescribeTableReplicaAutoScalingInput as DafnyDescribeTableReplicaAutoScalingInput, + DescribeTableReplicaAutoScalingOutput_DescribeTableReplicaAutoScalingOutput as DafnyDescribeTableReplicaAutoScalingOutput, + DescribeTimeToLiveInput_DescribeTimeToLiveInput as DafnyDescribeTimeToLiveInput, + DescribeTimeToLiveOutput_DescribeTimeToLiveOutput as DafnyDescribeTimeToLiveOutput, + DisableKinesisStreamingDestinationInput_DisableKinesisStreamingDestinationInput as DafnyDisableKinesisStreamingDestinationInput, + DisableKinesisStreamingDestinationOutput_DisableKinesisStreamingDestinationOutput as DafnyDisableKinesisStreamingDestinationOutput, + EnableKinesisStreamingDestinationInput_EnableKinesisStreamingDestinationInput as DafnyEnableKinesisStreamingDestinationInput, + EnableKinesisStreamingDestinationOutput_EnableKinesisStreamingDestinationOutput as DafnyEnableKinesisStreamingDestinationOutput, + ExecuteStatementInput_ExecuteStatementInput as DafnyExecuteStatementInput, + ExecuteStatementOutput_ExecuteStatementOutput as DafnyExecuteStatementOutput, + ExecuteTransactionInput_ExecuteTransactionInput as DafnyExecuteTransactionInput, + ExecuteTransactionOutput_ExecuteTransactionOutput as DafnyExecuteTransactionOutput, + ExportTableToPointInTimeInput_ExportTableToPointInTimeInput as DafnyExportTableToPointInTimeInput, + ExportTableToPointInTimeOutput_ExportTableToPointInTimeOutput as DafnyExportTableToPointInTimeOutput, + GetItemInput_GetItemInput as DafnyGetItemInput, + GetItemOutput_GetItemOutput as DafnyGetItemOutput, + ImportTableInput_ImportTableInput as DafnyImportTableInput, + ImportTableOutput_ImportTableOutput as DafnyImportTableOutput, + ListBackupsInput_ListBackupsInput as DafnyListBackupsInput, + ListBackupsOutput_ListBackupsOutput as DafnyListBackupsOutput, + ListContributorInsightsInput_ListContributorInsightsInput as DafnyListContributorInsightsInput, + ListContributorInsightsOutput_ListContributorInsightsOutput as DafnyListContributorInsightsOutput, + ListExportsInput_ListExportsInput as DafnyListExportsInput, + ListExportsOutput_ListExportsOutput as DafnyListExportsOutput, + ListGlobalTablesInput_ListGlobalTablesInput as DafnyListGlobalTablesInput, + ListGlobalTablesOutput_ListGlobalTablesOutput as DafnyListGlobalTablesOutput, + ListImportsInput_ListImportsInput as DafnyListImportsInput, + ListImportsOutput_ListImportsOutput as DafnyListImportsOutput, + ListTablesInput_ListTablesInput as DafnyListTablesInput, + ListTablesOutput_ListTablesOutput as DafnyListTablesOutput, + ListTagsOfResourceInput_ListTagsOfResourceInput as DafnyListTagsOfResourceInput, + ListTagsOfResourceOutput_ListTagsOfResourceOutput as DafnyListTagsOfResourceOutput, + PutItemInput_PutItemInput as DafnyPutItemInput, + PutItemOutput_PutItemOutput as DafnyPutItemOutput, + QueryInput_QueryInput as DafnyQueryInput, + QueryOutput_QueryOutput as DafnyQueryOutput, + RestoreTableFromBackupInput_RestoreTableFromBackupInput as DafnyRestoreTableFromBackupInput, + RestoreTableFromBackupOutput_RestoreTableFromBackupOutput as DafnyRestoreTableFromBackupOutput, + RestoreTableToPointInTimeInput_RestoreTableToPointInTimeInput as DafnyRestoreTableToPointInTimeInput, + RestoreTableToPointInTimeOutput_RestoreTableToPointInTimeOutput as DafnyRestoreTableToPointInTimeOutput, + ScanInput_ScanInput as DafnyScanInput, + ScanOutput_ScanOutput as DafnyScanOutput, + TagResourceInput_TagResourceInput as DafnyTagResourceInput, + TransactGetItemsInput_TransactGetItemsInput as DafnyTransactGetItemsInput, + TransactGetItemsOutput_TransactGetItemsOutput as DafnyTransactGetItemsOutput, + TransactWriteItemsInput_TransactWriteItemsInput as DafnyTransactWriteItemsInput, + TransactWriteItemsOutput_TransactWriteItemsOutput as DafnyTransactWriteItemsOutput, + UntagResourceInput_UntagResourceInput as DafnyUntagResourceInput, + UpdateContinuousBackupsInput_UpdateContinuousBackupsInput as DafnyUpdateContinuousBackupsInput, + UpdateContinuousBackupsOutput_UpdateContinuousBackupsOutput as DafnyUpdateContinuousBackupsOutput, + UpdateContributorInsightsInput_UpdateContributorInsightsInput as DafnyUpdateContributorInsightsInput, + UpdateContributorInsightsOutput_UpdateContributorInsightsOutput as DafnyUpdateContributorInsightsOutput, + UpdateGlobalTableInput_UpdateGlobalTableInput as DafnyUpdateGlobalTableInput, + UpdateGlobalTableOutput_UpdateGlobalTableOutput as DafnyUpdateGlobalTableOutput, + UpdateGlobalTableSettingsInput_UpdateGlobalTableSettingsInput as DafnyUpdateGlobalTableSettingsInput, + UpdateGlobalTableSettingsOutput_UpdateGlobalTableSettingsOutput as DafnyUpdateGlobalTableSettingsOutput, + UpdateItemInput_UpdateItemInput as DafnyUpdateItemInput, + UpdateItemOutput_UpdateItemOutput as DafnyUpdateItemOutput, + UpdateTableInput_UpdateTableInput as DafnyUpdateTableInput, + UpdateTableOutput_UpdateTableOutput as DafnyUpdateTableOutput, + UpdateTableReplicaAutoScalingInput_UpdateTableReplicaAutoScalingInput as DafnyUpdateTableReplicaAutoScalingInput, + UpdateTableReplicaAutoScalingOutput_UpdateTableReplicaAutoScalingOutput as DafnyUpdateTableReplicaAutoScalingOutput, + UpdateTimeToLiveInput_UpdateTimeToLiveInput as DafnyUpdateTimeToLiveInput, + UpdateTimeToLiveOutput_UpdateTimeToLiveOutput as DafnyUpdateTimeToLiveOutput, +) +import aws_cryptography_internal_dynamodb.internaldafny.generated.module_ +import aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny +import aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk + +from . import dafny_to_aws_sdk + + +import smithy_dafny_standard_library.internaldafny.generated.Wrappers as Wrappers +from botocore.exceptions import ClientError +import aws_cryptography_internal_dynamodb.internaldafny.generated.ComAmazonawsDynamodbTypes + + +def _sdk_error_to_dafny_error(e: ClientError): + """Converts the provided native Smithy-modelled error into the + corresponding Dafny error.""" + if e.response["Error"]["Code"] == "BackupInUseException": + return aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_BackupInUseException( + e.response + ) + + elif e.response["Error"]["Code"] == "BackupNotFoundException": + return aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_BackupNotFoundException( + e.response + ) + + elif e.response["Error"]["Code"] == "ConditionalCheckFailedException": + return aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ConditionalCheckFailedException( + e.response + ) + + elif e.response["Error"]["Code"] == "ContinuousBackupsUnavailableException": + return aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ContinuousBackupsUnavailableException( + e.response + ) + + elif e.response["Error"]["Code"] == "DuplicateItemException": + return aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_DuplicateItemException( + e.response + ) + + elif e.response["Error"]["Code"] == "ExportConflictException": + return aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ExportConflictException( + e.response + ) + + elif e.response["Error"]["Code"] == "ExportNotFoundException": + return aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ExportNotFoundException( + e.response + ) + + elif e.response["Error"]["Code"] == "GlobalTableAlreadyExistsException": + return aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_GlobalTableAlreadyExistsException( + e.response + ) + + elif e.response["Error"]["Code"] == "GlobalTableNotFoundException": + return aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_GlobalTableNotFoundException( + e.response + ) + + elif e.response["Error"]["Code"] == "IdempotentParameterMismatchException": + return aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_IdempotentParameterMismatchException( + e.response + ) + + elif e.response["Error"]["Code"] == "ImportConflictException": + return aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ImportConflictException( + e.response + ) + + elif e.response["Error"]["Code"] == "ImportNotFoundException": + return aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ImportNotFoundException( + e.response + ) + + elif e.response["Error"]["Code"] == "IndexNotFoundException": + return aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_IndexNotFoundException( + e.response + ) + + elif e.response["Error"]["Code"] == "InternalServerError": + return aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_InternalServerError( + e.response + ) + + elif e.response["Error"]["Code"] == "InvalidEndpointException": + return aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_InvalidEndpointException( + e.response + ) + + elif e.response["Error"]["Code"] == "InvalidExportTimeException": + return aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_InvalidExportTimeException( + e.response + ) + + elif e.response["Error"]["Code"] == "InvalidRestoreTimeException": + return aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_InvalidRestoreTimeException( + e.response + ) + + elif e.response["Error"]["Code"] == "ItemCollectionSizeLimitExceededException": + return aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ItemCollectionSizeLimitExceededException( + e.response + ) + + elif e.response["Error"]["Code"] == "LimitExceededException": + return aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_LimitExceededException( + e.response + ) + + elif e.response["Error"]["Code"] == "PointInTimeRecoveryUnavailableException": + return aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_PointInTimeRecoveryUnavailableException( + e.response + ) + + elif e.response["Error"]["Code"] == "ProvisionedThroughputExceededException": + return aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ProvisionedThroughputExceededException( + e.response + ) + + elif e.response["Error"]["Code"] == "ReplicaAlreadyExistsException": + return aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ReplicaAlreadyExistsException( + e.response + ) + + elif e.response["Error"]["Code"] == "ReplicaNotFoundException": + return aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ReplicaNotFoundException( + e.response + ) + + elif e.response["Error"]["Code"] == "RequestLimitExceeded": + return aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_RequestLimitExceeded( + e.response + ) + + elif e.response["Error"]["Code"] == "ResourceInUseException": + return aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ResourceInUseException( + e.response + ) + + elif e.response["Error"]["Code"] == "ResourceNotFoundException": + return aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ResourceNotFoundException( + e.response + ) + + elif e.response["Error"]["Code"] == "TableAlreadyExistsException": + return aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_TableAlreadyExistsException( + e.response + ) + + elif e.response["Error"]["Code"] == "TableInUseException": + return aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_TableInUseException( + e.response + ) + + elif e.response["Error"]["Code"] == "TableNotFoundException": + return aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_TableNotFoundException( + e.response + ) + + elif e.response["Error"]["Code"] == "TransactionCanceledException": + return aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_TransactionCanceledException( + e.response + ) + + elif e.response["Error"]["Code"] == "TransactionConflictException": + return aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_TransactionConflictException( + e.response + ) + + elif e.response["Error"]["Code"] == "TransactionInProgressException": + return aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_TransactionInProgressException( + e.response + ) + + return aws_cryptography_internal_dynamodb.internaldafny.generated.ComAmazonawsDynamodbTypes.Error_Opaque( + obj=e + ) + + +class DynamoDBClientShim: + def __init__(self, _impl, _region): + self._impl = _impl + self._region = _region + + def BatchExecuteStatement( + self, input: DafnyBatchExecuteStatementInput + ) -> DafnyBatchExecuteStatementOutput: + boto_request_dict = aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_BatchExecuteStatementInput( + input + ) + try: + boto_response_dict = self._impl.batch_execute_statement(**boto_request_dict) + except ClientError as e: + return Wrappers.Result_Failure(_sdk_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_BatchExecuteStatementOutput( + boto_response_dict + ) + ) + + def BatchGetItem(self, input: DafnyBatchGetItemInput) -> DafnyBatchGetItemOutput: + boto_request_dict = aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_BatchGetItemInput( + input + ) + try: + boto_response_dict = self._impl.batch_get_item(**boto_request_dict) + except ClientError as e: + return Wrappers.Result_Failure(_sdk_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_BatchGetItemOutput( + boto_response_dict + ) + ) + + def BatchWriteItem( + self, input: DafnyBatchWriteItemInput + ) -> DafnyBatchWriteItemOutput: + boto_request_dict = aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_BatchWriteItemInput( + input + ) + try: + boto_response_dict = self._impl.batch_write_item(**boto_request_dict) + except ClientError as e: + return Wrappers.Result_Failure(_sdk_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_BatchWriteItemOutput( + boto_response_dict + ) + ) + + def CreateBackup(self, input: DafnyCreateBackupInput) -> DafnyCreateBackupOutput: + boto_request_dict = aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_CreateBackupInput( + input + ) + try: + boto_response_dict = self._impl.create_backup(**boto_request_dict) + except ClientError as e: + return Wrappers.Result_Failure(_sdk_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_CreateBackupOutput( + boto_response_dict + ) + ) + + def CreateGlobalTable( + self, input: DafnyCreateGlobalTableInput + ) -> DafnyCreateGlobalTableOutput: + boto_request_dict = aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_CreateGlobalTableInput( + input + ) + try: + boto_response_dict = self._impl.create_global_table(**boto_request_dict) + except ClientError as e: + return Wrappers.Result_Failure(_sdk_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_CreateGlobalTableOutput( + boto_response_dict + ) + ) + + def CreateTable(self, input: DafnyCreateTableInput) -> DafnyCreateTableOutput: + boto_request_dict = aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_CreateTableInput( + input + ) + try: + boto_response_dict = self._impl.create_table(**boto_request_dict) + except ClientError as e: + return Wrappers.Result_Failure(_sdk_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_CreateTableOutput( + boto_response_dict + ) + ) + + def DeleteBackup(self, input: DafnyDeleteBackupInput) -> DafnyDeleteBackupOutput: + boto_request_dict = aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_DeleteBackupInput( + input + ) + try: + boto_response_dict = self._impl.delete_backup(**boto_request_dict) + except ClientError as e: + return Wrappers.Result_Failure(_sdk_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_DeleteBackupOutput( + boto_response_dict + ) + ) + + def DeleteItem(self, input: DafnyDeleteItemInput) -> DafnyDeleteItemOutput: + boto_request_dict = aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_DeleteItemInput( + input + ) + try: + boto_response_dict = self._impl.delete_item(**boto_request_dict) + except ClientError as e: + return Wrappers.Result_Failure(_sdk_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_DeleteItemOutput( + boto_response_dict + ) + ) + + def DeleteTable(self, input: DafnyDeleteTableInput) -> DafnyDeleteTableOutput: + boto_request_dict = aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_DeleteTableInput( + input + ) + try: + boto_response_dict = self._impl.delete_table(**boto_request_dict) + except ClientError as e: + return Wrappers.Result_Failure(_sdk_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_DeleteTableOutput( + boto_response_dict + ) + ) + + def DescribeBackup( + self, input: DafnyDescribeBackupInput + ) -> DafnyDescribeBackupOutput: + boto_request_dict = aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_DescribeBackupInput( + input + ) + try: + boto_response_dict = self._impl.describe_backup(**boto_request_dict) + except ClientError as e: + return Wrappers.Result_Failure(_sdk_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_DescribeBackupOutput( + boto_response_dict + ) + ) + + def DescribeContinuousBackups( + self, input: DafnyDescribeContinuousBackupsInput + ) -> DafnyDescribeContinuousBackupsOutput: + boto_request_dict = aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_DescribeContinuousBackupsInput( + input + ) + try: + boto_response_dict = self._impl.describe_continuous_backups( + **boto_request_dict + ) + except ClientError as e: + return Wrappers.Result_Failure(_sdk_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_DescribeContinuousBackupsOutput( + boto_response_dict + ) + ) + + def DescribeContributorInsights( + self, input: DafnyDescribeContributorInsightsInput + ) -> DafnyDescribeContributorInsightsOutput: + boto_request_dict = aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_DescribeContributorInsightsInput( + input + ) + try: + boto_response_dict = self._impl.describe_contributor_insights( + **boto_request_dict + ) + except ClientError as e: + return Wrappers.Result_Failure(_sdk_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_DescribeContributorInsightsOutput( + boto_response_dict + ) + ) + + def DescribeEndpoints( + self, input: DafnyDescribeEndpointsRequest + ) -> DafnyDescribeEndpointsResponse: + boto_request_dict = aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_DescribeEndpointsRequest( + input + ) + try: + boto_response_dict = self._impl.describe_endpoints(**boto_request_dict) + except ClientError as e: + return Wrappers.Result_Failure(_sdk_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_DescribeEndpointsResponse( + boto_response_dict + ) + ) + + def DescribeExport( + self, input: DafnyDescribeExportInput + ) -> DafnyDescribeExportOutput: + boto_request_dict = aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_DescribeExportInput( + input + ) + try: + boto_response_dict = self._impl.describe_export(**boto_request_dict) + except ClientError as e: + return Wrappers.Result_Failure(_sdk_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_DescribeExportOutput( + boto_response_dict + ) + ) + + def DescribeGlobalTable( + self, input: DafnyDescribeGlobalTableInput + ) -> DafnyDescribeGlobalTableOutput: + boto_request_dict = aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_DescribeGlobalTableInput( + input + ) + try: + boto_response_dict = self._impl.describe_global_table(**boto_request_dict) + except ClientError as e: + return Wrappers.Result_Failure(_sdk_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_DescribeGlobalTableOutput( + boto_response_dict + ) + ) + + def DescribeGlobalTableSettings( + self, input: DafnyDescribeGlobalTableSettingsInput + ) -> DafnyDescribeGlobalTableSettingsOutput: + boto_request_dict = aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_DescribeGlobalTableSettingsInput( + input + ) + try: + boto_response_dict = self._impl.describe_global_table_settings( + **boto_request_dict + ) + except ClientError as e: + return Wrappers.Result_Failure(_sdk_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_DescribeGlobalTableSettingsOutput( + boto_response_dict + ) + ) + + def DescribeImport( + self, input: DafnyDescribeImportInput + ) -> DafnyDescribeImportOutput: + boto_request_dict = aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_DescribeImportInput( + input + ) + try: + boto_response_dict = self._impl.describe_import(**boto_request_dict) + except ClientError as e: + return Wrappers.Result_Failure(_sdk_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_DescribeImportOutput( + boto_response_dict + ) + ) + + def DescribeKinesisStreamingDestination( + self, input: DafnyDescribeKinesisStreamingDestinationInput + ) -> DafnyDescribeKinesisStreamingDestinationOutput: + boto_request_dict = aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_DescribeKinesisStreamingDestinationInput( + input + ) + try: + boto_response_dict = self._impl.describe_kinesis_streaming_destination( + **boto_request_dict + ) + except ClientError as e: + return Wrappers.Result_Failure(_sdk_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_DescribeKinesisStreamingDestinationOutput( + boto_response_dict + ) + ) + + def DescribeLimits( + self, input: DafnyDescribeLimitsInput + ) -> DafnyDescribeLimitsOutput: + boto_request_dict = aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_DescribeLimitsInput( + input + ) + try: + boto_response_dict = self._impl.describe_limits(**boto_request_dict) + except ClientError as e: + return Wrappers.Result_Failure(_sdk_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_DescribeLimitsOutput( + boto_response_dict + ) + ) + + def DescribeTable(self, input: DafnyDescribeTableInput) -> DafnyDescribeTableOutput: + boto_request_dict = aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_DescribeTableInput( + input + ) + try: + boto_response_dict = self._impl.describe_table(**boto_request_dict) + except ClientError as e: + return Wrappers.Result_Failure(_sdk_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_DescribeTableOutput( + boto_response_dict + ) + ) + + def DescribeTableReplicaAutoScaling( + self, input: DafnyDescribeTableReplicaAutoScalingInput + ) -> DafnyDescribeTableReplicaAutoScalingOutput: + boto_request_dict = aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_DescribeTableReplicaAutoScalingInput( + input + ) + try: + boto_response_dict = self._impl.describe_table_replica_auto_scaling( + **boto_request_dict + ) + except ClientError as e: + return Wrappers.Result_Failure(_sdk_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_DescribeTableReplicaAutoScalingOutput( + boto_response_dict + ) + ) + + def DescribeTimeToLive( + self, input: DafnyDescribeTimeToLiveInput + ) -> DafnyDescribeTimeToLiveOutput: + boto_request_dict = aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_DescribeTimeToLiveInput( + input + ) + try: + boto_response_dict = self._impl.describe_time_to_live(**boto_request_dict) + except ClientError as e: + return Wrappers.Result_Failure(_sdk_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_DescribeTimeToLiveOutput( + boto_response_dict + ) + ) + + def DisableKinesisStreamingDestination( + self, input: DafnyDisableKinesisStreamingDestinationInput + ) -> DafnyDisableKinesisStreamingDestinationOutput: + boto_request_dict = aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_DisableKinesisStreamingDestinationInput( + input + ) + try: + boto_response_dict = self._impl.disable_kinesis_streaming_destination( + **boto_request_dict + ) + except ClientError as e: + return Wrappers.Result_Failure(_sdk_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_DisableKinesisStreamingDestinationOutput( + boto_response_dict + ) + ) + + def EnableKinesisStreamingDestination( + self, input: DafnyEnableKinesisStreamingDestinationInput + ) -> DafnyEnableKinesisStreamingDestinationOutput: + boto_request_dict = aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_EnableKinesisStreamingDestinationInput( + input + ) + try: + boto_response_dict = self._impl.enable_kinesis_streaming_destination( + **boto_request_dict + ) + except ClientError as e: + return Wrappers.Result_Failure(_sdk_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_EnableKinesisStreamingDestinationOutput( + boto_response_dict + ) + ) + + def ExecuteStatement( + self, input: DafnyExecuteStatementInput + ) -> DafnyExecuteStatementOutput: + boto_request_dict = aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ExecuteStatementInput( + input + ) + try: + boto_response_dict = self._impl.execute_statement(**boto_request_dict) + except ClientError as e: + return Wrappers.Result_Failure(_sdk_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ExecuteStatementOutput( + boto_response_dict + ) + ) + + def ExecuteTransaction( + self, input: DafnyExecuteTransactionInput + ) -> DafnyExecuteTransactionOutput: + boto_request_dict = aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ExecuteTransactionInput( + input + ) + try: + boto_response_dict = self._impl.execute_transaction(**boto_request_dict) + except ClientError as e: + return Wrappers.Result_Failure(_sdk_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ExecuteTransactionOutput( + boto_response_dict + ) + ) + + def ExportTableToPointInTime( + self, input: DafnyExportTableToPointInTimeInput + ) -> DafnyExportTableToPointInTimeOutput: + boto_request_dict = aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ExportTableToPointInTimeInput( + input + ) + try: + boto_response_dict = self._impl.export_table_to_point_in_time( + **boto_request_dict + ) + except ClientError as e: + return Wrappers.Result_Failure(_sdk_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ExportTableToPointInTimeOutput( + boto_response_dict + ) + ) + + def GetItem(self, input: DafnyGetItemInput) -> DafnyGetItemOutput: + boto_request_dict = aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_GetItemInput( + input + ) + try: + boto_response_dict = self._impl.get_item(**boto_request_dict) + except ClientError as e: + return Wrappers.Result_Failure(_sdk_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_GetItemOutput( + boto_response_dict + ) + ) + + def ImportTable(self, input: DafnyImportTableInput) -> DafnyImportTableOutput: + boto_request_dict = aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ImportTableInput( + input + ) + try: + boto_response_dict = self._impl.import_table(**boto_request_dict) + except ClientError as e: + return Wrappers.Result_Failure(_sdk_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ImportTableOutput( + boto_response_dict + ) + ) + + def ListBackups(self, input: DafnyListBackupsInput) -> DafnyListBackupsOutput: + boto_request_dict = aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ListBackupsInput( + input + ) + try: + boto_response_dict = self._impl.list_backups(**boto_request_dict) + except ClientError as e: + return Wrappers.Result_Failure(_sdk_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ListBackupsOutput( + boto_response_dict + ) + ) + + def ListContributorInsights( + self, input: DafnyListContributorInsightsInput + ) -> DafnyListContributorInsightsOutput: + boto_request_dict = aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ListContributorInsightsInput( + input + ) + try: + boto_response_dict = self._impl.list_contributor_insights( + **boto_request_dict + ) + except ClientError as e: + return Wrappers.Result_Failure(_sdk_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ListContributorInsightsOutput( + boto_response_dict + ) + ) + + def ListExports(self, input: DafnyListExportsInput) -> DafnyListExportsOutput: + boto_request_dict = aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ListExportsInput( + input + ) + try: + boto_response_dict = self._impl.list_exports(**boto_request_dict) + except ClientError as e: + return Wrappers.Result_Failure(_sdk_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ListExportsOutput( + boto_response_dict + ) + ) + + def ListGlobalTables( + self, input: DafnyListGlobalTablesInput + ) -> DafnyListGlobalTablesOutput: + boto_request_dict = aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ListGlobalTablesInput( + input + ) + try: + boto_response_dict = self._impl.list_global_tables(**boto_request_dict) + except ClientError as e: + return Wrappers.Result_Failure(_sdk_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ListGlobalTablesOutput( + boto_response_dict + ) + ) + + def ListImports(self, input: DafnyListImportsInput) -> DafnyListImportsOutput: + boto_request_dict = aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ListImportsInput( + input + ) + try: + boto_response_dict = self._impl.list_imports(**boto_request_dict) + except ClientError as e: + return Wrappers.Result_Failure(_sdk_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ListImportsOutput( + boto_response_dict + ) + ) + + def ListTables(self, input: DafnyListTablesInput) -> DafnyListTablesOutput: + boto_request_dict = aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ListTablesInput( + input + ) + try: + boto_response_dict = self._impl.list_tables(**boto_request_dict) + except ClientError as e: + return Wrappers.Result_Failure(_sdk_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ListTablesOutput( + boto_response_dict + ) + ) + + def ListTagsOfResource( + self, input: DafnyListTagsOfResourceInput + ) -> DafnyListTagsOfResourceOutput: + boto_request_dict = aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ListTagsOfResourceInput( + input + ) + try: + boto_response_dict = self._impl.list_tags_of_resource(**boto_request_dict) + except ClientError as e: + return Wrappers.Result_Failure(_sdk_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ListTagsOfResourceOutput( + boto_response_dict + ) + ) + + def PutItem(self, input: DafnyPutItemInput) -> DafnyPutItemOutput: + boto_request_dict = aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_PutItemInput( + input + ) + try: + boto_response_dict = self._impl.put_item(**boto_request_dict) + except ClientError as e: + return Wrappers.Result_Failure(_sdk_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_PutItemOutput( + boto_response_dict + ) + ) + + def Query(self, input: DafnyQueryInput) -> DafnyQueryOutput: + boto_request_dict = aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_QueryInput( + input + ) + try: + boto_response_dict = self._impl.query(**boto_request_dict) + except ClientError as e: + return Wrappers.Result_Failure(_sdk_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_QueryOutput( + boto_response_dict + ) + ) + + def RestoreTableFromBackup( + self, input: DafnyRestoreTableFromBackupInput + ) -> DafnyRestoreTableFromBackupOutput: + boto_request_dict = aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_RestoreTableFromBackupInput( + input + ) + try: + boto_response_dict = self._impl.restore_table_from_backup( + **boto_request_dict + ) + except ClientError as e: + return Wrappers.Result_Failure(_sdk_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_RestoreTableFromBackupOutput( + boto_response_dict + ) + ) + + def RestoreTableToPointInTime( + self, input: DafnyRestoreTableToPointInTimeInput + ) -> DafnyRestoreTableToPointInTimeOutput: + boto_request_dict = aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_RestoreTableToPointInTimeInput( + input + ) + try: + boto_response_dict = self._impl.restore_table_to_point_in_time( + **boto_request_dict + ) + except ClientError as e: + return Wrappers.Result_Failure(_sdk_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_RestoreTableToPointInTimeOutput( + boto_response_dict + ) + ) + + def Scan(self, input: DafnyScanInput) -> DafnyScanOutput: + boto_request_dict = aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_ScanInput( + input + ) + try: + boto_response_dict = self._impl.scan(**boto_request_dict) + except ClientError as e: + return Wrappers.Result_Failure(_sdk_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_ScanOutput( + boto_response_dict + ) + ) + + def TagResource(self, input: DafnyTagResourceInput) -> None: + boto_request_dict = aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_TagResourceInput( + input + ) + try: + boto_response_dict = self._impl.tag_resource(**boto_request_dict) + except ClientError as e: + return Wrappers.Result_Failure(_sdk_error_to_dafny_error(e)) + + return Wrappers.Result_Success(None) + + def TransactGetItems( + self, input: DafnyTransactGetItemsInput + ) -> DafnyTransactGetItemsOutput: + boto_request_dict = aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_TransactGetItemsInput( + input + ) + try: + boto_response_dict = self._impl.transact_get_items(**boto_request_dict) + except ClientError as e: + return Wrappers.Result_Failure(_sdk_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_TransactGetItemsOutput( + boto_response_dict + ) + ) + + def TransactWriteItems( + self, input: DafnyTransactWriteItemsInput + ) -> DafnyTransactWriteItemsOutput: + boto_request_dict = aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_TransactWriteItemsInput( + input + ) + try: + boto_response_dict = self._impl.transact_write_items(**boto_request_dict) + except ClientError as e: + return Wrappers.Result_Failure(_sdk_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_TransactWriteItemsOutput( + boto_response_dict + ) + ) + + def UntagResource(self, input: DafnyUntagResourceInput) -> None: + boto_request_dict = aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_UntagResourceInput( + input + ) + try: + boto_response_dict = self._impl.untag_resource(**boto_request_dict) + except ClientError as e: + return Wrappers.Result_Failure(_sdk_error_to_dafny_error(e)) + + return Wrappers.Result_Success(None) + + def UpdateContinuousBackups( + self, input: DafnyUpdateContinuousBackupsInput + ) -> DafnyUpdateContinuousBackupsOutput: + boto_request_dict = aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_UpdateContinuousBackupsInput( + input + ) + try: + boto_response_dict = self._impl.update_continuous_backups( + **boto_request_dict + ) + except ClientError as e: + return Wrappers.Result_Failure(_sdk_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_UpdateContinuousBackupsOutput( + boto_response_dict + ) + ) + + def UpdateContributorInsights( + self, input: DafnyUpdateContributorInsightsInput + ) -> DafnyUpdateContributorInsightsOutput: + boto_request_dict = aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_UpdateContributorInsightsInput( + input + ) + try: + boto_response_dict = self._impl.update_contributor_insights( + **boto_request_dict + ) + except ClientError as e: + return Wrappers.Result_Failure(_sdk_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_UpdateContributorInsightsOutput( + boto_response_dict + ) + ) + + def UpdateGlobalTable( + self, input: DafnyUpdateGlobalTableInput + ) -> DafnyUpdateGlobalTableOutput: + boto_request_dict = aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_UpdateGlobalTableInput( + input + ) + try: + boto_response_dict = self._impl.update_global_table(**boto_request_dict) + except ClientError as e: + return Wrappers.Result_Failure(_sdk_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_UpdateGlobalTableOutput( + boto_response_dict + ) + ) + + def UpdateGlobalTableSettings( + self, input: DafnyUpdateGlobalTableSettingsInput + ) -> DafnyUpdateGlobalTableSettingsOutput: + boto_request_dict = aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_UpdateGlobalTableSettingsInput( + input + ) + try: + boto_response_dict = self._impl.update_global_table_settings( + **boto_request_dict + ) + except ClientError as e: + return Wrappers.Result_Failure(_sdk_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_UpdateGlobalTableSettingsOutput( + boto_response_dict + ) + ) + + def UpdateItem(self, input: DafnyUpdateItemInput) -> DafnyUpdateItemOutput: + boto_request_dict = aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_UpdateItemInput( + input + ) + try: + boto_response_dict = self._impl.update_item(**boto_request_dict) + except ClientError as e: + return Wrappers.Result_Failure(_sdk_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_UpdateItemOutput( + boto_response_dict + ) + ) + + def UpdateTable(self, input: DafnyUpdateTableInput) -> DafnyUpdateTableOutput: + boto_request_dict = aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_UpdateTableInput( + input + ) + try: + boto_response_dict = self._impl.update_table(**boto_request_dict) + except ClientError as e: + return Wrappers.Result_Failure(_sdk_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_UpdateTableOutput( + boto_response_dict + ) + ) + + def UpdateTableReplicaAutoScaling( + self, input: DafnyUpdateTableReplicaAutoScalingInput + ) -> DafnyUpdateTableReplicaAutoScalingOutput: + boto_request_dict = aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_UpdateTableReplicaAutoScalingInput( + input + ) + try: + boto_response_dict = self._impl.update_table_replica_auto_scaling( + **boto_request_dict + ) + except ClientError as e: + return Wrappers.Result_Failure(_sdk_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_UpdateTableReplicaAutoScalingOutput( + boto_response_dict + ) + ) + + def UpdateTimeToLive( + self, input: DafnyUpdateTimeToLiveInput + ) -> DafnyUpdateTimeToLiveOutput: + boto_request_dict = aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.dafny_to_aws_sdk.com_amazonaws_dynamodb_UpdateTimeToLiveInput( + input + ) + try: + boto_response_dict = self._impl.update_time_to_live(**boto_request_dict) + except ClientError as e: + return Wrappers.Result_Failure(_sdk_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptography_internal_dynamodb.smithygenerated.com_amazonaws_dynamodb.aws_sdk_to_dafny.com_amazonaws_dynamodb_UpdateTimeToLiveOutput( + boto_response_dict + ) + ) diff --git a/ComAmazonawsDynamodb/runtimes/python/test/__init__.py b/ComAmazonawsDynamodb/runtimes/python/test/__init__.py new file mode 100644 index 000000000..f94fd12a2 --- /dev/null +++ b/ComAmazonawsDynamodb/runtimes/python/test/__init__.py @@ -0,0 +1,2 @@ +# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 diff --git a/ComAmazonawsDynamodb/runtimes/python/test/internaldafny/__init__.py b/ComAmazonawsDynamodb/runtimes/python/test/internaldafny/__init__.py new file mode 100644 index 000000000..f94fd12a2 --- /dev/null +++ b/ComAmazonawsDynamodb/runtimes/python/test/internaldafny/__init__.py @@ -0,0 +1,2 @@ +# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 diff --git a/ComAmazonawsDynamodb/runtimes/python/test/internaldafny/test_dafny_wrapper.py b/ComAmazonawsDynamodb/runtimes/python/test/internaldafny/test_dafny_wrapper.py new file mode 100644 index 000000000..6622cc3c3 --- /dev/null +++ b/ComAmazonawsDynamodb/runtimes/python/test/internaldafny/test_dafny_wrapper.py @@ -0,0 +1,19 @@ +# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 +""" +Wrapper file for executing Dafny tests from pytest. +This allows us to import modules required by Dafny-generated tests +before executing Dafny-generated tests. +pytest will find and execute the `test_dafny` method below, +which will execute the `internaldafny_test_executor.py` file in the `dafny` directory. +""" + +import sys + +internaldafny_dir = '/'.join(__file__.split("/")[:-1]) + +sys.path.append(internaldafny_dir + "/extern") +sys.path.append(internaldafny_dir + "/generated") + +def test_dafny(): + from .generated import __main__ \ No newline at end of file diff --git a/ComAmazonawsDynamodb/runtimes/python/tox.ini b/ComAmazonawsDynamodb/runtimes/python/tox.ini new file mode 100644 index 000000000..5e6bbcb9d --- /dev/null +++ b/ComAmazonawsDynamodb/runtimes/python/tox.ini @@ -0,0 +1,86 @@ +[tox] +isolated_build = True +envlist = + py{311,312}-{dafnytests} + +[testenv:base-command] +commands = poetry run pytest -l {posargs} + +[testenv] +skip_install = True +allowlist_externals = poetry +passenv = AWS_* +commands_pre = + poetry lock + poetry install --with test +commands = + dafnytests: {[testenv:base-command]commands} test/internaldafny -s -v + +# Release tooling +[testenv:build] +basepython = python3 +skip_install = True +allowlist_externals = poetry +commands = + poetry install --no-root --with release + poetry build + +[testenv:release-base] +basepython = python3 +skip_install = True +allowlist_externals = poetry +comands_pre = + poetry install --no-root --with release +passenv = + # Intentionally omit TWINE_REPOSITORY_URL from the passenv list, + # as this overrides other ways of setting the repository and could + # unexpectedly result in releasing to the wrong repo + {[testenv]passenv} \ + TWINE_USERNAME \ + TWINE_PASSWORD +commands = + {[testenv:build]commands} + +[testenv:release-private] +basepython = python3 +skip_install = True +allowlist_externals = poetry +comands_pre = + poetry install --no-root --with release +passenv = + {[testenv:release-base]passenv} \ + TWINE_REPOSITORY_URL +setenv = + # Explicitly set the URL as the env variable value, which will cause us to + # throw an error if the variable is not set. Otherwise, omission of the + # env variable could cause us to unintentionally upload to the wrong repo + TWINE_REPOSITORY_URL = {env:TWINE_REPOSITORY_URL} +commands = + {[testenv:release-base]commands} + # Omitting an explicit repository will cause twine to use the repository + # specified in the environment variable + poetry run twine upload --skip-existing {toxinidir}/dist/* + +[testenv:test-release] +basepython = python3 +skip_install = True +allowlist_externals = poetry +comands_pre = + poetry install --no-root --with release +passenv = + {[testenv:release-base]passenv} +commands = + {[testenv:release-base]commands} + poetry run twine upload --skip-existing --repository testpypi {toxinidir}/dist/* + +[testenv:release] +basepython = python3 +skip_install = True +allowlist_externals = poetry +comands_pre = + poetry install --no-root --with release +passenv = + {[testenv:release-base]passenv} +commands = + {[testenv:release-base]commands} + poetry run twine upload --skip-existing --repository pypi {toxinidir}/dist/* diff --git a/ComAmazonawsKms/Makefile b/ComAmazonawsKms/Makefile index 3b9d392b6..628f52c98 100644 --- a/ComAmazonawsKms/Makefile +++ b/ComAmazonawsKms/Makefile @@ -3,6 +3,8 @@ CORES=2 +ENABLE_EXTERN_PROCESSING=1 + include ../SharedMakefileV2.mk PROJECT_SERVICES := \ @@ -14,3 +16,19 @@ AWS_SDK_CMD := --aws-sdk STD_LIBRARY=StandardLibrary SMITHY_DEPS=model +# Constants for languages that drop extern names (Python, Go) + +TYPES_FILE_PATH=Model/ComAmazonawsKmsTypes.dfy +TYPES_FILE_WITH_EXTERN_STRING="module {:extern \"software.amazon.cryptography.services.kms.internaldafny.types\" } ComAmazonawsKmsTypes" +TYPES_FILE_WITHOUT_EXTERN_STRING="module ComAmazonawsKmsTypes" + +INDEX_FILE_PATH=src/Index.dfy +INDEX_FILE_WITH_EXTERN_STRING="module {:extern \"software.amazon.cryptography.services.kms.internaldafny\"} Com.Amazonaws.Kms refines AbstractComAmazonawsKmsService {" +INDEX_FILE_WITHOUT_EXTERN_STRING="module Com.Amazonaws.Kms refines AbstractComAmazonawsKmsService {" + +# Python + +PYTHON_MODULE_NAME=aws_cryptography_internal_kms + +TRANSLATION_RECORD_PYTHON := \ + --translation-record ../StandardLibrary/runtimes/python/src/smithy_dafny_standard_library/internaldafny/generated/dafny_src-py.dtr diff --git a/ComAmazonawsKms/codebuild/release-python/prod-release.yml b/ComAmazonawsKms/codebuild/release-python/prod-release.yml new file mode 100644 index 000000000..fe24b6e55 --- /dev/null +++ b/ComAmazonawsKms/codebuild/release-python/prod-release.yml @@ -0,0 +1,63 @@ +version: 0.2 + +env: + variables: + BRANCH: "main" + secrets-manager: + TWINE_USERNAME: PyPiAPIToken:username + TWINE_PASSWORD: PyPiAPIToken:password + +phases: + install: + commands: + - pip install "tox < 4.0" + - pip install --upgrade pip + runtime-versions: + python: latest + pre_build: + commands: + # Get Dafny + - export dafnyVersion=$(grep '^dafnyVersion=' project.properties | cut -d '=' -f 2) + - cd .. + - curl https://github.com/dafny-lang/dafny/releases/download/v$dafnyVersion/dafny-$dafnyVersion-x64-ubuntu-20.04.zip -L -o dafny.zip + - unzip -qq dafny.zip && rm dafny.zip + - export PATH="$PWD/dafny:$PATH" + # Switch back to the main directory + - cd aws-cryptographic-material-providers-library + # Assert that project version is the expected released version + - git checkout $COMMIT_ID + - FOUND_VERSION=$(sed -n 's/version = "\(.*\)"/\1/p' ComAmazonawsKms/runtimes/python/pyproject.toml) + - | + if expr ${FOUND_VERSION} != ${VERSION}; then + echo "pyproject.toml version (${FOUND_VERSION}) does not match expected version (${VERSION}), stopping" + exit 1; + fi + - cd ComAmazonawsKms + # Build Dafny test source code + - make transpile_only_test_python + build: + commands: + - cd runtimes/python/ + # Install poetry + # https://python-poetry.org/docs/#installing-manually + - pip install poetry + # Install project dependencies with release dependencies + - poetry install --with release + # Build whl/sdist, upload to PyPI + # TODO: When ready to prod release, uncomment this line + # tox -e release + +batch: + fast-fail: true + build-graph: + - identifier: release_to_prod + env: + image: aws/codebuild/standard:7.0 + - identifier: validate_prod_release + depend-on: + - release_to_prod + buildspec: ComAmazonawsKms/codebuild/release-python/validate.yml + env: + variables: + PIP_INDEX_URL: https://pypi.python.org/simple/ + image: aws/codebuild/standard:7.0 diff --git a/ComAmazonawsKms/codebuild/release-python/test-release.yml b/ComAmazonawsKms/codebuild/release-python/test-release.yml new file mode 100644 index 000000000..8f4afe360 --- /dev/null +++ b/ComAmazonawsKms/codebuild/release-python/test-release.yml @@ -0,0 +1,65 @@ +version: 0.2 + +env: + variables: + BRANCH: "main" + secrets-manager: + TWINE_USERNAME: TestPyPiAPIToken:username + TWINE_PASSWORD: TestPyPiAPIToken:password + +phases: + install: + commands: + - pip install "tox < 4.0" + - pip install --upgrade pip + runtime-versions: + python: latest + pre_build: + commands: + # Get Dafny + - export dafnyVersion=$(grep '^dafnyVersion=' project.properties | cut -d '=' -f 2) + - cd .. + - curl https://github.com/dafny-lang/dafny/releases/download/v$dafnyVersion/dafny-$dafnyVersion-x64-ubuntu-20.04.zip -L -o dafny.zip + - unzip -qq dafny.zip && rm dafny.zip + - export PATH="$PWD/dafny:$PATH" + # Switch back to the main directory + - cd aws-cryptographic-material-providers-library + # Assert that project version is the expected released version + - git checkout $COMMIT_ID + - FOUND_VERSION=$(sed -n 's/version = "\(.*\)"/\1/p' ComAmazonawsKms/runtimes/python/pyproject.toml) + - | + if expr ${FOUND_VERSION} != ${VERSION}; then + echo "pyproject.toml version (${FOUND_VERSION}) does not match expected version (${VERSION}), stopping" + exit 1; + fi + - cd ComAmazonawsKms + # Build Dafny test source code + - make transpile_only_test_python + build: + commands: + - cd runtimes/python/ + # Install poetry + # https://python-poetry.org/docs/#installing-manually + - pip install poetry + # Add test PyPI as a supplemental repo for installing previously published test packages + - poetry source add --priority=supplemental test https://test.pypi.org/simple/ + # Install project dependencies with release dependencies + - poetry install --with release + # Build whl/sdist, upload to test PyPI + - tox -e test-release + +batch: + fast-fail: true + build-graph: + - identifier: release_to_staging + env: + image: aws/codebuild/standard:7.0 + - identifier: validate_staging_release + depend-on: + - release_to_staging + buildspec: ComAmazonawsKms/codebuild/release-python/validate.yml + env: + variables: + PIP_INDEX_URL: https://test.pypi.org/simple/ + PIP_EXTRA_INDEX_URL: https://pypi.python.org/simple/ + image: aws/codebuild/standard:7.0 diff --git a/ComAmazonawsKms/codebuild/release-python/validate.yml b/ComAmazonawsKms/codebuild/release-python/validate.yml new file mode 100644 index 000000000..985bfef7c --- /dev/null +++ b/ComAmazonawsKms/codebuild/release-python/validate.yml @@ -0,0 +1,46 @@ +version: 0.2 + +# Validate that the released artifact is usable +# by installing it from PyPI +# then running tests from source against the published artifact. + +phases: + install: + commands: + - pip install "tox < 4.0" + runtime-versions: + python: latest + pre_build: + commands: + # Get Dafny + - export dafnyVersion=$(grep '^dafnyVersion=' project.properties | cut -d '=' -f 2) + - cd .. + - curl https://github.com/dafny-lang/dafny/releases/download/v$dafnyVersion/dafny-$dafnyVersion-x64-ubuntu-20.04.zip -L -o dafny.zip + - unzip -qq dafny.zip && rm dafny.zip + - export PATH="$PWD/dafny:$PATH" + # Switch back to the main directory + - cd aws-cryptographic-material-providers-library + # Install test dependencies + - pyenv install --skip-existing 3.11 + - pyenv local 3.11 + - pip install "tox < 4.0" + - pip install pytest + # Install the published artifact from PyPI. + # The tests will use the installed package, not the local code. + # The actual test code must be from local, since we don't publish tests. + - pip install aws-cryptography-internal-kms==$VERSION + # Get CI Creds to be able to call KMS + - TMP_ROLE=$(aws sts assume-role --role-arn "arn:aws:iam::370957321024:role/GitHub-CI-MPL-Dafny-Role-us-west-2" --role-session-name "MPL-Python-Release") + - export TMP_ROLE + - export AWS_ACCESS_KEY_ID=$(echo "${TMP_ROLE}" | jq -r '.Credentials.AccessKeyId') + - export AWS_SECRET_ACCESS_KEY=$(echo "${TMP_ROLE}" | jq -r '.Credentials.SecretAccessKey') + - export AWS_SESSION_TOKEN=$(echo "${TMP_ROLE}" | jq -r '.Credentials.SessionToken') + - aws sts get-caller-identity + build: + commands: + - NUM_RETRIES=3 + - cd ComAmazonawsKms + # Transpile code (for tests) + - make transpile_python + - cd runtimes/python + - python -m pytest test/ -s -v diff --git a/ComAmazonawsKms/runtimes/python/.gitignore b/ComAmazonawsKms/runtimes/python/.gitignore new file mode 100644 index 000000000..9cb72dcab --- /dev/null +++ b/ComAmazonawsKms/runtimes/python/.gitignore @@ -0,0 +1,16 @@ +# Python build artifacts +__pycache__ +**/__pycache__ +*.pyc +src/**.egg-info/ +build +poetry.lock +**/poetry.lock +dist + +# Dafny-generated Python +**/internaldafny/generated/*.py + +# Python test artifacts +.tox +.pytest_cache diff --git a/ComAmazonawsKms/runtimes/python/pyproject.toml b/ComAmazonawsKms/runtimes/python/pyproject.toml new file mode 100644 index 000000000..c01185c18 --- /dev/null +++ b/ComAmazonawsKms/runtimes/python/pyproject.toml @@ -0,0 +1,38 @@ +[tool.poetry] +name = "aws-cryptography-internal-kms" +version = "0.1.0" +description = "" +authors = ["AWS Crypto Tools "] +packages = [ + { include = "aws_cryptography_internal_kms", from = "src" } +] +# Include generated internaldafny files in package distributions, +# even though they are not included in version control +include = ["**/internaldafny/generated/*.py"] + +[tool.poetry.dependencies] +python = "^3.11.0" +boto3 = "^1.28.38" +aws-cryptography-internal-standard-library = {path = "../../../StandardLibrary/runtimes/python"} + +# Package testing + +[tool.poetry.group.test] +optional = true + +[tool.poetry.group.test.dependencies] +pytest = "^7.4.0" + +# Package release + +[tool.poetry.group.release] +optional = true + +[tool.poetry.group.release.dependencies] +poetry = "1.8.3" +twine = "5.1.1" +wheel = "0.38.4" + +[build-system] +requires = ["poetry-core"] +build-backend = "poetry.core.masonry.api" diff --git a/ComAmazonawsKms/runtimes/python/src/aws_cryptography_internal_kms/__init__.py b/ComAmazonawsKms/runtimes/python/src/aws_cryptography_internal_kms/__init__.py new file mode 100644 index 000000000..b9427e19d --- /dev/null +++ b/ComAmazonawsKms/runtimes/python/src/aws_cryptography_internal_kms/__init__.py @@ -0,0 +1,8 @@ +# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 + +# Initialize generated Dafny +from .internaldafny.generated import module_ + +# Initialize externs +from .internaldafny import extern diff --git a/ComAmazonawsKms/runtimes/python/src/aws_cryptography_internal_kms/internaldafny/extern/Com_Amazonaws_Kms.py b/ComAmazonawsKms/runtimes/python/src/aws_cryptography_internal_kms/internaldafny/extern/Com_Amazonaws_Kms.py new file mode 100644 index 000000000..16127204d --- /dev/null +++ b/ComAmazonawsKms/runtimes/python/src/aws_cryptography_internal_kms/internaldafny/extern/Com_Amazonaws_Kms.py @@ -0,0 +1,60 @@ +import boto3 +import _dafny + +from botocore.config import Config +from boto3.session import Session + +from smithy_dafny_standard_library.internaldafny.generated.Wrappers import Option_Some +from aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.shim import KMSClientShim +from aws_cryptography_internal_kms.internaldafny.generated.Com_Amazonaws_Kms import * +import aws_cryptography_internal_kms.internaldafny.generated.Com_Amazonaws_Kms + + +# Persist this across calls; this doesn't change +available_aws_regions: list[str] = None + +def get_available_aws_regions(): + global available_aws_regions + if available_aws_regions is not None: + return available_aws_regions + available_aws_regions = Session().get_available_regions("kms") + return available_aws_regions + +class default__(aws_cryptography_internal_kms.internaldafny.generated.Com_Amazonaws_Kms.default__): + @staticmethod + def KMSClient(boto_client = None, region = None): + if boto_client is None: + if region is not None and region in get_available_aws_regions(): + boto_config = Config( + region_name=region + ) + boto_client = boto3.client("kms", config=boto_config) + else: + # If no region is provided, + # boto_client will use the default region provided by boto3 + boto_client = boto3.client("kms") + region = boto_client.meta.region_name + wrapped_client = KMSClientShim(boto_client, region) + return Wrappers.Result_Success(wrapped_client) + + @staticmethod + def KMSClientForRegion(region: _dafny.Seq): + region_string = _dafny.string_of(region) + return default__.KMSClient(region=region_string) + + @staticmethod + def RegionMatch(client, region): + # We should never be passing anything other than Shim as the 'client'. + # If this assertion fails, that indicates that there is something wrong with + # our code generation. + try: + assert isinstance(client, KMSClientShim) + except AssertionError: + raise TypeError("Client provided to RegionMatch is not a KMSClientShim: " + client) + + # Since client is a KMSClientShim, we can reach into its _impl, which is a boto3 client, + # then into the client's .meta.region_name attribute + client_region_name = client._impl.meta.region_name + return Option_Some(region.VerbatimString(False) == client_region_name) + +aws_cryptography_internal_kms.internaldafny.generated.Com_Amazonaws_Kms.default__ = default__ diff --git a/ComAmazonawsKms/runtimes/python/src/aws_cryptography_internal_kms/internaldafny/extern/__init__.py b/ComAmazonawsKms/runtimes/python/src/aws_cryptography_internal_kms/internaldafny/extern/__init__.py new file mode 100644 index 000000000..396e3164c --- /dev/null +++ b/ComAmazonawsKms/runtimes/python/src/aws_cryptography_internal_kms/internaldafny/extern/__init__.py @@ -0,0 +1,3 @@ +from . import ( + Com_Amazonaws_Kms, +) \ No newline at end of file diff --git a/ComAmazonawsKms/runtimes/python/src/aws_cryptography_internal_kms/internaldafny/generated/dafny_src-py.dtr b/ComAmazonawsKms/runtimes/python/src/aws_cryptography_internal_kms/internaldafny/generated/dafny_src-py.dtr new file mode 100644 index 000000000..17f4d6fd5 --- /dev/null +++ b/ComAmazonawsKms/runtimes/python/src/aws_cryptography_internal_kms/internaldafny/generated/dafny_src-py.dtr @@ -0,0 +1,14 @@ +file_format_version = "1.0" +dafny_version = "4.8.0.0" +[options_by_module.ComAmazonawsKmsTypes] +legacy-module-names = false +python-module-name = "aws_cryptography_internal_kms.internaldafny.generated" +[options_by_module.AbstractComAmazonawsKmsService] +legacy-module-names = false +python-module-name = "aws_cryptography_internal_kms.internaldafny.generated" +[options_by_module.AbstractComAmazonawsKmsOperations] +legacy-module-names = false +python-module-name = "aws_cryptography_internal_kms.internaldafny.generated" +[options_by_module."Com.Amazonaws.Kms"] +legacy-module-names = false +python-module-name = "aws_cryptography_internal_kms.internaldafny.generated" diff --git a/ComAmazonawsKms/runtimes/python/src/aws_cryptography_internal_kms/smithygenerated/com_amazonaws_kms/__init__.py b/ComAmazonawsKms/runtimes/python/src/aws_cryptography_internal_kms/smithygenerated/com_amazonaws_kms/__init__.py new file mode 100644 index 000000000..09be6133b --- /dev/null +++ b/ComAmazonawsKms/runtimes/python/src/aws_cryptography_internal_kms/smithygenerated/com_amazonaws_kms/__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/ComAmazonawsKms/runtimes/python/src/aws_cryptography_internal_kms/smithygenerated/com_amazonaws_kms/aws_sdk_to_dafny.py b/ComAmazonawsKms/runtimes/python/src/aws_cryptography_internal_kms/smithygenerated/com_amazonaws_kms/aws_sdk_to_dafny.py new file mode 100644 index 000000000..71af58dff --- /dev/null +++ b/ComAmazonawsKms/runtimes/python/src/aws_cryptography_internal_kms/smithygenerated/com_amazonaws_kms/aws_sdk_to_dafny.py @@ -0,0 +1,6363 @@ +# 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 _dafny import Map, Seq +from aws_cryptography_internal_kms.internaldafny.generated.ComAmazonawsKmsTypes import ( + AlgorithmSpec_RSAES__OAEP__SHA__1, + AlgorithmSpec_RSAES__OAEP__SHA__256, + AlgorithmSpec_RSAES__PKCS1__V1__5, + AlgorithmSpec_RSA__AES__KEY__WRAP__SHA__1, + AlgorithmSpec_RSA__AES__KEY__WRAP__SHA__256, + AlgorithmSpec_SM2PKE, + AliasListEntry_AliasListEntry as DafnyAliasListEntry, + CancelKeyDeletionRequest_CancelKeyDeletionRequest as DafnyCancelKeyDeletionRequest, + CancelKeyDeletionResponse_CancelKeyDeletionResponse as DafnyCancelKeyDeletionResponse, + ConnectCustomKeyStoreRequest_ConnectCustomKeyStoreRequest as DafnyConnectCustomKeyStoreRequest, + ConnectCustomKeyStoreResponse_ConnectCustomKeyStoreResponse as DafnyConnectCustomKeyStoreResponse, + ConnectionErrorCodeType_CLUSTER__NOT__FOUND, + ConnectionErrorCodeType_INSUFFICIENT__CLOUDHSM__HSMS, + ConnectionErrorCodeType_INSUFFICIENT__FREE__ADDRESSES__IN__SUBNET, + ConnectionErrorCodeType_INTERNAL__ERROR, + ConnectionErrorCodeType_INVALID__CREDENTIALS, + ConnectionErrorCodeType_NETWORK__ERRORS, + ConnectionErrorCodeType_SUBNET__NOT__FOUND, + ConnectionErrorCodeType_USER__LOCKED__OUT, + ConnectionErrorCodeType_USER__LOGGED__IN, + ConnectionErrorCodeType_USER__NOT__FOUND, + ConnectionErrorCodeType_XKS__PROXY__ACCESS__DENIED, + ConnectionErrorCodeType_XKS__PROXY__INVALID__CONFIGURATION, + ConnectionErrorCodeType_XKS__PROXY__INVALID__RESPONSE, + ConnectionErrorCodeType_XKS__PROXY__INVALID__TLS__CONFIGURATION, + ConnectionErrorCodeType_XKS__PROXY__NOT__REACHABLE, + ConnectionErrorCodeType_XKS__PROXY__TIMED__OUT, + ConnectionErrorCodeType_XKS__VPC__ENDPOINT__SERVICE__INVALID__CONFIGURATION, + ConnectionErrorCodeType_XKS__VPC__ENDPOINT__SERVICE__NOT__FOUND, + ConnectionStateType_CONNECTED, + ConnectionStateType_CONNECTING, + ConnectionStateType_DISCONNECTED, + ConnectionStateType_DISCONNECTING, + ConnectionStateType_FAILED, + CreateAliasRequest_CreateAliasRequest as DafnyCreateAliasRequest, + CreateCustomKeyStoreRequest_CreateCustomKeyStoreRequest as DafnyCreateCustomKeyStoreRequest, + CreateCustomKeyStoreResponse_CreateCustomKeyStoreResponse as DafnyCreateCustomKeyStoreResponse, + CreateGrantRequest_CreateGrantRequest as DafnyCreateGrantRequest, + CreateGrantResponse_CreateGrantResponse as DafnyCreateGrantResponse, + CreateKeyRequest_CreateKeyRequest as DafnyCreateKeyRequest, + CreateKeyResponse_CreateKeyResponse as DafnyCreateKeyResponse, + CustomKeyStoreType_AWS__CLOUDHSM, + CustomKeyStoreType_EXTERNAL__KEY__STORE, + CustomKeyStoresListEntry_CustomKeyStoresListEntry as DafnyCustomKeyStoresListEntry, + CustomerMasterKeySpec_ECC__NIST__P256, + CustomerMasterKeySpec_ECC__NIST__P384, + CustomerMasterKeySpec_ECC__NIST__P521, + CustomerMasterKeySpec_ECC__SECG__P256K1, + CustomerMasterKeySpec_HMAC__224, + CustomerMasterKeySpec_HMAC__256, + CustomerMasterKeySpec_HMAC__384, + CustomerMasterKeySpec_HMAC__512, + CustomerMasterKeySpec_RSA__2048, + CustomerMasterKeySpec_RSA__3072, + CustomerMasterKeySpec_RSA__4096, + CustomerMasterKeySpec_SM2, + CustomerMasterKeySpec_SYMMETRIC__DEFAULT, + DataKeyPairSpec_ECC__NIST__P256, + DataKeyPairSpec_ECC__NIST__P384, + DataKeyPairSpec_ECC__NIST__P521, + DataKeyPairSpec_ECC__SECG__P256K1, + DataKeyPairSpec_RSA__2048, + DataKeyPairSpec_RSA__3072, + DataKeyPairSpec_RSA__4096, + DataKeyPairSpec_SM2, + DataKeySpec_AES__128, + DataKeySpec_AES__256, + DecryptRequest_DecryptRequest as DafnyDecryptRequest, + DecryptResponse_DecryptResponse as DafnyDecryptResponse, + DeleteAliasRequest_DeleteAliasRequest as DafnyDeleteAliasRequest, + DeleteCustomKeyStoreRequest_DeleteCustomKeyStoreRequest as DafnyDeleteCustomKeyStoreRequest, + DeleteCustomKeyStoreResponse_DeleteCustomKeyStoreResponse as DafnyDeleteCustomKeyStoreResponse, + DeleteImportedKeyMaterialRequest_DeleteImportedKeyMaterialRequest as DafnyDeleteImportedKeyMaterialRequest, + DeriveSharedSecretRequest_DeriveSharedSecretRequest as DafnyDeriveSharedSecretRequest, + DeriveSharedSecretResponse_DeriveSharedSecretResponse as DafnyDeriveSharedSecretResponse, + DescribeCustomKeyStoresRequest_DescribeCustomKeyStoresRequest as DafnyDescribeCustomKeyStoresRequest, + DescribeCustomKeyStoresResponse_DescribeCustomKeyStoresResponse as DafnyDescribeCustomKeyStoresResponse, + DescribeKeyRequest_DescribeKeyRequest as DafnyDescribeKeyRequest, + DescribeKeyResponse_DescribeKeyResponse as DafnyDescribeKeyResponse, + DisableKeyRequest_DisableKeyRequest as DafnyDisableKeyRequest, + DisableKeyRotationRequest_DisableKeyRotationRequest as DafnyDisableKeyRotationRequest, + DisconnectCustomKeyStoreRequest_DisconnectCustomKeyStoreRequest as DafnyDisconnectCustomKeyStoreRequest, + DisconnectCustomKeyStoreResponse_DisconnectCustomKeyStoreResponse as DafnyDisconnectCustomKeyStoreResponse, + EnableKeyRequest_EnableKeyRequest as DafnyEnableKeyRequest, + EnableKeyRotationRequest_EnableKeyRotationRequest as DafnyEnableKeyRotationRequest, + EncryptRequest_EncryptRequest as DafnyEncryptRequest, + EncryptResponse_EncryptResponse as DafnyEncryptResponse, + EncryptionAlgorithmSpec_RSAES__OAEP__SHA__1, + EncryptionAlgorithmSpec_RSAES__OAEP__SHA__256, + EncryptionAlgorithmSpec_SYMMETRIC__DEFAULT, + Error_AlreadyExistsException, + Error_CloudHsmClusterInUseException, + Error_CloudHsmClusterInvalidConfigurationException, + Error_CloudHsmClusterNotActiveException, + Error_CloudHsmClusterNotFoundException, + Error_CloudHsmClusterNotRelatedException, + Error_ConflictException, + Error_CustomKeyStoreHasCMKsException, + Error_CustomKeyStoreInvalidStateException, + Error_CustomKeyStoreNameInUseException, + Error_CustomKeyStoreNotFoundException, + Error_DependencyTimeoutException, + Error_DisabledException, + Error_DryRunOperationException, + Error_ExpiredImportTokenException, + Error_IncorrectKeyException, + Error_IncorrectKeyMaterialException, + Error_IncorrectTrustAnchorException, + Error_InvalidAliasNameException, + Error_InvalidArnException, + Error_InvalidCiphertextException, + Error_InvalidGrantIdException, + Error_InvalidGrantTokenException, + Error_InvalidImportTokenException, + Error_InvalidKeyUsageException, + Error_InvalidMarkerException, + Error_KMSInternalException, + Error_KMSInvalidMacException, + Error_KMSInvalidSignatureException, + Error_KMSInvalidStateException, + Error_KeyUnavailableException, + Error_LimitExceededException, + Error_MalformedPolicyDocumentException, + Error_NotFoundException, + Error_TagException, + Error_UnsupportedOperationException, + Error_XksKeyAlreadyInUseException, + Error_XksKeyInvalidConfigurationException, + Error_XksKeyNotFoundException, + Error_XksProxyIncorrectAuthenticationCredentialException, + Error_XksProxyInvalidConfigurationException, + Error_XksProxyInvalidResponseException, + Error_XksProxyUriEndpointInUseException, + Error_XksProxyUriInUseException, + Error_XksProxyUriUnreachableException, + Error_XksProxyVpcEndpointServiceInUseException, + Error_XksProxyVpcEndpointServiceInvalidConfigurationException, + Error_XksProxyVpcEndpointServiceNotFoundException, + ExpirationModelType_KEY__MATERIAL__DOES__NOT__EXPIRE, + ExpirationModelType_KEY__MATERIAL__EXPIRES, + GenerateDataKeyPairRequest_GenerateDataKeyPairRequest as DafnyGenerateDataKeyPairRequest, + GenerateDataKeyPairResponse_GenerateDataKeyPairResponse as DafnyGenerateDataKeyPairResponse, + GenerateDataKeyPairWithoutPlaintextRequest_GenerateDataKeyPairWithoutPlaintextRequest as DafnyGenerateDataKeyPairWithoutPlaintextRequest, + GenerateDataKeyPairWithoutPlaintextResponse_GenerateDataKeyPairWithoutPlaintextResponse as DafnyGenerateDataKeyPairWithoutPlaintextResponse, + GenerateDataKeyRequest_GenerateDataKeyRequest as DafnyGenerateDataKeyRequest, + GenerateDataKeyResponse_GenerateDataKeyResponse as DafnyGenerateDataKeyResponse, + GenerateDataKeyWithoutPlaintextRequest_GenerateDataKeyWithoutPlaintextRequest as DafnyGenerateDataKeyWithoutPlaintextRequest, + GenerateDataKeyWithoutPlaintextResponse_GenerateDataKeyWithoutPlaintextResponse as DafnyGenerateDataKeyWithoutPlaintextResponse, + GenerateMacRequest_GenerateMacRequest as DafnyGenerateMacRequest, + GenerateMacResponse_GenerateMacResponse as DafnyGenerateMacResponse, + GenerateRandomRequest_GenerateRandomRequest as DafnyGenerateRandomRequest, + GenerateRandomResponse_GenerateRandomResponse as DafnyGenerateRandomResponse, + GetKeyPolicyRequest_GetKeyPolicyRequest as DafnyGetKeyPolicyRequest, + GetKeyPolicyResponse_GetKeyPolicyResponse as DafnyGetKeyPolicyResponse, + GetKeyRotationStatusRequest_GetKeyRotationStatusRequest as DafnyGetKeyRotationStatusRequest, + GetKeyRotationStatusResponse_GetKeyRotationStatusResponse as DafnyGetKeyRotationStatusResponse, + GetParametersForImportRequest_GetParametersForImportRequest as DafnyGetParametersForImportRequest, + GetParametersForImportResponse_GetParametersForImportResponse as DafnyGetParametersForImportResponse, + GetPublicKeyRequest_GetPublicKeyRequest as DafnyGetPublicKeyRequest, + GetPublicKeyResponse_GetPublicKeyResponse as DafnyGetPublicKeyResponse, + GrantConstraints_GrantConstraints as DafnyGrantConstraints, + GrantListEntry_GrantListEntry as DafnyGrantListEntry, + GrantOperation_CreateGrant, + GrantOperation_Decrypt, + GrantOperation_DeriveSharedSecret, + GrantOperation_DescribeKey, + GrantOperation_Encrypt, + GrantOperation_GenerateDataKey, + GrantOperation_GenerateDataKeyPair, + GrantOperation_GenerateDataKeyPairWithoutPlaintext, + GrantOperation_GenerateDataKeyWithoutPlaintext, + GrantOperation_GenerateMac, + GrantOperation_GetPublicKey, + GrantOperation_ReEncryptFrom, + GrantOperation_ReEncryptTo, + GrantOperation_RetireGrant, + GrantOperation_Sign, + GrantOperation_Verify, + GrantOperation_VerifyMac, + ImportKeyMaterialRequest_ImportKeyMaterialRequest as DafnyImportKeyMaterialRequest, + ImportKeyMaterialResponse_ImportKeyMaterialResponse as DafnyImportKeyMaterialResponse, + KeyAgreementAlgorithmSpec_ECDH, + KeyEncryptionMechanism_RSAES__OAEP__SHA__256, + KeyListEntry_KeyListEntry as DafnyKeyListEntry, + KeyManagerType_AWS, + KeyManagerType_CUSTOMER, + KeyMetadata_KeyMetadata as DafnyKeyMetadata, + KeySpec_ECC__NIST__P256, + KeySpec_ECC__NIST__P384, + KeySpec_ECC__NIST__P521, + KeySpec_ECC__SECG__P256K1, + KeySpec_HMAC__224, + KeySpec_HMAC__256, + KeySpec_HMAC__384, + KeySpec_HMAC__512, + KeySpec_RSA__2048, + KeySpec_RSA__3072, + KeySpec_RSA__4096, + KeySpec_SM2, + KeySpec_SYMMETRIC__DEFAULT, + KeyState_Creating, + KeyState_Disabled, + KeyState_Enabled, + KeyState_PendingDeletion, + KeyState_PendingImport, + KeyState_PendingReplicaDeletion, + KeyState_Unavailable, + KeyState_Updating, + KeyUsageType_ENCRYPT__DECRYPT, + KeyUsageType_GENERATE__VERIFY__MAC, + KeyUsageType_KEY__AGREEMENT, + KeyUsageType_SIGN__VERIFY, + ListAliasesRequest_ListAliasesRequest as DafnyListAliasesRequest, + ListAliasesResponse_ListAliasesResponse as DafnyListAliasesResponse, + ListGrantsRequest_ListGrantsRequest as DafnyListGrantsRequest, + ListGrantsResponse_ListGrantsResponse as DafnyListGrantsResponse, + ListKeyPoliciesRequest_ListKeyPoliciesRequest as DafnyListKeyPoliciesRequest, + ListKeyPoliciesResponse_ListKeyPoliciesResponse as DafnyListKeyPoliciesResponse, + ListKeyRotationsRequest_ListKeyRotationsRequest as DafnyListKeyRotationsRequest, + ListKeyRotationsResponse_ListKeyRotationsResponse as DafnyListKeyRotationsResponse, + ListKeysRequest_ListKeysRequest as DafnyListKeysRequest, + ListKeysResponse_ListKeysResponse as DafnyListKeysResponse, + ListResourceTagsRequest_ListResourceTagsRequest as DafnyListResourceTagsRequest, + ListResourceTagsResponse_ListResourceTagsResponse as DafnyListResourceTagsResponse, + MacAlgorithmSpec_HMAC__SHA__224, + MacAlgorithmSpec_HMAC__SHA__256, + MacAlgorithmSpec_HMAC__SHA__384, + MacAlgorithmSpec_HMAC__SHA__512, + MessageType_DIGEST, + MessageType_RAW, + MultiRegionConfiguration_MultiRegionConfiguration as DafnyMultiRegionConfiguration, + MultiRegionKeyType_PRIMARY, + MultiRegionKeyType_REPLICA, + MultiRegionKey_MultiRegionKey as DafnyMultiRegionKey, + OriginType_AWS__CLOUDHSM, + OriginType_AWS__KMS, + OriginType_EXTERNAL, + OriginType_EXTERNAL__KEY__STORE, + PutKeyPolicyRequest_PutKeyPolicyRequest as DafnyPutKeyPolicyRequest, + ReEncryptRequest_ReEncryptRequest as DafnyReEncryptRequest, + ReEncryptResponse_ReEncryptResponse as DafnyReEncryptResponse, + RecipientInfo_RecipientInfo as DafnyRecipientInfo, + ReplicateKeyRequest_ReplicateKeyRequest as DafnyReplicateKeyRequest, + ReplicateKeyResponse_ReplicateKeyResponse as DafnyReplicateKeyResponse, + RetireGrantRequest_RetireGrantRequest as DafnyRetireGrantRequest, + RevokeGrantRequest_RevokeGrantRequest as DafnyRevokeGrantRequest, + RotateKeyOnDemandRequest_RotateKeyOnDemandRequest as DafnyRotateKeyOnDemandRequest, + RotateKeyOnDemandResponse_RotateKeyOnDemandResponse as DafnyRotateKeyOnDemandResponse, + RotationType_AUTOMATIC, + RotationType_ON__DEMAND, + RotationsListEntry_RotationsListEntry as DafnyRotationsListEntry, + ScheduleKeyDeletionRequest_ScheduleKeyDeletionRequest as DafnyScheduleKeyDeletionRequest, + ScheduleKeyDeletionResponse_ScheduleKeyDeletionResponse as DafnyScheduleKeyDeletionResponse, + SignRequest_SignRequest as DafnySignRequest, + SignResponse_SignResponse as DafnySignResponse, + SigningAlgorithmSpec_ECDSA__SHA__256, + SigningAlgorithmSpec_ECDSA__SHA__384, + SigningAlgorithmSpec_ECDSA__SHA__512, + SigningAlgorithmSpec_RSASSA__PKCS1__V1__5__SHA__256, + SigningAlgorithmSpec_RSASSA__PKCS1__V1__5__SHA__384, + SigningAlgorithmSpec_RSASSA__PKCS1__V1__5__SHA__512, + SigningAlgorithmSpec_RSASSA__PSS__SHA__256, + SigningAlgorithmSpec_RSASSA__PSS__SHA__384, + SigningAlgorithmSpec_RSASSA__PSS__SHA__512, + SigningAlgorithmSpec_SM2DSA, + TagResourceRequest_TagResourceRequest as DafnyTagResourceRequest, + Tag_Tag as DafnyTag, + UntagResourceRequest_UntagResourceRequest as DafnyUntagResourceRequest, + UpdateAliasRequest_UpdateAliasRequest as DafnyUpdateAliasRequest, + UpdateCustomKeyStoreRequest_UpdateCustomKeyStoreRequest as DafnyUpdateCustomKeyStoreRequest, + UpdateCustomKeyStoreResponse_UpdateCustomKeyStoreResponse as DafnyUpdateCustomKeyStoreResponse, + UpdateKeyDescriptionRequest_UpdateKeyDescriptionRequest as DafnyUpdateKeyDescriptionRequest, + UpdatePrimaryRegionRequest_UpdatePrimaryRegionRequest as DafnyUpdatePrimaryRegionRequest, + VerifyMacRequest_VerifyMacRequest as DafnyVerifyMacRequest, + VerifyMacResponse_VerifyMacResponse as DafnyVerifyMacResponse, + VerifyRequest_VerifyRequest as DafnyVerifyRequest, + VerifyResponse_VerifyResponse as DafnyVerifyResponse, + WrappingKeySpec_RSA__2048, + WrappingKeySpec_RSA__3072, + WrappingKeySpec_RSA__4096, + WrappingKeySpec_SM2, + XksKeyConfigurationType_XksKeyConfigurationType as DafnyXksKeyConfigurationType, + XksProxyAuthenticationCredentialType_XksProxyAuthenticationCredentialType as DafnyXksProxyAuthenticationCredentialType, + XksProxyConfigurationType_XksProxyConfigurationType as DafnyXksProxyConfigurationType, + XksProxyConnectivityType_PUBLIC__ENDPOINT, + XksProxyConnectivityType_VPC__ENDPOINT__SERVICE, +) +import aws_cryptography_internal_kms.internaldafny.generated.module_ +import aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny +from smithy_dafny_standard_library.internaldafny.generated.Wrappers import ( + Option_None, + Option_Some, +) + + +def com_amazonaws_kms_AlreadyExistsException(native_input): + return Error_AlreadyExistsException( + message=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Error"]["Message"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_kms_CloudHsmClusterInUseException(native_input): + return Error_CloudHsmClusterInUseException( + message=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Error"]["Message"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_kms_CloudHsmClusterInvalidConfigurationException(native_input): + return Error_CloudHsmClusterInvalidConfigurationException( + message=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Error"]["Message"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_kms_CloudHsmClusterNotActiveException(native_input): + return Error_CloudHsmClusterNotActiveException( + message=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Error"]["Message"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_kms_CloudHsmClusterNotFoundException(native_input): + return Error_CloudHsmClusterNotFoundException( + message=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Error"]["Message"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_kms_CloudHsmClusterNotRelatedException(native_input): + return Error_CloudHsmClusterNotRelatedException( + message=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Error"]["Message"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_kms_ConflictException(native_input): + return Error_ConflictException( + message=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Error"]["Message"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_kms_CustomKeyStoreHasCMKsException(native_input): + return Error_CustomKeyStoreHasCMKsException( + message=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Error"]["Message"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_kms_CustomKeyStoreInvalidStateException(native_input): + return Error_CustomKeyStoreInvalidStateException( + message=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Error"]["Message"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_kms_CustomKeyStoreNameInUseException(native_input): + return Error_CustomKeyStoreNameInUseException( + message=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Error"]["Message"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_kms_CustomKeyStoreNotFoundException(native_input): + return Error_CustomKeyStoreNotFoundException( + message=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Error"]["Message"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_kms_DependencyTimeoutException(native_input): + return Error_DependencyTimeoutException( + message=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Error"]["Message"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_kms_DisabledException(native_input): + return Error_DisabledException( + message=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Error"]["Message"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_kms_DryRunOperationException(native_input): + return Error_DryRunOperationException( + message=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Error"]["Message"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_kms_ExpiredImportTokenException(native_input): + return Error_ExpiredImportTokenException( + message=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Error"]["Message"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_kms_IncorrectKeyException(native_input): + return Error_IncorrectKeyException( + message=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Error"]["Message"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_kms_IncorrectKeyMaterialException(native_input): + return Error_IncorrectKeyMaterialException( + message=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Error"]["Message"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_kms_IncorrectTrustAnchorException(native_input): + return Error_IncorrectTrustAnchorException( + message=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Error"]["Message"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_kms_InvalidAliasNameException(native_input): + return Error_InvalidAliasNameException( + message=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Error"]["Message"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_kms_InvalidArnException(native_input): + return Error_InvalidArnException( + message=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Error"]["Message"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_kms_InvalidCiphertextException(native_input): + return Error_InvalidCiphertextException( + message=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Error"]["Message"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_kms_InvalidGrantIdException(native_input): + return Error_InvalidGrantIdException( + message=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Error"]["Message"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_kms_InvalidGrantTokenException(native_input): + return Error_InvalidGrantTokenException( + message=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Error"]["Message"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_kms_InvalidImportTokenException(native_input): + return Error_InvalidImportTokenException( + message=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Error"]["Message"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_kms_InvalidKeyUsageException(native_input): + return Error_InvalidKeyUsageException( + message=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Error"]["Message"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_kms_InvalidMarkerException(native_input): + return Error_InvalidMarkerException( + message=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Error"]["Message"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_kms_KeyUnavailableException(native_input): + return Error_KeyUnavailableException( + message=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Error"]["Message"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_kms_KMSInternalException(native_input): + return Error_KMSInternalException( + message=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Error"]["Message"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_kms_KMSInvalidMacException(native_input): + return Error_KMSInvalidMacException( + message=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Error"]["Message"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_kms_KMSInvalidSignatureException(native_input): + return Error_KMSInvalidSignatureException( + message=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Error"]["Message"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_kms_KMSInvalidStateException(native_input): + return Error_KMSInvalidStateException( + message=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Error"]["Message"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_kms_LimitExceededException(native_input): + return Error_LimitExceededException( + message=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Error"]["Message"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_kms_MalformedPolicyDocumentException(native_input): + return Error_MalformedPolicyDocumentException( + message=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Error"]["Message"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_kms_NotFoundException(native_input): + return Error_NotFoundException( + message=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Error"]["Message"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_kms_TagException(native_input): + return Error_TagException( + message=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Error"]["Message"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_kms_UnsupportedOperationException(native_input): + return Error_UnsupportedOperationException( + message=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Error"]["Message"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_kms_XksKeyAlreadyInUseException(native_input): + return Error_XksKeyAlreadyInUseException( + message=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Error"]["Message"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_kms_XksKeyInvalidConfigurationException(native_input): + return Error_XksKeyInvalidConfigurationException( + message=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Error"]["Message"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_kms_XksKeyNotFoundException(native_input): + return Error_XksKeyNotFoundException( + message=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Error"]["Message"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_kms_XksProxyIncorrectAuthenticationCredentialException(native_input): + return Error_XksProxyIncorrectAuthenticationCredentialException( + message=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Error"]["Message"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_kms_XksProxyInvalidConfigurationException(native_input): + return Error_XksProxyInvalidConfigurationException( + message=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Error"]["Message"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_kms_XksProxyInvalidResponseException(native_input): + return Error_XksProxyInvalidResponseException( + message=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Error"]["Message"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_kms_XksProxyUriEndpointInUseException(native_input): + return Error_XksProxyUriEndpointInUseException( + message=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Error"]["Message"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_kms_XksProxyUriInUseException(native_input): + return Error_XksProxyUriInUseException( + message=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Error"]["Message"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_kms_XksProxyUriUnreachableException(native_input): + return Error_XksProxyUriUnreachableException( + message=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Error"]["Message"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_kms_XksProxyVpcEndpointServiceInUseException(native_input): + return Error_XksProxyVpcEndpointServiceInUseException( + message=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Error"]["Message"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_kms_XksProxyVpcEndpointServiceInvalidConfigurationException( + native_input, +): + return Error_XksProxyVpcEndpointServiceInvalidConfigurationException( + message=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Error"]["Message"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_kms_XksProxyVpcEndpointServiceNotFoundException(native_input): + return Error_XksProxyVpcEndpointServiceNotFoundException( + message=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Error"]["Message"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_kms_CancelKeyDeletionRequest(native_input): + return DafnyCancelKeyDeletionRequest( + KeyId=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["KeyId"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_kms_CancelKeyDeletionResponse(native_input): + return DafnyCancelKeyDeletionResponse( + KeyId=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["KeyId"].encode("utf-16-be"))] * 2 + ) + ] + ) + ) + ) + if "KeyId" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_kms_ConnectCustomKeyStoreRequest(native_input): + return DafnyConnectCustomKeyStoreRequest( + CustomKeyStoreId=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["CustomKeyStoreId"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_kms_ConnectCustomKeyStoreResponse(native_input): + return DafnyConnectCustomKeyStoreResponse() + + +def com_amazonaws_kms_CreateAliasRequest(native_input): + return DafnyCreateAliasRequest( + AliasName=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["AliasName"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + TargetKeyId=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["TargetKeyId"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_kms_CreateCustomKeyStoreRequest(native_input): + return DafnyCreateCustomKeyStoreRequest( + CustomKeyStoreName=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["CustomKeyStoreName"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ), + CloudHsmClusterId=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[ + iter( + native_input["CloudHsmClusterId"].encode( + "utf-16-be" + ) + ) + ] + * 2 + ) + ] + ) + ) + ) + if "CloudHsmClusterId" in native_input.keys() + else Option_None() + ), + TrustAnchorCertificate=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[ + iter( + native_input["TrustAnchorCertificate"].encode( + "utf-16-be" + ) + ) + ] + * 2 + ) + ] + ) + ) + ) + if "TrustAnchorCertificate" in native_input.keys() + else Option_None() + ), + KeyStorePassword=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[ + iter( + native_input["KeyStorePassword"].encode( + "utf-16-be" + ) + ) + ] + * 2 + ) + ] + ) + ) + ) + if "KeyStorePassword" in native_input.keys() + else Option_None() + ), + CustomKeyStoreType=( + Option_Some( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_CustomKeyStoreType( + native_input["CustomKeyStoreType"] + ) + ) + if "CustomKeyStoreType" in native_input.keys() + else Option_None() + ), + XksProxyUriEndpoint=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[ + iter( + native_input["XksProxyUriEndpoint"].encode( + "utf-16-be" + ) + ) + ] + * 2 + ) + ] + ) + ) + ) + if "XksProxyUriEndpoint" in native_input.keys() + else Option_None() + ), + XksProxyUriPath=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[ + iter( + native_input["XksProxyUriPath"].encode( + "utf-16-be" + ) + ) + ] + * 2 + ) + ] + ) + ) + ) + if "XksProxyUriPath" in native_input.keys() + else Option_None() + ), + XksProxyVpcEndpointServiceName=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[ + iter( + native_input[ + "XksProxyVpcEndpointServiceName" + ].encode("utf-16-be") + ) + ] + * 2 + ) + ] + ) + ) + ) + if "XksProxyVpcEndpointServiceName" in native_input.keys() + else Option_None() + ), + XksProxyAuthenticationCredential=( + Option_Some( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_XksProxyAuthenticationCredentialType( + native_input["XksProxyAuthenticationCredential"] + ) + ) + if "XksProxyAuthenticationCredential" in native_input.keys() + else Option_None() + ), + XksProxyConnectivity=( + Option_Some( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_XksProxyConnectivityType( + native_input["XksProxyConnectivity"] + ) + ) + if "XksProxyConnectivity" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_kms_CustomKeyStoreType(native_input): + # Convert CustomKeyStoreType + if native_input == "AWS_CLOUDHSM": + return CustomKeyStoreType_AWS__CLOUDHSM() + elif native_input == "EXTERNAL_KEY_STORE": + return CustomKeyStoreType_EXTERNAL__KEY__STORE() + else: + raise ValueError("No recognized enum value in enum type: " + native_input) + + +def com_amazonaws_kms_XksProxyAuthenticationCredentialType(native_input): + return DafnyXksProxyAuthenticationCredentialType( + AccessKeyId=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["AccessKeyId"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + RawSecretAccessKey=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["RawSecretAccessKey"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_kms_XksProxyConnectivityType(native_input): + # Convert XksProxyConnectivityType + if native_input == "PUBLIC_ENDPOINT": + return XksProxyConnectivityType_PUBLIC__ENDPOINT() + elif native_input == "VPC_ENDPOINT_SERVICE": + return XksProxyConnectivityType_VPC__ENDPOINT__SERVICE() + else: + raise ValueError("No recognized enum value in enum type: " + native_input) + + +def com_amazonaws_kms_CreateCustomKeyStoreResponse(native_input): + return DafnyCreateCustomKeyStoreResponse( + CustomKeyStoreId=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[ + iter( + native_input["CustomKeyStoreId"].encode( + "utf-16-be" + ) + ) + ] + * 2 + ) + ] + ) + ) + ) + if "CustomKeyStoreId" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_kms_CreateGrantRequest(native_input): + return DafnyCreateGrantRequest( + KeyId=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["KeyId"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + GranteePrincipal=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["GranteePrincipal"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ), + RetiringPrincipal=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[ + iter( + native_input["RetiringPrincipal"].encode( + "utf-16-be" + ) + ) + ] + * 2 + ) + ] + ) + ) + ) + if "RetiringPrincipal" in native_input.keys() + else Option_None() + ), + Operations=Seq( + [ + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_GrantOperation( + list_element + ) + for list_element in native_input["Operations"] + ] + ), + Constraints=( + Option_Some( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_GrantConstraints( + native_input["Constraints"] + ) + ) + if "Constraints" in native_input.keys() + else Option_None() + ), + 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["GrantTokens"] + ] + ) + ) + if "GrantTokens" in native_input.keys() + else Option_None() + ), + Name=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Name"].encode("utf-16-be"))] * 2 + ) + ] + ) + ) + ) + if "Name" in native_input.keys() + else Option_None() + ), + DryRun=( + Option_Some(native_input["DryRun"]) + if "DryRun" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_kms_GrantOperation(native_input): + # Convert GrantOperation + if native_input == "Decrypt": + return GrantOperation_Decrypt() + elif native_input == "Encrypt": + return GrantOperation_Encrypt() + elif native_input == "GenerateDataKey": + return GrantOperation_GenerateDataKey() + elif native_input == "GenerateDataKeyWithoutPlaintext": + return GrantOperation_GenerateDataKeyWithoutPlaintext() + elif native_input == "ReEncryptFrom": + return GrantOperation_ReEncryptFrom() + elif native_input == "ReEncryptTo": + return GrantOperation_ReEncryptTo() + elif native_input == "Sign": + return GrantOperation_Sign() + elif native_input == "Verify": + return GrantOperation_Verify() + elif native_input == "GetPublicKey": + return GrantOperation_GetPublicKey() + elif native_input == "CreateGrant": + return GrantOperation_CreateGrant() + elif native_input == "RetireGrant": + return GrantOperation_RetireGrant() + elif native_input == "DescribeKey": + return GrantOperation_DescribeKey() + elif native_input == "GenerateDataKeyPair": + return GrantOperation_GenerateDataKeyPair() + elif native_input == "GenerateDataKeyPairWithoutPlaintext": + return GrantOperation_GenerateDataKeyPairWithoutPlaintext() + elif native_input == "GenerateMac": + return GrantOperation_GenerateMac() + elif native_input == "VerifyMac": + return GrantOperation_VerifyMac() + elif native_input == "DeriveSharedSecret": + return GrantOperation_DeriveSharedSecret() + else: + raise ValueError("No recognized enum value in enum type: " + native_input) + + +def com_amazonaws_kms_GrantConstraints(native_input): + return DafnyGrantConstraints( + EncryptionContextSubset=( + 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[ + "EncryptionContextSubset" + ].items() + } + ) + ) + if "EncryptionContextSubset" in native_input.keys() + else Option_None() + ), + EncryptionContextEquals=( + 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[ + "EncryptionContextEquals" + ].items() + } + ) + ) + if "EncryptionContextEquals" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_kms_CreateGrantResponse(native_input): + return DafnyCreateGrantResponse( + GrantToken=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["GrantToken"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ) + ) + if "GrantToken" in native_input.keys() + else Option_None() + ), + GrantId=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["GrantId"].encode("utf-16-be"))] * 2 + ) + ] + ) + ) + ) + if "GrantId" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_kms_CreateKeyRequest(native_input): + return DafnyCreateKeyRequest( + Policy=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Policy"].encode("utf-16-be"))] * 2 + ) + ] + ) + ) + ) + if "Policy" in native_input.keys() + else Option_None() + ), + Description=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Description"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ) + ) + if "Description" in native_input.keys() + else Option_None() + ), + KeyUsage=( + Option_Some( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_KeyUsageType( + native_input["KeyUsage"] + ) + ) + if "KeyUsage" in native_input.keys() + else Option_None() + ), + CustomerMasterKeySpec=( + Option_Some( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_CustomerMasterKeySpec( + native_input["CustomerMasterKeySpec"] + ) + ) + if "CustomerMasterKeySpec" in native_input.keys() + else Option_None() + ), + KeySpec=( + Option_Some( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_KeySpec( + native_input["KeySpec"] + ) + ) + if "KeySpec" in native_input.keys() + else Option_None() + ), + Origin=( + Option_Some( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_OriginType( + native_input["Origin"] + ) + ) + if "Origin" in native_input.keys() + else Option_None() + ), + CustomKeyStoreId=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[ + iter( + native_input["CustomKeyStoreId"].encode( + "utf-16-be" + ) + ) + ] + * 2 + ) + ] + ) + ) + ) + if "CustomKeyStoreId" in native_input.keys() + else Option_None() + ), + BypassPolicyLockoutSafetyCheck=( + Option_Some(native_input["BypassPolicyLockoutSafetyCheck"]) + if "BypassPolicyLockoutSafetyCheck" in native_input.keys() + else Option_None() + ), + Tags=( + Option_Some( + Seq( + [ + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_Tag( + list_element + ) + for list_element in native_input["Tags"] + ] + ) + ) + if "Tags" in native_input.keys() + else Option_None() + ), + MultiRegion=( + Option_Some(native_input["MultiRegion"]) + if "MultiRegion" in native_input.keys() + else Option_None() + ), + XksKeyId=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["XksKeyId"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ) + ) + if "XksKeyId" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_kms_KeyUsageType(native_input): + # Convert KeyUsageType + if native_input == "SIGN_VERIFY": + return KeyUsageType_SIGN__VERIFY() + elif native_input == "ENCRYPT_DECRYPT": + return KeyUsageType_ENCRYPT__DECRYPT() + elif native_input == "GENERATE_VERIFY_MAC": + return KeyUsageType_GENERATE__VERIFY__MAC() + elif native_input == "KEY_AGREEMENT": + return KeyUsageType_KEY__AGREEMENT() + else: + raise ValueError("No recognized enum value in enum type: " + native_input) + + +def com_amazonaws_kms_CustomerMasterKeySpec(native_input): + # Convert CustomerMasterKeySpec + if native_input == "RSA_2048": + return CustomerMasterKeySpec_RSA__2048() + elif native_input == "RSA_3072": + return CustomerMasterKeySpec_RSA__3072() + elif native_input == "RSA_4096": + return CustomerMasterKeySpec_RSA__4096() + elif native_input == "ECC_NIST_P256": + return CustomerMasterKeySpec_ECC__NIST__P256() + elif native_input == "ECC_NIST_P384": + return CustomerMasterKeySpec_ECC__NIST__P384() + elif native_input == "ECC_NIST_P521": + return CustomerMasterKeySpec_ECC__NIST__P521() + elif native_input == "ECC_SECG_P256K1": + return CustomerMasterKeySpec_ECC__SECG__P256K1() + elif native_input == "SYMMETRIC_DEFAULT": + return CustomerMasterKeySpec_SYMMETRIC__DEFAULT() + elif native_input == "HMAC_224": + return CustomerMasterKeySpec_HMAC__224() + elif native_input == "HMAC_256": + return CustomerMasterKeySpec_HMAC__256() + elif native_input == "HMAC_384": + return CustomerMasterKeySpec_HMAC__384() + elif native_input == "HMAC_512": + return CustomerMasterKeySpec_HMAC__512() + elif native_input == "SM2": + return CustomerMasterKeySpec_SM2() + else: + raise ValueError("No recognized enum value in enum type: " + native_input) + + +def com_amazonaws_kms_KeySpec(native_input): + # Convert KeySpec + if native_input == "RSA_2048": + return KeySpec_RSA__2048() + elif native_input == "RSA_3072": + return KeySpec_RSA__3072() + elif native_input == "RSA_4096": + return KeySpec_RSA__4096() + elif native_input == "ECC_NIST_P256": + return KeySpec_ECC__NIST__P256() + elif native_input == "ECC_NIST_P384": + return KeySpec_ECC__NIST__P384() + elif native_input == "ECC_NIST_P521": + return KeySpec_ECC__NIST__P521() + elif native_input == "ECC_SECG_P256K1": + return KeySpec_ECC__SECG__P256K1() + elif native_input == "SYMMETRIC_DEFAULT": + return KeySpec_SYMMETRIC__DEFAULT() + elif native_input == "HMAC_224": + return KeySpec_HMAC__224() + elif native_input == "HMAC_256": + return KeySpec_HMAC__256() + elif native_input == "HMAC_384": + return KeySpec_HMAC__384() + elif native_input == "HMAC_512": + return KeySpec_HMAC__512() + elif native_input == "SM2": + return KeySpec_SM2() + else: + raise ValueError("No recognized enum value in enum type: " + native_input) + + +def com_amazonaws_kms_OriginType(native_input): + # Convert OriginType + if native_input == "AWS_KMS": + return OriginType_AWS__KMS() + elif native_input == "EXTERNAL": + return OriginType_EXTERNAL() + elif native_input == "AWS_CLOUDHSM": + return OriginType_AWS__CLOUDHSM() + elif native_input == "EXTERNAL_KEY_STORE": + return OriginType_EXTERNAL__KEY__STORE() + else: + raise ValueError("No recognized enum value in enum type: " + native_input) + + +def com_amazonaws_kms_Tag(native_input): + return DafnyTag( + TagKey=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["TagKey"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + TagValue=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["TagValue"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_kms_CreateKeyResponse(native_input): + return DafnyCreateKeyResponse( + KeyMetadata=( + Option_Some( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_KeyMetadata( + native_input["KeyMetadata"] + ) + ) + if "KeyMetadata" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_kms_KeyMetadata(native_input): + return DafnyKeyMetadata( + AWSAccountId=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[ + iter( + native_input["AWSAccountId"].encode("utf-16-be") + ) + ] + * 2 + ) + ] + ) + ) + ) + if "AWSAccountId" in native_input.keys() + else Option_None() + ), + KeyId=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["KeyId"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + Arn=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Arn"].encode("utf-16-be"))] * 2 + ) + ] + ) + ) + ) + if "Arn" in native_input.keys() + else Option_None() + ), + CreationDate=( + Option_Some(_dafny.Seq(native_input["CreationDate"].isoformat())) + if "CreationDate" in native_input.keys() + else Option_None() + ), + Enabled=( + Option_Some(native_input["Enabled"]) + if "Enabled" in native_input.keys() + else Option_None() + ), + Description=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Description"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ) + ) + if "Description" in native_input.keys() + else Option_None() + ), + KeyUsage=( + Option_Some( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_KeyUsageType( + native_input["KeyUsage"] + ) + ) + if "KeyUsage" in native_input.keys() + else Option_None() + ), + KeyState=( + Option_Some( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_KeyState( + native_input["KeyState"] + ) + ) + if "KeyState" in native_input.keys() + else Option_None() + ), + DeletionDate=( + Option_Some(_dafny.Seq(native_input["DeletionDate"].isoformat())) + if "DeletionDate" in native_input.keys() + else Option_None() + ), + ValidTo=( + Option_Some(_dafny.Seq(native_input["ValidTo"].isoformat())) + if "ValidTo" in native_input.keys() + else Option_None() + ), + Origin=( + Option_Some( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_OriginType( + native_input["Origin"] + ) + ) + if "Origin" in native_input.keys() + else Option_None() + ), + CustomKeyStoreId=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[ + iter( + native_input["CustomKeyStoreId"].encode( + "utf-16-be" + ) + ) + ] + * 2 + ) + ] + ) + ) + ) + if "CustomKeyStoreId" in native_input.keys() + else Option_None() + ), + CloudHsmClusterId=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[ + iter( + native_input["CloudHsmClusterId"].encode( + "utf-16-be" + ) + ) + ] + * 2 + ) + ] + ) + ) + ) + if "CloudHsmClusterId" in native_input.keys() + else Option_None() + ), + ExpirationModel=( + Option_Some( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_ExpirationModelType( + native_input["ExpirationModel"] + ) + ) + if "ExpirationModel" in native_input.keys() + else Option_None() + ), + KeyManager=( + Option_Some( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_KeyManagerType( + native_input["KeyManager"] + ) + ) + if "KeyManager" in native_input.keys() + else Option_None() + ), + CustomerMasterKeySpec=( + Option_Some( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_CustomerMasterKeySpec( + native_input["CustomerMasterKeySpec"] + ) + ) + if "CustomerMasterKeySpec" in native_input.keys() + else Option_None() + ), + KeySpec=( + Option_Some( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_KeySpec( + native_input["KeySpec"] + ) + ) + if "KeySpec" in native_input.keys() + else Option_None() + ), + EncryptionAlgorithms=( + Option_Some( + Seq( + [ + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_EncryptionAlgorithmSpec( + list_element + ) + for list_element in native_input["EncryptionAlgorithms"] + ] + ) + ) + if "EncryptionAlgorithms" in native_input.keys() + else Option_None() + ), + SigningAlgorithms=( + Option_Some( + Seq( + [ + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_SigningAlgorithmSpec( + list_element + ) + for list_element in native_input["SigningAlgorithms"] + ] + ) + ) + if "SigningAlgorithms" in native_input.keys() + else Option_None() + ), + KeyAgreementAlgorithms=( + Option_Some( + Seq( + [ + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_KeyAgreementAlgorithmSpec( + list_element + ) + for list_element in native_input["KeyAgreementAlgorithms"] + ] + ) + ) + if "KeyAgreementAlgorithms" in native_input.keys() + else Option_None() + ), + MultiRegion=( + Option_Some(native_input["MultiRegion"]) + if "MultiRegion" in native_input.keys() + else Option_None() + ), + MultiRegionConfiguration=( + Option_Some( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_MultiRegionConfiguration( + native_input["MultiRegionConfiguration"] + ) + ) + if "MultiRegionConfiguration" in native_input.keys() + else Option_None() + ), + PendingDeletionWindowInDays=( + Option_Some(native_input["PendingDeletionWindowInDays"]) + if "PendingDeletionWindowInDays" in native_input.keys() + else Option_None() + ), + MacAlgorithms=( + Option_Some( + Seq( + [ + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_MacAlgorithmSpec( + list_element + ) + for list_element in native_input["MacAlgorithms"] + ] + ) + ) + if "MacAlgorithms" in native_input.keys() + else Option_None() + ), + XksKeyConfiguration=( + Option_Some( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_XksKeyConfigurationType( + native_input["XksKeyConfiguration"] + ) + ) + if "XksKeyConfiguration" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_kms_KeyState(native_input): + # Convert KeyState + if native_input == "Creating": + return KeyState_Creating() + elif native_input == "Enabled": + return KeyState_Enabled() + elif native_input == "Disabled": + return KeyState_Disabled() + elif native_input == "PendingDeletion": + return KeyState_PendingDeletion() + elif native_input == "PendingImport": + return KeyState_PendingImport() + elif native_input == "PendingReplicaDeletion": + return KeyState_PendingReplicaDeletion() + elif native_input == "Unavailable": + return KeyState_Unavailable() + elif native_input == "Updating": + return KeyState_Updating() + else: + raise ValueError("No recognized enum value in enum type: " + native_input) + + +def com_amazonaws_kms_ExpirationModelType(native_input): + # Convert ExpirationModelType + if native_input == "KEY_MATERIAL_EXPIRES": + return ExpirationModelType_KEY__MATERIAL__EXPIRES() + elif native_input == "KEY_MATERIAL_DOES_NOT_EXPIRE": + return ExpirationModelType_KEY__MATERIAL__DOES__NOT__EXPIRE() + else: + raise ValueError("No recognized enum value in enum type: " + native_input) + + +def com_amazonaws_kms_KeyManagerType(native_input): + # Convert KeyManagerType + if native_input == "AWS": + return KeyManagerType_AWS() + elif native_input == "CUSTOMER": + return KeyManagerType_CUSTOMER() + else: + raise ValueError("No recognized enum value in enum type: " + native_input) + + +def com_amazonaws_kms_EncryptionAlgorithmSpec(native_input): + # Convert EncryptionAlgorithmSpec + if native_input == "SYMMETRIC_DEFAULT": + return EncryptionAlgorithmSpec_SYMMETRIC__DEFAULT() + elif native_input == "RSAES_OAEP_SHA_1": + return EncryptionAlgorithmSpec_RSAES__OAEP__SHA__1() + elif native_input == "RSAES_OAEP_SHA_256": + return EncryptionAlgorithmSpec_RSAES__OAEP__SHA__256() + else: + raise ValueError("No recognized enum value in enum type: " + native_input) + + +def com_amazonaws_kms_SigningAlgorithmSpec(native_input): + # Convert SigningAlgorithmSpec + if native_input == "RSASSA_PSS_SHA_256": + return SigningAlgorithmSpec_RSASSA__PSS__SHA__256() + elif native_input == "RSASSA_PSS_SHA_384": + return SigningAlgorithmSpec_RSASSA__PSS__SHA__384() + elif native_input == "RSASSA_PSS_SHA_512": + return SigningAlgorithmSpec_RSASSA__PSS__SHA__512() + elif native_input == "RSASSA_PKCS1_V1_5_SHA_256": + return SigningAlgorithmSpec_RSASSA__PKCS1__V1__5__SHA__256() + elif native_input == "RSASSA_PKCS1_V1_5_SHA_384": + return SigningAlgorithmSpec_RSASSA__PKCS1__V1__5__SHA__384() + elif native_input == "RSASSA_PKCS1_V1_5_SHA_512": + return SigningAlgorithmSpec_RSASSA__PKCS1__V1__5__SHA__512() + elif native_input == "ECDSA_SHA_256": + return SigningAlgorithmSpec_ECDSA__SHA__256() + elif native_input == "ECDSA_SHA_384": + return SigningAlgorithmSpec_ECDSA__SHA__384() + elif native_input == "ECDSA_SHA_512": + return SigningAlgorithmSpec_ECDSA__SHA__512() + elif native_input == "SM2DSA": + return SigningAlgorithmSpec_SM2DSA() + else: + raise ValueError("No recognized enum value in enum type: " + native_input) + + +def com_amazonaws_kms_KeyAgreementAlgorithmSpec(native_input): + # Convert KeyAgreementAlgorithmSpec + if native_input == "ECDH": + return KeyAgreementAlgorithmSpec_ECDH() + else: + raise ValueError("No recognized enum value in enum type: " + native_input) + + +def com_amazonaws_kms_MultiRegionConfiguration(native_input): + return DafnyMultiRegionConfiguration( + MultiRegionKeyType=( + Option_Some( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_MultiRegionKeyType( + native_input["MultiRegionKeyType"] + ) + ) + if "MultiRegionKeyType" in native_input.keys() + else Option_None() + ), + PrimaryKey=( + Option_Some( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_MultiRegionKey( + native_input["PrimaryKey"] + ) + ) + if "PrimaryKey" in native_input.keys() + else Option_None() + ), + ReplicaKeys=( + Option_Some( + Seq( + [ + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_MultiRegionKey( + list_element + ) + for list_element in native_input["ReplicaKeys"] + ] + ) + ) + if "ReplicaKeys" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_kms_MacAlgorithmSpec(native_input): + # Convert MacAlgorithmSpec + if native_input == "HMAC_SHA_224": + return MacAlgorithmSpec_HMAC__SHA__224() + elif native_input == "HMAC_SHA_256": + return MacAlgorithmSpec_HMAC__SHA__256() + elif native_input == "HMAC_SHA_384": + return MacAlgorithmSpec_HMAC__SHA__384() + elif native_input == "HMAC_SHA_512": + return MacAlgorithmSpec_HMAC__SHA__512() + else: + raise ValueError("No recognized enum value in enum type: " + native_input) + + +def com_amazonaws_kms_XksKeyConfigurationType(native_input): + return DafnyXksKeyConfigurationType( + Id=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Id"].encode("utf-16-be"))] * 2 + ) + ] + ) + ) + ) + if "Id" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_kms_MultiRegionKeyType(native_input): + # Convert MultiRegionKeyType + if native_input == "PRIMARY": + return MultiRegionKeyType_PRIMARY() + elif native_input == "REPLICA": + return MultiRegionKeyType_REPLICA() + else: + raise ValueError("No recognized enum value in enum type: " + native_input) + + +def com_amazonaws_kms_MultiRegionKey(native_input): + return DafnyMultiRegionKey( + Arn=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Arn"].encode("utf-16-be"))] * 2 + ) + ] + ) + ) + ) + if "Arn" in native_input.keys() + else Option_None() + ), + Region=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Region"].encode("utf-16-be"))] * 2 + ) + ] + ) + ) + ) + if "Region" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_kms_DecryptRequest(native_input): + return DafnyDecryptRequest( + CiphertextBlob=Seq(native_input["CiphertextBlob"]), + EncryptionContext=( + 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["EncryptionContext"].items() + } + ) + ) + if "EncryptionContext" in native_input.keys() + else Option_None() + ), + 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["GrantTokens"] + ] + ) + ) + if "GrantTokens" in native_input.keys() + else Option_None() + ), + KeyId=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["KeyId"].encode("utf-16-be"))] * 2 + ) + ] + ) + ) + ) + if "KeyId" in native_input.keys() + else Option_None() + ), + EncryptionAlgorithm=( + Option_Some( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_EncryptionAlgorithmSpec( + native_input["EncryptionAlgorithm"] + ) + ) + if "EncryptionAlgorithm" in native_input.keys() + else Option_None() + ), + Recipient=( + Option_Some( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_RecipientInfo( + native_input["Recipient"] + ) + ) + if "Recipient" in native_input.keys() + else Option_None() + ), + DryRun=( + Option_Some(native_input["DryRun"]) + if "DryRun" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_kms_RecipientInfo(native_input): + return DafnyRecipientInfo( + KeyEncryptionAlgorithm=( + Option_Some( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_KeyEncryptionMechanism( + native_input["KeyEncryptionAlgorithm"] + ) + ) + if "KeyEncryptionAlgorithm" in native_input.keys() + else Option_None() + ), + AttestationDocument=( + Option_Some(Seq(native_input["AttestationDocument"])) + if "AttestationDocument" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_kms_KeyEncryptionMechanism(native_input): + # Convert KeyEncryptionMechanism + if native_input == "RSAES_OAEP_SHA_256": + return KeyEncryptionMechanism_RSAES__OAEP__SHA__256() + else: + raise ValueError("No recognized enum value in enum type: " + native_input) + + +def com_amazonaws_kms_DecryptResponse(native_input): + return DafnyDecryptResponse( + KeyId=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["KeyId"].encode("utf-16-be"))] * 2 + ) + ] + ) + ) + ) + if "KeyId" in native_input.keys() + else Option_None() + ), + Plaintext=( + Option_Some(Seq(native_input["Plaintext"])) + if "Plaintext" in native_input.keys() + else Option_None() + ), + EncryptionAlgorithm=( + Option_Some( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_EncryptionAlgorithmSpec( + native_input["EncryptionAlgorithm"] + ) + ) + if "EncryptionAlgorithm" in native_input.keys() + else Option_None() + ), + CiphertextForRecipient=( + Option_Some(Seq(native_input["CiphertextForRecipient"])) + if "CiphertextForRecipient" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_kms_DeleteAliasRequest(native_input): + return DafnyDeleteAliasRequest( + AliasName=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["AliasName"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_kms_DeleteCustomKeyStoreRequest(native_input): + return DafnyDeleteCustomKeyStoreRequest( + CustomKeyStoreId=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["CustomKeyStoreId"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_kms_DeleteCustomKeyStoreResponse(native_input): + return DafnyDeleteCustomKeyStoreResponse() + + +def com_amazonaws_kms_DeleteImportedKeyMaterialRequest(native_input): + return DafnyDeleteImportedKeyMaterialRequest( + KeyId=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["KeyId"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_kms_DeriveSharedSecretRequest(native_input): + return DafnyDeriveSharedSecretRequest( + KeyId=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["KeyId"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + KeyAgreementAlgorithm=aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_KeyAgreementAlgorithmSpec( + native_input["KeyAgreementAlgorithm"] + ), + PublicKey=Seq(native_input["PublicKey"]), + 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["GrantTokens"] + ] + ) + ) + if "GrantTokens" in native_input.keys() + else Option_None() + ), + DryRun=( + Option_Some(native_input["DryRun"]) + if "DryRun" in native_input.keys() + else Option_None() + ), + Recipient=( + Option_Some( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_RecipientInfo( + native_input["Recipient"] + ) + ) + if "Recipient" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_kms_DeriveSharedSecretResponse(native_input): + return DafnyDeriveSharedSecretResponse( + KeyId=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["KeyId"].encode("utf-16-be"))] * 2 + ) + ] + ) + ) + ) + if "KeyId" in native_input.keys() + else Option_None() + ), + SharedSecret=( + Option_Some(Seq(native_input["SharedSecret"])) + if "SharedSecret" in native_input.keys() + else Option_None() + ), + CiphertextForRecipient=( + Option_Some(Seq(native_input["CiphertextForRecipient"])) + if "CiphertextForRecipient" in native_input.keys() + else Option_None() + ), + KeyAgreementAlgorithm=( + Option_Some( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_KeyAgreementAlgorithmSpec( + native_input["KeyAgreementAlgorithm"] + ) + ) + if "KeyAgreementAlgorithm" in native_input.keys() + else Option_None() + ), + KeyOrigin=( + Option_Some( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_OriginType( + native_input["KeyOrigin"] + ) + ) + if "KeyOrigin" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_kms_DescribeCustomKeyStoresRequest(native_input): + return DafnyDescribeCustomKeyStoresRequest( + CustomKeyStoreId=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[ + iter( + native_input["CustomKeyStoreId"].encode( + "utf-16-be" + ) + ) + ] + * 2 + ) + ] + ) + ) + ) + if "CustomKeyStoreId" in native_input.keys() + else Option_None() + ), + CustomKeyStoreName=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[ + iter( + native_input["CustomKeyStoreName"].encode( + "utf-16-be" + ) + ) + ] + * 2 + ) + ] + ) + ) + ) + if "CustomKeyStoreName" in native_input.keys() + else Option_None() + ), + Limit=( + Option_Some(native_input["Limit"]) + if "Limit" in native_input.keys() + else Option_None() + ), + Marker=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Marker"].encode("utf-16-be"))] * 2 + ) + ] + ) + ) + ) + if "Marker" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_kms_DescribeCustomKeyStoresResponse(native_input): + return DafnyDescribeCustomKeyStoresResponse( + CustomKeyStores=( + Option_Some( + Seq( + [ + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_CustomKeyStoresListEntry( + list_element + ) + for list_element in native_input["CustomKeyStores"] + ] + ) + ) + if "CustomKeyStores" in native_input.keys() + else Option_None() + ), + NextMarker=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["NextMarker"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ) + ) + if "NextMarker" in native_input.keys() + else Option_None() + ), + Truncated=( + Option_Some(native_input["Truncated"]) + if "Truncated" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_kms_CustomKeyStoresListEntry(native_input): + return DafnyCustomKeyStoresListEntry( + CustomKeyStoreId=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[ + iter( + native_input["CustomKeyStoreId"].encode( + "utf-16-be" + ) + ) + ] + * 2 + ) + ] + ) + ) + ) + if "CustomKeyStoreId" in native_input.keys() + else Option_None() + ), + CustomKeyStoreName=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[ + iter( + native_input["CustomKeyStoreName"].encode( + "utf-16-be" + ) + ) + ] + * 2 + ) + ] + ) + ) + ) + if "CustomKeyStoreName" in native_input.keys() + else Option_None() + ), + CloudHsmClusterId=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[ + iter( + native_input["CloudHsmClusterId"].encode( + "utf-16-be" + ) + ) + ] + * 2 + ) + ] + ) + ) + ) + if "CloudHsmClusterId" in native_input.keys() + else Option_None() + ), + TrustAnchorCertificate=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[ + iter( + native_input["TrustAnchorCertificate"].encode( + "utf-16-be" + ) + ) + ] + * 2 + ) + ] + ) + ) + ) + if "TrustAnchorCertificate" in native_input.keys() + else Option_None() + ), + ConnectionState=( + Option_Some( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_ConnectionStateType( + native_input["ConnectionState"] + ) + ) + if "ConnectionState" in native_input.keys() + else Option_None() + ), + ConnectionErrorCode=( + Option_Some( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_ConnectionErrorCodeType( + native_input["ConnectionErrorCode"] + ) + ) + if "ConnectionErrorCode" in native_input.keys() + else Option_None() + ), + CreationDate=( + Option_Some(_dafny.Seq(native_input["CreationDate"].isoformat())) + if "CreationDate" in native_input.keys() + else Option_None() + ), + CustomKeyStoreType=( + Option_Some( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_CustomKeyStoreType( + native_input["CustomKeyStoreType"] + ) + ) + if "CustomKeyStoreType" in native_input.keys() + else Option_None() + ), + XksProxyConfiguration=( + Option_Some( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_XksProxyConfigurationType( + native_input["XksProxyConfiguration"] + ) + ) + if "XksProxyConfiguration" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_kms_ConnectionStateType(native_input): + # Convert ConnectionStateType + if native_input == "CONNECTED": + return ConnectionStateType_CONNECTED() + elif native_input == "CONNECTING": + return ConnectionStateType_CONNECTING() + elif native_input == "FAILED": + return ConnectionStateType_FAILED() + elif native_input == "DISCONNECTED": + return ConnectionStateType_DISCONNECTED() + elif native_input == "DISCONNECTING": + return ConnectionStateType_DISCONNECTING() + else: + raise ValueError("No recognized enum value in enum type: " + native_input) + + +def com_amazonaws_kms_ConnectionErrorCodeType(native_input): + # Convert ConnectionErrorCodeType + if native_input == "INVALID_CREDENTIALS": + return ConnectionErrorCodeType_INVALID__CREDENTIALS() + elif native_input == "CLUSTER_NOT_FOUND": + return ConnectionErrorCodeType_CLUSTER__NOT__FOUND() + elif native_input == "NETWORK_ERRORS": + return ConnectionErrorCodeType_NETWORK__ERRORS() + elif native_input == "INTERNAL_ERROR": + return ConnectionErrorCodeType_INTERNAL__ERROR() + elif native_input == "INSUFFICIENT_CLOUDHSM_HSMS": + return ConnectionErrorCodeType_INSUFFICIENT__CLOUDHSM__HSMS() + elif native_input == "USER_LOCKED_OUT": + return ConnectionErrorCodeType_USER__LOCKED__OUT() + elif native_input == "USER_NOT_FOUND": + return ConnectionErrorCodeType_USER__NOT__FOUND() + elif native_input == "USER_LOGGED_IN": + return ConnectionErrorCodeType_USER__LOGGED__IN() + elif native_input == "SUBNET_NOT_FOUND": + return ConnectionErrorCodeType_SUBNET__NOT__FOUND() + elif native_input == "INSUFFICIENT_FREE_ADDRESSES_IN_SUBNET": + return ConnectionErrorCodeType_INSUFFICIENT__FREE__ADDRESSES__IN__SUBNET() + elif native_input == "XKS_PROXY_ACCESS_DENIED": + return ConnectionErrorCodeType_XKS__PROXY__ACCESS__DENIED() + elif native_input == "XKS_PROXY_NOT_REACHABLE": + return ConnectionErrorCodeType_XKS__PROXY__NOT__REACHABLE() + elif native_input == "XKS_VPC_ENDPOINT_SERVICE_NOT_FOUND": + return ConnectionErrorCodeType_XKS__VPC__ENDPOINT__SERVICE__NOT__FOUND() + elif native_input == "XKS_PROXY_INVALID_RESPONSE": + return ConnectionErrorCodeType_XKS__PROXY__INVALID__RESPONSE() + elif native_input == "XKS_PROXY_INVALID_CONFIGURATION": + return ConnectionErrorCodeType_XKS__PROXY__INVALID__CONFIGURATION() + elif native_input == "XKS_VPC_ENDPOINT_SERVICE_INVALID_CONFIGURATION": + return ( + ConnectionErrorCodeType_XKS__VPC__ENDPOINT__SERVICE__INVALID__CONFIGURATION() + ) + elif native_input == "XKS_PROXY_TIMED_OUT": + return ConnectionErrorCodeType_XKS__PROXY__TIMED__OUT() + elif native_input == "XKS_PROXY_INVALID_TLS_CONFIGURATION": + return ConnectionErrorCodeType_XKS__PROXY__INVALID__TLS__CONFIGURATION() + else: + raise ValueError("No recognized enum value in enum type: " + native_input) + + +def com_amazonaws_kms_XksProxyConfigurationType(native_input): + return DafnyXksProxyConfigurationType( + Connectivity=( + Option_Some( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_XksProxyConnectivityType( + native_input["Connectivity"] + ) + ) + if "Connectivity" in native_input.keys() + else Option_None() + ), + AccessKeyId=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["AccessKeyId"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ) + ) + if "AccessKeyId" in native_input.keys() + else Option_None() + ), + UriEndpoint=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["UriEndpoint"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ) + ) + if "UriEndpoint" in native_input.keys() + else Option_None() + ), + UriPath=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["UriPath"].encode("utf-16-be"))] * 2 + ) + ] + ) + ) + ) + if "UriPath" in native_input.keys() + else Option_None() + ), + VpcEndpointServiceName=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[ + iter( + native_input["VpcEndpointServiceName"].encode( + "utf-16-be" + ) + ) + ] + * 2 + ) + ] + ) + ) + ) + if "VpcEndpointServiceName" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_kms_DescribeKeyRequest(native_input): + return DafnyDescribeKeyRequest( + KeyId=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["KeyId"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + 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["GrantTokens"] + ] + ) + ) + if "GrantTokens" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_kms_DescribeKeyResponse(native_input): + return DafnyDescribeKeyResponse( + KeyMetadata=( + Option_Some( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_KeyMetadata( + native_input["KeyMetadata"] + ) + ) + if "KeyMetadata" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_kms_DisableKeyRequest(native_input): + return DafnyDisableKeyRequest( + KeyId=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["KeyId"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_kms_DisableKeyRotationRequest(native_input): + return DafnyDisableKeyRotationRequest( + KeyId=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["KeyId"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_kms_DisconnectCustomKeyStoreRequest(native_input): + return DafnyDisconnectCustomKeyStoreRequest( + CustomKeyStoreId=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["CustomKeyStoreId"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_kms_DisconnectCustomKeyStoreResponse(native_input): + return DafnyDisconnectCustomKeyStoreResponse() + + +def com_amazonaws_kms_EnableKeyRequest(native_input): + return DafnyEnableKeyRequest( + KeyId=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["KeyId"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_kms_EnableKeyRotationRequest(native_input): + return DafnyEnableKeyRotationRequest( + KeyId=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["KeyId"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + RotationPeriodInDays=( + Option_Some(native_input["RotationPeriodInDays"]) + if "RotationPeriodInDays" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_kms_EncryptRequest(native_input): + return DafnyEncryptRequest( + KeyId=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["KeyId"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + Plaintext=Seq(native_input["Plaintext"]), + EncryptionContext=( + 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["EncryptionContext"].items() + } + ) + ) + if "EncryptionContext" in native_input.keys() + else Option_None() + ), + 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["GrantTokens"] + ] + ) + ) + if "GrantTokens" in native_input.keys() + else Option_None() + ), + EncryptionAlgorithm=( + Option_Some( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_EncryptionAlgorithmSpec( + native_input["EncryptionAlgorithm"] + ) + ) + if "EncryptionAlgorithm" in native_input.keys() + else Option_None() + ), + DryRun=( + Option_Some(native_input["DryRun"]) + if "DryRun" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_kms_EncryptResponse(native_input): + return DafnyEncryptResponse( + CiphertextBlob=( + Option_Some(Seq(native_input["CiphertextBlob"])) + if "CiphertextBlob" in native_input.keys() + else Option_None() + ), + KeyId=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["KeyId"].encode("utf-16-be"))] * 2 + ) + ] + ) + ) + ) + if "KeyId" in native_input.keys() + else Option_None() + ), + EncryptionAlgorithm=( + Option_Some( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_EncryptionAlgorithmSpec( + native_input["EncryptionAlgorithm"] + ) + ) + if "EncryptionAlgorithm" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_kms_GenerateDataKeyRequest(native_input): + return DafnyGenerateDataKeyRequest( + KeyId=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["KeyId"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + EncryptionContext=( + 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["EncryptionContext"].items() + } + ) + ) + if "EncryptionContext" in native_input.keys() + else Option_None() + ), + NumberOfBytes=( + Option_Some(native_input["NumberOfBytes"]) + if "NumberOfBytes" in native_input.keys() + else Option_None() + ), + KeySpec=( + Option_Some( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_DataKeySpec( + native_input["KeySpec"] + ) + ) + if "KeySpec" in native_input.keys() + else Option_None() + ), + 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["GrantTokens"] + ] + ) + ) + if "GrantTokens" in native_input.keys() + else Option_None() + ), + Recipient=( + Option_Some( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_RecipientInfo( + native_input["Recipient"] + ) + ) + if "Recipient" in native_input.keys() + else Option_None() + ), + DryRun=( + Option_Some(native_input["DryRun"]) + if "DryRun" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_kms_DataKeySpec(native_input): + # Convert DataKeySpec + if native_input == "AES_256": + return DataKeySpec_AES__256() + elif native_input == "AES_128": + return DataKeySpec_AES__128() + else: + raise ValueError("No recognized enum value in enum type: " + native_input) + + +def com_amazonaws_kms_GenerateDataKeyResponse(native_input): + return DafnyGenerateDataKeyResponse( + CiphertextBlob=( + Option_Some(Seq(native_input["CiphertextBlob"])) + if "CiphertextBlob" in native_input.keys() + else Option_None() + ), + Plaintext=( + Option_Some(Seq(native_input["Plaintext"])) + if "Plaintext" in native_input.keys() + else Option_None() + ), + KeyId=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["KeyId"].encode("utf-16-be"))] * 2 + ) + ] + ) + ) + ) + if "KeyId" in native_input.keys() + else Option_None() + ), + CiphertextForRecipient=( + Option_Some(Seq(native_input["CiphertextForRecipient"])) + if "CiphertextForRecipient" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_kms_GenerateDataKeyPairRequest(native_input): + return DafnyGenerateDataKeyPairRequest( + EncryptionContext=( + 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["EncryptionContext"].items() + } + ) + ) + if "EncryptionContext" in native_input.keys() + else Option_None() + ), + KeyId=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["KeyId"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + KeyPairSpec=aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_DataKeyPairSpec( + native_input["KeyPairSpec"] + ), + 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["GrantTokens"] + ] + ) + ) + if "GrantTokens" in native_input.keys() + else Option_None() + ), + Recipient=( + Option_Some( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_RecipientInfo( + native_input["Recipient"] + ) + ) + if "Recipient" in native_input.keys() + else Option_None() + ), + DryRun=( + Option_Some(native_input["DryRun"]) + if "DryRun" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_kms_DataKeyPairSpec(native_input): + # Convert DataKeyPairSpec + if native_input == "RSA_2048": + return DataKeyPairSpec_RSA__2048() + elif native_input == "RSA_3072": + return DataKeyPairSpec_RSA__3072() + elif native_input == "RSA_4096": + return DataKeyPairSpec_RSA__4096() + elif native_input == "ECC_NIST_P256": + return DataKeyPairSpec_ECC__NIST__P256() + elif native_input == "ECC_NIST_P384": + return DataKeyPairSpec_ECC__NIST__P384() + elif native_input == "ECC_NIST_P521": + return DataKeyPairSpec_ECC__NIST__P521() + elif native_input == "ECC_SECG_P256K1": + return DataKeyPairSpec_ECC__SECG__P256K1() + elif native_input == "SM2": + return DataKeyPairSpec_SM2() + else: + raise ValueError("No recognized enum value in enum type: " + native_input) + + +def com_amazonaws_kms_GenerateDataKeyPairResponse(native_input): + return DafnyGenerateDataKeyPairResponse( + PrivateKeyCiphertextBlob=( + Option_Some(Seq(native_input["PrivateKeyCiphertextBlob"])) + if "PrivateKeyCiphertextBlob" in native_input.keys() + else Option_None() + ), + PrivateKeyPlaintext=( + Option_Some(Seq(native_input["PrivateKeyPlaintext"])) + if "PrivateKeyPlaintext" in native_input.keys() + else Option_None() + ), + PublicKey=( + Option_Some(Seq(native_input["PublicKey"])) + if "PublicKey" in native_input.keys() + else Option_None() + ), + KeyId=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["KeyId"].encode("utf-16-be"))] * 2 + ) + ] + ) + ) + ) + if "KeyId" in native_input.keys() + else Option_None() + ), + KeyPairSpec=( + Option_Some( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_DataKeyPairSpec( + native_input["KeyPairSpec"] + ) + ) + if "KeyPairSpec" in native_input.keys() + else Option_None() + ), + CiphertextForRecipient=( + Option_Some(Seq(native_input["CiphertextForRecipient"])) + if "CiphertextForRecipient" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_kms_GenerateDataKeyPairWithoutPlaintextRequest(native_input): + return DafnyGenerateDataKeyPairWithoutPlaintextRequest( + EncryptionContext=( + 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["EncryptionContext"].items() + } + ) + ) + if "EncryptionContext" in native_input.keys() + else Option_None() + ), + KeyId=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["KeyId"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + KeyPairSpec=aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_DataKeyPairSpec( + native_input["KeyPairSpec"] + ), + 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["GrantTokens"] + ] + ) + ) + if "GrantTokens" in native_input.keys() + else Option_None() + ), + DryRun=( + Option_Some(native_input["DryRun"]) + if "DryRun" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_kms_GenerateDataKeyPairWithoutPlaintextResponse(native_input): + return DafnyGenerateDataKeyPairWithoutPlaintextResponse( + PrivateKeyCiphertextBlob=( + Option_Some(Seq(native_input["PrivateKeyCiphertextBlob"])) + if "PrivateKeyCiphertextBlob" in native_input.keys() + else Option_None() + ), + PublicKey=( + Option_Some(Seq(native_input["PublicKey"])) + if "PublicKey" in native_input.keys() + else Option_None() + ), + KeyId=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["KeyId"].encode("utf-16-be"))] * 2 + ) + ] + ) + ) + ) + if "KeyId" in native_input.keys() + else Option_None() + ), + KeyPairSpec=( + Option_Some( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_DataKeyPairSpec( + native_input["KeyPairSpec"] + ) + ) + if "KeyPairSpec" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_kms_GenerateDataKeyWithoutPlaintextRequest(native_input): + return DafnyGenerateDataKeyWithoutPlaintextRequest( + KeyId=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["KeyId"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + EncryptionContext=( + 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["EncryptionContext"].items() + } + ) + ) + if "EncryptionContext" in native_input.keys() + else Option_None() + ), + KeySpec=( + Option_Some( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_DataKeySpec( + native_input["KeySpec"] + ) + ) + if "KeySpec" in native_input.keys() + else Option_None() + ), + NumberOfBytes=( + Option_Some(native_input["NumberOfBytes"]) + if "NumberOfBytes" in native_input.keys() + else Option_None() + ), + 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["GrantTokens"] + ] + ) + ) + if "GrantTokens" in native_input.keys() + else Option_None() + ), + DryRun=( + Option_Some(native_input["DryRun"]) + if "DryRun" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_kms_GenerateDataKeyWithoutPlaintextResponse(native_input): + return DafnyGenerateDataKeyWithoutPlaintextResponse( + CiphertextBlob=( + Option_Some(Seq(native_input["CiphertextBlob"])) + if "CiphertextBlob" in native_input.keys() + else Option_None() + ), + KeyId=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["KeyId"].encode("utf-16-be"))] * 2 + ) + ] + ) + ) + ) + if "KeyId" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_kms_GenerateMacRequest(native_input): + return DafnyGenerateMacRequest( + Message=Seq(native_input["Message"]), + KeyId=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["KeyId"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + MacAlgorithm=aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_MacAlgorithmSpec( + native_input["MacAlgorithm"] + ), + 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["GrantTokens"] + ] + ) + ) + if "GrantTokens" in native_input.keys() + else Option_None() + ), + DryRun=( + Option_Some(native_input["DryRun"]) + if "DryRun" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_kms_GenerateMacResponse(native_input): + return DafnyGenerateMacResponse( + Mac=( + Option_Some(Seq(native_input["Mac"])) + if "Mac" in native_input.keys() + else Option_None() + ), + MacAlgorithm=( + Option_Some( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_MacAlgorithmSpec( + native_input["MacAlgorithm"] + ) + ) + if "MacAlgorithm" in native_input.keys() + else Option_None() + ), + KeyId=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["KeyId"].encode("utf-16-be"))] * 2 + ) + ] + ) + ) + ) + if "KeyId" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_kms_GenerateRandomRequest(native_input): + return DafnyGenerateRandomRequest( + NumberOfBytes=( + Option_Some(native_input["NumberOfBytes"]) + if "NumberOfBytes" in native_input.keys() + else Option_None() + ), + CustomKeyStoreId=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[ + iter( + native_input["CustomKeyStoreId"].encode( + "utf-16-be" + ) + ) + ] + * 2 + ) + ] + ) + ) + ) + if "CustomKeyStoreId" in native_input.keys() + else Option_None() + ), + Recipient=( + Option_Some( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_RecipientInfo( + native_input["Recipient"] + ) + ) + if "Recipient" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_kms_GenerateRandomResponse(native_input): + return DafnyGenerateRandomResponse( + Plaintext=( + Option_Some(Seq(native_input["Plaintext"])) + if "Plaintext" in native_input.keys() + else Option_None() + ), + CiphertextForRecipient=( + Option_Some(Seq(native_input["CiphertextForRecipient"])) + if "CiphertextForRecipient" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_kms_GetKeyPolicyRequest(native_input): + return DafnyGetKeyPolicyRequest( + KeyId=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["KeyId"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + PolicyName=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["PolicyName"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ) + ) + if "PolicyName" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_kms_GetKeyPolicyResponse(native_input): + return DafnyGetKeyPolicyResponse( + Policy=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Policy"].encode("utf-16-be"))] * 2 + ) + ] + ) + ) + ) + if "Policy" in native_input.keys() + else Option_None() + ), + PolicyName=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["PolicyName"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ) + ) + if "PolicyName" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_kms_GetKeyRotationStatusRequest(native_input): + return DafnyGetKeyRotationStatusRequest( + KeyId=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["KeyId"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_kms_GetKeyRotationStatusResponse(native_input): + return DafnyGetKeyRotationStatusResponse( + KeyRotationEnabled=( + Option_Some(native_input["KeyRotationEnabled"]) + if "KeyRotationEnabled" in native_input.keys() + else Option_None() + ), + KeyId=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["KeyId"].encode("utf-16-be"))] * 2 + ) + ] + ) + ) + ) + if "KeyId" in native_input.keys() + else Option_None() + ), + RotationPeriodInDays=( + Option_Some(native_input["RotationPeriodInDays"]) + if "RotationPeriodInDays" in native_input.keys() + else Option_None() + ), + NextRotationDate=( + Option_Some(_dafny.Seq(native_input["NextRotationDate"].isoformat())) + if "NextRotationDate" in native_input.keys() + else Option_None() + ), + OnDemandRotationStartDate=( + Option_Some( + _dafny.Seq(native_input["OnDemandRotationStartDate"].isoformat()) + ) + if "OnDemandRotationStartDate" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_kms_GetParametersForImportRequest(native_input): + return DafnyGetParametersForImportRequest( + KeyId=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["KeyId"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + WrappingAlgorithm=aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_AlgorithmSpec( + native_input["WrappingAlgorithm"] + ), + WrappingKeySpec=aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_WrappingKeySpec( + native_input["WrappingKeySpec"] + ), + ) + + +def com_amazonaws_kms_AlgorithmSpec(native_input): + # Convert AlgorithmSpec + if native_input == "RSAES_PKCS1_V1_5": + return AlgorithmSpec_RSAES__PKCS1__V1__5() + elif native_input == "RSAES_OAEP_SHA_1": + return AlgorithmSpec_RSAES__OAEP__SHA__1() + elif native_input == "RSAES_OAEP_SHA_256": + return AlgorithmSpec_RSAES__OAEP__SHA__256() + elif native_input == "RSA_AES_KEY_WRAP_SHA_1": + return AlgorithmSpec_RSA__AES__KEY__WRAP__SHA__1() + elif native_input == "RSA_AES_KEY_WRAP_SHA_256": + return AlgorithmSpec_RSA__AES__KEY__WRAP__SHA__256() + elif native_input == "SM2PKE": + return AlgorithmSpec_SM2PKE() + else: + raise ValueError("No recognized enum value in enum type: " + native_input) + + +def com_amazonaws_kms_WrappingKeySpec(native_input): + # Convert WrappingKeySpec + if native_input == "RSA_2048": + return WrappingKeySpec_RSA__2048() + elif native_input == "RSA_3072": + return WrappingKeySpec_RSA__3072() + elif native_input == "RSA_4096": + return WrappingKeySpec_RSA__4096() + elif native_input == "SM2": + return WrappingKeySpec_SM2() + else: + raise ValueError("No recognized enum value in enum type: " + native_input) + + +def com_amazonaws_kms_GetParametersForImportResponse(native_input): + return DafnyGetParametersForImportResponse( + KeyId=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["KeyId"].encode("utf-16-be"))] * 2 + ) + ] + ) + ) + ) + if "KeyId" in native_input.keys() + else Option_None() + ), + ImportToken=( + Option_Some(Seq(native_input["ImportToken"])) + if "ImportToken" in native_input.keys() + else Option_None() + ), + PublicKey=( + Option_Some(Seq(native_input["PublicKey"])) + if "PublicKey" in native_input.keys() + else Option_None() + ), + ParametersValidTo=( + Option_Some(_dafny.Seq(native_input["ParametersValidTo"].isoformat())) + if "ParametersValidTo" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_kms_GetPublicKeyRequest(native_input): + return DafnyGetPublicKeyRequest( + KeyId=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["KeyId"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + 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["GrantTokens"] + ] + ) + ) + if "GrantTokens" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_kms_GetPublicKeyResponse(native_input): + return DafnyGetPublicKeyResponse( + KeyId=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["KeyId"].encode("utf-16-be"))] * 2 + ) + ] + ) + ) + ) + if "KeyId" in native_input.keys() + else Option_None() + ), + PublicKey=( + Option_Some(Seq(native_input["PublicKey"])) + if "PublicKey" in native_input.keys() + else Option_None() + ), + CustomerMasterKeySpec=( + Option_Some( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_CustomerMasterKeySpec( + native_input["CustomerMasterKeySpec"] + ) + ) + if "CustomerMasterKeySpec" in native_input.keys() + else Option_None() + ), + KeySpec=( + Option_Some( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_KeySpec( + native_input["KeySpec"] + ) + ) + if "KeySpec" in native_input.keys() + else Option_None() + ), + KeyUsage=( + Option_Some( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_KeyUsageType( + native_input["KeyUsage"] + ) + ) + if "KeyUsage" in native_input.keys() + else Option_None() + ), + EncryptionAlgorithms=( + Option_Some( + Seq( + [ + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_EncryptionAlgorithmSpec( + list_element + ) + for list_element in native_input["EncryptionAlgorithms"] + ] + ) + ) + if "EncryptionAlgorithms" in native_input.keys() + else Option_None() + ), + SigningAlgorithms=( + Option_Some( + Seq( + [ + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_SigningAlgorithmSpec( + list_element + ) + for list_element in native_input["SigningAlgorithms"] + ] + ) + ) + if "SigningAlgorithms" in native_input.keys() + else Option_None() + ), + KeyAgreementAlgorithms=( + Option_Some( + Seq( + [ + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_KeyAgreementAlgorithmSpec( + list_element + ) + for list_element in native_input["KeyAgreementAlgorithms"] + ] + ) + ) + if "KeyAgreementAlgorithms" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_kms_ImportKeyMaterialRequest(native_input): + return DafnyImportKeyMaterialRequest( + KeyId=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["KeyId"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + ImportToken=Seq(native_input["ImportToken"]), + EncryptedKeyMaterial=Seq(native_input["EncryptedKeyMaterial"]), + ValidTo=( + Option_Some(_dafny.Seq(native_input["ValidTo"].isoformat())) + if "ValidTo" in native_input.keys() + else Option_None() + ), + ExpirationModel=( + Option_Some( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_ExpirationModelType( + native_input["ExpirationModel"] + ) + ) + if "ExpirationModel" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_kms_ImportKeyMaterialResponse(native_input): + return DafnyImportKeyMaterialResponse() + + +def com_amazonaws_kms_ListAliasesRequest(native_input): + return DafnyListAliasesRequest( + KeyId=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["KeyId"].encode("utf-16-be"))] * 2 + ) + ] + ) + ) + ) + if "KeyId" in native_input.keys() + else Option_None() + ), + Limit=( + Option_Some(native_input["Limit"]) + if "Limit" in native_input.keys() + else Option_None() + ), + Marker=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Marker"].encode("utf-16-be"))] * 2 + ) + ] + ) + ) + ) + if "Marker" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_kms_ListAliasesResponse(native_input): + return DafnyListAliasesResponse( + Aliases=( + Option_Some( + Seq( + [ + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_AliasListEntry( + list_element + ) + for list_element in native_input["Aliases"] + ] + ) + ) + if "Aliases" in native_input.keys() + else Option_None() + ), + NextMarker=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["NextMarker"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ) + ) + if "NextMarker" in native_input.keys() + else Option_None() + ), + Truncated=( + Option_Some(native_input["Truncated"]) + if "Truncated" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_kms_AliasListEntry(native_input): + return DafnyAliasListEntry( + AliasName=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["AliasName"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ) + ) + if "AliasName" in native_input.keys() + else Option_None() + ), + AliasArn=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["AliasArn"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ) + ) + if "AliasArn" in native_input.keys() + else Option_None() + ), + TargetKeyId=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["TargetKeyId"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ) + ) + if "TargetKeyId" in native_input.keys() + else Option_None() + ), + CreationDate=( + Option_Some(_dafny.Seq(native_input["CreationDate"].isoformat())) + if "CreationDate" in native_input.keys() + else Option_None() + ), + LastUpdatedDate=( + Option_Some(_dafny.Seq(native_input["LastUpdatedDate"].isoformat())) + if "LastUpdatedDate" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_kms_ListGrantsRequest(native_input): + return DafnyListGrantsRequest( + Limit=( + Option_Some(native_input["Limit"]) + if "Limit" in native_input.keys() + else Option_None() + ), + Marker=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Marker"].encode("utf-16-be"))] * 2 + ) + ] + ) + ) + ) + if "Marker" in native_input.keys() + else Option_None() + ), + KeyId=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["KeyId"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + GrantId=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["GrantId"].encode("utf-16-be"))] * 2 + ) + ] + ) + ) + ) + if "GrantId" in native_input.keys() + else Option_None() + ), + GranteePrincipal=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[ + iter( + native_input["GranteePrincipal"].encode( + "utf-16-be" + ) + ) + ] + * 2 + ) + ] + ) + ) + ) + if "GranteePrincipal" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_kms_ListGrantsResponse(native_input): + return DafnyListGrantsResponse( + Grants=( + Option_Some( + Seq( + [ + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_GrantListEntry( + list_element + ) + for list_element in native_input["Grants"] + ] + ) + ) + if "Grants" in native_input.keys() + else Option_None() + ), + NextMarker=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["NextMarker"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ) + ) + if "NextMarker" in native_input.keys() + else Option_None() + ), + Truncated=( + Option_Some(native_input["Truncated"]) + if "Truncated" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_kms_GrantListEntry(native_input): + return DafnyGrantListEntry( + KeyId=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["KeyId"].encode("utf-16-be"))] * 2 + ) + ] + ) + ) + ) + if "KeyId" in native_input.keys() + else Option_None() + ), + GrantId=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["GrantId"].encode("utf-16-be"))] * 2 + ) + ] + ) + ) + ) + if "GrantId" in native_input.keys() + else Option_None() + ), + Name=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Name"].encode("utf-16-be"))] * 2 + ) + ] + ) + ) + ) + if "Name" in native_input.keys() + else Option_None() + ), + CreationDate=( + Option_Some(_dafny.Seq(native_input["CreationDate"].isoformat())) + if "CreationDate" in native_input.keys() + else Option_None() + ), + GranteePrincipal=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[ + iter( + native_input["GranteePrincipal"].encode( + "utf-16-be" + ) + ) + ] + * 2 + ) + ] + ) + ) + ) + if "GranteePrincipal" in native_input.keys() + else Option_None() + ), + RetiringPrincipal=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[ + iter( + native_input["RetiringPrincipal"].encode( + "utf-16-be" + ) + ) + ] + * 2 + ) + ] + ) + ) + ) + if "RetiringPrincipal" in native_input.keys() + else Option_None() + ), + IssuingAccount=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[ + iter( + native_input["IssuingAccount"].encode( + "utf-16-be" + ) + ) + ] + * 2 + ) + ] + ) + ) + ) + if "IssuingAccount" in native_input.keys() + else Option_None() + ), + Operations=( + Option_Some( + Seq( + [ + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_GrantOperation( + list_element + ) + for list_element in native_input["Operations"] + ] + ) + ) + if "Operations" in native_input.keys() + else Option_None() + ), + Constraints=( + Option_Some( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_GrantConstraints( + native_input["Constraints"] + ) + ) + if "Constraints" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_kms_ListKeyPoliciesRequest(native_input): + return DafnyListKeyPoliciesRequest( + KeyId=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["KeyId"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + Limit=( + Option_Some(native_input["Limit"]) + if "Limit" in native_input.keys() + else Option_None() + ), + Marker=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Marker"].encode("utf-16-be"))] * 2 + ) + ] + ) + ) + ) + if "Marker" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_kms_ListKeyPoliciesResponse(native_input): + return DafnyListKeyPoliciesResponse( + PolicyNames=( + 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["PolicyNames"] + ] + ) + ) + if "PolicyNames" in native_input.keys() + else Option_None() + ), + NextMarker=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["NextMarker"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ) + ) + if "NextMarker" in native_input.keys() + else Option_None() + ), + Truncated=( + Option_Some(native_input["Truncated"]) + if "Truncated" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_kms_ListKeyRotationsRequest(native_input): + return DafnyListKeyRotationsRequest( + KeyId=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["KeyId"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + Limit=( + Option_Some(native_input["Limit"]) + if "Limit" in native_input.keys() + else Option_None() + ), + Marker=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Marker"].encode("utf-16-be"))] * 2 + ) + ] + ) + ) + ) + if "Marker" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_kms_ListKeyRotationsResponse(native_input): + return DafnyListKeyRotationsResponse( + Rotations=( + Option_Some( + Seq( + [ + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_RotationsListEntry( + list_element + ) + for list_element in native_input["Rotations"] + ] + ) + ) + if "Rotations" in native_input.keys() + else Option_None() + ), + NextMarker=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["NextMarker"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ) + ) + if "NextMarker" in native_input.keys() + else Option_None() + ), + Truncated=( + Option_Some(native_input["Truncated"]) + if "Truncated" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_kms_RotationsListEntry(native_input): + return DafnyRotationsListEntry( + KeyId=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["KeyId"].encode("utf-16-be"))] * 2 + ) + ] + ) + ) + ) + if "KeyId" in native_input.keys() + else Option_None() + ), + RotationDate=( + Option_Some(_dafny.Seq(native_input["RotationDate"].isoformat())) + if "RotationDate" in native_input.keys() + else Option_None() + ), + RotationType=( + Option_Some( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_RotationType( + native_input["RotationType"] + ) + ) + if "RotationType" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_kms_RotationType(native_input): + # Convert RotationType + if native_input == "AUTOMATIC": + return RotationType_AUTOMATIC() + elif native_input == "ON_DEMAND": + return RotationType_ON__DEMAND() + else: + raise ValueError("No recognized enum value in enum type: " + native_input) + + +def com_amazonaws_kms_ListKeysRequest(native_input): + return DafnyListKeysRequest( + Limit=( + Option_Some(native_input["Limit"]) + if "Limit" in native_input.keys() + else Option_None() + ), + Marker=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Marker"].encode("utf-16-be"))] * 2 + ) + ] + ) + ) + ) + if "Marker" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_kms_ListKeysResponse(native_input): + return DafnyListKeysResponse( + Keys=( + Option_Some( + Seq( + [ + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_KeyListEntry( + list_element + ) + for list_element in native_input["Keys"] + ] + ) + ) + if "Keys" in native_input.keys() + else Option_None() + ), + NextMarker=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["NextMarker"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ) + ) + if "NextMarker" in native_input.keys() + else Option_None() + ), + Truncated=( + Option_Some(native_input["Truncated"]) + if "Truncated" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_kms_KeyListEntry(native_input): + return DafnyKeyListEntry( + KeyId=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["KeyId"].encode("utf-16-be"))] * 2 + ) + ] + ) + ) + ) + if "KeyId" in native_input.keys() + else Option_None() + ), + KeyArn=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["KeyArn"].encode("utf-16-be"))] * 2 + ) + ] + ) + ) + ) + if "KeyArn" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_kms_ListResourceTagsRequest(native_input): + return DafnyListResourceTagsRequest( + KeyId=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["KeyId"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + Limit=( + Option_Some(native_input["Limit"]) + if "Limit" in native_input.keys() + else Option_None() + ), + Marker=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Marker"].encode("utf-16-be"))] * 2 + ) + ] + ) + ) + ) + if "Marker" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_kms_ListResourceTagsResponse(native_input): + return DafnyListResourceTagsResponse( + Tags=( + Option_Some( + Seq( + [ + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_Tag( + list_element + ) + for list_element in native_input["Tags"] + ] + ) + ) + if "Tags" in native_input.keys() + else Option_None() + ), + NextMarker=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["NextMarker"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ) + ) + if "NextMarker" in native_input.keys() + else Option_None() + ), + Truncated=( + Option_Some(native_input["Truncated"]) + if "Truncated" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_kms_PutKeyPolicyRequest(native_input): + return DafnyPutKeyPolicyRequest( + KeyId=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["KeyId"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + PolicyName=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["PolicyName"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ) + ) + if "PolicyName" in native_input.keys() + else Option_None() + ), + Policy=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Policy"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + BypassPolicyLockoutSafetyCheck=( + Option_Some(native_input["BypassPolicyLockoutSafetyCheck"]) + if "BypassPolicyLockoutSafetyCheck" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_kms_ReEncryptRequest(native_input): + return DafnyReEncryptRequest( + CiphertextBlob=Seq(native_input["CiphertextBlob"]), + SourceEncryptionContext=( + 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[ + "SourceEncryptionContext" + ].items() + } + ) + ) + if "SourceEncryptionContext" in native_input.keys() + else Option_None() + ), + SourceKeyId=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["SourceKeyId"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ) + ) + if "SourceKeyId" in native_input.keys() + else Option_None() + ), + DestinationKeyId=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["DestinationKeyId"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ), + DestinationEncryptionContext=( + 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[ + "DestinationEncryptionContext" + ].items() + } + ) + ) + if "DestinationEncryptionContext" in native_input.keys() + else Option_None() + ), + SourceEncryptionAlgorithm=( + Option_Some( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_EncryptionAlgorithmSpec( + native_input["SourceEncryptionAlgorithm"] + ) + ) + if "SourceEncryptionAlgorithm" in native_input.keys() + else Option_None() + ), + DestinationEncryptionAlgorithm=( + Option_Some( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_EncryptionAlgorithmSpec( + native_input["DestinationEncryptionAlgorithm"] + ) + ) + if "DestinationEncryptionAlgorithm" in native_input.keys() + else Option_None() + ), + 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["GrantTokens"] + ] + ) + ) + if "GrantTokens" in native_input.keys() + else Option_None() + ), + DryRun=( + Option_Some(native_input["DryRun"]) + if "DryRun" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_kms_ReEncryptResponse(native_input): + return DafnyReEncryptResponse( + CiphertextBlob=( + Option_Some(Seq(native_input["CiphertextBlob"])) + if "CiphertextBlob" in native_input.keys() + else Option_None() + ), + SourceKeyId=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["SourceKeyId"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ) + ) + if "SourceKeyId" in native_input.keys() + else Option_None() + ), + KeyId=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["KeyId"].encode("utf-16-be"))] * 2 + ) + ] + ) + ) + ) + if "KeyId" in native_input.keys() + else Option_None() + ), + SourceEncryptionAlgorithm=( + Option_Some( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_EncryptionAlgorithmSpec( + native_input["SourceEncryptionAlgorithm"] + ) + ) + if "SourceEncryptionAlgorithm" in native_input.keys() + else Option_None() + ), + DestinationEncryptionAlgorithm=( + Option_Some( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_EncryptionAlgorithmSpec( + native_input["DestinationEncryptionAlgorithm"] + ) + ) + if "DestinationEncryptionAlgorithm" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_kms_ReplicateKeyRequest(native_input): + return DafnyReplicateKeyRequest( + KeyId=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["KeyId"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + ReplicaRegion=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["ReplicaRegion"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + Policy=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Policy"].encode("utf-16-be"))] * 2 + ) + ] + ) + ) + ) + if "Policy" in native_input.keys() + else Option_None() + ), + BypassPolicyLockoutSafetyCheck=( + Option_Some(native_input["BypassPolicyLockoutSafetyCheck"]) + if "BypassPolicyLockoutSafetyCheck" in native_input.keys() + else Option_None() + ), + Description=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["Description"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ) + ) + if "Description" in native_input.keys() + else Option_None() + ), + Tags=( + Option_Some( + Seq( + [ + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_Tag( + list_element + ) + for list_element in native_input["Tags"] + ] + ) + ) + if "Tags" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_kms_ReplicateKeyResponse(native_input): + return DafnyReplicateKeyResponse( + ReplicaKeyMetadata=( + Option_Some( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_KeyMetadata( + native_input["ReplicaKeyMetadata"] + ) + ) + if "ReplicaKeyMetadata" in native_input.keys() + else Option_None() + ), + ReplicaPolicy=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[ + iter( + native_input["ReplicaPolicy"].encode( + "utf-16-be" + ) + ) + ] + * 2 + ) + ] + ) + ) + ) + if "ReplicaPolicy" in native_input.keys() + else Option_None() + ), + ReplicaTags=( + Option_Some( + Seq( + [ + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_Tag( + list_element + ) + for list_element in native_input["ReplicaTags"] + ] + ) + ) + if "ReplicaTags" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_kms_RetireGrantRequest(native_input): + return DafnyRetireGrantRequest( + GrantToken=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["GrantToken"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ) + ) + if "GrantToken" in native_input.keys() + else Option_None() + ), + KeyId=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["KeyId"].encode("utf-16-be"))] * 2 + ) + ] + ) + ) + ) + if "KeyId" in native_input.keys() + else Option_None() + ), + GrantId=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["GrantId"].encode("utf-16-be"))] * 2 + ) + ] + ) + ) + ) + if "GrantId" in native_input.keys() + else Option_None() + ), + DryRun=( + Option_Some(native_input["DryRun"]) + if "DryRun" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_kms_RevokeGrantRequest(native_input): + return DafnyRevokeGrantRequest( + KeyId=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["KeyId"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + GrantId=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["GrantId"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + DryRun=( + Option_Some(native_input["DryRun"]) + if "DryRun" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_kms_RotateKeyOnDemandRequest(native_input): + return DafnyRotateKeyOnDemandRequest( + KeyId=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["KeyId"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_kms_RotateKeyOnDemandResponse(native_input): + return DafnyRotateKeyOnDemandResponse( + KeyId=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["KeyId"].encode("utf-16-be"))] * 2 + ) + ] + ) + ) + ) + if "KeyId" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_kms_ScheduleKeyDeletionRequest(native_input): + return DafnyScheduleKeyDeletionRequest( + KeyId=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["KeyId"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + PendingWindowInDays=( + Option_Some(native_input["PendingWindowInDays"]) + if "PendingWindowInDays" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_kms_ScheduleKeyDeletionResponse(native_input): + return DafnyScheduleKeyDeletionResponse( + KeyId=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["KeyId"].encode("utf-16-be"))] * 2 + ) + ] + ) + ) + ) + if "KeyId" in native_input.keys() + else Option_None() + ), + DeletionDate=( + Option_Some(_dafny.Seq(native_input["DeletionDate"].isoformat())) + if "DeletionDate" in native_input.keys() + else Option_None() + ), + KeyState=( + Option_Some( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_KeyState( + native_input["KeyState"] + ) + ) + if "KeyState" in native_input.keys() + else Option_None() + ), + PendingWindowInDays=( + Option_Some(native_input["PendingWindowInDays"]) + if "PendingWindowInDays" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_kms_SignRequest(native_input): + return DafnySignRequest( + KeyId=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["KeyId"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + Message=Seq(native_input["Message"]), + MessageType=( + Option_Some( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_MessageType( + native_input["MessageType"] + ) + ) + if "MessageType" in native_input.keys() + else Option_None() + ), + 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["GrantTokens"] + ] + ) + ) + if "GrantTokens" in native_input.keys() + else Option_None() + ), + SigningAlgorithm=aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_SigningAlgorithmSpec( + native_input["SigningAlgorithm"] + ), + DryRun=( + Option_Some(native_input["DryRun"]) + if "DryRun" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_kms_MessageType(native_input): + # Convert MessageType + if native_input == "RAW": + return MessageType_RAW() + elif native_input == "DIGEST": + return MessageType_DIGEST() + else: + raise ValueError("No recognized enum value in enum type: " + native_input) + + +def com_amazonaws_kms_SignResponse(native_input): + return DafnySignResponse( + KeyId=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["KeyId"].encode("utf-16-be"))] * 2 + ) + ] + ) + ) + ) + if "KeyId" in native_input.keys() + else Option_None() + ), + Signature=( + Option_Some(Seq(native_input["Signature"])) + if "Signature" in native_input.keys() + else Option_None() + ), + SigningAlgorithm=( + Option_Some( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_SigningAlgorithmSpec( + native_input["SigningAlgorithm"] + ) + ) + if "SigningAlgorithm" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_kms_TagResourceRequest(native_input): + return DafnyTagResourceRequest( + KeyId=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["KeyId"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + Tags=Seq( + [ + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_Tag( + list_element + ) + for list_element in native_input["Tags"] + ] + ), + ) + + +def com_amazonaws_kms_UntagResourceRequest(native_input): + return DafnyUntagResourceRequest( + KeyId=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["KeyId"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + TagKeys=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["TagKeys"] + ] + ), + ) + + +def com_amazonaws_kms_UpdateAliasRequest(native_input): + return DafnyUpdateAliasRequest( + AliasName=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["AliasName"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + TargetKeyId=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["TargetKeyId"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_kms_UpdateCustomKeyStoreRequest(native_input): + return DafnyUpdateCustomKeyStoreRequest( + CustomKeyStoreId=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["CustomKeyStoreId"].encode("utf-16-be"))] + * 2 + ) + ] + ) + ), + NewCustomKeyStoreName=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[ + iter( + native_input["NewCustomKeyStoreName"].encode( + "utf-16-be" + ) + ) + ] + * 2 + ) + ] + ) + ) + ) + if "NewCustomKeyStoreName" in native_input.keys() + else Option_None() + ), + KeyStorePassword=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[ + iter( + native_input["KeyStorePassword"].encode( + "utf-16-be" + ) + ) + ] + * 2 + ) + ] + ) + ) + ) + if "KeyStorePassword" in native_input.keys() + else Option_None() + ), + CloudHsmClusterId=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[ + iter( + native_input["CloudHsmClusterId"].encode( + "utf-16-be" + ) + ) + ] + * 2 + ) + ] + ) + ) + ) + if "CloudHsmClusterId" in native_input.keys() + else Option_None() + ), + XksProxyUriEndpoint=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[ + iter( + native_input["XksProxyUriEndpoint"].encode( + "utf-16-be" + ) + ) + ] + * 2 + ) + ] + ) + ) + ) + if "XksProxyUriEndpoint" in native_input.keys() + else Option_None() + ), + XksProxyUriPath=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[ + iter( + native_input["XksProxyUriPath"].encode( + "utf-16-be" + ) + ) + ] + * 2 + ) + ] + ) + ) + ) + if "XksProxyUriPath" in native_input.keys() + else Option_None() + ), + XksProxyVpcEndpointServiceName=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[ + iter( + native_input[ + "XksProxyVpcEndpointServiceName" + ].encode("utf-16-be") + ) + ] + * 2 + ) + ] + ) + ) + ) + if "XksProxyVpcEndpointServiceName" in native_input.keys() + else Option_None() + ), + XksProxyAuthenticationCredential=( + Option_Some( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_XksProxyAuthenticationCredentialType( + native_input["XksProxyAuthenticationCredential"] + ) + ) + if "XksProxyAuthenticationCredential" in native_input.keys() + else Option_None() + ), + XksProxyConnectivity=( + Option_Some( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_XksProxyConnectivityType( + native_input["XksProxyConnectivity"] + ) + ) + if "XksProxyConnectivity" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_kms_UpdateCustomKeyStoreResponse(native_input): + return DafnyUpdateCustomKeyStoreResponse() + + +def com_amazonaws_kms_UpdateKeyDescriptionRequest(native_input): + return DafnyUpdateKeyDescriptionRequest( + KeyId=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["KeyId"].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 com_amazonaws_kms_UpdatePrimaryRegionRequest(native_input): + return DafnyUpdatePrimaryRegionRequest( + KeyId=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["KeyId"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + PrimaryRegion=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["PrimaryRegion"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + ) + + +def com_amazonaws_kms_VerifyRequest(native_input): + return DafnyVerifyRequest( + KeyId=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["KeyId"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + Message=Seq(native_input["Message"]), + MessageType=( + Option_Some( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_MessageType( + native_input["MessageType"] + ) + ) + if "MessageType" in native_input.keys() + else Option_None() + ), + Signature=Seq(native_input["Signature"]), + SigningAlgorithm=aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_SigningAlgorithmSpec( + native_input["SigningAlgorithm"] + ), + 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["GrantTokens"] + ] + ) + ) + if "GrantTokens" in native_input.keys() + else Option_None() + ), + DryRun=( + Option_Some(native_input["DryRun"]) + if "DryRun" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_kms_VerifyResponse(native_input): + return DafnyVerifyResponse( + KeyId=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["KeyId"].encode("utf-16-be"))] * 2 + ) + ] + ) + ) + ) + if "KeyId" in native_input.keys() + else Option_None() + ), + SignatureValid=( + Option_Some(native_input["SignatureValid"]) + if "SignatureValid" in native_input.keys() + else Option_None() + ), + SigningAlgorithm=( + Option_Some( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_SigningAlgorithmSpec( + native_input["SigningAlgorithm"] + ) + ) + if "SigningAlgorithm" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_kms_VerifyMacRequest(native_input): + return DafnyVerifyMacRequest( + Message=Seq(native_input["Message"]), + KeyId=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["KeyId"].encode("utf-16-be"))] * 2 + ) + ] + ) + ), + MacAlgorithm=aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_MacAlgorithmSpec( + native_input["MacAlgorithm"] + ), + Mac=Seq(native_input["Mac"]), + 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["GrantTokens"] + ] + ) + ) + if "GrantTokens" in native_input.keys() + else Option_None() + ), + DryRun=( + Option_Some(native_input["DryRun"]) + if "DryRun" in native_input.keys() + else Option_None() + ), + ) + + +def com_amazonaws_kms_VerifyMacResponse(native_input): + return DafnyVerifyMacResponse( + KeyId=( + Option_Some( + Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input["KeyId"].encode("utf-16-be"))] * 2 + ) + ] + ) + ) + ) + if "KeyId" in native_input.keys() + else Option_None() + ), + MacValid=( + Option_Some(native_input["MacValid"]) + if "MacValid" in native_input.keys() + else Option_None() + ), + MacAlgorithm=( + Option_Some( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_MacAlgorithmSpec( + native_input["MacAlgorithm"] + ) + ) + if "MacAlgorithm" in native_input.keys() + else Option_None() + ), + ) diff --git a/ComAmazonawsKms/runtimes/python/src/aws_cryptography_internal_kms/smithygenerated/com_amazonaws_kms/dafny_to_aws_sdk.py b/ComAmazonawsKms/runtimes/python/src/aws_cryptography_internal_kms/smithygenerated/com_amazonaws_kms/dafny_to_aws_sdk.py new file mode 100644 index 000000000..ec3b1ec54 --- /dev/null +++ b/ComAmazonawsKms/runtimes/python/src/aws_cryptography_internal_kms/smithygenerated/com_amazonaws_kms/dafny_to_aws_sdk.py @@ -0,0 +1,3533 @@ +# 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_cryptography_internal_kms.internaldafny.generated.ComAmazonawsKmsTypes import ( + AlgorithmSpec_RSAES__OAEP__SHA__1, + AlgorithmSpec_RSAES__OAEP__SHA__256, + AlgorithmSpec_RSAES__PKCS1__V1__5, + AlgorithmSpec_RSA__AES__KEY__WRAP__SHA__1, + AlgorithmSpec_RSA__AES__KEY__WRAP__SHA__256, + AlgorithmSpec_SM2PKE, + ConnectionErrorCodeType_CLUSTER__NOT__FOUND, + ConnectionErrorCodeType_INSUFFICIENT__CLOUDHSM__HSMS, + ConnectionErrorCodeType_INSUFFICIENT__FREE__ADDRESSES__IN__SUBNET, + ConnectionErrorCodeType_INTERNAL__ERROR, + ConnectionErrorCodeType_INVALID__CREDENTIALS, + ConnectionErrorCodeType_NETWORK__ERRORS, + ConnectionErrorCodeType_SUBNET__NOT__FOUND, + ConnectionErrorCodeType_USER__LOCKED__OUT, + ConnectionErrorCodeType_USER__LOGGED__IN, + ConnectionErrorCodeType_USER__NOT__FOUND, + ConnectionErrorCodeType_XKS__PROXY__ACCESS__DENIED, + ConnectionErrorCodeType_XKS__PROXY__INVALID__CONFIGURATION, + ConnectionErrorCodeType_XKS__PROXY__INVALID__RESPONSE, + ConnectionErrorCodeType_XKS__PROXY__INVALID__TLS__CONFIGURATION, + ConnectionErrorCodeType_XKS__PROXY__NOT__REACHABLE, + ConnectionErrorCodeType_XKS__PROXY__TIMED__OUT, + ConnectionErrorCodeType_XKS__VPC__ENDPOINT__SERVICE__INVALID__CONFIGURATION, + ConnectionErrorCodeType_XKS__VPC__ENDPOINT__SERVICE__NOT__FOUND, + ConnectionStateType_CONNECTED, + ConnectionStateType_CONNECTING, + ConnectionStateType_DISCONNECTED, + ConnectionStateType_DISCONNECTING, + ConnectionStateType_FAILED, + CustomKeyStoreType_AWS__CLOUDHSM, + CustomKeyStoreType_EXTERNAL__KEY__STORE, + CustomerMasterKeySpec_ECC__NIST__P256, + CustomerMasterKeySpec_ECC__NIST__P384, + CustomerMasterKeySpec_ECC__NIST__P521, + CustomerMasterKeySpec_ECC__SECG__P256K1, + CustomerMasterKeySpec_HMAC__224, + CustomerMasterKeySpec_HMAC__256, + CustomerMasterKeySpec_HMAC__384, + CustomerMasterKeySpec_HMAC__512, + CustomerMasterKeySpec_RSA__2048, + CustomerMasterKeySpec_RSA__3072, + CustomerMasterKeySpec_RSA__4096, + CustomerMasterKeySpec_SM2, + CustomerMasterKeySpec_SYMMETRIC__DEFAULT, + DataKeyPairSpec_ECC__NIST__P256, + DataKeyPairSpec_ECC__NIST__P384, + DataKeyPairSpec_ECC__NIST__P521, + DataKeyPairSpec_ECC__SECG__P256K1, + DataKeyPairSpec_RSA__2048, + DataKeyPairSpec_RSA__3072, + DataKeyPairSpec_RSA__4096, + DataKeyPairSpec_SM2, + DataKeySpec_AES__128, + DataKeySpec_AES__256, + EncryptionAlgorithmSpec_RSAES__OAEP__SHA__1, + EncryptionAlgorithmSpec_RSAES__OAEP__SHA__256, + EncryptionAlgorithmSpec_SYMMETRIC__DEFAULT, + ExpirationModelType_KEY__MATERIAL__DOES__NOT__EXPIRE, + ExpirationModelType_KEY__MATERIAL__EXPIRES, + GrantOperation_CreateGrant, + GrantOperation_Decrypt, + GrantOperation_DeriveSharedSecret, + GrantOperation_DescribeKey, + GrantOperation_Encrypt, + GrantOperation_GenerateDataKey, + GrantOperation_GenerateDataKeyPair, + GrantOperation_GenerateDataKeyPairWithoutPlaintext, + GrantOperation_GenerateDataKeyWithoutPlaintext, + GrantOperation_GenerateMac, + GrantOperation_GetPublicKey, + GrantOperation_ReEncryptFrom, + GrantOperation_ReEncryptTo, + GrantOperation_RetireGrant, + GrantOperation_Sign, + GrantOperation_Verify, + GrantOperation_VerifyMac, + KeyAgreementAlgorithmSpec_ECDH, + KeyEncryptionMechanism_RSAES__OAEP__SHA__256, + KeyManagerType_AWS, + KeyManagerType_CUSTOMER, + KeySpec_ECC__NIST__P256, + KeySpec_ECC__NIST__P384, + KeySpec_ECC__NIST__P521, + KeySpec_ECC__SECG__P256K1, + KeySpec_HMAC__224, + KeySpec_HMAC__256, + KeySpec_HMAC__384, + KeySpec_HMAC__512, + KeySpec_RSA__2048, + KeySpec_RSA__3072, + KeySpec_RSA__4096, + KeySpec_SM2, + KeySpec_SYMMETRIC__DEFAULT, + KeyState_Creating, + KeyState_Disabled, + KeyState_Enabled, + KeyState_PendingDeletion, + KeyState_PendingImport, + KeyState_PendingReplicaDeletion, + KeyState_Unavailable, + KeyState_Updating, + KeyUsageType_ENCRYPT__DECRYPT, + KeyUsageType_GENERATE__VERIFY__MAC, + KeyUsageType_KEY__AGREEMENT, + KeyUsageType_SIGN__VERIFY, + MacAlgorithmSpec_HMAC__SHA__224, + MacAlgorithmSpec_HMAC__SHA__256, + MacAlgorithmSpec_HMAC__SHA__384, + MacAlgorithmSpec_HMAC__SHA__512, + MessageType_DIGEST, + MessageType_RAW, + MultiRegionKeyType_PRIMARY, + MultiRegionKeyType_REPLICA, + OriginType_AWS__CLOUDHSM, + OriginType_AWS__KMS, + OriginType_EXTERNAL, + OriginType_EXTERNAL__KEY__STORE, + RotationType_AUTOMATIC, + RotationType_ON__DEMAND, + SigningAlgorithmSpec_ECDSA__SHA__256, + SigningAlgorithmSpec_ECDSA__SHA__384, + SigningAlgorithmSpec_ECDSA__SHA__512, + SigningAlgorithmSpec_RSASSA__PKCS1__V1__5__SHA__256, + SigningAlgorithmSpec_RSASSA__PKCS1__V1__5__SHA__384, + SigningAlgorithmSpec_RSASSA__PKCS1__V1__5__SHA__512, + SigningAlgorithmSpec_RSASSA__PSS__SHA__256, + SigningAlgorithmSpec_RSASSA__PSS__SHA__384, + SigningAlgorithmSpec_RSASSA__PSS__SHA__512, + SigningAlgorithmSpec_SM2DSA, + WrappingKeySpec_RSA__2048, + WrappingKeySpec_RSA__3072, + WrappingKeySpec_RSA__4096, + WrappingKeySpec_SM2, + XksProxyConnectivityType_PUBLIC__ENDPOINT, + XksProxyConnectivityType_VPC__ENDPOINT__SERVICE, +) +import aws_cryptography_internal_kms.internaldafny.generated.module_ +import aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk +from datetime import datetime + + +def com_amazonaws_kms_AlreadyExistsException(dafny_input): + output = {} + if dafny_input.message.is_Some: + output["message"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.message.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_kms_CloudHsmClusterInUseException(dafny_input): + output = {} + if dafny_input.message.is_Some: + output["message"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.message.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_kms_CloudHsmClusterInvalidConfigurationException(dafny_input): + output = {} + if dafny_input.message.is_Some: + output["message"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.message.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_kms_CloudHsmClusterNotActiveException(dafny_input): + output = {} + if dafny_input.message.is_Some: + output["message"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.message.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_kms_CloudHsmClusterNotFoundException(dafny_input): + output = {} + if dafny_input.message.is_Some: + output["message"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.message.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_kms_CloudHsmClusterNotRelatedException(dafny_input): + output = {} + if dafny_input.message.is_Some: + output["message"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.message.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_kms_ConflictException(dafny_input): + output = {} + if dafny_input.message.is_Some: + output["message"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.message.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_kms_CustomKeyStoreHasCMKsException(dafny_input): + output = {} + if dafny_input.message.is_Some: + output["message"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.message.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_kms_CustomKeyStoreInvalidStateException(dafny_input): + output = {} + if dafny_input.message.is_Some: + output["message"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.message.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_kms_CustomKeyStoreNameInUseException(dafny_input): + output = {} + if dafny_input.message.is_Some: + output["message"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.message.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_kms_CustomKeyStoreNotFoundException(dafny_input): + output = {} + if dafny_input.message.is_Some: + output["message"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.message.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_kms_DependencyTimeoutException(dafny_input): + output = {} + if dafny_input.message.is_Some: + output["message"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.message.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_kms_DisabledException(dafny_input): + output = {} + if dafny_input.message.is_Some: + output["message"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.message.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_kms_DryRunOperationException(dafny_input): + output = {} + if dafny_input.message.is_Some: + output["message"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.message.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_kms_ExpiredImportTokenException(dafny_input): + output = {} + if dafny_input.message.is_Some: + output["message"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.message.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_kms_IncorrectKeyException(dafny_input): + output = {} + if dafny_input.message.is_Some: + output["message"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.message.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_kms_IncorrectKeyMaterialException(dafny_input): + output = {} + if dafny_input.message.is_Some: + output["message"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.message.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_kms_IncorrectTrustAnchorException(dafny_input): + output = {} + if dafny_input.message.is_Some: + output["message"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.message.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_kms_InvalidAliasNameException(dafny_input): + output = {} + if dafny_input.message.is_Some: + output["message"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.message.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_kms_InvalidArnException(dafny_input): + output = {} + if dafny_input.message.is_Some: + output["message"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.message.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_kms_InvalidCiphertextException(dafny_input): + output = {} + if dafny_input.message.is_Some: + output["message"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.message.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_kms_InvalidGrantIdException(dafny_input): + output = {} + if dafny_input.message.is_Some: + output["message"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.message.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_kms_InvalidGrantTokenException(dafny_input): + output = {} + if dafny_input.message.is_Some: + output["message"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.message.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_kms_InvalidImportTokenException(dafny_input): + output = {} + if dafny_input.message.is_Some: + output["message"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.message.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_kms_InvalidKeyUsageException(dafny_input): + output = {} + if dafny_input.message.is_Some: + output["message"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.message.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_kms_InvalidMarkerException(dafny_input): + output = {} + if dafny_input.message.is_Some: + output["message"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.message.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_kms_KeyUnavailableException(dafny_input): + output = {} + if dafny_input.message.is_Some: + output["message"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.message.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_kms_KMSInternalException(dafny_input): + output = {} + if dafny_input.message.is_Some: + output["message"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.message.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_kms_KMSInvalidMacException(dafny_input): + output = {} + if dafny_input.message.is_Some: + output["message"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.message.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_kms_KMSInvalidSignatureException(dafny_input): + output = {} + if dafny_input.message.is_Some: + output["message"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.message.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_kms_KMSInvalidStateException(dafny_input): + output = {} + if dafny_input.message.is_Some: + output["message"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.message.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_kms_LimitExceededException(dafny_input): + output = {} + if dafny_input.message.is_Some: + output["message"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.message.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_kms_MalformedPolicyDocumentException(dafny_input): + output = {} + if dafny_input.message.is_Some: + output["message"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.message.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_kms_NotFoundException(dafny_input): + output = {} + if dafny_input.message.is_Some: + output["message"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.message.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_kms_TagException(dafny_input): + output = {} + if dafny_input.message.is_Some: + output["message"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.message.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_kms_UnsupportedOperationException(dafny_input): + output = {} + if dafny_input.message.is_Some: + output["message"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.message.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_kms_XksKeyAlreadyInUseException(dafny_input): + output = {} + if dafny_input.message.is_Some: + output["message"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.message.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_kms_XksKeyInvalidConfigurationException(dafny_input): + output = {} + if dafny_input.message.is_Some: + output["message"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.message.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_kms_XksKeyNotFoundException(dafny_input): + output = {} + if dafny_input.message.is_Some: + output["message"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.message.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_kms_XksProxyIncorrectAuthenticationCredentialException(dafny_input): + output = {} + if dafny_input.message.is_Some: + output["message"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.message.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_kms_XksProxyInvalidConfigurationException(dafny_input): + output = {} + if dafny_input.message.is_Some: + output["message"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.message.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_kms_XksProxyInvalidResponseException(dafny_input): + output = {} + if dafny_input.message.is_Some: + output["message"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.message.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_kms_XksProxyUriEndpointInUseException(dafny_input): + output = {} + if dafny_input.message.is_Some: + output["message"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.message.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_kms_XksProxyUriInUseException(dafny_input): + output = {} + if dafny_input.message.is_Some: + output["message"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.message.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_kms_XksProxyUriUnreachableException(dafny_input): + output = {} + if dafny_input.message.is_Some: + output["message"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.message.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_kms_XksProxyVpcEndpointServiceInUseException(dafny_input): + output = {} + if dafny_input.message.is_Some: + output["message"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.message.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_kms_XksProxyVpcEndpointServiceInvalidConfigurationException( + dafny_input, +): + output = {} + if dafny_input.message.is_Some: + output["message"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.message.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_kms_XksProxyVpcEndpointServiceNotFoundException(dafny_input): + output = {} + if dafny_input.message.is_Some: + output["message"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.message.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_kms_CancelKeyDeletionRequest(dafny_input): + output = {} + output["KeyId"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.KeyId + ).decode("utf-16-be") + return output + + +def com_amazonaws_kms_CancelKeyDeletionResponse(dafny_input): + output = {} + if dafny_input.KeyId.is_Some: + output["KeyId"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.KeyId.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_kms_ConnectCustomKeyStoreRequest(dafny_input): + output = {} + output["CustomKeyStoreId"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.CustomKeyStoreId + ).decode("utf-16-be") + return output + + +def com_amazonaws_kms_ConnectCustomKeyStoreResponse(dafny_input): + output = {} + return output + + +def com_amazonaws_kms_CreateAliasRequest(dafny_input): + output = {} + output["AliasName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.AliasName + ).decode("utf-16-be") + output["TargetKeyId"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.TargetKeyId + ).decode("utf-16-be") + return output + + +def com_amazonaws_kms_CustomKeyStoreType(dafny_input): + # Convert CustomKeyStoreType + if isinstance(dafny_input, CustomKeyStoreType_AWS__CLOUDHSM): + return "AWS_CLOUDHSM" + + elif isinstance(dafny_input, CustomKeyStoreType_EXTERNAL__KEY__STORE): + return "EXTERNAL_KEY_STORE" + + else: + raise ValueError("No recognized enum value in enum type: " + dafny_input) + + +def com_amazonaws_kms_XksProxyAuthenticationCredentialType(dafny_input): + output = {} + output["AccessKeyId"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.AccessKeyId + ).decode("utf-16-be") + output["RawSecretAccessKey"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.RawSecretAccessKey + ).decode("utf-16-be") + return output + + +def com_amazonaws_kms_XksProxyConnectivityType(dafny_input): + # Convert XksProxyConnectivityType + if isinstance(dafny_input, XksProxyConnectivityType_PUBLIC__ENDPOINT): + return "PUBLIC_ENDPOINT" + + elif isinstance(dafny_input, XksProxyConnectivityType_VPC__ENDPOINT__SERVICE): + return "VPC_ENDPOINT_SERVICE" + + else: + raise ValueError("No recognized enum value in enum type: " + dafny_input) + + +def com_amazonaws_kms_CreateCustomKeyStoreRequest(dafny_input): + output = {} + output["CustomKeyStoreName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.CustomKeyStoreName + ).decode("utf-16-be") + if dafny_input.CloudHsmClusterId.is_Some: + output["CloudHsmClusterId"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.CloudHsmClusterId.value + ).decode("utf-16-be") + + if dafny_input.TrustAnchorCertificate.is_Some: + output["TrustAnchorCertificate"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.TrustAnchorCertificate.value + ).decode("utf-16-be") + + if dafny_input.KeyStorePassword.is_Some: + output["KeyStorePassword"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.KeyStorePassword.value + ).decode("utf-16-be") + + if dafny_input.CustomKeyStoreType.is_Some: + output["CustomKeyStoreType"] = ( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_CustomKeyStoreType( + dafny_input.CustomKeyStoreType.value + ) + ) + + if dafny_input.XksProxyUriEndpoint.is_Some: + output["XksProxyUriEndpoint"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.XksProxyUriEndpoint.value + ).decode("utf-16-be") + + if dafny_input.XksProxyUriPath.is_Some: + output["XksProxyUriPath"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.XksProxyUriPath.value + ).decode("utf-16-be") + + if dafny_input.XksProxyVpcEndpointServiceName.is_Some: + output["XksProxyVpcEndpointServiceName"] = b"".join( + ord(c).to_bytes(2, "big") + for c in dafny_input.XksProxyVpcEndpointServiceName.value + ).decode("utf-16-be") + + if dafny_input.XksProxyAuthenticationCredential.is_Some: + output["XksProxyAuthenticationCredential"] = ( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_XksProxyAuthenticationCredentialType( + dafny_input.XksProxyAuthenticationCredential.value + ) + ) + + if dafny_input.XksProxyConnectivity.is_Some: + output["XksProxyConnectivity"] = ( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_XksProxyConnectivityType( + dafny_input.XksProxyConnectivity.value + ) + ) + + return output + + +def com_amazonaws_kms_CreateCustomKeyStoreResponse(dafny_input): + output = {} + if dafny_input.CustomKeyStoreId.is_Some: + output["CustomKeyStoreId"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.CustomKeyStoreId.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_kms_GrantOperation(dafny_input): + # Convert GrantOperation + if isinstance(dafny_input, GrantOperation_Decrypt): + return "Decrypt" + + elif isinstance(dafny_input, GrantOperation_Encrypt): + return "Encrypt" + + elif isinstance(dafny_input, GrantOperation_GenerateDataKey): + return "GenerateDataKey" + + elif isinstance(dafny_input, GrantOperation_GenerateDataKeyWithoutPlaintext): + return "GenerateDataKeyWithoutPlaintext" + + elif isinstance(dafny_input, GrantOperation_ReEncryptFrom): + return "ReEncryptFrom" + + elif isinstance(dafny_input, GrantOperation_ReEncryptTo): + return "ReEncryptTo" + + elif isinstance(dafny_input, GrantOperation_Sign): + return "Sign" + + elif isinstance(dafny_input, GrantOperation_Verify): + return "Verify" + + elif isinstance(dafny_input, GrantOperation_GetPublicKey): + return "GetPublicKey" + + elif isinstance(dafny_input, GrantOperation_CreateGrant): + return "CreateGrant" + + elif isinstance(dafny_input, GrantOperation_RetireGrant): + return "RetireGrant" + + elif isinstance(dafny_input, GrantOperation_DescribeKey): + return "DescribeKey" + + elif isinstance(dafny_input, GrantOperation_GenerateDataKeyPair): + return "GenerateDataKeyPair" + + elif isinstance(dafny_input, GrantOperation_GenerateDataKeyPairWithoutPlaintext): + return "GenerateDataKeyPairWithoutPlaintext" + + elif isinstance(dafny_input, GrantOperation_GenerateMac): + return "GenerateMac" + + elif isinstance(dafny_input, GrantOperation_VerifyMac): + return "VerifyMac" + + elif isinstance(dafny_input, GrantOperation_DeriveSharedSecret): + return "DeriveSharedSecret" + + else: + raise ValueError("No recognized enum value in enum type: " + dafny_input) + + +def com_amazonaws_kms_GrantConstraints(dafny_input): + output = {} + if dafny_input.EncryptionContextSubset.is_Some: + output["EncryptionContextSubset"] = { + 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.EncryptionContextSubset.value.items + } + + if dafny_input.EncryptionContextEquals.is_Some: + output["EncryptionContextEquals"] = { + 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.EncryptionContextEquals.value.items + } + + return output + + +def com_amazonaws_kms_CreateGrantRequest(dafny_input): + output = {} + output["KeyId"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.KeyId + ).decode("utf-16-be") + output["GranteePrincipal"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.GranteePrincipal + ).decode("utf-16-be") + if dafny_input.RetiringPrincipal.is_Some: + output["RetiringPrincipal"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.RetiringPrincipal.value + ).decode("utf-16-be") + + output["Operations"] = [ + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_GrantOperation( + list_element + ) + for list_element in dafny_input.Operations + ] + if dafny_input.Constraints.is_Some: + output["Constraints"] = ( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_GrantConstraints( + dafny_input.Constraints.value + ) + ) + + if dafny_input.GrantTokens.is_Some: + output["GrantTokens"] = [ + 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.Name.is_Some: + output["Name"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.Name.value + ).decode("utf-16-be") + + if dafny_input.DryRun.is_Some: + output["DryRun"] = dafny_input.DryRun.value + + return output + + +def com_amazonaws_kms_CreateGrantResponse(dafny_input): + output = {} + if dafny_input.GrantToken.is_Some: + output["GrantToken"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.GrantToken.value + ).decode("utf-16-be") + + if dafny_input.GrantId.is_Some: + output["GrantId"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.GrantId.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_kms_KeyUsageType(dafny_input): + # Convert KeyUsageType + if isinstance(dafny_input, KeyUsageType_SIGN__VERIFY): + return "SIGN_VERIFY" + + elif isinstance(dafny_input, KeyUsageType_ENCRYPT__DECRYPT): + return "ENCRYPT_DECRYPT" + + elif isinstance(dafny_input, KeyUsageType_GENERATE__VERIFY__MAC): + return "GENERATE_VERIFY_MAC" + + elif isinstance(dafny_input, KeyUsageType_KEY__AGREEMENT): + return "KEY_AGREEMENT" + + else: + raise ValueError("No recognized enum value in enum type: " + dafny_input) + + +def com_amazonaws_kms_CustomerMasterKeySpec(dafny_input): + # Convert CustomerMasterKeySpec + if isinstance(dafny_input, CustomerMasterKeySpec_RSA__2048): + return "RSA_2048" + + elif isinstance(dafny_input, CustomerMasterKeySpec_RSA__3072): + return "RSA_3072" + + elif isinstance(dafny_input, CustomerMasterKeySpec_RSA__4096): + return "RSA_4096" + + elif isinstance(dafny_input, CustomerMasterKeySpec_ECC__NIST__P256): + return "ECC_NIST_P256" + + elif isinstance(dafny_input, CustomerMasterKeySpec_ECC__NIST__P384): + return "ECC_NIST_P384" + + elif isinstance(dafny_input, CustomerMasterKeySpec_ECC__NIST__P521): + return "ECC_NIST_P521" + + elif isinstance(dafny_input, CustomerMasterKeySpec_ECC__SECG__P256K1): + return "ECC_SECG_P256K1" + + elif isinstance(dafny_input, CustomerMasterKeySpec_SYMMETRIC__DEFAULT): + return "SYMMETRIC_DEFAULT" + + elif isinstance(dafny_input, CustomerMasterKeySpec_HMAC__224): + return "HMAC_224" + + elif isinstance(dafny_input, CustomerMasterKeySpec_HMAC__256): + return "HMAC_256" + + elif isinstance(dafny_input, CustomerMasterKeySpec_HMAC__384): + return "HMAC_384" + + elif isinstance(dafny_input, CustomerMasterKeySpec_HMAC__512): + return "HMAC_512" + + elif isinstance(dafny_input, CustomerMasterKeySpec_SM2): + return "SM2" + + else: + raise ValueError("No recognized enum value in enum type: " + dafny_input) + + +def com_amazonaws_kms_KeySpec(dafny_input): + # Convert KeySpec + if isinstance(dafny_input, KeySpec_RSA__2048): + return "RSA_2048" + + elif isinstance(dafny_input, KeySpec_RSA__3072): + return "RSA_3072" + + elif isinstance(dafny_input, KeySpec_RSA__4096): + return "RSA_4096" + + elif isinstance(dafny_input, KeySpec_ECC__NIST__P256): + return "ECC_NIST_P256" + + elif isinstance(dafny_input, KeySpec_ECC__NIST__P384): + return "ECC_NIST_P384" + + elif isinstance(dafny_input, KeySpec_ECC__NIST__P521): + return "ECC_NIST_P521" + + elif isinstance(dafny_input, KeySpec_ECC__SECG__P256K1): + return "ECC_SECG_P256K1" + + elif isinstance(dafny_input, KeySpec_SYMMETRIC__DEFAULT): + return "SYMMETRIC_DEFAULT" + + elif isinstance(dafny_input, KeySpec_HMAC__224): + return "HMAC_224" + + elif isinstance(dafny_input, KeySpec_HMAC__256): + return "HMAC_256" + + elif isinstance(dafny_input, KeySpec_HMAC__384): + return "HMAC_384" + + elif isinstance(dafny_input, KeySpec_HMAC__512): + return "HMAC_512" + + elif isinstance(dafny_input, KeySpec_SM2): + return "SM2" + + else: + raise ValueError("No recognized enum value in enum type: " + dafny_input) + + +def com_amazonaws_kms_OriginType(dafny_input): + # Convert OriginType + if isinstance(dafny_input, OriginType_AWS__KMS): + return "AWS_KMS" + + elif isinstance(dafny_input, OriginType_EXTERNAL): + return "EXTERNAL" + + elif isinstance(dafny_input, OriginType_AWS__CLOUDHSM): + return "AWS_CLOUDHSM" + + elif isinstance(dafny_input, OriginType_EXTERNAL__KEY__STORE): + return "EXTERNAL_KEY_STORE" + + else: + raise ValueError("No recognized enum value in enum type: " + dafny_input) + + +def com_amazonaws_kms_Tag(dafny_input): + output = {} + output["TagKey"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.TagKey + ).decode("utf-16-be") + output["TagValue"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.TagValue + ).decode("utf-16-be") + return output + + +def com_amazonaws_kms_CreateKeyRequest(dafny_input): + output = {} + if dafny_input.Policy.is_Some: + output["Policy"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.Policy.value + ).decode("utf-16-be") + + if dafny_input.Description.is_Some: + output["Description"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.Description.value + ).decode("utf-16-be") + + if dafny_input.KeyUsage.is_Some: + output["KeyUsage"] = ( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_KeyUsageType( + dafny_input.KeyUsage.value + ) + ) + + if dafny_input.CustomerMasterKeySpec.is_Some: + output["CustomerMasterKeySpec"] = ( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_CustomerMasterKeySpec( + dafny_input.CustomerMasterKeySpec.value + ) + ) + + if dafny_input.KeySpec.is_Some: + output["KeySpec"] = ( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_KeySpec( + dafny_input.KeySpec.value + ) + ) + + if dafny_input.Origin.is_Some: + output["Origin"] = ( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_OriginType( + dafny_input.Origin.value + ) + ) + + if dafny_input.CustomKeyStoreId.is_Some: + output["CustomKeyStoreId"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.CustomKeyStoreId.value + ).decode("utf-16-be") + + if dafny_input.BypassPolicyLockoutSafetyCheck.is_Some: + output["BypassPolicyLockoutSafetyCheck"] = ( + dafny_input.BypassPolicyLockoutSafetyCheck.value + ) + + if dafny_input.Tags.is_Some: + output["Tags"] = [ + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_Tag( + list_element + ) + for list_element in dafny_input.Tags.value + ] + + if dafny_input.MultiRegion.is_Some: + output["MultiRegion"] = dafny_input.MultiRegion.value + + if dafny_input.XksKeyId.is_Some: + output["XksKeyId"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.XksKeyId.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_kms_KeyMetadata(dafny_input): + output = {} + if dafny_input.AWSAccountId.is_Some: + output["AWSAccountId"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.AWSAccountId.value + ).decode("utf-16-be") + + output["KeyId"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.KeyId + ).decode("utf-16-be") + if dafny_input.Arn.is_Some: + output["Arn"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.Arn.value + ).decode("utf-16-be") + + if dafny_input.CreationDate.is_Some: + output["CreationDate"] = datetime.fromisoformat( + dafny_input.CreationDate.value.VerbatimString(False) + ) + + if dafny_input.Enabled.is_Some: + output["Enabled"] = dafny_input.Enabled.value + + if dafny_input.Description.is_Some: + output["Description"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.Description.value + ).decode("utf-16-be") + + if dafny_input.KeyUsage.is_Some: + output["KeyUsage"] = ( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_KeyUsageType( + dafny_input.KeyUsage.value + ) + ) + + if dafny_input.KeyState.is_Some: + output["KeyState"] = ( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_KeyState( + dafny_input.KeyState.value + ) + ) + + if dafny_input.DeletionDate.is_Some: + output["DeletionDate"] = datetime.fromisoformat( + dafny_input.DeletionDate.value.VerbatimString(False) + ) + + if dafny_input.ValidTo.is_Some: + output["ValidTo"] = datetime.fromisoformat( + dafny_input.ValidTo.value.VerbatimString(False) + ) + + if dafny_input.Origin.is_Some: + output["Origin"] = ( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_OriginType( + dafny_input.Origin.value + ) + ) + + if dafny_input.CustomKeyStoreId.is_Some: + output["CustomKeyStoreId"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.CustomKeyStoreId.value + ).decode("utf-16-be") + + if dafny_input.CloudHsmClusterId.is_Some: + output["CloudHsmClusterId"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.CloudHsmClusterId.value + ).decode("utf-16-be") + + if dafny_input.ExpirationModel.is_Some: + output["ExpirationModel"] = ( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_ExpirationModelType( + dafny_input.ExpirationModel.value + ) + ) + + if dafny_input.KeyManager.is_Some: + output["KeyManager"] = ( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_KeyManagerType( + dafny_input.KeyManager.value + ) + ) + + if dafny_input.CustomerMasterKeySpec.is_Some: + output["CustomerMasterKeySpec"] = ( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_CustomerMasterKeySpec( + dafny_input.CustomerMasterKeySpec.value + ) + ) + + if dafny_input.KeySpec.is_Some: + output["KeySpec"] = ( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_KeySpec( + dafny_input.KeySpec.value + ) + ) + + if dafny_input.EncryptionAlgorithms.is_Some: + output["EncryptionAlgorithms"] = [ + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_EncryptionAlgorithmSpec( + list_element + ) + for list_element in dafny_input.EncryptionAlgorithms.value + ] + + if dafny_input.SigningAlgorithms.is_Some: + output["SigningAlgorithms"] = [ + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_SigningAlgorithmSpec( + list_element + ) + for list_element in dafny_input.SigningAlgorithms.value + ] + + if dafny_input.KeyAgreementAlgorithms.is_Some: + output["KeyAgreementAlgorithms"] = [ + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_KeyAgreementAlgorithmSpec( + list_element + ) + for list_element in dafny_input.KeyAgreementAlgorithms.value + ] + + if dafny_input.MultiRegion.is_Some: + output["MultiRegion"] = dafny_input.MultiRegion.value + + if dafny_input.MultiRegionConfiguration.is_Some: + output["MultiRegionConfiguration"] = ( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_MultiRegionConfiguration( + dafny_input.MultiRegionConfiguration.value + ) + ) + + if dafny_input.PendingDeletionWindowInDays.is_Some: + output["PendingDeletionWindowInDays"] = ( + dafny_input.PendingDeletionWindowInDays.value + ) + + if dafny_input.MacAlgorithms.is_Some: + output["MacAlgorithms"] = [ + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_MacAlgorithmSpec( + list_element + ) + for list_element in dafny_input.MacAlgorithms.value + ] + + if dafny_input.XksKeyConfiguration.is_Some: + output["XksKeyConfiguration"] = ( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_XksKeyConfigurationType( + dafny_input.XksKeyConfiguration.value + ) + ) + + return output + + +def com_amazonaws_kms_KeyState(dafny_input): + # Convert KeyState + if isinstance(dafny_input, KeyState_Creating): + return "Creating" + + elif isinstance(dafny_input, KeyState_Enabled): + return "Enabled" + + elif isinstance(dafny_input, KeyState_Disabled): + return "Disabled" + + elif isinstance(dafny_input, KeyState_PendingDeletion): + return "PendingDeletion" + + elif isinstance(dafny_input, KeyState_PendingImport): + return "PendingImport" + + elif isinstance(dafny_input, KeyState_PendingReplicaDeletion): + return "PendingReplicaDeletion" + + elif isinstance(dafny_input, KeyState_Unavailable): + return "Unavailable" + + elif isinstance(dafny_input, KeyState_Updating): + return "Updating" + + else: + raise ValueError("No recognized enum value in enum type: " + dafny_input) + + +def com_amazonaws_kms_ExpirationModelType(dafny_input): + # Convert ExpirationModelType + if isinstance(dafny_input, ExpirationModelType_KEY__MATERIAL__EXPIRES): + return "KEY_MATERIAL_EXPIRES" + + elif isinstance(dafny_input, ExpirationModelType_KEY__MATERIAL__DOES__NOT__EXPIRE): + return "KEY_MATERIAL_DOES_NOT_EXPIRE" + + else: + raise ValueError("No recognized enum value in enum type: " + dafny_input) + + +def com_amazonaws_kms_KeyManagerType(dafny_input): + # Convert KeyManagerType + if isinstance(dafny_input, KeyManagerType_AWS): + return "AWS" + + elif isinstance(dafny_input, KeyManagerType_CUSTOMER): + return "CUSTOMER" + + else: + raise ValueError("No recognized enum value in enum type: " + dafny_input) + + +def com_amazonaws_kms_EncryptionAlgorithmSpec(dafny_input): + # Convert EncryptionAlgorithmSpec + if isinstance(dafny_input, EncryptionAlgorithmSpec_SYMMETRIC__DEFAULT): + return "SYMMETRIC_DEFAULT" + + elif isinstance(dafny_input, EncryptionAlgorithmSpec_RSAES__OAEP__SHA__1): + return "RSAES_OAEP_SHA_1" + + elif isinstance(dafny_input, EncryptionAlgorithmSpec_RSAES__OAEP__SHA__256): + return "RSAES_OAEP_SHA_256" + + else: + raise ValueError("No recognized enum value in enum type: " + dafny_input) + + +def com_amazonaws_kms_SigningAlgorithmSpec(dafny_input): + # Convert SigningAlgorithmSpec + if isinstance(dafny_input, SigningAlgorithmSpec_RSASSA__PSS__SHA__256): + return "RSASSA_PSS_SHA_256" + + elif isinstance(dafny_input, SigningAlgorithmSpec_RSASSA__PSS__SHA__384): + return "RSASSA_PSS_SHA_384" + + elif isinstance(dafny_input, SigningAlgorithmSpec_RSASSA__PSS__SHA__512): + return "RSASSA_PSS_SHA_512" + + elif isinstance(dafny_input, SigningAlgorithmSpec_RSASSA__PKCS1__V1__5__SHA__256): + return "RSASSA_PKCS1_V1_5_SHA_256" + + elif isinstance(dafny_input, SigningAlgorithmSpec_RSASSA__PKCS1__V1__5__SHA__384): + return "RSASSA_PKCS1_V1_5_SHA_384" + + elif isinstance(dafny_input, SigningAlgorithmSpec_RSASSA__PKCS1__V1__5__SHA__512): + return "RSASSA_PKCS1_V1_5_SHA_512" + + elif isinstance(dafny_input, SigningAlgorithmSpec_ECDSA__SHA__256): + return "ECDSA_SHA_256" + + elif isinstance(dafny_input, SigningAlgorithmSpec_ECDSA__SHA__384): + return "ECDSA_SHA_384" + + elif isinstance(dafny_input, SigningAlgorithmSpec_ECDSA__SHA__512): + return "ECDSA_SHA_512" + + elif isinstance(dafny_input, SigningAlgorithmSpec_SM2DSA): + return "SM2DSA" + + else: + raise ValueError("No recognized enum value in enum type: " + dafny_input) + + +def com_amazonaws_kms_KeyAgreementAlgorithmSpec(dafny_input): + # Convert KeyAgreementAlgorithmSpec + if isinstance(dafny_input, KeyAgreementAlgorithmSpec_ECDH): + return "ECDH" + + else: + raise ValueError("No recognized enum value in enum type: " + dafny_input) + + +def com_amazonaws_kms_MultiRegionConfiguration(dafny_input): + output = {} + if dafny_input.MultiRegionKeyType.is_Some: + output["MultiRegionKeyType"] = ( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_MultiRegionKeyType( + dafny_input.MultiRegionKeyType.value + ) + ) + + if dafny_input.PrimaryKey.is_Some: + output["PrimaryKey"] = ( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_MultiRegionKey( + dafny_input.PrimaryKey.value + ) + ) + + if dafny_input.ReplicaKeys.is_Some: + output["ReplicaKeys"] = [ + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_MultiRegionKey( + list_element + ) + for list_element in dafny_input.ReplicaKeys.value + ] + + return output + + +def com_amazonaws_kms_MacAlgorithmSpec(dafny_input): + # Convert MacAlgorithmSpec + if isinstance(dafny_input, MacAlgorithmSpec_HMAC__SHA__224): + return "HMAC_SHA_224" + + elif isinstance(dafny_input, MacAlgorithmSpec_HMAC__SHA__256): + return "HMAC_SHA_256" + + elif isinstance(dafny_input, MacAlgorithmSpec_HMAC__SHA__384): + return "HMAC_SHA_384" + + elif isinstance(dafny_input, MacAlgorithmSpec_HMAC__SHA__512): + return "HMAC_SHA_512" + + else: + raise ValueError("No recognized enum value in enum type: " + dafny_input) + + +def com_amazonaws_kms_XksKeyConfigurationType(dafny_input): + output = {} + if dafny_input.Id.is_Some: + output["Id"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.Id.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_kms_MultiRegionKeyType(dafny_input): + # Convert MultiRegionKeyType + if isinstance(dafny_input, MultiRegionKeyType_PRIMARY): + return "PRIMARY" + + elif isinstance(dafny_input, MultiRegionKeyType_REPLICA): + return "REPLICA" + + else: + raise ValueError("No recognized enum value in enum type: " + dafny_input) + + +def com_amazonaws_kms_MultiRegionKey(dafny_input): + output = {} + if dafny_input.Arn.is_Some: + output["Arn"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.Arn.value + ).decode("utf-16-be") + + if dafny_input.Region.is_Some: + output["Region"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.Region.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_kms_CreateKeyResponse(dafny_input): + output = {} + if dafny_input.KeyMetadata.is_Some: + output["KeyMetadata"] = ( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_KeyMetadata( + dafny_input.KeyMetadata.value + ) + ) + + return output + + +def com_amazonaws_kms_RecipientInfo(dafny_input): + output = {} + if dafny_input.KeyEncryptionAlgorithm.is_Some: + output["KeyEncryptionAlgorithm"] = ( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_KeyEncryptionMechanism( + dafny_input.KeyEncryptionAlgorithm.value + ) + ) + + if dafny_input.AttestationDocument.is_Some: + output["AttestationDocument"] = bytes(dafny_input.AttestationDocument.value) + + return output + + +def com_amazonaws_kms_KeyEncryptionMechanism(dafny_input): + # Convert KeyEncryptionMechanism + if isinstance(dafny_input, KeyEncryptionMechanism_RSAES__OAEP__SHA__256): + return "RSAES_OAEP_SHA_256" + + else: + raise ValueError("No recognized enum value in enum type: " + dafny_input) + + +def com_amazonaws_kms_DecryptRequest(dafny_input): + output = {} + output["CiphertextBlob"] = bytes(dafny_input.CiphertextBlob) + if dafny_input.EncryptionContext.is_Some: + output["EncryptionContext"] = { + 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.value.items + } + + if dafny_input.GrantTokens.is_Some: + output["GrantTokens"] = [ + 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.KeyId.is_Some: + output["KeyId"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.KeyId.value + ).decode("utf-16-be") + + if dafny_input.EncryptionAlgorithm.is_Some: + output["EncryptionAlgorithm"] = ( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_EncryptionAlgorithmSpec( + dafny_input.EncryptionAlgorithm.value + ) + ) + + if dafny_input.Recipient.is_Some: + output["Recipient"] = ( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_RecipientInfo( + dafny_input.Recipient.value + ) + ) + + if dafny_input.DryRun.is_Some: + output["DryRun"] = dafny_input.DryRun.value + + return output + + +def com_amazonaws_kms_DecryptResponse(dafny_input): + output = {} + if dafny_input.KeyId.is_Some: + output["KeyId"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.KeyId.value + ).decode("utf-16-be") + + if dafny_input.Plaintext.is_Some: + output["Plaintext"] = bytes(dafny_input.Plaintext.value) + + if dafny_input.EncryptionAlgorithm.is_Some: + output["EncryptionAlgorithm"] = ( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_EncryptionAlgorithmSpec( + dafny_input.EncryptionAlgorithm.value + ) + ) + + if dafny_input.CiphertextForRecipient.is_Some: + output["CiphertextForRecipient"] = bytes( + dafny_input.CiphertextForRecipient.value + ) + + return output + + +def com_amazonaws_kms_DeleteAliasRequest(dafny_input): + output = {} + output["AliasName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.AliasName + ).decode("utf-16-be") + return output + + +def com_amazonaws_kms_DeleteCustomKeyStoreRequest(dafny_input): + output = {} + output["CustomKeyStoreId"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.CustomKeyStoreId + ).decode("utf-16-be") + return output + + +def com_amazonaws_kms_DeleteCustomKeyStoreResponse(dafny_input): + output = {} + return output + + +def com_amazonaws_kms_DeleteImportedKeyMaterialRequest(dafny_input): + output = {} + output["KeyId"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.KeyId + ).decode("utf-16-be") + return output + + +def com_amazonaws_kms_DeriveSharedSecretRequest(dafny_input): + output = {} + output["KeyId"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.KeyId + ).decode("utf-16-be") + output["KeyAgreementAlgorithm"] = ( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_KeyAgreementAlgorithmSpec( + dafny_input.KeyAgreementAlgorithm + ) + ) + output["PublicKey"] = bytes(dafny_input.PublicKey) + if dafny_input.GrantTokens.is_Some: + output["GrantTokens"] = [ + 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.DryRun.is_Some: + output["DryRun"] = dafny_input.DryRun.value + + if dafny_input.Recipient.is_Some: + output["Recipient"] = ( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_RecipientInfo( + dafny_input.Recipient.value + ) + ) + + return output + + +def com_amazonaws_kms_DeriveSharedSecretResponse(dafny_input): + output = {} + if dafny_input.KeyId.is_Some: + output["KeyId"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.KeyId.value + ).decode("utf-16-be") + + if dafny_input.SharedSecret.is_Some: + output["SharedSecret"] = bytes(dafny_input.SharedSecret.value) + + if dafny_input.CiphertextForRecipient.is_Some: + output["CiphertextForRecipient"] = bytes( + dafny_input.CiphertextForRecipient.value + ) + + if dafny_input.KeyAgreementAlgorithm.is_Some: + output["KeyAgreementAlgorithm"] = ( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_KeyAgreementAlgorithmSpec( + dafny_input.KeyAgreementAlgorithm.value + ) + ) + + if dafny_input.KeyOrigin.is_Some: + output["KeyOrigin"] = ( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_OriginType( + dafny_input.KeyOrigin.value + ) + ) + + return output + + +def com_amazonaws_kms_DescribeCustomKeyStoresRequest(dafny_input): + output = {} + if dafny_input.CustomKeyStoreId.is_Some: + output["CustomKeyStoreId"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.CustomKeyStoreId.value + ).decode("utf-16-be") + + if dafny_input.CustomKeyStoreName.is_Some: + output["CustomKeyStoreName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.CustomKeyStoreName.value + ).decode("utf-16-be") + + if dafny_input.Limit.is_Some: + output["Limit"] = dafny_input.Limit.value + + if dafny_input.Marker.is_Some: + output["Marker"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.Marker.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_kms_CustomKeyStoresListEntry(dafny_input): + output = {} + if dafny_input.CustomKeyStoreId.is_Some: + output["CustomKeyStoreId"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.CustomKeyStoreId.value + ).decode("utf-16-be") + + if dafny_input.CustomKeyStoreName.is_Some: + output["CustomKeyStoreName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.CustomKeyStoreName.value + ).decode("utf-16-be") + + if dafny_input.CloudHsmClusterId.is_Some: + output["CloudHsmClusterId"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.CloudHsmClusterId.value + ).decode("utf-16-be") + + if dafny_input.TrustAnchorCertificate.is_Some: + output["TrustAnchorCertificate"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.TrustAnchorCertificate.value + ).decode("utf-16-be") + + if dafny_input.ConnectionState.is_Some: + output["ConnectionState"] = ( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_ConnectionStateType( + dafny_input.ConnectionState.value + ) + ) + + if dafny_input.ConnectionErrorCode.is_Some: + output["ConnectionErrorCode"] = ( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_ConnectionErrorCodeType( + dafny_input.ConnectionErrorCode.value + ) + ) + + if dafny_input.CreationDate.is_Some: + output["CreationDate"] = datetime.fromisoformat( + dafny_input.CreationDate.value.VerbatimString(False) + ) + + if dafny_input.CustomKeyStoreType.is_Some: + output["CustomKeyStoreType"] = ( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_CustomKeyStoreType( + dafny_input.CustomKeyStoreType.value + ) + ) + + if dafny_input.XksProxyConfiguration.is_Some: + output["XksProxyConfiguration"] = ( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_XksProxyConfigurationType( + dafny_input.XksProxyConfiguration.value + ) + ) + + return output + + +def com_amazonaws_kms_ConnectionStateType(dafny_input): + # Convert ConnectionStateType + if isinstance(dafny_input, ConnectionStateType_CONNECTED): + return "CONNECTED" + + elif isinstance(dafny_input, ConnectionStateType_CONNECTING): + return "CONNECTING" + + elif isinstance(dafny_input, ConnectionStateType_FAILED): + return "FAILED" + + elif isinstance(dafny_input, ConnectionStateType_DISCONNECTED): + return "DISCONNECTED" + + elif isinstance(dafny_input, ConnectionStateType_DISCONNECTING): + return "DISCONNECTING" + + else: + raise ValueError("No recognized enum value in enum type: " + dafny_input) + + +def com_amazonaws_kms_ConnectionErrorCodeType(dafny_input): + # Convert ConnectionErrorCodeType + if isinstance(dafny_input, ConnectionErrorCodeType_INVALID__CREDENTIALS): + return "INVALID_CREDENTIALS" + + elif isinstance(dafny_input, ConnectionErrorCodeType_CLUSTER__NOT__FOUND): + return "CLUSTER_NOT_FOUND" + + elif isinstance(dafny_input, ConnectionErrorCodeType_NETWORK__ERRORS): + return "NETWORK_ERRORS" + + elif isinstance(dafny_input, ConnectionErrorCodeType_INTERNAL__ERROR): + return "INTERNAL_ERROR" + + elif isinstance(dafny_input, ConnectionErrorCodeType_INSUFFICIENT__CLOUDHSM__HSMS): + return "INSUFFICIENT_CLOUDHSM_HSMS" + + elif isinstance(dafny_input, ConnectionErrorCodeType_USER__LOCKED__OUT): + return "USER_LOCKED_OUT" + + elif isinstance(dafny_input, ConnectionErrorCodeType_USER__NOT__FOUND): + return "USER_NOT_FOUND" + + elif isinstance(dafny_input, ConnectionErrorCodeType_USER__LOGGED__IN): + return "USER_LOGGED_IN" + + elif isinstance(dafny_input, ConnectionErrorCodeType_SUBNET__NOT__FOUND): + return "SUBNET_NOT_FOUND" + + elif isinstance( + dafny_input, ConnectionErrorCodeType_INSUFFICIENT__FREE__ADDRESSES__IN__SUBNET + ): + return "INSUFFICIENT_FREE_ADDRESSES_IN_SUBNET" + + elif isinstance(dafny_input, ConnectionErrorCodeType_XKS__PROXY__ACCESS__DENIED): + return "XKS_PROXY_ACCESS_DENIED" + + elif isinstance(dafny_input, ConnectionErrorCodeType_XKS__PROXY__NOT__REACHABLE): + return "XKS_PROXY_NOT_REACHABLE" + + elif isinstance( + dafny_input, ConnectionErrorCodeType_XKS__VPC__ENDPOINT__SERVICE__NOT__FOUND + ): + return "XKS_VPC_ENDPOINT_SERVICE_NOT_FOUND" + + elif isinstance(dafny_input, ConnectionErrorCodeType_XKS__PROXY__INVALID__RESPONSE): + return "XKS_PROXY_INVALID_RESPONSE" + + elif isinstance( + dafny_input, ConnectionErrorCodeType_XKS__PROXY__INVALID__CONFIGURATION + ): + return "XKS_PROXY_INVALID_CONFIGURATION" + + elif isinstance( + dafny_input, + ConnectionErrorCodeType_XKS__VPC__ENDPOINT__SERVICE__INVALID__CONFIGURATION, + ): + return "XKS_VPC_ENDPOINT_SERVICE_INVALID_CONFIGURATION" + + elif isinstance(dafny_input, ConnectionErrorCodeType_XKS__PROXY__TIMED__OUT): + return "XKS_PROXY_TIMED_OUT" + + elif isinstance( + dafny_input, ConnectionErrorCodeType_XKS__PROXY__INVALID__TLS__CONFIGURATION + ): + return "XKS_PROXY_INVALID_TLS_CONFIGURATION" + + else: + raise ValueError("No recognized enum value in enum type: " + dafny_input) + + +def com_amazonaws_kms_XksProxyConfigurationType(dafny_input): + output = {} + if dafny_input.Connectivity.is_Some: + output["Connectivity"] = ( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_XksProxyConnectivityType( + dafny_input.Connectivity.value + ) + ) + + if dafny_input.AccessKeyId.is_Some: + output["AccessKeyId"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.AccessKeyId.value + ).decode("utf-16-be") + + if dafny_input.UriEndpoint.is_Some: + output["UriEndpoint"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.UriEndpoint.value + ).decode("utf-16-be") + + if dafny_input.UriPath.is_Some: + output["UriPath"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.UriPath.value + ).decode("utf-16-be") + + if dafny_input.VpcEndpointServiceName.is_Some: + output["VpcEndpointServiceName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.VpcEndpointServiceName.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_kms_DescribeCustomKeyStoresResponse(dafny_input): + output = {} + if dafny_input.CustomKeyStores.is_Some: + output["CustomKeyStores"] = [ + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_CustomKeyStoresListEntry( + list_element + ) + for list_element in dafny_input.CustomKeyStores.value + ] + + if dafny_input.NextMarker.is_Some: + output["NextMarker"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.NextMarker.value + ).decode("utf-16-be") + + if dafny_input.Truncated.is_Some: + output["Truncated"] = dafny_input.Truncated.value + + return output + + +def com_amazonaws_kms_DescribeKeyRequest(dafny_input): + output = {} + output["KeyId"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.KeyId + ).decode("utf-16-be") + if dafny_input.GrantTokens.is_Some: + output["GrantTokens"] = [ + 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 + ] + + return output + + +def com_amazonaws_kms_DescribeKeyResponse(dafny_input): + output = {} + if dafny_input.KeyMetadata.is_Some: + output["KeyMetadata"] = ( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_KeyMetadata( + dafny_input.KeyMetadata.value + ) + ) + + return output + + +def com_amazonaws_kms_DisableKeyRequest(dafny_input): + output = {} + output["KeyId"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.KeyId + ).decode("utf-16-be") + return output + + +def com_amazonaws_kms_DisableKeyRotationRequest(dafny_input): + output = {} + output["KeyId"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.KeyId + ).decode("utf-16-be") + return output + + +def com_amazonaws_kms_DisconnectCustomKeyStoreRequest(dafny_input): + output = {} + output["CustomKeyStoreId"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.CustomKeyStoreId + ).decode("utf-16-be") + return output + + +def com_amazonaws_kms_DisconnectCustomKeyStoreResponse(dafny_input): + output = {} + return output + + +def com_amazonaws_kms_EnableKeyRequest(dafny_input): + output = {} + output["KeyId"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.KeyId + ).decode("utf-16-be") + return output + + +def com_amazonaws_kms_EnableKeyRotationRequest(dafny_input): + output = {} + output["KeyId"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.KeyId + ).decode("utf-16-be") + if dafny_input.RotationPeriodInDays.is_Some: + output["RotationPeriodInDays"] = dafny_input.RotationPeriodInDays.value + + return output + + +def com_amazonaws_kms_EncryptRequest(dafny_input): + output = {} + output["KeyId"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.KeyId + ).decode("utf-16-be") + output["Plaintext"] = bytes(dafny_input.Plaintext) + if dafny_input.EncryptionContext.is_Some: + output["EncryptionContext"] = { + 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.value.items + } + + if dafny_input.GrantTokens.is_Some: + output["GrantTokens"] = [ + 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.EncryptionAlgorithm.is_Some: + output["EncryptionAlgorithm"] = ( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_EncryptionAlgorithmSpec( + dafny_input.EncryptionAlgorithm.value + ) + ) + + if dafny_input.DryRun.is_Some: + output["DryRun"] = dafny_input.DryRun.value + + return output + + +def com_amazonaws_kms_EncryptResponse(dafny_input): + output = {} + if dafny_input.CiphertextBlob.is_Some: + output["CiphertextBlob"] = bytes(dafny_input.CiphertextBlob.value) + + if dafny_input.KeyId.is_Some: + output["KeyId"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.KeyId.value + ).decode("utf-16-be") + + if dafny_input.EncryptionAlgorithm.is_Some: + output["EncryptionAlgorithm"] = ( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_EncryptionAlgorithmSpec( + dafny_input.EncryptionAlgorithm.value + ) + ) + + return output + + +def com_amazonaws_kms_DataKeySpec(dafny_input): + # Convert DataKeySpec + if isinstance(dafny_input, DataKeySpec_AES__256): + return "AES_256" + + elif isinstance(dafny_input, DataKeySpec_AES__128): + return "AES_128" + + else: + raise ValueError("No recognized enum value in enum type: " + dafny_input) + + +def com_amazonaws_kms_GenerateDataKeyRequest(dafny_input): + output = {} + output["KeyId"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.KeyId + ).decode("utf-16-be") + if dafny_input.EncryptionContext.is_Some: + output["EncryptionContext"] = { + 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.value.items + } + + if dafny_input.NumberOfBytes.is_Some: + output["NumberOfBytes"] = dafny_input.NumberOfBytes.value + + if dafny_input.KeySpec.is_Some: + output["KeySpec"] = ( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_DataKeySpec( + dafny_input.KeySpec.value + ) + ) + + if dafny_input.GrantTokens.is_Some: + output["GrantTokens"] = [ + 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.Recipient.is_Some: + output["Recipient"] = ( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_RecipientInfo( + dafny_input.Recipient.value + ) + ) + + if dafny_input.DryRun.is_Some: + output["DryRun"] = dafny_input.DryRun.value + + return output + + +def com_amazonaws_kms_GenerateDataKeyResponse(dafny_input): + output = {} + if dafny_input.CiphertextBlob.is_Some: + output["CiphertextBlob"] = bytes(dafny_input.CiphertextBlob.value) + + if dafny_input.Plaintext.is_Some: + output["Plaintext"] = bytes(dafny_input.Plaintext.value) + + if dafny_input.KeyId.is_Some: + output["KeyId"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.KeyId.value + ).decode("utf-16-be") + + if dafny_input.CiphertextForRecipient.is_Some: + output["CiphertextForRecipient"] = bytes( + dafny_input.CiphertextForRecipient.value + ) + + return output + + +def com_amazonaws_kms_DataKeyPairSpec(dafny_input): + # Convert DataKeyPairSpec + if isinstance(dafny_input, DataKeyPairSpec_RSA__2048): + return "RSA_2048" + + elif isinstance(dafny_input, DataKeyPairSpec_RSA__3072): + return "RSA_3072" + + elif isinstance(dafny_input, DataKeyPairSpec_RSA__4096): + return "RSA_4096" + + elif isinstance(dafny_input, DataKeyPairSpec_ECC__NIST__P256): + return "ECC_NIST_P256" + + elif isinstance(dafny_input, DataKeyPairSpec_ECC__NIST__P384): + return "ECC_NIST_P384" + + elif isinstance(dafny_input, DataKeyPairSpec_ECC__NIST__P521): + return "ECC_NIST_P521" + + elif isinstance(dafny_input, DataKeyPairSpec_ECC__SECG__P256K1): + return "ECC_SECG_P256K1" + + elif isinstance(dafny_input, DataKeyPairSpec_SM2): + return "SM2" + + else: + raise ValueError("No recognized enum value in enum type: " + dafny_input) + + +def com_amazonaws_kms_GenerateDataKeyPairRequest(dafny_input): + output = {} + if dafny_input.EncryptionContext.is_Some: + output["EncryptionContext"] = { + 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.value.items + } + + output["KeyId"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.KeyId + ).decode("utf-16-be") + output["KeyPairSpec"] = ( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_DataKeyPairSpec( + dafny_input.KeyPairSpec + ) + ) + if dafny_input.GrantTokens.is_Some: + output["GrantTokens"] = [ + 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.Recipient.is_Some: + output["Recipient"] = ( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_RecipientInfo( + dafny_input.Recipient.value + ) + ) + + if dafny_input.DryRun.is_Some: + output["DryRun"] = dafny_input.DryRun.value + + return output + + +def com_amazonaws_kms_GenerateDataKeyPairResponse(dafny_input): + output = {} + if dafny_input.PrivateKeyCiphertextBlob.is_Some: + output["PrivateKeyCiphertextBlob"] = bytes( + dafny_input.PrivateKeyCiphertextBlob.value + ) + + if dafny_input.PrivateKeyPlaintext.is_Some: + output["PrivateKeyPlaintext"] = bytes(dafny_input.PrivateKeyPlaintext.value) + + if dafny_input.PublicKey.is_Some: + output["PublicKey"] = bytes(dafny_input.PublicKey.value) + + if dafny_input.KeyId.is_Some: + output["KeyId"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.KeyId.value + ).decode("utf-16-be") + + if dafny_input.KeyPairSpec.is_Some: + output["KeyPairSpec"] = ( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_DataKeyPairSpec( + dafny_input.KeyPairSpec.value + ) + ) + + if dafny_input.CiphertextForRecipient.is_Some: + output["CiphertextForRecipient"] = bytes( + dafny_input.CiphertextForRecipient.value + ) + + return output + + +def com_amazonaws_kms_GenerateDataKeyPairWithoutPlaintextRequest(dafny_input): + output = {} + if dafny_input.EncryptionContext.is_Some: + output["EncryptionContext"] = { + 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.value.items + } + + output["KeyId"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.KeyId + ).decode("utf-16-be") + output["KeyPairSpec"] = ( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_DataKeyPairSpec( + dafny_input.KeyPairSpec + ) + ) + if dafny_input.GrantTokens.is_Some: + output["GrantTokens"] = [ + 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.DryRun.is_Some: + output["DryRun"] = dafny_input.DryRun.value + + return output + + +def com_amazonaws_kms_GenerateDataKeyPairWithoutPlaintextResponse(dafny_input): + output = {} + if dafny_input.PrivateKeyCiphertextBlob.is_Some: + output["PrivateKeyCiphertextBlob"] = bytes( + dafny_input.PrivateKeyCiphertextBlob.value + ) + + if dafny_input.PublicKey.is_Some: + output["PublicKey"] = bytes(dafny_input.PublicKey.value) + + if dafny_input.KeyId.is_Some: + output["KeyId"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.KeyId.value + ).decode("utf-16-be") + + if dafny_input.KeyPairSpec.is_Some: + output["KeyPairSpec"] = ( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_DataKeyPairSpec( + dafny_input.KeyPairSpec.value + ) + ) + + return output + + +def com_amazonaws_kms_GenerateDataKeyWithoutPlaintextRequest(dafny_input): + output = {} + output["KeyId"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.KeyId + ).decode("utf-16-be") + if dafny_input.EncryptionContext.is_Some: + output["EncryptionContext"] = { + 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.value.items + } + + if dafny_input.KeySpec.is_Some: + output["KeySpec"] = ( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_DataKeySpec( + dafny_input.KeySpec.value + ) + ) + + if dafny_input.NumberOfBytes.is_Some: + output["NumberOfBytes"] = dafny_input.NumberOfBytes.value + + if dafny_input.GrantTokens.is_Some: + output["GrantTokens"] = [ + 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.DryRun.is_Some: + output["DryRun"] = dafny_input.DryRun.value + + return output + + +def com_amazonaws_kms_GenerateDataKeyWithoutPlaintextResponse(dafny_input): + output = {} + if dafny_input.CiphertextBlob.is_Some: + output["CiphertextBlob"] = bytes(dafny_input.CiphertextBlob.value) + + if dafny_input.KeyId.is_Some: + output["KeyId"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.KeyId.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_kms_GenerateMacRequest(dafny_input): + output = {} + output["Message"] = bytes(dafny_input.Message) + output["KeyId"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.KeyId + ).decode("utf-16-be") + output["MacAlgorithm"] = ( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_MacAlgorithmSpec( + dafny_input.MacAlgorithm + ) + ) + if dafny_input.GrantTokens.is_Some: + output["GrantTokens"] = [ + 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.DryRun.is_Some: + output["DryRun"] = dafny_input.DryRun.value + + return output + + +def com_amazonaws_kms_GenerateMacResponse(dafny_input): + output = {} + if dafny_input.Mac.is_Some: + output["Mac"] = bytes(dafny_input.Mac.value) + + if dafny_input.MacAlgorithm.is_Some: + output["MacAlgorithm"] = ( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_MacAlgorithmSpec( + dafny_input.MacAlgorithm.value + ) + ) + + if dafny_input.KeyId.is_Some: + output["KeyId"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.KeyId.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_kms_GenerateRandomRequest(dafny_input): + output = {} + if dafny_input.NumberOfBytes.is_Some: + output["NumberOfBytes"] = dafny_input.NumberOfBytes.value + + if dafny_input.CustomKeyStoreId.is_Some: + output["CustomKeyStoreId"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.CustomKeyStoreId.value + ).decode("utf-16-be") + + if dafny_input.Recipient.is_Some: + output["Recipient"] = ( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_RecipientInfo( + dafny_input.Recipient.value + ) + ) + + return output + + +def com_amazonaws_kms_GenerateRandomResponse(dafny_input): + output = {} + if dafny_input.Plaintext.is_Some: + output["Plaintext"] = bytes(dafny_input.Plaintext.value) + + if dafny_input.CiphertextForRecipient.is_Some: + output["CiphertextForRecipient"] = bytes( + dafny_input.CiphertextForRecipient.value + ) + + return output + + +def com_amazonaws_kms_GetKeyPolicyRequest(dafny_input): + output = {} + output["KeyId"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.KeyId + ).decode("utf-16-be") + if dafny_input.PolicyName.is_Some: + output["PolicyName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.PolicyName.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_kms_GetKeyPolicyResponse(dafny_input): + output = {} + if dafny_input.Policy.is_Some: + output["Policy"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.Policy.value + ).decode("utf-16-be") + + if dafny_input.PolicyName.is_Some: + output["PolicyName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.PolicyName.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_kms_GetKeyRotationStatusRequest(dafny_input): + output = {} + output["KeyId"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.KeyId + ).decode("utf-16-be") + return output + + +def com_amazonaws_kms_GetKeyRotationStatusResponse(dafny_input): + output = {} + if dafny_input.KeyRotationEnabled.is_Some: + output["KeyRotationEnabled"] = dafny_input.KeyRotationEnabled.value + + if dafny_input.KeyId.is_Some: + output["KeyId"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.KeyId.value + ).decode("utf-16-be") + + if dafny_input.RotationPeriodInDays.is_Some: + output["RotationPeriodInDays"] = dafny_input.RotationPeriodInDays.value + + if dafny_input.NextRotationDate.is_Some: + output["NextRotationDate"] = datetime.fromisoformat( + dafny_input.NextRotationDate.value.VerbatimString(False) + ) + + if dafny_input.OnDemandRotationStartDate.is_Some: + output["OnDemandRotationStartDate"] = datetime.fromisoformat( + dafny_input.OnDemandRotationStartDate.value.VerbatimString(False) + ) + + return output + + +def com_amazonaws_kms_AlgorithmSpec(dafny_input): + # Convert AlgorithmSpec + if isinstance(dafny_input, AlgorithmSpec_RSAES__PKCS1__V1__5): + return "RSAES_PKCS1_V1_5" + + elif isinstance(dafny_input, AlgorithmSpec_RSAES__OAEP__SHA__1): + return "RSAES_OAEP_SHA_1" + + elif isinstance(dafny_input, AlgorithmSpec_RSAES__OAEP__SHA__256): + return "RSAES_OAEP_SHA_256" + + elif isinstance(dafny_input, AlgorithmSpec_RSA__AES__KEY__WRAP__SHA__1): + return "RSA_AES_KEY_WRAP_SHA_1" + + elif isinstance(dafny_input, AlgorithmSpec_RSA__AES__KEY__WRAP__SHA__256): + return "RSA_AES_KEY_WRAP_SHA_256" + + elif isinstance(dafny_input, AlgorithmSpec_SM2PKE): + return "SM2PKE" + + else: + raise ValueError("No recognized enum value in enum type: " + dafny_input) + + +def com_amazonaws_kms_WrappingKeySpec(dafny_input): + # Convert WrappingKeySpec + if isinstance(dafny_input, WrappingKeySpec_RSA__2048): + return "RSA_2048" + + elif isinstance(dafny_input, WrappingKeySpec_RSA__3072): + return "RSA_3072" + + elif isinstance(dafny_input, WrappingKeySpec_RSA__4096): + return "RSA_4096" + + elif isinstance(dafny_input, WrappingKeySpec_SM2): + return "SM2" + + else: + raise ValueError("No recognized enum value in enum type: " + dafny_input) + + +def com_amazonaws_kms_GetParametersForImportRequest(dafny_input): + output = {} + output["KeyId"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.KeyId + ).decode("utf-16-be") + output["WrappingAlgorithm"] = ( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_AlgorithmSpec( + dafny_input.WrappingAlgorithm + ) + ) + output["WrappingKeySpec"] = ( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_WrappingKeySpec( + dafny_input.WrappingKeySpec + ) + ) + return output + + +def com_amazonaws_kms_GetParametersForImportResponse(dafny_input): + output = {} + if dafny_input.KeyId.is_Some: + output["KeyId"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.KeyId.value + ).decode("utf-16-be") + + if dafny_input.ImportToken.is_Some: + output["ImportToken"] = bytes(dafny_input.ImportToken.value) + + if dafny_input.PublicKey.is_Some: + output["PublicKey"] = bytes(dafny_input.PublicKey.value) + + if dafny_input.ParametersValidTo.is_Some: + output["ParametersValidTo"] = datetime.fromisoformat( + dafny_input.ParametersValidTo.value.VerbatimString(False) + ) + + return output + + +def com_amazonaws_kms_GetPublicKeyRequest(dafny_input): + output = {} + output["KeyId"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.KeyId + ).decode("utf-16-be") + if dafny_input.GrantTokens.is_Some: + output["GrantTokens"] = [ + 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 + ] + + return output + + +def com_amazonaws_kms_GetPublicKeyResponse(dafny_input): + output = {} + if dafny_input.KeyId.is_Some: + output["KeyId"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.KeyId.value + ).decode("utf-16-be") + + if dafny_input.PublicKey.is_Some: + output["PublicKey"] = bytes(dafny_input.PublicKey.value) + + if dafny_input.CustomerMasterKeySpec.is_Some: + output["CustomerMasterKeySpec"] = ( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_CustomerMasterKeySpec( + dafny_input.CustomerMasterKeySpec.value + ) + ) + + if dafny_input.KeySpec.is_Some: + output["KeySpec"] = ( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_KeySpec( + dafny_input.KeySpec.value + ) + ) + + if dafny_input.KeyUsage.is_Some: + output["KeyUsage"] = ( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_KeyUsageType( + dafny_input.KeyUsage.value + ) + ) + + if dafny_input.EncryptionAlgorithms.is_Some: + output["EncryptionAlgorithms"] = [ + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_EncryptionAlgorithmSpec( + list_element + ) + for list_element in dafny_input.EncryptionAlgorithms.value + ] + + if dafny_input.SigningAlgorithms.is_Some: + output["SigningAlgorithms"] = [ + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_SigningAlgorithmSpec( + list_element + ) + for list_element in dafny_input.SigningAlgorithms.value + ] + + if dafny_input.KeyAgreementAlgorithms.is_Some: + output["KeyAgreementAlgorithms"] = [ + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_KeyAgreementAlgorithmSpec( + list_element + ) + for list_element in dafny_input.KeyAgreementAlgorithms.value + ] + + return output + + +def com_amazonaws_kms_ImportKeyMaterialRequest(dafny_input): + output = {} + output["KeyId"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.KeyId + ).decode("utf-16-be") + output["ImportToken"] = bytes(dafny_input.ImportToken) + output["EncryptedKeyMaterial"] = bytes(dafny_input.EncryptedKeyMaterial) + if dafny_input.ValidTo.is_Some: + output["ValidTo"] = datetime.fromisoformat( + dafny_input.ValidTo.value.VerbatimString(False) + ) + + if dafny_input.ExpirationModel.is_Some: + output["ExpirationModel"] = ( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_ExpirationModelType( + dafny_input.ExpirationModel.value + ) + ) + + return output + + +def com_amazonaws_kms_ImportKeyMaterialResponse(dafny_input): + output = {} + return output + + +def com_amazonaws_kms_ListAliasesRequest(dafny_input): + output = {} + if dafny_input.KeyId.is_Some: + output["KeyId"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.KeyId.value + ).decode("utf-16-be") + + if dafny_input.Limit.is_Some: + output["Limit"] = dafny_input.Limit.value + + if dafny_input.Marker.is_Some: + output["Marker"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.Marker.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_kms_AliasListEntry(dafny_input): + output = {} + if dafny_input.AliasName.is_Some: + output["AliasName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.AliasName.value + ).decode("utf-16-be") + + if dafny_input.AliasArn.is_Some: + output["AliasArn"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.AliasArn.value + ).decode("utf-16-be") + + if dafny_input.TargetKeyId.is_Some: + output["TargetKeyId"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.TargetKeyId.value + ).decode("utf-16-be") + + if dafny_input.CreationDate.is_Some: + output["CreationDate"] = datetime.fromisoformat( + dafny_input.CreationDate.value.VerbatimString(False) + ) + + if dafny_input.LastUpdatedDate.is_Some: + output["LastUpdatedDate"] = datetime.fromisoformat( + dafny_input.LastUpdatedDate.value.VerbatimString(False) + ) + + return output + + +def com_amazonaws_kms_ListAliasesResponse(dafny_input): + output = {} + if dafny_input.Aliases.is_Some: + output["Aliases"] = [ + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_AliasListEntry( + list_element + ) + for list_element in dafny_input.Aliases.value + ] + + if dafny_input.NextMarker.is_Some: + output["NextMarker"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.NextMarker.value + ).decode("utf-16-be") + + if dafny_input.Truncated.is_Some: + output["Truncated"] = dafny_input.Truncated.value + + return output + + +def com_amazonaws_kms_ListGrantsRequest(dafny_input): + output = {} + if dafny_input.Limit.is_Some: + output["Limit"] = dafny_input.Limit.value + + if dafny_input.Marker.is_Some: + output["Marker"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.Marker.value + ).decode("utf-16-be") + + output["KeyId"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.KeyId + ).decode("utf-16-be") + if dafny_input.GrantId.is_Some: + output["GrantId"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.GrantId.value + ).decode("utf-16-be") + + if dafny_input.GranteePrincipal.is_Some: + output["GranteePrincipal"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.GranteePrincipal.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_kms_GrantListEntry(dafny_input): + output = {} + if dafny_input.KeyId.is_Some: + output["KeyId"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.KeyId.value + ).decode("utf-16-be") + + if dafny_input.GrantId.is_Some: + output["GrantId"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.GrantId.value + ).decode("utf-16-be") + + if dafny_input.Name.is_Some: + output["Name"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.Name.value + ).decode("utf-16-be") + + if dafny_input.CreationDate.is_Some: + output["CreationDate"] = datetime.fromisoformat( + dafny_input.CreationDate.value.VerbatimString(False) + ) + + if dafny_input.GranteePrincipal.is_Some: + output["GranteePrincipal"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.GranteePrincipal.value + ).decode("utf-16-be") + + if dafny_input.RetiringPrincipal.is_Some: + output["RetiringPrincipal"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.RetiringPrincipal.value + ).decode("utf-16-be") + + if dafny_input.IssuingAccount.is_Some: + output["IssuingAccount"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.IssuingAccount.value + ).decode("utf-16-be") + + if dafny_input.Operations.is_Some: + output["Operations"] = [ + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_GrantOperation( + list_element + ) + for list_element in dafny_input.Operations.value + ] + + if dafny_input.Constraints.is_Some: + output["Constraints"] = ( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_GrantConstraints( + dafny_input.Constraints.value + ) + ) + + return output + + +def com_amazonaws_kms_ListGrantsResponse(dafny_input): + output = {} + if dafny_input.Grants.is_Some: + output["Grants"] = [ + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_GrantListEntry( + list_element + ) + for list_element in dafny_input.Grants.value + ] + + if dafny_input.NextMarker.is_Some: + output["NextMarker"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.NextMarker.value + ).decode("utf-16-be") + + if dafny_input.Truncated.is_Some: + output["Truncated"] = dafny_input.Truncated.value + + return output + + +def com_amazonaws_kms_ListKeyPoliciesRequest(dafny_input): + output = {} + output["KeyId"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.KeyId + ).decode("utf-16-be") + if dafny_input.Limit.is_Some: + output["Limit"] = dafny_input.Limit.value + + if dafny_input.Marker.is_Some: + output["Marker"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.Marker.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_kms_ListKeyPoliciesResponse(dafny_input): + output = {} + if dafny_input.PolicyNames.is_Some: + output["PolicyNames"] = [ + b"".join(ord(c).to_bytes(2, "big") for c in list_element).decode( + "utf-16-be" + ) + for list_element in dafny_input.PolicyNames.value + ] + + if dafny_input.NextMarker.is_Some: + output["NextMarker"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.NextMarker.value + ).decode("utf-16-be") + + if dafny_input.Truncated.is_Some: + output["Truncated"] = dafny_input.Truncated.value + + return output + + +def com_amazonaws_kms_ListKeyRotationsRequest(dafny_input): + output = {} + output["KeyId"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.KeyId + ).decode("utf-16-be") + if dafny_input.Limit.is_Some: + output["Limit"] = dafny_input.Limit.value + + if dafny_input.Marker.is_Some: + output["Marker"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.Marker.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_kms_RotationsListEntry(dafny_input): + output = {} + if dafny_input.KeyId.is_Some: + output["KeyId"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.KeyId.value + ).decode("utf-16-be") + + if dafny_input.RotationDate.is_Some: + output["RotationDate"] = datetime.fromisoformat( + dafny_input.RotationDate.value.VerbatimString(False) + ) + + if dafny_input.RotationType.is_Some: + output["RotationType"] = ( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_RotationType( + dafny_input.RotationType.value + ) + ) + + return output + + +def com_amazonaws_kms_RotationType(dafny_input): + # Convert RotationType + if isinstance(dafny_input, RotationType_AUTOMATIC): + return "AUTOMATIC" + + elif isinstance(dafny_input, RotationType_ON__DEMAND): + return "ON_DEMAND" + + else: + raise ValueError("No recognized enum value in enum type: " + dafny_input) + + +def com_amazonaws_kms_ListKeyRotationsResponse(dafny_input): + output = {} + if dafny_input.Rotations.is_Some: + output["Rotations"] = [ + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_RotationsListEntry( + list_element + ) + for list_element in dafny_input.Rotations.value + ] + + if dafny_input.NextMarker.is_Some: + output["NextMarker"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.NextMarker.value + ).decode("utf-16-be") + + if dafny_input.Truncated.is_Some: + output["Truncated"] = dafny_input.Truncated.value + + return output + + +def com_amazonaws_kms_ListKeysRequest(dafny_input): + output = {} + if dafny_input.Limit.is_Some: + output["Limit"] = dafny_input.Limit.value + + if dafny_input.Marker.is_Some: + output["Marker"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.Marker.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_kms_KeyListEntry(dafny_input): + output = {} + if dafny_input.KeyId.is_Some: + output["KeyId"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.KeyId.value + ).decode("utf-16-be") + + if dafny_input.KeyArn.is_Some: + output["KeyArn"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.KeyArn.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_kms_ListKeysResponse(dafny_input): + output = {} + if dafny_input.Keys.is_Some: + output["Keys"] = [ + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_KeyListEntry( + list_element + ) + for list_element in dafny_input.Keys.value + ] + + if dafny_input.NextMarker.is_Some: + output["NextMarker"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.NextMarker.value + ).decode("utf-16-be") + + if dafny_input.Truncated.is_Some: + output["Truncated"] = dafny_input.Truncated.value + + return output + + +def com_amazonaws_kms_ListResourceTagsRequest(dafny_input): + output = {} + output["KeyId"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.KeyId + ).decode("utf-16-be") + if dafny_input.Limit.is_Some: + output["Limit"] = dafny_input.Limit.value + + if dafny_input.Marker.is_Some: + output["Marker"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.Marker.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_kms_ListResourceTagsResponse(dafny_input): + output = {} + if dafny_input.Tags.is_Some: + output["Tags"] = [ + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_Tag( + list_element + ) + for list_element in dafny_input.Tags.value + ] + + if dafny_input.NextMarker.is_Some: + output["NextMarker"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.NextMarker.value + ).decode("utf-16-be") + + if dafny_input.Truncated.is_Some: + output["Truncated"] = dafny_input.Truncated.value + + return output + + +def com_amazonaws_kms_PutKeyPolicyRequest(dafny_input): + output = {} + output["KeyId"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.KeyId + ).decode("utf-16-be") + if dafny_input.PolicyName.is_Some: + output["PolicyName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.PolicyName.value + ).decode("utf-16-be") + + output["Policy"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.Policy + ).decode("utf-16-be") + if dafny_input.BypassPolicyLockoutSafetyCheck.is_Some: + output["BypassPolicyLockoutSafetyCheck"] = ( + dafny_input.BypassPolicyLockoutSafetyCheck.value + ) + + return output + + +def com_amazonaws_kms_ReEncryptRequest(dafny_input): + output = {} + output["CiphertextBlob"] = bytes(dafny_input.CiphertextBlob) + if dafny_input.SourceEncryptionContext.is_Some: + output["SourceEncryptionContext"] = { + 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.SourceEncryptionContext.value.items + } + + if dafny_input.SourceKeyId.is_Some: + output["SourceKeyId"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.SourceKeyId.value + ).decode("utf-16-be") + + output["DestinationKeyId"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.DestinationKeyId + ).decode("utf-16-be") + if dafny_input.DestinationEncryptionContext.is_Some: + output["DestinationEncryptionContext"] = { + 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.DestinationEncryptionContext.value.items + } + + if dafny_input.SourceEncryptionAlgorithm.is_Some: + output["SourceEncryptionAlgorithm"] = ( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_EncryptionAlgorithmSpec( + dafny_input.SourceEncryptionAlgorithm.value + ) + ) + + if dafny_input.DestinationEncryptionAlgorithm.is_Some: + output["DestinationEncryptionAlgorithm"] = ( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_EncryptionAlgorithmSpec( + dafny_input.DestinationEncryptionAlgorithm.value + ) + ) + + if dafny_input.GrantTokens.is_Some: + output["GrantTokens"] = [ + 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.DryRun.is_Some: + output["DryRun"] = dafny_input.DryRun.value + + return output + + +def com_amazonaws_kms_ReEncryptResponse(dafny_input): + output = {} + if dafny_input.CiphertextBlob.is_Some: + output["CiphertextBlob"] = bytes(dafny_input.CiphertextBlob.value) + + if dafny_input.SourceKeyId.is_Some: + output["SourceKeyId"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.SourceKeyId.value + ).decode("utf-16-be") + + if dafny_input.KeyId.is_Some: + output["KeyId"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.KeyId.value + ).decode("utf-16-be") + + if dafny_input.SourceEncryptionAlgorithm.is_Some: + output["SourceEncryptionAlgorithm"] = ( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_EncryptionAlgorithmSpec( + dafny_input.SourceEncryptionAlgorithm.value + ) + ) + + if dafny_input.DestinationEncryptionAlgorithm.is_Some: + output["DestinationEncryptionAlgorithm"] = ( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_EncryptionAlgorithmSpec( + dafny_input.DestinationEncryptionAlgorithm.value + ) + ) + + return output + + +def com_amazonaws_kms_ReplicateKeyRequest(dafny_input): + output = {} + output["KeyId"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.KeyId + ).decode("utf-16-be") + output["ReplicaRegion"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.ReplicaRegion + ).decode("utf-16-be") + if dafny_input.Policy.is_Some: + output["Policy"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.Policy.value + ).decode("utf-16-be") + + if dafny_input.BypassPolicyLockoutSafetyCheck.is_Some: + output["BypassPolicyLockoutSafetyCheck"] = ( + dafny_input.BypassPolicyLockoutSafetyCheck.value + ) + + if dafny_input.Description.is_Some: + output["Description"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.Description.value + ).decode("utf-16-be") + + if dafny_input.Tags.is_Some: + output["Tags"] = [ + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_Tag( + list_element + ) + for list_element in dafny_input.Tags.value + ] + + return output + + +def com_amazonaws_kms_ReplicateKeyResponse(dafny_input): + output = {} + if dafny_input.ReplicaKeyMetadata.is_Some: + output["ReplicaKeyMetadata"] = ( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_KeyMetadata( + dafny_input.ReplicaKeyMetadata.value + ) + ) + + if dafny_input.ReplicaPolicy.is_Some: + output["ReplicaPolicy"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.ReplicaPolicy.value + ).decode("utf-16-be") + + if dafny_input.ReplicaTags.is_Some: + output["ReplicaTags"] = [ + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_Tag( + list_element + ) + for list_element in dafny_input.ReplicaTags.value + ] + + return output + + +def com_amazonaws_kms_RetireGrantRequest(dafny_input): + output = {} + if dafny_input.GrantToken.is_Some: + output["GrantToken"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.GrantToken.value + ).decode("utf-16-be") + + if dafny_input.KeyId.is_Some: + output["KeyId"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.KeyId.value + ).decode("utf-16-be") + + if dafny_input.GrantId.is_Some: + output["GrantId"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.GrantId.value + ).decode("utf-16-be") + + if dafny_input.DryRun.is_Some: + output["DryRun"] = dafny_input.DryRun.value + + return output + + +def com_amazonaws_kms_RevokeGrantRequest(dafny_input): + output = {} + output["KeyId"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.KeyId + ).decode("utf-16-be") + output["GrantId"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.GrantId + ).decode("utf-16-be") + if dafny_input.DryRun.is_Some: + output["DryRun"] = dafny_input.DryRun.value + + return output + + +def com_amazonaws_kms_RotateKeyOnDemandRequest(dafny_input): + output = {} + output["KeyId"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.KeyId + ).decode("utf-16-be") + return output + + +def com_amazonaws_kms_RotateKeyOnDemandResponse(dafny_input): + output = {} + if dafny_input.KeyId.is_Some: + output["KeyId"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.KeyId.value + ).decode("utf-16-be") + + return output + + +def com_amazonaws_kms_ScheduleKeyDeletionRequest(dafny_input): + output = {} + output["KeyId"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.KeyId + ).decode("utf-16-be") + if dafny_input.PendingWindowInDays.is_Some: + output["PendingWindowInDays"] = dafny_input.PendingWindowInDays.value + + return output + + +def com_amazonaws_kms_ScheduleKeyDeletionResponse(dafny_input): + output = {} + if dafny_input.KeyId.is_Some: + output["KeyId"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.KeyId.value + ).decode("utf-16-be") + + if dafny_input.DeletionDate.is_Some: + output["DeletionDate"] = datetime.fromisoformat( + dafny_input.DeletionDate.value.VerbatimString(False) + ) + + if dafny_input.KeyState.is_Some: + output["KeyState"] = ( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_KeyState( + dafny_input.KeyState.value + ) + ) + + if dafny_input.PendingWindowInDays.is_Some: + output["PendingWindowInDays"] = dafny_input.PendingWindowInDays.value + + return output + + +def com_amazonaws_kms_MessageType(dafny_input): + # Convert MessageType + if isinstance(dafny_input, MessageType_RAW): + return "RAW" + + elif isinstance(dafny_input, MessageType_DIGEST): + return "DIGEST" + + else: + raise ValueError("No recognized enum value in enum type: " + dafny_input) + + +def com_amazonaws_kms_SignRequest(dafny_input): + output = {} + output["KeyId"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.KeyId + ).decode("utf-16-be") + output["Message"] = bytes(dafny_input.Message) + if dafny_input.MessageType.is_Some: + output["MessageType"] = ( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_MessageType( + dafny_input.MessageType.value + ) + ) + + if dafny_input.GrantTokens.is_Some: + output["GrantTokens"] = [ + 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 + ] + + output["SigningAlgorithm"] = ( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_SigningAlgorithmSpec( + dafny_input.SigningAlgorithm + ) + ) + if dafny_input.DryRun.is_Some: + output["DryRun"] = dafny_input.DryRun.value + + return output + + +def com_amazonaws_kms_SignResponse(dafny_input): + output = {} + if dafny_input.KeyId.is_Some: + output["KeyId"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.KeyId.value + ).decode("utf-16-be") + + if dafny_input.Signature.is_Some: + output["Signature"] = bytes(dafny_input.Signature.value) + + if dafny_input.SigningAlgorithm.is_Some: + output["SigningAlgorithm"] = ( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_SigningAlgorithmSpec( + dafny_input.SigningAlgorithm.value + ) + ) + + return output + + +def com_amazonaws_kms_TagResourceRequest(dafny_input): + output = {} + output["KeyId"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.KeyId + ).decode("utf-16-be") + output["Tags"] = [ + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_Tag( + list_element + ) + for list_element in dafny_input.Tags + ] + return output + + +def com_amazonaws_kms_UntagResourceRequest(dafny_input): + output = {} + output["KeyId"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.KeyId + ).decode("utf-16-be") + output["TagKeys"] = [ + b"".join(ord(c).to_bytes(2, "big") for c in list_element).decode("utf-16-be") + for list_element in dafny_input.TagKeys + ] + return output + + +def com_amazonaws_kms_UpdateAliasRequest(dafny_input): + output = {} + output["AliasName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.AliasName + ).decode("utf-16-be") + output["TargetKeyId"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.TargetKeyId + ).decode("utf-16-be") + return output + + +def com_amazonaws_kms_UpdateCustomKeyStoreRequest(dafny_input): + output = {} + output["CustomKeyStoreId"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.CustomKeyStoreId + ).decode("utf-16-be") + if dafny_input.NewCustomKeyStoreName.is_Some: + output["NewCustomKeyStoreName"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.NewCustomKeyStoreName.value + ).decode("utf-16-be") + + if dafny_input.KeyStorePassword.is_Some: + output["KeyStorePassword"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.KeyStorePassword.value + ).decode("utf-16-be") + + if dafny_input.CloudHsmClusterId.is_Some: + output["CloudHsmClusterId"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.CloudHsmClusterId.value + ).decode("utf-16-be") + + if dafny_input.XksProxyUriEndpoint.is_Some: + output["XksProxyUriEndpoint"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.XksProxyUriEndpoint.value + ).decode("utf-16-be") + + if dafny_input.XksProxyUriPath.is_Some: + output["XksProxyUriPath"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.XksProxyUriPath.value + ).decode("utf-16-be") + + if dafny_input.XksProxyVpcEndpointServiceName.is_Some: + output["XksProxyVpcEndpointServiceName"] = b"".join( + ord(c).to_bytes(2, "big") + for c in dafny_input.XksProxyVpcEndpointServiceName.value + ).decode("utf-16-be") + + if dafny_input.XksProxyAuthenticationCredential.is_Some: + output["XksProxyAuthenticationCredential"] = ( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_XksProxyAuthenticationCredentialType( + dafny_input.XksProxyAuthenticationCredential.value + ) + ) + + if dafny_input.XksProxyConnectivity.is_Some: + output["XksProxyConnectivity"] = ( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_XksProxyConnectivityType( + dafny_input.XksProxyConnectivity.value + ) + ) + + return output + + +def com_amazonaws_kms_UpdateCustomKeyStoreResponse(dafny_input): + output = {} + return output + + +def com_amazonaws_kms_UpdateKeyDescriptionRequest(dafny_input): + output = {} + output["KeyId"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.KeyId + ).decode("utf-16-be") + output["Description"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.Description + ).decode("utf-16-be") + return output + + +def com_amazonaws_kms_UpdatePrimaryRegionRequest(dafny_input): + output = {} + output["KeyId"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.KeyId + ).decode("utf-16-be") + output["PrimaryRegion"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.PrimaryRegion + ).decode("utf-16-be") + return output + + +def com_amazonaws_kms_VerifyRequest(dafny_input): + output = {} + output["KeyId"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.KeyId + ).decode("utf-16-be") + output["Message"] = bytes(dafny_input.Message) + if dafny_input.MessageType.is_Some: + output["MessageType"] = ( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_MessageType( + dafny_input.MessageType.value + ) + ) + + output["Signature"] = bytes(dafny_input.Signature) + output["SigningAlgorithm"] = ( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_SigningAlgorithmSpec( + dafny_input.SigningAlgorithm + ) + ) + if dafny_input.GrantTokens.is_Some: + output["GrantTokens"] = [ + 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.DryRun.is_Some: + output["DryRun"] = dafny_input.DryRun.value + + return output + + +def com_amazonaws_kms_VerifyResponse(dafny_input): + output = {} + if dafny_input.KeyId.is_Some: + output["KeyId"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.KeyId.value + ).decode("utf-16-be") + + if dafny_input.SignatureValid.is_Some: + output["SignatureValid"] = dafny_input.SignatureValid.value + + if dafny_input.SigningAlgorithm.is_Some: + output["SigningAlgorithm"] = ( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_SigningAlgorithmSpec( + dafny_input.SigningAlgorithm.value + ) + ) + + return output + + +def com_amazonaws_kms_VerifyMacRequest(dafny_input): + output = {} + output["Message"] = bytes(dafny_input.Message) + output["KeyId"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.KeyId + ).decode("utf-16-be") + output["MacAlgorithm"] = ( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_MacAlgorithmSpec( + dafny_input.MacAlgorithm + ) + ) + output["Mac"] = bytes(dafny_input.Mac) + if dafny_input.GrantTokens.is_Some: + output["GrantTokens"] = [ + 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.DryRun.is_Some: + output["DryRun"] = dafny_input.DryRun.value + + return output + + +def com_amazonaws_kms_VerifyMacResponse(dafny_input): + output = {} + if dafny_input.KeyId.is_Some: + output["KeyId"] = b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.KeyId.value + ).decode("utf-16-be") + + if dafny_input.MacValid.is_Some: + output["MacValid"] = dafny_input.MacValid.value + + if dafny_input.MacAlgorithm.is_Some: + output["MacAlgorithm"] = ( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_MacAlgorithmSpec( + dafny_input.MacAlgorithm.value + ) + ) + + return output diff --git a/ComAmazonawsKms/runtimes/python/src/aws_cryptography_internal_kms/smithygenerated/com_amazonaws_kms/shim.py b/ComAmazonawsKms/runtimes/python/src/aws_cryptography_internal_kms/smithygenerated/com_amazonaws_kms/shim.py new file mode 100644 index 000000000..8bf832b48 --- /dev/null +++ b/ComAmazonawsKms/runtimes/python/src/aws_cryptography_internal_kms/smithygenerated/com_amazonaws_kms/shim.py @@ -0,0 +1,1149 @@ +# 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_cryptography_internal_kms.internaldafny.generated.ComAmazonawsKmsTypes import ( + CancelKeyDeletionRequest_CancelKeyDeletionRequest as DafnyCancelKeyDeletionRequest, + CancelKeyDeletionResponse_CancelKeyDeletionResponse as DafnyCancelKeyDeletionResponse, + ConnectCustomKeyStoreRequest_ConnectCustomKeyStoreRequest as DafnyConnectCustomKeyStoreRequest, + ConnectCustomKeyStoreResponse_ConnectCustomKeyStoreResponse as DafnyConnectCustomKeyStoreResponse, + CreateAliasRequest_CreateAliasRequest as DafnyCreateAliasRequest, + CreateCustomKeyStoreRequest_CreateCustomKeyStoreRequest as DafnyCreateCustomKeyStoreRequest, + CreateCustomKeyStoreResponse_CreateCustomKeyStoreResponse as DafnyCreateCustomKeyStoreResponse, + CreateGrantRequest_CreateGrantRequest as DafnyCreateGrantRequest, + CreateGrantResponse_CreateGrantResponse as DafnyCreateGrantResponse, + CreateKeyRequest_CreateKeyRequest as DafnyCreateKeyRequest, + CreateKeyResponse_CreateKeyResponse as DafnyCreateKeyResponse, + DecryptRequest_DecryptRequest as DafnyDecryptRequest, + DecryptResponse_DecryptResponse as DafnyDecryptResponse, + DeleteAliasRequest_DeleteAliasRequest as DafnyDeleteAliasRequest, + DeleteCustomKeyStoreRequest_DeleteCustomKeyStoreRequest as DafnyDeleteCustomKeyStoreRequest, + DeleteCustomKeyStoreResponse_DeleteCustomKeyStoreResponse as DafnyDeleteCustomKeyStoreResponse, + DeleteImportedKeyMaterialRequest_DeleteImportedKeyMaterialRequest as DafnyDeleteImportedKeyMaterialRequest, + DeriveSharedSecretRequest_DeriveSharedSecretRequest as DafnyDeriveSharedSecretRequest, + DeriveSharedSecretResponse_DeriveSharedSecretResponse as DafnyDeriveSharedSecretResponse, + DescribeCustomKeyStoresRequest_DescribeCustomKeyStoresRequest as DafnyDescribeCustomKeyStoresRequest, + DescribeCustomKeyStoresResponse_DescribeCustomKeyStoresResponse as DafnyDescribeCustomKeyStoresResponse, + DescribeKeyRequest_DescribeKeyRequest as DafnyDescribeKeyRequest, + DescribeKeyResponse_DescribeKeyResponse as DafnyDescribeKeyResponse, + DisableKeyRequest_DisableKeyRequest as DafnyDisableKeyRequest, + DisableKeyRotationRequest_DisableKeyRotationRequest as DafnyDisableKeyRotationRequest, + DisconnectCustomKeyStoreRequest_DisconnectCustomKeyStoreRequest as DafnyDisconnectCustomKeyStoreRequest, + DisconnectCustomKeyStoreResponse_DisconnectCustomKeyStoreResponse as DafnyDisconnectCustomKeyStoreResponse, + EnableKeyRequest_EnableKeyRequest as DafnyEnableKeyRequest, + EnableKeyRotationRequest_EnableKeyRotationRequest as DafnyEnableKeyRotationRequest, + EncryptRequest_EncryptRequest as DafnyEncryptRequest, + EncryptResponse_EncryptResponse as DafnyEncryptResponse, + GenerateDataKeyPairRequest_GenerateDataKeyPairRequest as DafnyGenerateDataKeyPairRequest, + GenerateDataKeyPairResponse_GenerateDataKeyPairResponse as DafnyGenerateDataKeyPairResponse, + GenerateDataKeyPairWithoutPlaintextRequest_GenerateDataKeyPairWithoutPlaintextRequest as DafnyGenerateDataKeyPairWithoutPlaintextRequest, + GenerateDataKeyPairWithoutPlaintextResponse_GenerateDataKeyPairWithoutPlaintextResponse as DafnyGenerateDataKeyPairWithoutPlaintextResponse, + GenerateDataKeyRequest_GenerateDataKeyRequest as DafnyGenerateDataKeyRequest, + GenerateDataKeyResponse_GenerateDataKeyResponse as DafnyGenerateDataKeyResponse, + GenerateDataKeyWithoutPlaintextRequest_GenerateDataKeyWithoutPlaintextRequest as DafnyGenerateDataKeyWithoutPlaintextRequest, + GenerateDataKeyWithoutPlaintextResponse_GenerateDataKeyWithoutPlaintextResponse as DafnyGenerateDataKeyWithoutPlaintextResponse, + GenerateMacRequest_GenerateMacRequest as DafnyGenerateMacRequest, + GenerateMacResponse_GenerateMacResponse as DafnyGenerateMacResponse, + GenerateRandomRequest_GenerateRandomRequest as DafnyGenerateRandomRequest, + GenerateRandomResponse_GenerateRandomResponse as DafnyGenerateRandomResponse, + GetKeyPolicyRequest_GetKeyPolicyRequest as DafnyGetKeyPolicyRequest, + GetKeyPolicyResponse_GetKeyPolicyResponse as DafnyGetKeyPolicyResponse, + GetKeyRotationStatusRequest_GetKeyRotationStatusRequest as DafnyGetKeyRotationStatusRequest, + GetKeyRotationStatusResponse_GetKeyRotationStatusResponse as DafnyGetKeyRotationStatusResponse, + GetParametersForImportRequest_GetParametersForImportRequest as DafnyGetParametersForImportRequest, + GetParametersForImportResponse_GetParametersForImportResponse as DafnyGetParametersForImportResponse, + GetPublicKeyRequest_GetPublicKeyRequest as DafnyGetPublicKeyRequest, + GetPublicKeyResponse_GetPublicKeyResponse as DafnyGetPublicKeyResponse, + ImportKeyMaterialRequest_ImportKeyMaterialRequest as DafnyImportKeyMaterialRequest, + ImportKeyMaterialResponse_ImportKeyMaterialResponse as DafnyImportKeyMaterialResponse, + ListAliasesRequest_ListAliasesRequest as DafnyListAliasesRequest, + ListAliasesResponse_ListAliasesResponse as DafnyListAliasesResponse, + ListGrantsRequest_ListGrantsRequest as DafnyListGrantsRequest, + ListGrantsResponse_ListGrantsResponse as DafnyListGrantsResponse, + ListKeyPoliciesRequest_ListKeyPoliciesRequest as DafnyListKeyPoliciesRequest, + ListKeyPoliciesResponse_ListKeyPoliciesResponse as DafnyListKeyPoliciesResponse, + ListKeyRotationsRequest_ListKeyRotationsRequest as DafnyListKeyRotationsRequest, + ListKeyRotationsResponse_ListKeyRotationsResponse as DafnyListKeyRotationsResponse, + ListKeysRequest_ListKeysRequest as DafnyListKeysRequest, + ListKeysResponse_ListKeysResponse as DafnyListKeysResponse, + ListResourceTagsRequest_ListResourceTagsRequest as DafnyListResourceTagsRequest, + ListResourceTagsResponse_ListResourceTagsResponse as DafnyListResourceTagsResponse, + PutKeyPolicyRequest_PutKeyPolicyRequest as DafnyPutKeyPolicyRequest, + ReEncryptRequest_ReEncryptRequest as DafnyReEncryptRequest, + ReEncryptResponse_ReEncryptResponse as DafnyReEncryptResponse, + ReplicateKeyRequest_ReplicateKeyRequest as DafnyReplicateKeyRequest, + ReplicateKeyResponse_ReplicateKeyResponse as DafnyReplicateKeyResponse, + RetireGrantRequest_RetireGrantRequest as DafnyRetireGrantRequest, + RevokeGrantRequest_RevokeGrantRequest as DafnyRevokeGrantRequest, + RotateKeyOnDemandRequest_RotateKeyOnDemandRequest as DafnyRotateKeyOnDemandRequest, + RotateKeyOnDemandResponse_RotateKeyOnDemandResponse as DafnyRotateKeyOnDemandResponse, + ScheduleKeyDeletionRequest_ScheduleKeyDeletionRequest as DafnyScheduleKeyDeletionRequest, + ScheduleKeyDeletionResponse_ScheduleKeyDeletionResponse as DafnyScheduleKeyDeletionResponse, + SignRequest_SignRequest as DafnySignRequest, + SignResponse_SignResponse as DafnySignResponse, + TagResourceRequest_TagResourceRequest as DafnyTagResourceRequest, + UntagResourceRequest_UntagResourceRequest as DafnyUntagResourceRequest, + UpdateAliasRequest_UpdateAliasRequest as DafnyUpdateAliasRequest, + UpdateCustomKeyStoreRequest_UpdateCustomKeyStoreRequest as DafnyUpdateCustomKeyStoreRequest, + UpdateCustomKeyStoreResponse_UpdateCustomKeyStoreResponse as DafnyUpdateCustomKeyStoreResponse, + UpdateKeyDescriptionRequest_UpdateKeyDescriptionRequest as DafnyUpdateKeyDescriptionRequest, + UpdatePrimaryRegionRequest_UpdatePrimaryRegionRequest as DafnyUpdatePrimaryRegionRequest, + VerifyMacRequest_VerifyMacRequest as DafnyVerifyMacRequest, + VerifyMacResponse_VerifyMacResponse as DafnyVerifyMacResponse, + VerifyRequest_VerifyRequest as DafnyVerifyRequest, + VerifyResponse_VerifyResponse as DafnyVerifyResponse, +) +import aws_cryptography_internal_kms.internaldafny.generated.module_ +import aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny +import aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk + +from . import dafny_to_aws_sdk + + +import smithy_dafny_standard_library.internaldafny.generated.Wrappers as Wrappers +from botocore.exceptions import ClientError +import aws_cryptography_internal_kms.internaldafny.generated.ComAmazonawsKmsTypes + + +def _sdk_error_to_dafny_error(e: ClientError): + """Converts the provided native Smithy-modelled error into the + corresponding Dafny error.""" + if e.response["Error"]["Code"] == "AlreadyExistsException": + return aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_AlreadyExistsException( + e.response + ) + + elif e.response["Error"]["Code"] == "CloudHsmClusterInUseException": + return aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_CloudHsmClusterInUseException( + e.response + ) + + elif e.response["Error"]["Code"] == "CloudHsmClusterInvalidConfigurationException": + return aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_CloudHsmClusterInvalidConfigurationException( + e.response + ) + + elif e.response["Error"]["Code"] == "CloudHsmClusterNotActiveException": + return aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_CloudHsmClusterNotActiveException( + e.response + ) + + elif e.response["Error"]["Code"] == "CloudHsmClusterNotFoundException": + return aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_CloudHsmClusterNotFoundException( + e.response + ) + + elif e.response["Error"]["Code"] == "CloudHsmClusterNotRelatedException": + return aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_CloudHsmClusterNotRelatedException( + e.response + ) + + elif e.response["Error"]["Code"] == "ConflictException": + return aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_ConflictException( + e.response + ) + + elif e.response["Error"]["Code"] == "CustomKeyStoreHasCMKsException": + return aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_CustomKeyStoreHasCMKsException( + e.response + ) + + elif e.response["Error"]["Code"] == "CustomKeyStoreInvalidStateException": + return aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_CustomKeyStoreInvalidStateException( + e.response + ) + + elif e.response["Error"]["Code"] == "CustomKeyStoreNameInUseException": + return aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_CustomKeyStoreNameInUseException( + e.response + ) + + elif e.response["Error"]["Code"] == "CustomKeyStoreNotFoundException": + return aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_CustomKeyStoreNotFoundException( + e.response + ) + + elif e.response["Error"]["Code"] == "DependencyTimeoutException": + return aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_DependencyTimeoutException( + e.response + ) + + elif e.response["Error"]["Code"] == "DisabledException": + return aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_DisabledException( + e.response + ) + + elif e.response["Error"]["Code"] == "DryRunOperationException": + return aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_DryRunOperationException( + e.response + ) + + elif e.response["Error"]["Code"] == "ExpiredImportTokenException": + return aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_ExpiredImportTokenException( + e.response + ) + + elif e.response["Error"]["Code"] == "IncorrectKeyException": + return aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_IncorrectKeyException( + e.response + ) + + elif e.response["Error"]["Code"] == "IncorrectKeyMaterialException": + return aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_IncorrectKeyMaterialException( + e.response + ) + + elif e.response["Error"]["Code"] == "IncorrectTrustAnchorException": + return aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_IncorrectTrustAnchorException( + e.response + ) + + elif e.response["Error"]["Code"] == "InvalidAliasNameException": + return aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_InvalidAliasNameException( + e.response + ) + + elif e.response["Error"]["Code"] == "InvalidArnException": + return aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_InvalidArnException( + e.response + ) + + elif e.response["Error"]["Code"] == "InvalidCiphertextException": + return aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_InvalidCiphertextException( + e.response + ) + + elif e.response["Error"]["Code"] == "InvalidGrantIdException": + return aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_InvalidGrantIdException( + e.response + ) + + elif e.response["Error"]["Code"] == "InvalidGrantTokenException": + return aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_InvalidGrantTokenException( + e.response + ) + + elif e.response["Error"]["Code"] == "InvalidImportTokenException": + return aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_InvalidImportTokenException( + e.response + ) + + elif e.response["Error"]["Code"] == "InvalidKeyUsageException": + return aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_InvalidKeyUsageException( + e.response + ) + + elif e.response["Error"]["Code"] == "InvalidMarkerException": + return aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_InvalidMarkerException( + e.response + ) + + elif e.response["Error"]["Code"] == "KeyUnavailableException": + return aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_KeyUnavailableException( + e.response + ) + + elif e.response["Error"]["Code"] == "KMSInternalException": + return aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_KMSInternalException( + e.response + ) + + elif e.response["Error"]["Code"] == "KMSInvalidMacException": + return aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_KMSInvalidMacException( + e.response + ) + + elif e.response["Error"]["Code"] == "KMSInvalidSignatureException": + return aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_KMSInvalidSignatureException( + e.response + ) + + elif e.response["Error"]["Code"] == "KMSInvalidStateException": + return aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_KMSInvalidStateException( + e.response + ) + + elif e.response["Error"]["Code"] == "LimitExceededException": + return aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_LimitExceededException( + e.response + ) + + elif e.response["Error"]["Code"] == "MalformedPolicyDocumentException": + return aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_MalformedPolicyDocumentException( + e.response + ) + + elif e.response["Error"]["Code"] == "NotFoundException": + return aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_NotFoundException( + e.response + ) + + elif e.response["Error"]["Code"] == "TagException": + return aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_TagException( + e.response + ) + + elif e.response["Error"]["Code"] == "UnsupportedOperationException": + return aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_UnsupportedOperationException( + e.response + ) + + elif e.response["Error"]["Code"] == "XksKeyAlreadyInUseException": + return aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_XksKeyAlreadyInUseException( + e.response + ) + + elif e.response["Error"]["Code"] == "XksKeyInvalidConfigurationException": + return aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_XksKeyInvalidConfigurationException( + e.response + ) + + elif e.response["Error"]["Code"] == "XksKeyNotFoundException": + return aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_XksKeyNotFoundException( + e.response + ) + + elif ( + e.response["Error"]["Code"] + == "XksProxyIncorrectAuthenticationCredentialException" + ): + return aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_XksProxyIncorrectAuthenticationCredentialException( + e.response + ) + + elif e.response["Error"]["Code"] == "XksProxyInvalidConfigurationException": + return aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_XksProxyInvalidConfigurationException( + e.response + ) + + elif e.response["Error"]["Code"] == "XksProxyInvalidResponseException": + return aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_XksProxyInvalidResponseException( + e.response + ) + + elif e.response["Error"]["Code"] == "XksProxyUriEndpointInUseException": + return aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_XksProxyUriEndpointInUseException( + e.response + ) + + elif e.response["Error"]["Code"] == "XksProxyUriInUseException": + return aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_XksProxyUriInUseException( + e.response + ) + + elif e.response["Error"]["Code"] == "XksProxyUriUnreachableException": + return aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_XksProxyUriUnreachableException( + e.response + ) + + elif e.response["Error"]["Code"] == "XksProxyVpcEndpointServiceInUseException": + return aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_XksProxyVpcEndpointServiceInUseException( + e.response + ) + + elif ( + e.response["Error"]["Code"] + == "XksProxyVpcEndpointServiceInvalidConfigurationException" + ): + return aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_XksProxyVpcEndpointServiceInvalidConfigurationException( + e.response + ) + + elif e.response["Error"]["Code"] == "XksProxyVpcEndpointServiceNotFoundException": + return aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_XksProxyVpcEndpointServiceNotFoundException( + e.response + ) + + return aws_cryptography_internal_kms.internaldafny.generated.ComAmazonawsKmsTypes.Error_Opaque( + obj=e + ) + + +class KMSClientShim: + def __init__(self, _impl, _region): + self._impl = _impl + self._region = _region + + def CancelKeyDeletion( + self, input: DafnyCancelKeyDeletionRequest + ) -> DafnyCancelKeyDeletionResponse: + boto_request_dict = aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_CancelKeyDeletionRequest( + input + ) + try: + boto_response_dict = self._impl.cancel_key_deletion(**boto_request_dict) + except ClientError as e: + return Wrappers.Result_Failure(_sdk_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_CancelKeyDeletionResponse( + boto_response_dict + ) + ) + + def ConnectCustomKeyStore( + self, input: DafnyConnectCustomKeyStoreRequest + ) -> DafnyConnectCustomKeyStoreResponse: + boto_request_dict = aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_ConnectCustomKeyStoreRequest( + input + ) + try: + boto_response_dict = self._impl.connect_custom_key_store( + **boto_request_dict + ) + except ClientError as e: + return Wrappers.Result_Failure(_sdk_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_ConnectCustomKeyStoreResponse( + boto_response_dict + ) + ) + + def CreateAlias(self, input: DafnyCreateAliasRequest) -> None: + boto_request_dict = aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_CreateAliasRequest( + input + ) + try: + boto_response_dict = self._impl.create_alias(**boto_request_dict) + except ClientError as e: + return Wrappers.Result_Failure(_sdk_error_to_dafny_error(e)) + + return Wrappers.Result_Success(None) + + def CreateCustomKeyStore( + self, input: DafnyCreateCustomKeyStoreRequest + ) -> DafnyCreateCustomKeyStoreResponse: + boto_request_dict = aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_CreateCustomKeyStoreRequest( + input + ) + try: + boto_response_dict = self._impl.create_custom_key_store(**boto_request_dict) + except ClientError as e: + return Wrappers.Result_Failure(_sdk_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_CreateCustomKeyStoreResponse( + boto_response_dict + ) + ) + + def CreateGrant(self, input: DafnyCreateGrantRequest) -> DafnyCreateGrantResponse: + boto_request_dict = aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_CreateGrantRequest( + input + ) + try: + boto_response_dict = self._impl.create_grant(**boto_request_dict) + except ClientError as e: + return Wrappers.Result_Failure(_sdk_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_CreateGrantResponse( + boto_response_dict + ) + ) + + def CreateKey(self, input: DafnyCreateKeyRequest) -> DafnyCreateKeyResponse: + boto_request_dict = aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_CreateKeyRequest( + input + ) + try: + boto_response_dict = self._impl.create_key(**boto_request_dict) + except ClientError as e: + return Wrappers.Result_Failure(_sdk_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_CreateKeyResponse( + boto_response_dict + ) + ) + + def Decrypt(self, input: DafnyDecryptRequest) -> DafnyDecryptResponse: + boto_request_dict = aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_DecryptRequest( + input + ) + try: + boto_response_dict = self._impl.decrypt(**boto_request_dict) + except ClientError as e: + return Wrappers.Result_Failure(_sdk_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_DecryptResponse( + boto_response_dict + ) + ) + + def DeleteAlias(self, input: DafnyDeleteAliasRequest) -> None: + boto_request_dict = aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_DeleteAliasRequest( + input + ) + try: + boto_response_dict = self._impl.delete_alias(**boto_request_dict) + except ClientError as e: + return Wrappers.Result_Failure(_sdk_error_to_dafny_error(e)) + + return Wrappers.Result_Success(None) + + def DeleteCustomKeyStore( + self, input: DafnyDeleteCustomKeyStoreRequest + ) -> DafnyDeleteCustomKeyStoreResponse: + boto_request_dict = aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_DeleteCustomKeyStoreRequest( + input + ) + try: + boto_response_dict = self._impl.delete_custom_key_store(**boto_request_dict) + except ClientError as e: + return Wrappers.Result_Failure(_sdk_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_DeleteCustomKeyStoreResponse( + boto_response_dict + ) + ) + + def DeleteImportedKeyMaterial( + self, input: DafnyDeleteImportedKeyMaterialRequest + ) -> None: + boto_request_dict = aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_DeleteImportedKeyMaterialRequest( + input + ) + try: + boto_response_dict = self._impl.delete_imported_key_material( + **boto_request_dict + ) + except ClientError as e: + return Wrappers.Result_Failure(_sdk_error_to_dafny_error(e)) + + return Wrappers.Result_Success(None) + + def DeriveSharedSecret( + self, input: DafnyDeriveSharedSecretRequest + ) -> DafnyDeriveSharedSecretResponse: + boto_request_dict = aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_DeriveSharedSecretRequest( + input + ) + try: + boto_response_dict = self._impl.derive_shared_secret(**boto_request_dict) + except ClientError as e: + return Wrappers.Result_Failure(_sdk_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_DeriveSharedSecretResponse( + boto_response_dict + ) + ) + + def DescribeCustomKeyStores( + self, input: DafnyDescribeCustomKeyStoresRequest + ) -> DafnyDescribeCustomKeyStoresResponse: + boto_request_dict = aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_DescribeCustomKeyStoresRequest( + input + ) + try: + boto_response_dict = self._impl.describe_custom_key_stores( + **boto_request_dict + ) + except ClientError as e: + return Wrappers.Result_Failure(_sdk_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_DescribeCustomKeyStoresResponse( + boto_response_dict + ) + ) + + def DescribeKey(self, input: DafnyDescribeKeyRequest) -> DafnyDescribeKeyResponse: + boto_request_dict = aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_DescribeKeyRequest( + input + ) + try: + boto_response_dict = self._impl.describe_key(**boto_request_dict) + except ClientError as e: + return Wrappers.Result_Failure(_sdk_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_DescribeKeyResponse( + boto_response_dict + ) + ) + + def DisableKey(self, input: DafnyDisableKeyRequest) -> None: + boto_request_dict = aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_DisableKeyRequest( + input + ) + try: + boto_response_dict = self._impl.disable_key(**boto_request_dict) + except ClientError as e: + return Wrappers.Result_Failure(_sdk_error_to_dafny_error(e)) + + return Wrappers.Result_Success(None) + + def DisableKeyRotation(self, input: DafnyDisableKeyRotationRequest) -> None: + boto_request_dict = aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_DisableKeyRotationRequest( + input + ) + try: + boto_response_dict = self._impl.disable_key_rotation(**boto_request_dict) + except ClientError as e: + return Wrappers.Result_Failure(_sdk_error_to_dafny_error(e)) + + return Wrappers.Result_Success(None) + + def DisconnectCustomKeyStore( + self, input: DafnyDisconnectCustomKeyStoreRequest + ) -> DafnyDisconnectCustomKeyStoreResponse: + boto_request_dict = aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_DisconnectCustomKeyStoreRequest( + input + ) + try: + boto_response_dict = self._impl.disconnect_custom_key_store( + **boto_request_dict + ) + except ClientError as e: + return Wrappers.Result_Failure(_sdk_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_DisconnectCustomKeyStoreResponse( + boto_response_dict + ) + ) + + def EnableKey(self, input: DafnyEnableKeyRequest) -> None: + boto_request_dict = aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_EnableKeyRequest( + input + ) + try: + boto_response_dict = self._impl.enable_key(**boto_request_dict) + except ClientError as e: + return Wrappers.Result_Failure(_sdk_error_to_dafny_error(e)) + + return Wrappers.Result_Success(None) + + def EnableKeyRotation(self, input: DafnyEnableKeyRotationRequest) -> None: + boto_request_dict = aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_EnableKeyRotationRequest( + input + ) + try: + boto_response_dict = self._impl.enable_key_rotation(**boto_request_dict) + except ClientError as e: + return Wrappers.Result_Failure(_sdk_error_to_dafny_error(e)) + + return Wrappers.Result_Success(None) + + def Encrypt(self, input: DafnyEncryptRequest) -> DafnyEncryptResponse: + boto_request_dict = aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_EncryptRequest( + input + ) + try: + boto_response_dict = self._impl.encrypt(**boto_request_dict) + except ClientError as e: + return Wrappers.Result_Failure(_sdk_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_EncryptResponse( + boto_response_dict + ) + ) + + def GenerateDataKey( + self, input: DafnyGenerateDataKeyRequest + ) -> DafnyGenerateDataKeyResponse: + boto_request_dict = aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_GenerateDataKeyRequest( + input + ) + try: + boto_response_dict = self._impl.generate_data_key(**boto_request_dict) + except ClientError as e: + return Wrappers.Result_Failure(_sdk_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_GenerateDataKeyResponse( + boto_response_dict + ) + ) + + def GenerateDataKeyPair( + self, input: DafnyGenerateDataKeyPairRequest + ) -> DafnyGenerateDataKeyPairResponse: + boto_request_dict = aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_GenerateDataKeyPairRequest( + input + ) + try: + boto_response_dict = self._impl.generate_data_key_pair(**boto_request_dict) + except ClientError as e: + return Wrappers.Result_Failure(_sdk_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_GenerateDataKeyPairResponse( + boto_response_dict + ) + ) + + def GenerateDataKeyPairWithoutPlaintext( + self, input: DafnyGenerateDataKeyPairWithoutPlaintextRequest + ) -> DafnyGenerateDataKeyPairWithoutPlaintextResponse: + boto_request_dict = aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_GenerateDataKeyPairWithoutPlaintextRequest( + input + ) + try: + boto_response_dict = self._impl.generate_data_key_pair_without_plaintext( + **boto_request_dict + ) + except ClientError as e: + return Wrappers.Result_Failure(_sdk_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_GenerateDataKeyPairWithoutPlaintextResponse( + boto_response_dict + ) + ) + + def GenerateDataKeyWithoutPlaintext( + self, input: DafnyGenerateDataKeyWithoutPlaintextRequest + ) -> DafnyGenerateDataKeyWithoutPlaintextResponse: + boto_request_dict = aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_GenerateDataKeyWithoutPlaintextRequest( + input + ) + try: + boto_response_dict = self._impl.generate_data_key_without_plaintext( + **boto_request_dict + ) + except ClientError as e: + return Wrappers.Result_Failure(_sdk_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_GenerateDataKeyWithoutPlaintextResponse( + boto_response_dict + ) + ) + + def GenerateMac(self, input: DafnyGenerateMacRequest) -> DafnyGenerateMacResponse: + boto_request_dict = aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_GenerateMacRequest( + input + ) + try: + boto_response_dict = self._impl.generate_mac(**boto_request_dict) + except ClientError as e: + return Wrappers.Result_Failure(_sdk_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_GenerateMacResponse( + boto_response_dict + ) + ) + + def GenerateRandom( + self, input: DafnyGenerateRandomRequest + ) -> DafnyGenerateRandomResponse: + boto_request_dict = aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_GenerateRandomRequest( + input + ) + try: + boto_response_dict = self._impl.generate_random(**boto_request_dict) + except ClientError as e: + return Wrappers.Result_Failure(_sdk_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_GenerateRandomResponse( + boto_response_dict + ) + ) + + def GetKeyPolicy( + self, input: DafnyGetKeyPolicyRequest + ) -> DafnyGetKeyPolicyResponse: + boto_request_dict = aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_GetKeyPolicyRequest( + input + ) + try: + boto_response_dict = self._impl.get_key_policy(**boto_request_dict) + except ClientError as e: + return Wrappers.Result_Failure(_sdk_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_GetKeyPolicyResponse( + boto_response_dict + ) + ) + + def GetKeyRotationStatus( + self, input: DafnyGetKeyRotationStatusRequest + ) -> DafnyGetKeyRotationStatusResponse: + boto_request_dict = aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_GetKeyRotationStatusRequest( + input + ) + try: + boto_response_dict = self._impl.get_key_rotation_status(**boto_request_dict) + except ClientError as e: + return Wrappers.Result_Failure(_sdk_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_GetKeyRotationStatusResponse( + boto_response_dict + ) + ) + + def GetParametersForImport( + self, input: DafnyGetParametersForImportRequest + ) -> DafnyGetParametersForImportResponse: + boto_request_dict = aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_GetParametersForImportRequest( + input + ) + try: + boto_response_dict = self._impl.get_parameters_for_import( + **boto_request_dict + ) + except ClientError as e: + return Wrappers.Result_Failure(_sdk_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_GetParametersForImportResponse( + boto_response_dict + ) + ) + + def GetPublicKey( + self, input: DafnyGetPublicKeyRequest + ) -> DafnyGetPublicKeyResponse: + boto_request_dict = aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_GetPublicKeyRequest( + input + ) + try: + boto_response_dict = self._impl.get_public_key(**boto_request_dict) + except ClientError as e: + return Wrappers.Result_Failure(_sdk_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_GetPublicKeyResponse( + boto_response_dict + ) + ) + + def ImportKeyMaterial( + self, input: DafnyImportKeyMaterialRequest + ) -> DafnyImportKeyMaterialResponse: + boto_request_dict = aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_ImportKeyMaterialRequest( + input + ) + try: + boto_response_dict = self._impl.import_key_material(**boto_request_dict) + except ClientError as e: + return Wrappers.Result_Failure(_sdk_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_ImportKeyMaterialResponse( + boto_response_dict + ) + ) + + def ListAliases(self, input: DafnyListAliasesRequest) -> DafnyListAliasesResponse: + boto_request_dict = aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_ListAliasesRequest( + input + ) + try: + boto_response_dict = self._impl.list_aliases(**boto_request_dict) + except ClientError as e: + return Wrappers.Result_Failure(_sdk_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_ListAliasesResponse( + boto_response_dict + ) + ) + + def ListGrants(self, input: DafnyListGrantsRequest) -> DafnyListGrantsResponse: + boto_request_dict = aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_ListGrantsRequest( + input + ) + try: + boto_response_dict = self._impl.list_grants(**boto_request_dict) + except ClientError as e: + return Wrappers.Result_Failure(_sdk_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_ListGrantsResponse( + boto_response_dict + ) + ) + + def ListKeyPolicies( + self, input: DafnyListKeyPoliciesRequest + ) -> DafnyListKeyPoliciesResponse: + boto_request_dict = aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_ListKeyPoliciesRequest( + input + ) + try: + boto_response_dict = self._impl.list_key_policies(**boto_request_dict) + except ClientError as e: + return Wrappers.Result_Failure(_sdk_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_ListKeyPoliciesResponse( + boto_response_dict + ) + ) + + def ListKeyRotations( + self, input: DafnyListKeyRotationsRequest + ) -> DafnyListKeyRotationsResponse: + boto_request_dict = aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_ListKeyRotationsRequest( + input + ) + try: + boto_response_dict = self._impl.list_key_rotations(**boto_request_dict) + except ClientError as e: + return Wrappers.Result_Failure(_sdk_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_ListKeyRotationsResponse( + boto_response_dict + ) + ) + + def ListKeys(self, input: DafnyListKeysRequest) -> DafnyListKeysResponse: + boto_request_dict = aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_ListKeysRequest( + input + ) + try: + boto_response_dict = self._impl.list_keys(**boto_request_dict) + except ClientError as e: + return Wrappers.Result_Failure(_sdk_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_ListKeysResponse( + boto_response_dict + ) + ) + + def ListResourceTags( + self, input: DafnyListResourceTagsRequest + ) -> DafnyListResourceTagsResponse: + boto_request_dict = aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_ListResourceTagsRequest( + input + ) + try: + boto_response_dict = self._impl.list_resource_tags(**boto_request_dict) + except ClientError as e: + return Wrappers.Result_Failure(_sdk_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_ListResourceTagsResponse( + boto_response_dict + ) + ) + + def PutKeyPolicy(self, input: DafnyPutKeyPolicyRequest) -> None: + boto_request_dict = aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_PutKeyPolicyRequest( + input + ) + try: + boto_response_dict = self._impl.put_key_policy(**boto_request_dict) + except ClientError as e: + return Wrappers.Result_Failure(_sdk_error_to_dafny_error(e)) + + return Wrappers.Result_Success(None) + + def ReEncrypt(self, input: DafnyReEncryptRequest) -> DafnyReEncryptResponse: + boto_request_dict = aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_ReEncryptRequest( + input + ) + try: + boto_response_dict = self._impl.re_encrypt(**boto_request_dict) + except ClientError as e: + return Wrappers.Result_Failure(_sdk_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_ReEncryptResponse( + boto_response_dict + ) + ) + + def ReplicateKey( + self, input: DafnyReplicateKeyRequest + ) -> DafnyReplicateKeyResponse: + boto_request_dict = aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_ReplicateKeyRequest( + input + ) + try: + boto_response_dict = self._impl.replicate_key(**boto_request_dict) + except ClientError as e: + return Wrappers.Result_Failure(_sdk_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_ReplicateKeyResponse( + boto_response_dict + ) + ) + + def RetireGrant(self, input: DafnyRetireGrantRequest) -> None: + boto_request_dict = aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_RetireGrantRequest( + input + ) + try: + boto_response_dict = self._impl.retire_grant(**boto_request_dict) + except ClientError as e: + return Wrappers.Result_Failure(_sdk_error_to_dafny_error(e)) + + return Wrappers.Result_Success(None) + + def RevokeGrant(self, input: DafnyRevokeGrantRequest) -> None: + boto_request_dict = aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_RevokeGrantRequest( + input + ) + try: + boto_response_dict = self._impl.revoke_grant(**boto_request_dict) + except ClientError as e: + return Wrappers.Result_Failure(_sdk_error_to_dafny_error(e)) + + return Wrappers.Result_Success(None) + + def RotateKeyOnDemand( + self, input: DafnyRotateKeyOnDemandRequest + ) -> DafnyRotateKeyOnDemandResponse: + boto_request_dict = aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_RotateKeyOnDemandRequest( + input + ) + try: + boto_response_dict = self._impl.rotate_key_on_demand(**boto_request_dict) + except ClientError as e: + return Wrappers.Result_Failure(_sdk_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_RotateKeyOnDemandResponse( + boto_response_dict + ) + ) + + def ScheduleKeyDeletion( + self, input: DafnyScheduleKeyDeletionRequest + ) -> DafnyScheduleKeyDeletionResponse: + boto_request_dict = aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_ScheduleKeyDeletionRequest( + input + ) + try: + boto_response_dict = self._impl.schedule_key_deletion(**boto_request_dict) + except ClientError as e: + return Wrappers.Result_Failure(_sdk_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_ScheduleKeyDeletionResponse( + boto_response_dict + ) + ) + + def Sign(self, input: DafnySignRequest) -> DafnySignResponse: + boto_request_dict = aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_SignRequest( + input + ) + try: + boto_response_dict = self._impl.sign(**boto_request_dict) + except ClientError as e: + return Wrappers.Result_Failure(_sdk_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_SignResponse( + boto_response_dict + ) + ) + + def TagResource(self, input: DafnyTagResourceRequest) -> None: + boto_request_dict = aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_TagResourceRequest( + input + ) + try: + boto_response_dict = self._impl.tag_resource(**boto_request_dict) + except ClientError as e: + return Wrappers.Result_Failure(_sdk_error_to_dafny_error(e)) + + return Wrappers.Result_Success(None) + + def UntagResource(self, input: DafnyUntagResourceRequest) -> None: + boto_request_dict = aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_UntagResourceRequest( + input + ) + try: + boto_response_dict = self._impl.untag_resource(**boto_request_dict) + except ClientError as e: + return Wrappers.Result_Failure(_sdk_error_to_dafny_error(e)) + + return Wrappers.Result_Success(None) + + def UpdateAlias(self, input: DafnyUpdateAliasRequest) -> None: + boto_request_dict = aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_UpdateAliasRequest( + input + ) + try: + boto_response_dict = self._impl.update_alias(**boto_request_dict) + except ClientError as e: + return Wrappers.Result_Failure(_sdk_error_to_dafny_error(e)) + + return Wrappers.Result_Success(None) + + def UpdateCustomKeyStore( + self, input: DafnyUpdateCustomKeyStoreRequest + ) -> DafnyUpdateCustomKeyStoreResponse: + boto_request_dict = aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_UpdateCustomKeyStoreRequest( + input + ) + try: + boto_response_dict = self._impl.update_custom_key_store(**boto_request_dict) + except ClientError as e: + return Wrappers.Result_Failure(_sdk_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_UpdateCustomKeyStoreResponse( + boto_response_dict + ) + ) + + def UpdateKeyDescription(self, input: DafnyUpdateKeyDescriptionRequest) -> None: + boto_request_dict = aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_UpdateKeyDescriptionRequest( + input + ) + try: + boto_response_dict = self._impl.update_key_description(**boto_request_dict) + except ClientError as e: + return Wrappers.Result_Failure(_sdk_error_to_dafny_error(e)) + + return Wrappers.Result_Success(None) + + def UpdatePrimaryRegion(self, input: DafnyUpdatePrimaryRegionRequest) -> None: + boto_request_dict = aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_UpdatePrimaryRegionRequest( + input + ) + try: + boto_response_dict = self._impl.update_primary_region(**boto_request_dict) + except ClientError as e: + return Wrappers.Result_Failure(_sdk_error_to_dafny_error(e)) + + return Wrappers.Result_Success(None) + + def Verify(self, input: DafnyVerifyRequest) -> DafnyVerifyResponse: + boto_request_dict = aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_VerifyRequest( + input + ) + try: + boto_response_dict = self._impl.verify(**boto_request_dict) + except ClientError as e: + return Wrappers.Result_Failure(_sdk_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_VerifyResponse( + boto_response_dict + ) + ) + + def VerifyMac(self, input: DafnyVerifyMacRequest) -> DafnyVerifyMacResponse: + boto_request_dict = aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_VerifyMacRequest( + input + ) + try: + boto_response_dict = self._impl.verify_mac(**boto_request_dict) + except ClientError as e: + return Wrappers.Result_Failure(_sdk_error_to_dafny_error(e)) + + return Wrappers.Result_Success( + aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_VerifyMacResponse( + boto_response_dict + ) + ) diff --git a/ComAmazonawsKms/runtimes/python/test/__init__.py b/ComAmazonawsKms/runtimes/python/test/__init__.py new file mode 100644 index 000000000..f94fd12a2 --- /dev/null +++ b/ComAmazonawsKms/runtimes/python/test/__init__.py @@ -0,0 +1,2 @@ +# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 diff --git a/ComAmazonawsKms/runtimes/python/test/internaldafny/__init__.py b/ComAmazonawsKms/runtimes/python/test/internaldafny/__init__.py new file mode 100644 index 000000000..f94fd12a2 --- /dev/null +++ b/ComAmazonawsKms/runtimes/python/test/internaldafny/__init__.py @@ -0,0 +1,2 @@ +# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 diff --git a/ComAmazonawsKms/runtimes/python/test/internaldafny/test_dafny_wrapper.py b/ComAmazonawsKms/runtimes/python/test/internaldafny/test_dafny_wrapper.py new file mode 100644 index 000000000..6622cc3c3 --- /dev/null +++ b/ComAmazonawsKms/runtimes/python/test/internaldafny/test_dafny_wrapper.py @@ -0,0 +1,19 @@ +# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 +""" +Wrapper file for executing Dafny tests from pytest. +This allows us to import modules required by Dafny-generated tests +before executing Dafny-generated tests. +pytest will find and execute the `test_dafny` method below, +which will execute the `internaldafny_test_executor.py` file in the `dafny` directory. +""" + +import sys + +internaldafny_dir = '/'.join(__file__.split("/")[:-1]) + +sys.path.append(internaldafny_dir + "/extern") +sys.path.append(internaldafny_dir + "/generated") + +def test_dafny(): + from .generated import __main__ \ No newline at end of file diff --git a/ComAmazonawsKms/runtimes/python/tox.ini b/ComAmazonawsKms/runtimes/python/tox.ini new file mode 100644 index 000000000..5e6bbcb9d --- /dev/null +++ b/ComAmazonawsKms/runtimes/python/tox.ini @@ -0,0 +1,86 @@ +[tox] +isolated_build = True +envlist = + py{311,312}-{dafnytests} + +[testenv:base-command] +commands = poetry run pytest -l {posargs} + +[testenv] +skip_install = True +allowlist_externals = poetry +passenv = AWS_* +commands_pre = + poetry lock + poetry install --with test +commands = + dafnytests: {[testenv:base-command]commands} test/internaldafny -s -v + +# Release tooling +[testenv:build] +basepython = python3 +skip_install = True +allowlist_externals = poetry +commands = + poetry install --no-root --with release + poetry build + +[testenv:release-base] +basepython = python3 +skip_install = True +allowlist_externals = poetry +comands_pre = + poetry install --no-root --with release +passenv = + # Intentionally omit TWINE_REPOSITORY_URL from the passenv list, + # as this overrides other ways of setting the repository and could + # unexpectedly result in releasing to the wrong repo + {[testenv]passenv} \ + TWINE_USERNAME \ + TWINE_PASSWORD +commands = + {[testenv:build]commands} + +[testenv:release-private] +basepython = python3 +skip_install = True +allowlist_externals = poetry +comands_pre = + poetry install --no-root --with release +passenv = + {[testenv:release-base]passenv} \ + TWINE_REPOSITORY_URL +setenv = + # Explicitly set the URL as the env variable value, which will cause us to + # throw an error if the variable is not set. Otherwise, omission of the + # env variable could cause us to unintentionally upload to the wrong repo + TWINE_REPOSITORY_URL = {env:TWINE_REPOSITORY_URL} +commands = + {[testenv:release-base]commands} + # Omitting an explicit repository will cause twine to use the repository + # specified in the environment variable + poetry run twine upload --skip-existing {toxinidir}/dist/* + +[testenv:test-release] +basepython = python3 +skip_install = True +allowlist_externals = poetry +comands_pre = + poetry install --no-root --with release +passenv = + {[testenv:release-base]passenv} +commands = + {[testenv:release-base]commands} + poetry run twine upload --skip-existing --repository testpypi {toxinidir}/dist/* + +[testenv:release] +basepython = python3 +skip_install = True +allowlist_externals = poetry +comands_pre = + poetry install --no-root --with release +passenv = + {[testenv:release-base]passenv} +commands = + {[testenv:release-base]commands} + poetry run twine upload --skip-existing --repository pypi {toxinidir}/dist/* diff --git a/Makefile b/Makefile index 8e3cacb2c..22401b4af 100644 --- a/Makefile +++ b/Makefile @@ -47,7 +47,7 @@ polymorph_code_gen: ) true setup_semantic_release: - npm i --no-save semantic-release @semantic-release/changelog semantic-release-replace-plugin @semantic-release/git + npm i --no-save semantic-release @semantic-release/changelog semantic-release-replace-plugin @semantic-release/git @semantic-release/exec run_semantic_release: npx semantic-release --no-ci diff --git a/README.md b/README.md index 68ecc7192..2352ca8a6 100644 --- a/README.md +++ b/README.md @@ -35,7 +35,7 @@ This repository is a top level repository which houses all source code in order different runtimes. This library is written in Dafny, a formally verifiable programming language that can be compiled into -different runtimes. This library is currently **ONLY** supported in Java and .NET +different runtimes. This library is currently **ONLY** supported in Java, .NET, and Python. ### Optional Prerequisites @@ -45,6 +45,7 @@ You don't need an Amazon Web Services (AWS) account to use the AWS Cryptographic but some APIs require an AWS account, an AWS KMS key, or an Amazon DynamoDB Table. If you are using the AWS Cryptographic Material Providers Library for Java you will need the AWS SDK for Java V2. If you are using the AWS Cryptographic Material Providers Library for .NET you will need the AWS SDK for .NET V3. +If you are using the AWS Cryptographic Material Providers Library for Python you will need boto3. **NOTE**: The `KmsAsyncClient` and `DynamoDBAsyncClient` are not supported, only the synchronous clients. @@ -59,6 +60,7 @@ If you are using the AWS Cryptographic Material Providers Library for .NET you w - Java - .NET +- Python - Dafny ## FAQ diff --git a/SharedMakefileV2.mk b/SharedMakefileV2.mk index 1d38f3c35..38dfa2111 100644 --- a/SharedMakefileV2.mk +++ b/SharedMakefileV2.mk @@ -21,3 +21,5 @@ transpile_test_net: DAFNY_OPTIONS=--allow-warnings --include-test-runner --compi transpile_implementation_java: DAFNY_OPTIONS=--allow-warnings --compile-suffix --legacy-data-constructors --legacy-module-names --allow-external-contracts transpile_test_java: DAFNY_OPTIONS=--allow-warnings --include-test-runner --compile-suffix --legacy-data-constructors --legacy-module-names --allow-external-contracts +transpile_implementation_python: DAFNY_OPTIONS=--allow-warnings --allow-external-contracts +transpile_test_python: DAFNY_OPTIONS=--allow-warnings --include-test-runner --allow-external-contracts diff --git a/StandardLibrary/Makefile b/StandardLibrary/Makefile index a91545fa8..dfcb308be 100644 --- a/StandardLibrary/Makefile +++ b/StandardLibrary/Makefile @@ -17,3 +17,6 @@ transpile_implementation: STD_LIBRARY= transpile_test: STD_LIBRARY= transpile_dependencies: STD_LIBRARY= +# Python + +PYTHON_MODULE_NAME=smithy_dafny_standard_library diff --git a/StandardLibrary/codebuild/release-python/prod-release.yml b/StandardLibrary/codebuild/release-python/prod-release.yml new file mode 100644 index 000000000..b6e498857 --- /dev/null +++ b/StandardLibrary/codebuild/release-python/prod-release.yml @@ -0,0 +1,63 @@ +version: 0.2 + +env: + variables: + BRANCH: "main" + secrets-manager: + TWINE_USERNAME: PyPiAPIToken:username + TWINE_PASSWORD: PyPiAPIToken:password + +phases: + install: + commands: + - pip install "tox < 4.0" + - pip install --upgrade pip + runtime-versions: + python: latest + pre_build: + commands: + # Get Dafny + - export dafnyVersion=$(grep '^dafnyVersion=' project.properties | cut -d '=' -f 2) + - cd .. + - curl https://github.com/dafny-lang/dafny/releases/download/v$dafnyVersion/dafny-$dafnyVersion-x64-ubuntu-20.04.zip -L -o dafny.zip + - unzip -qq dafny.zip && rm dafny.zip + - export PATH="$PWD/dafny:$PATH" + # Switch back to the main directory + - cd aws-cryptographic-material-providers-library + # Assert that project version is the expected released version + - git checkout $COMMIT_ID + - FOUND_VERSION=$(sed -n 's/version = "\(.*\)"/\1/p' StandardLibrary/runtimes/python/pyproject.toml) + - | + if expr ${FOUND_VERSION} != ${VERSION}; then + echo "pyproject.toml version (${FOUND_VERSION}) does not match expected version (${VERSION}), stopping" + exit 1; + fi + - cd StandardLibrary + # Build Dafny test source code + - make transpile_only_test_python + build: + commands: + - cd runtimes/python/ + # Install poetry + # https://python-poetry.org/docs/#installing-manually + - pip install poetry + # Install project dependencies with release dependencies + - poetry install --with release + # Build whl/sdist, upload to PyPI + # TODO: When ready to prod release, uncomment this line + # tox -e release + +batch: + fast-fail: true + build-graph: + - identifier: release_to_prod + env: + image: aws/codebuild/standard:7.0 + - identifier: validate_prod_release + depend-on: + - release_to_prod + buildspec: StandardLibrary/codebuild/release-python/validate.yml + env: + variables: + PIP_INDEX_URL: https://pypi.python.org/simple/ + image: aws/codebuild/standard:7.0 diff --git a/StandardLibrary/codebuild/release-python/test-release.yml b/StandardLibrary/codebuild/release-python/test-release.yml new file mode 100644 index 000000000..75c809a99 --- /dev/null +++ b/StandardLibrary/codebuild/release-python/test-release.yml @@ -0,0 +1,63 @@ +version: 0.2 + +env: + variables: + BRANCH: "main" + secrets-manager: + TWINE_USERNAME: TestPyPiAPIToken:username + TWINE_PASSWORD: TestPyPiAPIToken:password + +phases: + install: + commands: + - pip install "tox < 4.0" + - pip install --upgrade pip + runtime-versions: + python: latest + pre_build: + commands: + # Get Dafny + - export dafnyVersion=$(grep '^dafnyVersion=' project.properties | cut -d '=' -f 2) + - cd .. + - curl https://github.com/dafny-lang/dafny/releases/download/v$dafnyVersion/dafny-$dafnyVersion-x64-ubuntu-20.04.zip -L -o dafny.zip + - unzip -qq dafny.zip && rm dafny.zip + - export PATH="$PWD/dafny:$PATH" + # Switch back to the main directory + - cd aws-cryptographic-material-providers-library + # Assert that project version is the expected released version + - git checkout $COMMIT_ID + - FOUND_VERSION=$(sed -n 's/version = "\(.*\)"/\1/p' StandardLibrary/runtimes/python/pyproject.toml) + - | + if expr ${FOUND_VERSION} != ${VERSION}; then + echo "pyproject.toml version (${FOUND_VERSION}) does not match expected version (${VERSION}), stopping" + exit 1; + fi + - cd StandardLibrary + # Build Dafny test source code + - make transpile_only_test_python + build: + commands: + - cd runtimes/python/ + # Install poetry + # https://python-poetry.org/docs/#installing-manually + - pip install poetry + # Install project dependencies with release dependencies + - poetry install --with release + # Build whl/sdist, upload to test PyPI + - tox -e test-release + +batch: + fast-fail: true + build-graph: + - identifier: release_to_staging + env: + image: aws/codebuild/standard:7.0 + - identifier: validate_staging_release + depend-on: + - release_to_staging + buildspec: StandardLibrary/codebuild/release-python/validate.yml + env: + variables: + PIP_INDEX_URL: https://test.pypi.org/simple/ + PIP_EXTRA_INDEX_URL: https://pypi.python.org/simple/ + image: aws/codebuild/standard:7.0 diff --git a/StandardLibrary/codebuild/release-python/validate.yml b/StandardLibrary/codebuild/release-python/validate.yml new file mode 100644 index 000000000..330c95f8c --- /dev/null +++ b/StandardLibrary/codebuild/release-python/validate.yml @@ -0,0 +1,39 @@ +version: 0.2 + +# Validate that the released artifact is usable +# by installing it from PyPI +# then running tests from source against the published artifact. + +phases: + install: + commands: + - pip install "tox < 4.0" + runtime-versions: + python: latest + pre_build: + commands: + # Get Dafny + - export dafnyVersion=$(grep '^dafnyVersion=' project.properties | cut -d '=' -f 2) + - cd .. + - curl https://github.com/dafny-lang/dafny/releases/download/v$dafnyVersion/dafny-$dafnyVersion-x64-ubuntu-20.04.zip -L -o dafny.zip + - unzip -qq dafny.zip && rm dafny.zip + - export PATH="$PWD/dafny:$PATH" + # Switch back to the main directory + - cd aws-cryptographic-material-providers-library + # Install test dependencies + - pyenv install --skip-existing 3.11 + - pyenv local 3.11 + - pip install "tox < 4.0" + - pip install pytest + # Install the published artifact from PyPI. + # The tests will use the installed package, not the local code. + # The actual test code must be from local, since we don't publish tests. + - pip install aws-cryptography-internal-standard-library==$VERSION + build: + commands: + - NUM_RETRIES=3 + - cd StandardLibrary + # Transpile code (for tests) + - make transpile_python + - cd runtimes/python + - python -m pytest test/ -s -v diff --git a/StandardLibrary/runtimes/python/.gitignore b/StandardLibrary/runtimes/python/.gitignore new file mode 100644 index 000000000..ebca80af6 --- /dev/null +++ b/StandardLibrary/runtimes/python/.gitignore @@ -0,0 +1,16 @@ +# Python build artifacts +__pycache__ +**/__pycache__ +*.pyc +**.egg-info/ +build +poetry.lock +**/poetry.lock +dist + +# Dafny-generated Python +**/internaldafny/generated/*.py + +# Python test artifacts +.tox +.pytest_cache diff --git a/StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/MANIFEST.in b/StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/MANIFEST.in new file mode 100644 index 000000000..50093a0b7 --- /dev/null +++ b/StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/MANIFEST.in @@ -0,0 +1 @@ +include smithy_python/py.typed diff --git a/StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/NOTICE b/StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/NOTICE new file mode 100644 index 000000000..616fc5889 --- /dev/null +++ b/StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/NOTICE @@ -0,0 +1 @@ +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. diff --git a/StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/README.md b/StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/README.md new file mode 100644 index 000000000..80737e898 --- /dev/null +++ b/StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/README.md @@ -0,0 +1,4 @@ +# smithy-python + +This is the core package that provides interfaces for both client and server +tooling generated by Smithy. diff --git a/StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/pyproject.toml b/StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/pyproject.toml new file mode 100644 index 000000000..6f61403ec --- /dev/null +++ b/StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/pyproject.toml @@ -0,0 +1,50 @@ +[build-system] +requires = ["setuptools", "setuptools-scm", "wheel"] +build-backend = "setuptools.build_meta" + +[project] +name = "smithy_python" +version = "0.0.1" +description = "Core libraries for Smithy defined services in Python" +readme = "README.md" +authors = [{name = "Amazon Web Services"}] +keywords = ["python", "sdk", "amazon", "smithy", "codegen"] +requires-python = ">=3.11" +license = {text = "Apache License 2.0"} +classifiers = [ + "Development Status :: 2 - Pre-Alpha", + "Intended Audience :: Developers", + "Intended Audience :: System Administrators", + "Natural Language :: English", + "License :: OSI Approved :: Apache Software License", + "Operating System :: OS Independent", + "Programming Language :: Python", + "Programming Language :: Python :: 3 :: Only", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: Implementation :: CPython", + "Topic :: Software Development :: Libraries" +] +dependencies = [ + "awscrt>=0.15,<1.0", + "aiohttp>=3.9.0" +] + +[project.urls] +source = "https://github.com/awslabs/smithy-python/tree/develop/python-packages/smithy-python" +changelog = "https://github.com/awslabs/smithy-python/blob/develop/CHANGES.md" + +[tool.setuptools] +license-files = ["NOTICE"] +include-package-data = true + +[tool.setuptools.packages.find] +exclude=["tests*", "codegen", "designs"] + +[tool.isort] +profile = "black" +honor_noqa = true +src_paths = ["smithy_python", "tests"] + +[tool.pytest.ini_options] +asyncio_mode = "auto" diff --git a/StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/requirements-dev.txt b/StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/requirements-dev.txt new file mode 100644 index 000000000..ff6665bce --- /dev/null +++ b/StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/requirements-dev.txt @@ -0,0 +1,6 @@ +black==21.11b1 +flake8<6.1 +mypy==1.0.0 +pytest<7.3 +pytest-asyncio<0.21.0 +pytest-cov<3.1 diff --git a/StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/requirements.txt b/StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/requirements.txt new file mode 100644 index 000000000..a65376bc3 --- /dev/null +++ b/StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/requirements.txt @@ -0,0 +1,2 @@ +awscrt>=0.15,<1.0 +aiohttp>=3.9.0 diff --git a/StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/smithy_python/__init__.py b/StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/smithy_python/__init__.py new file mode 100644 index 000000000..9a8a05063 --- /dev/null +++ b/StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/smithy_python/__init__.py @@ -0,0 +1,15 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). You +# may not use this file except in compliance with the License. A copy of +# the License is located at +# +# http://aws.amazon.com/apache2.0/ +# +# or in the "license" file accompanying this file. This file is +# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF +# ANY KIND, either express or implied. See the License for the specific +# language governing permissions and limitations under the License. + + +__version__ = "0.0.1" diff --git a/StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/smithy_python/_private/__init__.py b/StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/smithy_python/_private/__init__.py new file mode 100644 index 000000000..124e7f751 --- /dev/null +++ b/StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/smithy_python/_private/__init__.py @@ -0,0 +1,341 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). You +# may not use this file except in compliance with the License. A copy of +# the License is located at +# +# http://aws.amazon.com/apache2.0/ +# +# or in the "license" file accompanying this file. This file is +# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF +# ANY KIND, either express or implied. See the License for the specific +# language governing permissions and limitations under the License. +from collections import Counter, OrderedDict +from collections.abc import Iterable, Iterator +from dataclasses import dataclass +from enum import Enum +from functools import cached_property +from urllib.parse import urlunparse + +from .. import interfaces +from ..exceptions import SmithyHTTPException +from ..interfaces import FieldPosition as FieldPosition # re-export +from . import abnf + + +class HostType(Enum): + """Enumeration of possible host types.""" + + IPv6 = "IPv6" + """Host is an IPv6 address.""" + + IPv4 = "IPv4" + """Host is an IPv4 address.""" + + DOMAIN = "DOMAIN" + """Host type is a domain name.""" + + UNKNOWN = "UNKNOWN" + """Host type is unknown.""" + + +@dataclass(kw_only=True, frozen=True) +class URI(interfaces.URI): + """Universal Resource Identifier, target location for a :py:class:`HTTPRequest`.""" + + scheme: str = "https" + """For example ``http`` or ``https``.""" + + username: str | None = None + """Username part of the userinfo URI component.""" + + password: str | None = None + """Password part of the userinfo URI component.""" + + host: str + """The hostname, for example ``amazonaws.com``.""" + + port: int | None = None + """An explicit port number.""" + + path: str | None = None + """Path component of the URI.""" + + query: str | None = None + """Query component of the URI as string.""" + + fragment: str | None = None + """Part of the URI specification, but may not be transmitted by a client.""" + + def __post_init__(self) -> None: + """Validate host component.""" + if not abnf.HOST_MATCHER.match(self.host) and not abnf.IPv6_MATCHER.match( + f"[{self.host}]" + ): + raise SmithyHTTPException(f"Invalid host: {self.host}") + + @cached_property + def netloc(self) -> str: + """Construct netloc string in format ``{username}:{password}@{host}:{port}`` + + ``username``, ``password``, and ``port`` are only included if set. ``password`` + is ignored, unless ``username`` is also set. Add square brackets around the host + if it is a valid IPv6 endpoint URI per :rfc:`3986#section-3.2.2`. + """ + if self.username is not None: + password = "" if self.password is None else f":{self.password}" + userinfo = f"{self.username}{password}@" + else: + userinfo = "" + + if self.port is not None: + port = f":{self.port}" + else: + port = "" + + if self.host_type == HostType.IPv6: + host = f"[{self.host}]" + else: + host = self.host + + return f"{userinfo}{host}{port}" + + @cached_property + def host_type(self) -> HostType: + """Return the type of host.""" + if abnf.IPv6_MATCHER.match(f"[{self.host}]"): + return HostType.IPv6 + if abnf.IPv4_MATCHER.match(self.host): + return HostType.IPv4 + if abnf.HOST_MATCHER.match(self.host): + return HostType.DOMAIN + return HostType.UNKNOWN + + def build(self) -> str: + """Construct URI string representation. + + Validate host. Returns a string of the form + ``{scheme}://{username}:{password}@{host}:{port}{path}?{query}#{fragment}`` + """ + components = ( + self.scheme, + self.netloc, + self.path or "", + "", # params + self.query, + self.fragment, + ) + return urlunparse(components) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, URI): + return False + return ( + self.scheme == other.scheme + and self.host == other.host + and self.port == other.port + and self.path == other.path + and self.query == other.query + and self.username == other.username + and self.password == other.password + and self.fragment == other.fragment + ) + + +class Field(interfaces.Field): + """A name-value pair representing a single field in an HTTP Request or Response. + + The kind will dictate metadata placement within an HTTP message. + + All field names are case insensitive and case-variance must be treated as + equivalent. Names may be normalized but should be preserved for accuracy during + transmission. + """ + + def __init__( + self, + *, + name: str, + values: Iterable[str] | None = None, + kind: FieldPosition = FieldPosition.HEADER, + ): + self.name = name + self.values: list[str] = [val for val in values] if values is not None else [] + self.kind = kind + + def add(self, value: str) -> None: + """Append a value to a field.""" + self.values.append(value) + + def set(self, values: list[str]) -> None: + """Overwrite existing field values.""" + self.values = values + + def remove(self, value: str) -> None: + """Remove all matching entries from list.""" + try: + while True: + self.values.remove(value) + except ValueError: + return + + def as_string(self) -> str: + """Get comma-delimited string of all values. + + If the ``Field`` has zero values, the empty string is returned. If the ``Field`` + has exactly one value, the value is returned unmodified. + + For ``Field``s with more than one value, the values are joined by a comma and a + space. For such multi-valued ``Field``s, any values that already contain + commas or double quotes will be surrounded by double quotes. Within any values + that get quoted, pre-existing double quotes and backslashes are escaped with a + backslash. + """ + value_count = len(self.values) + if value_count == 0: + return "" + if value_count == 1: + return self.values[0] + return ", ".join(quote_and_escape_field_value(val) for val in self.values) + + def as_tuples(self) -> list[tuple[str, str]]: + """Get list of ``name``, ``value`` tuples where each tuple represents one + value.""" + return [(self.name, val) for val in self.values] + + def __eq__(self, other: object) -> bool: + """Name, values, and kind must match. + + Values order must match. + """ + if not isinstance(other, Field): + return False + return ( + self.name == other.name + and self.kind is other.kind + and self.values == other.values + ) + + def __repr__(self) -> str: + return f"Field(name={self.name!r}, value={self.values!r}, kind={self.kind!r})" + + +class Fields(interfaces.Fields): + def __init__( + self, + initial: Iterable[interfaces.Field] | None = None, + *, + encoding: str = "utf-8", + ): + """Collection of header and trailer entries mapped by name. + + :param initial: Initial list of ``Field`` objects. ``Field``s can alse be added + with :func:`set_field` and later removed with :func:`remove_field`. + :param encoding: The string encoding to be used when converting the ``Field`` + name and value from ``str`` to ``bytes`` for transmission. + """ + init_fields = [fld for fld in initial] if initial is not None else [] + init_field_names = [self._normalize_field_name(fld.name) for fld in init_fields] + fname_counter = Counter(init_field_names) + repeated_names_exist = ( + len(init_fields) > 0 and fname_counter.most_common(1)[0][1] > 1 + ) + if repeated_names_exist: + non_unique_names = [name for name, num in fname_counter.items() if num > 1] + raise ValueError( + "Field names of the initial list of fields must be unique. The " + "following normalized field names appear more than once: " + f"{', '.join(non_unique_names)}." + ) + init_tuples = zip(init_field_names, init_fields) + self.entries: OrderedDict[str, interfaces.Field] = OrderedDict(init_tuples) + self.encoding: str = encoding + + def set_field(self, field: interfaces.Field) -> None: + """Set entry for a Field name.""" + normalized_name = self._normalize_field_name(field.name) + self.entries[normalized_name] = field + + def get_field(self, name: str) -> interfaces.Field: + """Retrieve Field entry.""" + normalized_name = self._normalize_field_name(name) + return self.entries[normalized_name] + + def remove_field(self, name: str) -> None: + """Delete entry from collection.""" + normalized_name = self._normalize_field_name(name) + del self.entries[normalized_name] + + def get_by_type(self, kind: FieldPosition) -> list[interfaces.Field]: + """Helper function for retrieving specific types of fields. + + Used to grab all headers or all trailers. + """ + return [entry for entry in self.entries.values() if entry.kind is kind] + + def extend(self, other: interfaces.Fields) -> None: + """Merges ``entries`` of ``other`` into the current ``entries``. + + For every `Field` in the ``entries`` of ``other``: If the normalized name + already exists in the current ``entries``, the values from ``other`` are + appended. Otherwise, the ``Field`` is added to the list of ``entries``. + """ + for other_field in other: + try: + cur_field = self.get_field(name=other_field.name) + for other_value in other_field.values: + cur_field.add(other_value) + except KeyError: + self.set_field(other_field) + + def _normalize_field_name(self, name: str) -> str: + """Normalize field names. + + For use as key in ``entries``. + """ + return name.lower() + + def __eq__(self, other: object) -> bool: + """Encoding must match. + + Entries must match in values and order. + """ + if not isinstance(other, Fields): + return False + return self.encoding == other.encoding and self.entries == other.entries + + def __iter__(self) -> Iterator[interfaces.Field]: + yield from self.entries.values() + + +def quote_and_escape_field_value(value: str) -> str: + """Escapes and quotes a single :class:`Field` value if necessary. + + See :func:`Field.as_string` for quoting and escaping logic. + """ + chars_to_quote = (",", '"') + if any(char in chars_to_quote for char in value): + escaped = value.replace("\\", "\\\\").replace('"', '\\"') + return f'"{escaped}"' + else: + return value + + +def tuples_to_fields( + tuples: Iterable[tuple[str, str]], *, kind: FieldPosition | None = None +) -> Fields: + """Convert ``name``, ``value`` tuples to ``Fields`` object. Each tuple represents + one Field value. + + :param kind: The Field kind to define for all tuples. + """ + fields = Fields() + for name, value in tuples: + try: + fields.get_field(name).add(value) + except KeyError: + fields.set_field( + Field(name=name, values=[value], kind=kind or FieldPosition.HEADER) + ) + + return fields diff --git a/StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/smithy_python/_private/abnf.py b/StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/smithy_python/_private/abnf.py new file mode 100644 index 000000000..d2188e13d --- /dev/null +++ b/StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/smithy_python/_private/abnf.py @@ -0,0 +1,120 @@ +# Copyright 2014 Ian Cordasco, Rackspace + +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at + +# http://www.apache.org/licenses/LICENSE-2.0 + +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Module vended from rfc3986 ``abnf_rexexp.py`` and ``misc.py``. + +https://github.com/python-hyper/rfc3986/blob/main/src/rfc3986/abnf_regexp.py +https://github.com/python-hyper/rfc3986/blob/main/src/rfc3986/misc.py +""" +import re + +# ######################### +# Start abnf_regexp.py +# ######################### + +# Escape the '*' for use in regular expressions +SUB_DELIMITERS_RE = r"!$&'()\*+,;=" +# We need to escape the '-' in this case: +UNRESERVED_RE = r"A-Za-z0-9._~\-" + +# Percent encoded character values +PERCENT_ENCODED = PCT_ENCODED = "%[A-Fa-f0-9]{2}" +PCHAR = "([" + UNRESERVED_RE + SUB_DELIMITERS_RE + ":@]|%s)" % PCT_ENCODED + +# ######################### +# Authority Matcher Section +# ######################### + +# Host patterns, see: http://tools.ietf.org/html/rfc3986#section-3.2.2 +# The pattern for a regular name, e.g., www.google.com, api.github.com +REGULAR_NAME_RE = REG_NAME = "((?:{}|[{}])*)".format( + "%[0-9A-Fa-f]{2}", SUB_DELIMITERS_RE + UNRESERVED_RE +) +# The pattern for an IPv4 address, e.g., 192.168.255.255, 127.0.0.1, +IPv4_RE = r"([0-9]{1,3}\.){3}[0-9]{1,3}" +# Hexadecimal characters used in each piece of an IPv6 address +HEXDIG_RE = "[0-9A-Fa-f]{1,4}" +# Least-significant 32 bits of an IPv6 address +LS32_RE = "({hex}:{hex}|{ipv4})".format(hex=HEXDIG_RE, ipv4=IPv4_RE) +# Substitutions into the following patterns for IPv6 patterns defined +# http://tools.ietf.org/html/rfc3986#page-20 +_subs = {"hex": HEXDIG_RE, "ls32": LS32_RE} + +# Below: h16 = hexdig, see: https://tools.ietf.org/html/rfc5234 for details +# about ABNF (Augmented Backus-Naur Form) use in the comments +variations = [ + # 6( h16 ":" ) ls32 + "(%(hex)s:){6}%(ls32)s" % _subs, + # "::" 5( h16 ":" ) ls32 + "::(%(hex)s:){5}%(ls32)s" % _subs, + # [ h16 ] "::" 4( h16 ":" ) ls32 + "(%(hex)s)?::(%(hex)s:){4}%(ls32)s" % _subs, + # [ *1( h16 ":" ) h16 ] "::" 3( h16 ":" ) ls32 + "((%(hex)s:)?%(hex)s)?::(%(hex)s:){3}%(ls32)s" % _subs, + # [ *2( h16 ":" ) h16 ] "::" 2( h16 ":" ) ls32 + "((%(hex)s:){0,2}%(hex)s)?::(%(hex)s:){2}%(ls32)s" % _subs, + # [ *3( h16 ":" ) h16 ] "::" h16 ":" ls32 + "((%(hex)s:){0,3}%(hex)s)?::%(hex)s:%(ls32)s" % _subs, + # [ *4( h16 ":" ) h16 ] "::" ls32 + "((%(hex)s:){0,4}%(hex)s)?::%(ls32)s" % _subs, + # [ *5( h16 ":" ) h16 ] "::" h16 + "((%(hex)s:){0,5}%(hex)s)?::%(hex)s" % _subs, + # [ *6( h16 ":" ) h16 ] "::" + "((%(hex)s:){0,6}%(hex)s)?::" % _subs, +] + +IPv6_RE = "(({})|({})|({})|({})|({})|({})|({})|({})|({}))".format(*variations) + +IPv_FUTURE_RE = r"v[0-9A-Fa-f]+\.[%s]+" % (UNRESERVED_RE + SUB_DELIMITERS_RE + ":") + +# RFC 6874 Zone ID ABNF +ZONE_ID = "(?:[" + UNRESERVED_RE + "]|" + PCT_ENCODED + ")+" + +IPv6_ADDRZ_RFC4007_RE = IPv6_RE + "(?:(?:%25|%)" + ZONE_ID + ")?" +IPv6_ADDRZ_RE = IPv6_RE + "(?:%25" + ZONE_ID + ")?" + +IP_LITERAL_RE = r"\[({}|{})\]".format( + IPv6_ADDRZ_RFC4007_RE, + IPv_FUTURE_RE, +) + +# Pattern for matching the host piece of the authority +HOST_RE = HOST_PATTERN = "({}|{}|{})".format( + REG_NAME, + IPv4_RE, + IP_LITERAL_RE, +) + +# ######################### +# End abnf_regexp.py +# ######################### + + +# ######################### +# Start misc.py +# ######################### + +# These are enumerated for the named tuple used as a superclass of +# URIReference + +HOST_MATCHER = re.compile("^" + HOST_RE + "$") +IPv4_MATCHER = re.compile("^" + IPv4_RE + "$") +IPv6_MATCHER = re.compile(r"^\[" + IPv6_ADDRZ_RFC4007_RE + r"\]$") + +# Used by host validator +IPv6_NO_RFC4007_MATCHER = re.compile(r"^\[%s\]$" % (IPv6_ADDRZ_RE)) + +# ######################### +# End misc.py +# ######################### diff --git a/StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/smithy_python/_private/api_key_auth.py b/StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/smithy_python/_private/api_key_auth.py new file mode 100644 index 000000000..cb95b1701 --- /dev/null +++ b/StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/smithy_python/_private/api_key_auth.py @@ -0,0 +1,145 @@ +from dataclasses import dataclass +from enum import Enum +from typing import NotRequired, Protocol, TypedDict + +from ..exceptions import SmithyIdentityException +from ..interfaces.auth import HTTPAuthScheme, HTTPSigner +from ..interfaces.http import HTTPRequest +from ..interfaces.identity import IdentityProperties, IdentityResolver +from . import URI, Field +from .identity import Identity + + +class ApiKeyIdentity(Identity): + """The identity for auth that uses an api key.""" + + def __init__(self, *, api_key: str) -> None: + super().__init__(expiration=None) + self.api_key = api_key + + +class ApiKeyIdentityResolver(IdentityResolver[ApiKeyIdentity, IdentityProperties]): + """Loads the api key identity from the configuration.""" + + def __init__(self, *, api_key: str | ApiKeyIdentity) -> None: + """ + :param api_key: The API key to authenticate with. + """ + match api_key: + case str(): + self._identity = ApiKeyIdentity(api_key=api_key) + case ApiKeyIdentity(): + self._identity = api_key + + async def get_identity( + self, *, identity_properties: IdentityProperties + ) -> ApiKeyIdentity: + """Load the user's api key identity from this resolver. + + :param identity_properties: Properties used to help determine the + identity to return. + :returns: The api key identity. + """ + return self._identity + + +class ApiKeyLocation(Enum): + """The locations that the api key could be placed in the signed request.""" + + HEADER = "header" + QUERY = "query" + + +class ApiKeySigningProperties(TypedDict): + """The properties needed to sign a request with api key auth. + + seealso:: The `Smithy API Key auth trait docs `_ + , which have more details on these properties, including examples. + """ + + name: str + """The name of the HTTP header or query string parameter containing the key.""" + + scheme: NotRequired[str] + """The :rfc:`9110#section-11.4` scheme to prefix a header value with.""" + + location: ApiKeyLocation + """Where the key is serialized.""" + + +class ApiKeyConfig(Protocol): + api_key_identity_resolver: IdentityResolver[ + ApiKeyIdentity, IdentityProperties + ] | None + + +@dataclass(init=False) +class ApiKeyAuthScheme( + HTTPAuthScheme[ + ApiKeyIdentity, ApiKeyConfig, IdentityProperties, ApiKeySigningProperties + ] +): + """An auth scheme containing necessary data and tools for api key auth.""" + + scheme_id: str + signer: HTTPSigner[ApiKeyIdentity, ApiKeySigningProperties] + + def __init__( + self, + *, + signer: HTTPSigner[ApiKeyIdentity, ApiKeySigningProperties] | None = None, + ) -> None: + """Constructor. + + :param identity_resolver: The identity resolver to extract the api key identity. + :param signer: The signer used to sign the request. + """ + self.scheme_id = "smithy.api#httpApiKeyAuth" + self.signer = signer or ApiKeySigner() + + def identity_resolver( + self, *, config: ApiKeyConfig + ) -> IdentityResolver[ApiKeyIdentity, IdentityProperties]: + if not config.api_key_identity_resolver: + raise SmithyIdentityException( + "Attempted to use API key auth, but api_key_identity_resolver was not" + "set on the config." + ) + return config.api_key_identity_resolver + + +class ApiKeySigner(HTTPSigner[ApiKeyIdentity, ApiKeySigningProperties]): + """A signer that signs http requests with an api key.""" + + async def sign( + self, + *, + http_request: HTTPRequest, + identity: ApiKeyIdentity, + signing_properties: ApiKeySigningProperties, + ) -> HTTPRequest: + match signing_properties["location"]: + case ApiKeyLocation.QUERY: + query = http_request.destination.query or "" + if query: + query += "&" + query += f"{signing_properties['name']}={identity.api_key}" + http_request.destination = URI( + scheme=http_request.destination.scheme, + username=http_request.destination.username, + password=http_request.destination.password, + host=http_request.destination.host, + port=http_request.destination.port, + path=http_request.destination.password, + query=query, + fragment=http_request.destination.fragment, + ) + case ApiKeyLocation.HEADER: + value = identity.api_key + if "scheme" in signing_properties and signing_properties["scheme"]: + value = f"{signing_properties['scheme']} {value}" + http_request.fields.set_field( + Field(name=signing_properties["name"], values=[value]) + ) + + return http_request diff --git a/StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/smithy_python/_private/auth.py b/StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/smithy_python/_private/auth.py new file mode 100644 index 000000000..e8bf986c3 --- /dev/null +++ b/StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/smithy_python/_private/auth.py @@ -0,0 +1,42 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). You +# may not use this file except in compliance with the License. A copy of +# the License is located at +# +# http://aws.amazon.com/apache2.0/ +# +# or in the "license" file accompanying this file. This file is +# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF +# ANY KIND, either express or implied. See the License for the specific +# language governing permissions and limitations under the License. + +from ..interfaces.auth import HTTPSigner as HTTPSignerInterface +from ..interfaces.auth import SigningPropertiesType_contra +from ..interfaces.http import HTTPRequest as HTTPRequestInterface +from ..interfaces.identity import IdentityType_contra +from .http import HTTPRequest + + +class HTTPSigner( + HTTPSignerInterface[IdentityType_contra, SigningPropertiesType_contra] +): + """An interface for generating a signed HTTP request.""" + + async def sign( + self, + *, + http_request: HTTPRequestInterface, + identity: IdentityType_contra, + signing_properties: SigningPropertiesType_contra, + ) -> HTTPRequest: + """Generate a new signed HTTPRequest based on the one provided. + + :param http_request: The HTTP request to sign. + + :param identity: The signing identity. + + :param signing_properties: Additional properties loaded to modify the + signing process. + """ + raise NotImplementedError() diff --git a/StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/smithy_python/_private/http/__init__.py b/StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/smithy_python/_private/http/__init__.py new file mode 100644 index 000000000..c25471cd0 --- /dev/null +++ b/StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/smithy_python/_private/http/__init__.py @@ -0,0 +1,116 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). You +# may not use this file except in compliance with the License. A copy of +# the License is located at +# +# http://aws.amazon.com/apache2.0/ +# +# or in the "license" file accompanying this file. This file is +# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF +# ANY KIND, either express or implied. See the License for the specific +# language governing permissions and limitations under the License. + +# TODO: move all of this out of _private + +from collections.abc import AsyncIterable +from dataclasses import dataclass, field +from urllib.parse import urlparse + +from ... import interfaces +from ...interfaces import http as http_interface +from .. import URI, Fields + + +@dataclass(kw_only=True) +class HTTPRequest(http_interface.HTTPRequest): + """HTTP primitives for an Exchange to construct a version agnostic HTTP message.""" + + destination: interfaces.URI + body: AsyncIterable[bytes] + method: str + fields: interfaces.Fields + + async def consume_body(self) -> bytes: + """Iterate over request body and return as bytes.""" + body = b"" + async for chunk in self.body: + body += chunk + return body + + +# HTTPResponse implements interfaces.http.HTTPResponse but cannot be explicitly +# annotated to reflect this because doing so causes Python to raise an AttributeError. +# See https://github.com/python/typing/discussions/903#discussioncomment-4866851 for +# details. +@dataclass(kw_only=True) +class HTTPResponse: + """Basic implementation of :py:class:`...interfaces.http.HTTPResponse`. + + Implementations of :py:class:`...interfaces.http.HTTPClient` may return instances of + this class or of custom response implementations. + """ + + body: AsyncIterable[bytes] + """The response payload as iterable of chunks of bytes.""" + + status: int + """The 3 digit response status code (1xx, 2xx, 3xx, 4xx, 5xx).""" + + fields: interfaces.Fields + """HTTP header and trailer fields.""" + + reason: str | None = None + """Optional string provided by the server explaining the status.""" + + async def consume_body(self) -> bytes: + """Iterate over response body and return as bytes.""" + body = b"" + async for chunk in self.body: + body += chunk + return body + + +@dataclass +class Endpoint(http_interface.Endpoint): + uri: interfaces.URI + headers: interfaces.Fields = field(default_factory=Fields) + + +@dataclass +class StaticEndpointParams: + """Static endpoint params. + + :param uri: A static URI to route requests to. + """ + + uri: str | interfaces.URI + + +class StaticEndpointResolver(http_interface.EndpointResolver[StaticEndpointParams]): + """A basic endpoint resolver that forwards a static URI.""" + + async def resolve_endpoint(self, params: StaticEndpointParams) -> Endpoint: + # If it's not a string, it's already a parsed URI so just pass it along. + if not isinstance(params.uri, str): + return Endpoint(uri=params.uri) + + # Does crt have implementations of these parsing methods? Using the standard + # library is probably fine. + parsed = urlparse(params.uri) + + # This will end up getting wrapped in the client. + if parsed.hostname is None: + raise ValueError( + f"Unable to parse hostname from provided URI: {params.uri}" + ) + + return Endpoint( + uri=URI( + host=parsed.hostname, + path=parsed.path, + scheme=parsed.scheme, + query=parsed.query, + port=parsed.port, + ) + ) diff --git a/StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/smithy_python/_private/http/aiohttp_client.py b/StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/smithy_python/_private/http/aiohttp_client.py new file mode 100644 index 000000000..a24d32da7 --- /dev/null +++ b/StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/smithy_python/_private/http/aiohttp_client.py @@ -0,0 +1,113 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). You +# may not use this file except in compliance with the License. A copy of +# the License is located at +# +# http://aws.amazon.com/apache2.0/ +# +# or in the "license" file accompanying this file. This file is +# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF +# ANY KIND, either express or implied. See the License for the specific +# language governing permissions and limitations under the License. +from copy import copy, deepcopy +from itertools import chain +from typing import Any +from urllib.parse import parse_qs, urlunparse + +import aiohttp + +from ... import interfaces +from ...async_utils import async_list +from .. import Field, FieldPosition, Fields +from . import HTTPResponse + + +class AIOHTTPClientConfig(interfaces.http.HTTPClientConfiguration): + pass + + +class AIOHTTPClient(interfaces.http.HTTPClient): + """Implementation of :py:class:`...interfaces.http.HTTPClient` using aiohttp.""" + + def __init__( + self, + *, + client_config: AIOHTTPClientConfig | None = None, + _session: aiohttp.ClientSession | None = None, + ) -> None: + """ + :param client_config: Configuration that applies to all requests made with this + client. + """ + self._config = client_config or AIOHTTPClientConfig() + self._session = _session or aiohttp.ClientSession() + + async def send( + self, + *, + request: interfaces.http.HTTPRequest, + request_config: interfaces.http.HTTPRequestConfiguration | None = None, + ) -> HTTPResponse: + """Send HTTP request using aiohttp client. + + :param request: The request including destination URI, fields, payload. + :param request_config: Configuration specific to this request. + """ + request_config = ( + interfaces.http.HTTPRequestConfiguration() # todo: should be an implementation + if request_config is None + else request_config + ) + + headers_list = list( + chain.from_iterable( + fld.as_tuples() + for fld in request.fields.get_by_type(FieldPosition.HEADER) + ) + ) + + async with self._session.request( + method=request.method, + url=self._serialize_uri_without_query(request.destination), + params=parse_qs(request.destination.query), + headers=headers_list, + data=request.body, + ) as resp: + return await self._marshal_response(resp) + + def _serialize_uri_without_query(self, uri: interfaces.URI) -> str: + """Serialize all parts of the URI up to and including the path.""" + components = (uri.scheme, uri.host, uri.path or "", "", "", "") + return urlunparse(components) + + async def _marshal_response( + self, aiohttp_resp: aiohttp.ClientResponse + ) -> HTTPResponse: + """Convert a ``aiohttp.ClientResponse`` to a + ``smithy_python.http.HTTPResponse``""" + headers = Fields() + for header_name, header_val in aiohttp_resp.headers.items(): + try: + headers.get_field(header_name).add(header_val) + except KeyError: + headers.set_field( + Field( + name=header_name, + values=[header_val], + kind=FieldPosition.HEADER, + ) + ) + + return HTTPResponse( + status=aiohttp_resp.status, + fields=headers, + body=async_list([await aiohttp_resp.read()]), + reason=aiohttp_resp.reason, + ) + + def __deepcopy__(self, memo: Any) -> "AIOHTTPClient": + return AIOHTTPClient( + client_config=deepcopy(self._config), + _session=copy(self._session), + ) diff --git a/StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/smithy_python/_private/http/crt.py b/StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/smithy_python/_private/http/crt.py new file mode 100644 index 000000000..ccc58027d --- /dev/null +++ b/StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/smithy_python/_private/http/crt.py @@ -0,0 +1,296 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). You +# may not use this file except in compliance with the License. A copy of +# the License is located at +# +# http://aws.amazon.com/apache2.0/ +# +# or in the "license" file accompanying this file. This file is +# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF +# ANY KIND, either express or implied. See the License for the specific +# language governing permissions and limitations under the License. + + +import asyncio +from collections.abc import AsyncIterable +from concurrent.futures import Future +from io import BytesIO +from threading import Lock +from typing import Any, AsyncGenerator, Awaitable + +from awscrt import http as crt_http +from awscrt import io as crt_io + +from ... import interfaces +from ...exceptions import SmithyHTTPException +from .. import Field, FieldPosition, Fields + + +class _AWSCRTEventLoop: + def __init__(self) -> None: + self.bootstrap = self._initialize_default_loop() + + def _initialize_default_loop(self) -> crt_io.ClientBootstrap: + event_loop_group = crt_io.EventLoopGroup(1) + host_resolver = crt_io.DefaultHostResolver(event_loop_group) + return crt_io.ClientBootstrap(event_loop_group, host_resolver) + + +class AWSCRTHTTPResponse(interfaces.http.HTTPResponse): + def __init__(self) -> None: + self._stream: crt_http.HttpClientStream | None = None + self._status_code_future: Future[int] = Future() + self._headers_future: Future[Fields] = Future() + self._chunk_futures: list[Future[bytes]] = [] + self._received_chunks: list[bytes] = [] + self._chunk_lock: Lock = Lock() + + def _set_stream(self, stream: crt_http.HttpClientStream) -> None: + if self._stream is not None: + raise SmithyHTTPException("Stream already set on AWSCRTHTTPResponse object") + self._stream = stream + self._stream.completion_future.add_done_callback(self._on_complete) + self._stream.activate() + + def _on_headers( + self, status_code: int, headers: list[tuple[str, str]], **kwargs: Any + ) -> None: # pragma: crt-callback + fields = Fields() + for header_name, header_val in headers: + try: + fields.get_field(header_name).add(header_val) + except KeyError: + fields.set_field( + Field( + name=header_name, + values=[header_val], + kind=FieldPosition.HEADER, + ) + ) + self._status_code_future.set_result(status_code) + self._headers_future.set_result(fields) + + def _on_body(self, chunk: bytes, **kwargs: Any) -> None: # pragma: crt-callback + with self._chunk_lock: + # TODO: update back pressure window once CRT supports it + if self._chunk_futures: + future = self._chunk_futures.pop(0) + future.set_result(chunk) + else: + self._received_chunks.append(chunk) + + def _get_chunk_future(self) -> Future[bytes]: + if self._stream is None: + raise SmithyHTTPException("Stream not set") + with self._chunk_lock: + future: Future[bytes] = Future() + # TODO: update backpressure window once CRT supports it + if self._received_chunks: + chunk = self._received_chunks.pop(0) + future.set_result(chunk) + elif self._stream.completion_future.done(): + future.set_result(b"") + else: + self._chunk_futures.append(future) + return future + + def _on_complete( + self, completion_future: Future[int] + ) -> None: # pragma: crt-callback + with self._chunk_lock: + if self._chunk_futures: + future = self._chunk_futures.pop(0) + future.set_result(b"") + + @property + def body(self) -> AsyncIterable[bytes]: + return self.chunks() + + @property + def status(self) -> int: + """The 3 digit response status code (1xx, 2xx, 3xx, 4xx, 5xx).""" + return self._status_code_future.result() + + @property + def fields(self) -> Fields: + """List of HTTP header fields.""" + if self._stream is None: + raise SmithyHTTPException("Stream not set") + if not self._headers_future.done(): + raise SmithyHTTPException("Headers not received yet") + return self._headers_future.result() + + @property + def reason(self) -> str | None: + """Optional string provided by the server explaining the status.""" + # TODO: See how CRT exposes reason. + return None + + def get_chunk(self) -> Awaitable[bytes]: + future = self._get_chunk_future() + return asyncio.wrap_future(future) + + async def chunks(self) -> AsyncGenerator[bytes, None]: + while True: + chunk = await self.get_chunk() + if chunk: + yield chunk + else: + break + + async def consume_body(self) -> bytes: + """Iterate over request body and return as bytes.""" + body = b"" + async for chunk in self.body: + body += chunk + return body + + +ConnectionPoolKey = tuple[str, str, int | None] +ConnectionPoolDict = dict[ConnectionPoolKey, crt_http.HttpClientConnection] + + +class AWSCRTHTTPClientConfig(interfaces.http.HTTPClientConfiguration): + pass + + +class AWSCRTHTTPClient(interfaces.http.HTTPClient): + _HTTP_PORT = 80 + _HTTPS_PORT = 443 + + def __init__( + self, + eventloop: _AWSCRTEventLoop | None = None, + client_config: AWSCRTHTTPClientConfig | None = None, + ) -> None: + """ + :param client_config: Configuration that applies to all requests made with this + client. + """ + self._config = ( + AWSCRTHTTPClientConfig() if client_config is None else client_config + ) + if eventloop is None: + eventloop = _AWSCRTEventLoop() + self._eventloop = eventloop + self._client_bootstrap = self._eventloop.bootstrap + self._tls_ctx = crt_io.ClientTlsContext(crt_io.TlsContextOptions()) + self._socket_options = crt_io.SocketOptions() + self._connections: ConnectionPoolDict = {} + + async def send( + self, + request: interfaces.http.HTTPRequest, + request_config: interfaces.http.HTTPRequestConfiguration | None = None, + ) -> AWSCRTHTTPResponse: + """Send HTTP request using awscrt client. + + :param request: The request including destination URI, fields, payload. + :param request_config: Configuration specific to this request. + """ + crt_request = await self._marshal_request(request) + connection = await self._get_connection(request.destination) + crt_response = AWSCRTHTTPResponse() + crt_stream = connection.request( + crt_request, + crt_response._on_headers, + crt_response._on_body, + ) + crt_response._set_stream(crt_stream) + return crt_response + + async def _create_connection( + self, url: interfaces.URI + ) -> crt_http.HttpClientConnection: + """Builds and validates connection to ``url``, returns it as + ``asyncio.Future``""" + connect_future = self._build_new_connection(url) + connection = await asyncio.wrap_future(connect_future) + self._validate_connection(connection) + return connection + + async def _get_connection( + self, url: interfaces.URI + ) -> crt_http.HttpClientConnection: + # TODO: Use CRT connection pooling instead of this basic kind + connection_key = (url.scheme, url.host, url.port) + if connection_key in self._connections: + return self._connections[connection_key] + else: + connection = await self._create_connection(url) + self._connections[connection_key] = connection + return connection + + def _build_new_connection( + self, url: interfaces.URI + ) -> Future[crt_http.HttpClientConnection]: + if url.scheme == "http": + port = self._HTTP_PORT + tls_connection_options = None + elif url.scheme == "https": + port = self._HTTPS_PORT + tls_connection_options = self._tls_ctx.new_connection_options() + tls_connection_options.set_server_name(url.host) + # TODO: Support TLS configuration, including alpn + tls_connection_options.set_alpn_list(["h2", "http/1.1"]) + else: + raise SmithyHTTPException( + f"AWSCRTHTTPClient does not support URL scheme {url.scheme}" + ) + if url.port is not None: + port = url.port + + connect_future: Future[ + crt_http.HttpClientConnection + ] = crt_http.HttpClientConnection.new( + bootstrap=self._client_bootstrap, + host_name=url.host, + port=port, + socket_options=self._socket_options, + tls_connection_options=tls_connection_options, + ) + return connect_future + + def _validate_connection(self, connection: crt_http.HttpClientConnection) -> None: + """Validates an existing connection against the client config. + + Checks performed: + * If ``force_http_2`` is enabled: Is the connection HTTP/2? + """ + force_http_2 = self._config.force_http_2 + if force_http_2 and connection.version is not crt_http.HttpVersion.Http2: + connection.close() + negotiated = crt_http.HttpVersion(connection.version).name + raise SmithyHTTPException(f"HTTP/2 could not be negotiated: {negotiated}") + + def _render_path(self, url: interfaces.URI) -> str: + path = url.path if url.path is not None else "/" + query = f"?{url.query}" if url.query is not None else "" + return f"{path}{query}" + + async def _marshal_request( + self, request: interfaces.http.HTTPRequest + ) -> crt_http.HttpRequest: + """ + Create :py:class:`awscrt.http.HttpRequest` from + :py:class:`smithy_python.interfaces.http.HTTPRequest` + """ + headers_list = [] + for fld in request.fields.entries.values(): + if fld.kind != FieldPosition.HEADER: + continue + for val in fld.values: + headers_list.append((fld.name, val)) + + path = self._render_path(request.destination) + headers = crt_http.HttpHeaders(headers_list) + body = BytesIO(await request.consume_body()) + + crt_request = crt_http.HttpRequest( + method=request.method, + path=path, + headers=headers, + body_stream=body, + ) + return crt_request diff --git a/StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/smithy_python/_private/identity.py b/StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/smithy_python/_private/identity.py new file mode 100644 index 000000000..125aa8ee6 --- /dev/null +++ b/StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/smithy_python/_private/identity.py @@ -0,0 +1,41 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). You +# may not use this file except in compliance with the License. A copy of +# the License is located at +# +# http://aws.amazon.com/apache2.0/ +# +# or in the "license" file accompanying this file. This file is +# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF +# ANY KIND, either express or implied. See the License for the specific +# language governing permissions and limitations under the License. +from datetime import datetime, timezone + +from ..interfaces import identity as identity_interface +from ..utils import ensure_utc + + +class Identity(identity_interface.Identity): + """An entity available to the client representing who the user is.""" + + def __init__( + self, + *, + expiration: datetime | None = None, + ) -> None: + """Initialize an identity. + + :param expiration: The expiration time of the identity. If time zone is + provided, it is updated to UTC. The value must always be in UTC. + """ + if expiration is not None: + expiration = ensure_utc(expiration) + self.expiration: datetime | None = expiration + + @property + def is_expired(self) -> bool: + """Whether the identity is expired.""" + if self.expiration is None: + return False + return datetime.now(tz=timezone.utc) >= self.expiration diff --git a/StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/smithy_python/_private/retries/__init__.py b/StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/smithy_python/_private/retries/__init__.py new file mode 100644 index 000000000..d4a917f4a --- /dev/null +++ b/StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/smithy_python/_private/retries/__init__.py @@ -0,0 +1,256 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). You +# may not use this file except in compliance with the License. A copy of +# the License is located at +# +# http://aws.amazon.com/apache2.0/ +# +# or in the "license" file accompanying this file. This file is +# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF +# ANY KIND, either express or implied. See the License for the specific +# language governing permissions and limitations under the License. + +import random +from dataclasses import dataclass +from enum import Enum +from typing import Callable + +from ...exceptions import SmithyRetryException +from ...interfaces import retries as retries_interface + + +class ExponentialBackoffJitterType(Enum): + """Jitter mode for exponential backoff. + + For use with :py:class:`ExponentialRetryBackoffStrategy`. + """ + + DEFAULT = 1 + """Truncated binary exponential backoff delay with equal jitter: + + .. code-block:: python + + capped = min(max_backoff, backoff_scale_value * 2 ** (retry_attempt - 1)) + (capped / 2) + random_between(0, capped / 2) + + Also known as "Equal Jitter". Similar to :py:var:`FULL` but always keep some of the + backoff and jitters by a smaller amount. + """ + + NONE = 2 + """Truncated binary exponential backoff delay without jitter: + + .. code-block:: python + + min(max_backoff, backoff_scale_value * 2 ** (retry_attempt - 1)) + """ + + FULL = 3 + """Truncated binary exponential backoff delay with full jitter: + + .. code-block:: python + + random_between( + max_backoff, + min(max_backoff, backoff_scale_value * 2 ** (retry_attempt - 1)) + ) + """ + + DECORRELATED = 4 + """Truncated binary exponential backoff delay with decorrelated jitter: + + .. code-block:: python + + min(max_backoff, random_between(backoff_scale_value, t_(i-1) * 3)) + + Similar to :py:var:`FULL`, but also increases the maximum jitter at each retry. + """ + + +class ExponentialRetryBackoffStrategy(retries_interface.RetryBackoffStrategy): + def __init__( + self, + *, + backoff_scale_value: float = 0.025, + max_backoff: float = 20, + jitter_type: ExponentialBackoffJitterType = ExponentialBackoffJitterType.DEFAULT, + random: Callable[[], float] = random.random, + ): + """Exponential backoff with optional jitter. + + .. seealso:: https://aws.amazon.com/blogs/architecture/exponential-backoff-and-jitter/ + + :param backoff_scale_value: Factor that linearly adjusts returned backoff delay + values. See the methods ``_next_delay_*`` for the formula used to calculate the + delay for each jitter type. If set to ``None`` (the default), :py:attr:`random` + will be called to generate a value. + + :param max_backoff: Upper limit for backoff delay values returned, in seconds. + + :param jitter_type: Determines the formula used to apply jitter to the backoff + delay. + + :param random: A callable that returns random numbers between ``0`` and ``1``. + Use the default ``random.random`` unless you require an alternate source of + randomness or a non-uniform distribution. + """ + self._backoff_scale_value = backoff_scale_value + self._max_backoff = max_backoff + self._jitter_type = jitter_type + self._random = random + self._previous_delay_seconds = self._backoff_scale_value + + def compute_next_backoff_delay(self, retry_attempt: int) -> float: + """Calculate timespan in seconds to delay before next retry. + + See the methods ``_next_delay_*`` for the formula used to calculate the delay + for each jitter type for values of ``retry_attempt > 0``. + + :param retry_attempt: The index of the retry attempt that is about to be made + after the delay. The initial attempt, before any retries, is index ``0``, and + will return a delay of ``0``. The first retry attempt after a failed initial + attempt is index ``1``, and so on. + """ + if retry_attempt == 0: + return 0 + + match self._jitter_type: + case ExponentialBackoffJitterType.NONE: + seconds = self._next_delay_no_jitter(retry_attempt=retry_attempt) + case ExponentialBackoffJitterType.DEFAULT: + seconds = self._next_delay_equal_jitter(retry_attempt=retry_attempt) + case ExponentialBackoffJitterType.FULL: + seconds = self._next_delay_full_jitter(retry_attempt=retry_attempt) + case ExponentialBackoffJitterType.DECORRELATED: + seconds = self._next_delay_decorrelated_jitter( + previous_delay=self._previous_delay_seconds + ) + + self._previous_delay_seconds = seconds + return seconds + + def _jitter_free_uncapped_delay(self, retry_attempt: int) -> float: + """The basic exponential delay without jitter or upper bound: + + .. code-block:: python + + backoff_scale_value * 2 ** (retry_attempt - 1) + """ + return self._backoff_scale_value * (2.0 ** (retry_attempt - 1)) + + def _next_delay_no_jitter(self, retry_attempt: int) -> float: + """Calculates truncated binary exponential backoff delay without jitter. + + Used when :py:var:`jitter_type` is :py:attr:`ExponentialBackoffJitterType.NONE`. + """ + no_jitter_delay = self._jitter_free_uncapped_delay(retry_attempt) + return min(no_jitter_delay, self._max_backoff) + + def _next_delay_full_jitter(self, retry_attempt: int) -> float: + """Calculates truncated binary exponential backoff delay with full jitter. + + Used when :py:var:`jitter_type` is :py:attr:`ExponentialBackoffJitterType.FULL`. + """ + + no_jitter_delay = self._jitter_free_uncapped_delay(retry_attempt) + return self._random() * min(no_jitter_delay, self._max_backoff) + + def _next_delay_equal_jitter(self, retry_attempt: int) -> float: + """Calculates truncated binary exponential backoff delay with equal jitter: + + Used when :py:var:`jitter_type` is + :py:attr:`ExponentialBackoffJitterType.DEFAULT`. + """ + no_jitter_delay = self._jitter_free_uncapped_delay(retry_attempt) + return (self._random() * 0.5 + 0.5) * min(no_jitter_delay, self._max_backoff) + + def _next_delay_decorrelated_jitter(self, previous_delay: float) -> float: + """Calculates truncated binary exp. backoff delay with decorrelated jitter: + + Used when :py:var:`jitter_type` is + :py:attr:`ExponentialBackoffJitterType.DECORRELATED`. + """ + return min( + self._backoff_scale_value + self._random() * previous_delay * 3, + self._max_backoff, + ) + + +@dataclass(kw_only=True) +class SimpleRetryToken: + """Basic retry token that stores only the attempt count and backoff strategy. + + Retry tokens should always be obtained from an implementation of + :py:class:`retries_interface.RetryStrategy`. + """ + + retry_count: int + """Retry count is the total number of attempts minus the initial attempt.""" + + retry_delay: float + """Delay in seconds to wait before the retry attempt.""" + + @property + def attempt_count(self) -> int: + """The total number of attempts including the initial attempt and retries.""" + return self.retry_count + 1 + + +class SimpleRetryStrategy(retries_interface.RetryStrategy): + def __init__( + self, + *, + backoff_strategy: retries_interface.RetryBackoffStrategy | None = None, + max_attempts: int = 5, + ): + """Basic retry strategy that simply invokes the given backoff strategy. + + :param backoff_strategy: The backoff strategy used by returned tokens to compute + the retry delay. Defaults to :py:class:`ExponentialRetryBackoffStrategy`. + + :param max_attempts: Upper limit on total number of attempts made, including + initial attempt and retries. + """ + self.backoff_strategy = backoff_strategy or ExponentialRetryBackoffStrategy() + self.max_attempts = max_attempts + + def acquire_initial_retry_token( + self, *, token_scope: str | None = None + ) -> SimpleRetryToken: + """Called before any retries (for the first attempt at the operation). + + :param token_scope: This argument is ignored by this retry strategy. + """ + retry_delay = self.backoff_strategy.compute_next_backoff_delay(0) + return SimpleRetryToken(retry_count=0, retry_delay=retry_delay) + + def refresh_retry_token_for_retry( + self, + *, + token_to_renew: retries_interface.RetryToken, + error_info: retries_interface.RetryErrorInfo, + ) -> SimpleRetryToken: + """Replace an existing retry token from a failed attempt with a new token. + + This retry strategy always returns a token until the attempt count stored in + the new token exceeds the ``max_attempts`` value. + + :param token_to_renew: The token used for the previous failed attempt. + + :param error_info: If no further retry is allowed, this information is used to + construct the exception. + + :raises SmithyRetryException: If no further retry attempts are allowed. + """ + retry_count = token_to_renew.retry_count + 1 + if retry_count >= self.max_attempts: + raise SmithyRetryException( + f"Reached maximum number of allowed attempts: {self.max_attempts}" + ) + retry_delay = self.backoff_strategy.compute_next_backoff_delay(retry_count) + return SimpleRetryToken(retry_count=retry_count, retry_delay=retry_delay) + + def record_success(self, *, token: retries_interface.RetryToken) -> None: + """Not used by this retry strategy.""" + pass diff --git a/StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/smithy_python/async_utils.py b/StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/smithy_python/async_utils.py new file mode 100644 index 000000000..581099097 --- /dev/null +++ b/StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/smithy_python/async_utils.py @@ -0,0 +1,25 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). You +# may not use this file except in compliance with the License. A copy of +# the License is located at +# +# http://aws.amazon.com/apache2.0/ +# +# or in the "license" file accompanying this file. This file is +# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF +# ANY KIND, either express or implied. See the License for the specific +# language governing permissions and limitations under the License. + +from asyncio import sleep +from collections.abc import AsyncIterable, Iterable +from typing import TypeVar + +_ListEl = TypeVar("_ListEl") + + +async def async_list(lst: Iterable[_ListEl]) -> AsyncIterable[_ListEl]: + """Turn an Iterable into an AsyncIterable.""" + for x in lst: + await sleep(0) + yield x diff --git a/StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/smithy_python/exceptions.py b/StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/smithy_python/exceptions.py new file mode 100644 index 000000000..77eed206f --- /dev/null +++ b/StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/smithy_python/exceptions.py @@ -0,0 +1,32 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). You +# may not use this file except in compliance with the License. A copy of +# the License is located at +# +# http://aws.amazon.com/apache2.0/ +# +# or in the "license" file accompanying this file. This file is +# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF +# ANY KIND, either express or implied. See the License for the specific +# language governing permissions and limitations under the License. + + +class SmithyException(Exception): + """Base exception type for all exceptions raised by smithy-python.""" + + +class SmithyRetryException(SmithyException): + """Base exception type for all exceptions raised in retry strategies.""" + + +class ExpectationNotMetException(SmithyException): + """Exception type for exceptions thrown by unmet assertions.""" + + +class SmithyIdentityException(SmithyException): + """Base exception type for all exceptions raised in identity resolution.""" + + +class SmithyHTTPException(SmithyException): + """Base exception type for all exceptions raised in HTTP clients.""" diff --git a/StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/smithy_python/httputils.py b/StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/smithy_python/httputils.py new file mode 100644 index 000000000..3182e0e4a --- /dev/null +++ b/StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/smithy_python/httputils.py @@ -0,0 +1,133 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). You +# may not use this file except in compliance with the License. A copy of +# the License is located at +# +# http://aws.amazon.com/apache2.0/ +# +# or in the "license" file accompanying this file. This file is +# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF +# ANY KIND, either express or implied. See the License for the specific +# language governing permissions and limitations under the License. + +from urllib.parse import quote as urlquote + +from .exceptions import SmithyException + + +def split_header(given: str, handle_unquoted_http_date: bool = False) -> list[str]: + """Splits a header value into a list of strings. + + The format is based on RFC9110's list production found in secion 5.6.1 with + the quoted string production found in section 5.6.4. In short: + + A list is 1 or more elements surrounded by optional whitespace and separated by + commas. Elements may be quoted with double quotes (``"``) to contain leading or + trailing whitespace, commas, or double quotes. Inside the the double quotes, a + value may be escaped with a backslash (``\\``). Elements that contain no contents + are ignored. + + If the list is known to contain unquoted IMF-fixdate formatted timestamps, the + ``handle_unquoted_http_date`` parameter can be set to ensure the list isn't + split on the commas inside the timestamps. + + :param given: The header value to split. + :param handle_unquoted_http_date: Support splitting IMF-fixdate lists without + quotes. Defaults to False. + :returns: The header value split on commas. + """ + result: list[str] = [] + + i = 0 + while i < len(given): + if given[i].isspace(): + # Skip any leading space. + i += 1 + elif given[i] == '"': + # Grab the contents of the quoted value and append it. + entry, i = _consume_until(given, i + 1, '"', escape_char="\\") + result.append(entry) + + if i > len(given) or given[i - 1] != '"': + raise SmithyException( + f"Invalid header list syntax: expected end quote but reached end " + f"of value: `{given}`" + ) + + # Skip until the next comma. + excess, i = _consume_until(given, i, ",") + if excess.strip(): + raise SmithyException( + f"Invalid header list syntax: Found quote contents after " + f"end-quote: `{excess}` in `{given}`" + ) + else: + entry, i = _consume_until( + given, i, ",", skip_first=handle_unquoted_http_date + ) + if stripped := entry.strip(): + result.append(stripped) + + return result + + +def _consume_until( + given: str, + start_index: int, + end_char: str, + escape_char: str | None = None, + skip_first: bool = False, +) -> tuple[str, int]: + """Creates a slice of the given string from the start index to the end character. + + This also handles resolving escaped characters using the given escape_char if + provided. + + If `skip_first` is true, the first instance of the end character will be skipped. + This is to enable support for unquoted IMF fixdate timestamps. + + :param given: The whole header string. + :param start_index: The index at which to start slicing. + :param end_char: The character to split on. This is not included in the output. + :param escape_char: The character to escape with, e.g. ``\\``. + :param skip_first: Whether to skip the first instance of the end character. + :returns: A substring from the start index to the first instance of the end char. + """ + should_skip = skip_first + end_index = start_index + result = "" + escaped = False + while end_index < len(given): + if escaped: + result += given[end_index] + escaped = False + elif given[end_index] == escape_char: + escaped = True + elif given[end_index] == end_char: + if should_skip: + result += given[end_index] + should_skip = False + else: + break + else: + result += given[end_index] + end_index += 1 + return result, end_index + 1 + + +def join_query_params(params: list[tuple[str, str | None]], prefix: str = "") -> str: + """Join a list of query parameter key-value tuples. + + :param params: The list of key-value query parameter tuples. + :param prefix: An optional query prefix. + """ + query: str = prefix + for param in params: + if query: + query += "&" + if param[1] is None: + query += urlquote(param[0], safe="") + else: + query += f"{urlquote(param[0], safe='')}={urlquote(param[1], safe='')}" + return query diff --git a/StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/smithy_python/interfaces/__init__.py b/StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/smithy_python/interfaces/__init__.py new file mode 100644 index 000000000..322bd6283 --- /dev/null +++ b/StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/smithy_python/interfaces/__init__.py @@ -0,0 +1,181 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). You +# may not use this file except in compliance with the License. A copy of +# the License is located at +# +# http://aws.amazon.com/apache2.0/ +# +# or in the "license" file accompanying this file. This file is +# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF +# ANY KIND, either express or implied. See the License for the specific +# language governing permissions and limitations under the License. + +from collections import OrderedDict +from collections.abc import AsyncIterable, Iterator +from enum import Enum +from typing import Protocol + + +class URI(Protocol): + """Universal Resource Identifier, target location for a :py:class:`Request`.""" + + scheme: str + """For example ``http`` or ``mqtts``.""" + + username: str | None + """Username part of the userinfo URI component.""" + + password: str | None + """Password part of the userinfo URI component.""" + + host: str + """The hostname, for example ``amazonaws.com``.""" + + port: int | None + """An explicit port number.""" + + path: str | None + """Path component of the URI.""" + + query: str | None + """Query component of the URI as string.""" + + fragment: str | None + """Part of the URI specification, but may not be transmitted by a client.""" + + def build(self) -> str: + """Construct URI string representation. + + Returns a string of the form + ``{scheme}://{username}:{password}@{host}:{port}{path}?{query}#{fragment}`` + """ + ... + + @property + def netloc(self) -> str: + """Construct netloc string in format ``{username}:{password}@{host}:{port}``""" + ... + + +class Request(Protocol): + """Protocol-agnostic representation of a request.""" + + destination: URI + body: AsyncIterable[bytes] + + async def consume_body(self) -> bytes: + """Iterate over request body and return as bytes.""" + ... + + +class Response(Protocol): + """Protocol-agnostic representation of a response.""" + + @property + def body(self) -> AsyncIterable[bytes]: + """The response payload as iterable of chunks of bytes.""" + ... + + async def consume_body(self) -> bytes: + """Iterate over response body and return as bytes.""" + ... + + +class FieldPosition(Enum): + """The type of a field. + + Defines its placement in a request or response. + """ + + HEADER = 0 + """Header field. + + In HTTP this is a header as defined in RFC 9110 Section 6.3. Implementations of + other protocols may use this FieldPosition for similar types of metadata. + """ + + TRAILER = 1 + """Trailer field. + + In HTTP this is a trailer as defined in RFC 9110 Section 6.5. Implementations of + other protocols may use this FieldPosition for similar types of metadata. + """ + + +class Field(Protocol): + """A name-value pair representing a single field in a request or response. + + The kind will dictate metadata placement within an the message, for example as + header or trailer field in a HTTP request as defined in RFC 9110 Section 5. + + All field names are case insensitive and case-variance must be treated as + equivalent. Names may be normalized but should be preserved for accuracy during + transmission. + """ + + name: str + values: list[str] + kind: FieldPosition = FieldPosition.HEADER + + def add(self, value: str) -> None: + """Append a value to a field.""" + ... + + def set(self, values: list[str]) -> None: + """Overwrite existing field values.""" + ... + + def remove(self, value: str) -> None: + """Remove all matching entries from list.""" + ... + + def as_string(self) -> str: + """Serialize the ``Field``'s values into a single line string.""" + ... + + def as_tuples(self) -> list[tuple[str, str]]: + """Get list of ``name``, ``value`` tuples where each tuple represents one + value.""" + ... + + +class Fields(Protocol): + """Protocol agnostic mapping of key-value pair request metadata, such as HTTP + fields.""" + + # Entries are keyed off the name of a provided Field + entries: OrderedDict[str, Field] + encoding: str | None = "utf-8" + + def set_field(self, field: Field) -> None: + """Set entry for a Field name.""" + ... + + def get_field(self, name: str) -> Field: + """Retrieve Field entry.""" + ... + + def remove_field(self, name: str) -> None: + """Delete entry from collection.""" + ... + + def get_by_type(self, kind: FieldPosition) -> list[Field]: + """Helper function for retrieving specific types of fields. + + Used to grab all headers or all trailers. + """ + ... + + def extend(self, other: "Fields") -> None: + """Merges ``entries`` of ``other`` into the current ``entries``. + + For every `Field` in the ``entries`` of ``other``: If the normalized name + already exists in the current ``entries``, the values from ``other`` are + appended. Otherwise, the ``Field`` is added to the list of ``entries``. + """ + ... + + def __iter__(self) -> Iterator[Field]: + """Allow iteration over entries.""" + ... diff --git a/StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/smithy_python/interfaces/auth.py b/StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/smithy_python/interfaces/auth.py new file mode 100644 index 000000000..b815a8d79 --- /dev/null +++ b/StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/smithy_python/interfaces/auth.py @@ -0,0 +1,122 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). You +# may not use this file except in compliance with the License. A copy of +# the License is located at +# +# http://aws.amazon.com/apache2.0/ +# +# or in the "license" file accompanying this file. This file is +# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF +# ANY KIND, either express or implied. See the License for the specific +# language governing permissions and limitations under the License. + +from dataclasses import dataclass +from typing import Any, Protocol, TypedDict, TypeVar + +from .http import HTTPRequest +from .identity import ( + IdentityConfig_contra, + IdentityPropertiesType_contra, + IdentityResolver, + IdentityType, + IdentityType_contra, +) + + +class SigningProperties(TypedDict): + """Additional properties loaded to modify the signing process.""" + + ... + + +SigningPropertiesType = TypeVar("SigningPropertiesType", bound=SigningProperties) +SigningPropertiesType_contra = TypeVar( + "SigningPropertiesType_contra", bound=SigningProperties, contravariant=True +) + + +class HTTPSigner(Protocol[IdentityType_contra, SigningPropertiesType_contra]): + """An interface for generating a signed HTTP request.""" + + async def sign( + self, + *, + http_request: HTTPRequest, + identity: IdentityType_contra, + signing_properties: SigningPropertiesType_contra, + ) -> HTTPRequest: + """Generate a new signed HTTPRequest based on the one provided. + + :param http_request: The HTTP request to sign. + + :param identity: The signing identity. + + :param signing_properties: Additional properties loaded to modify the + signing process. + """ + ... + + +class HTTPAuthScheme( + Protocol[ + IdentityType, + IdentityConfig_contra, + IdentityPropertiesType_contra, + SigningPropertiesType, + ] +): + """Represents a way a service will authenticate the user's identity.""" + + # A unique identifier for the authentication scheme. + scheme_id: str + + # An API that can be used to sign HTTP requests. + signer: HTTPSigner[IdentityType, SigningPropertiesType] + + def identity_resolver( + self, *, config: IdentityConfig_contra + ) -> IdentityResolver[IdentityType, IdentityPropertiesType_contra]: + """An API that can be queried to resolve identity.""" + ... + + +@dataclass(kw_only=True) +class HTTPAuthOption: + """Auth scheme used for signing and identity resolution.""" + + # The ID of the scheme to use. This string matches the one returned by + # HttpAuthScheme.scheme_id + scheme_id: str + + # Parameters to pass to IdentityResolver.get_identity. + identity_properties: dict[str, Any] + + # Parameters to pass to HttpSigner.sign. + signer_properties: dict[str, Any] + + +@dataclass(kw_only=True) +class AuthSchemeParameters: + """The input to the auth scheme resolver. + + A code-generated interface for passing in the data required for determining the + authentication scheme. By default, this only includes the operation name. + """ + + # The service operation being invoked by the client. + operation: str + + +class AuthSchemeResolver(Protocol): + """Determines which authentication scheme to use for a given service.""" + + def resolve_auth_scheme( + self, *, auth_parameters: AuthSchemeParameters + ) -> list[HTTPAuthOption]: + """Resolve an ordered list of applicable auth schemes. + + :param auth_parameters: The parameters required for determining which + authentication schemes to potentially use. + """ + ... diff --git a/StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/smithy_python/interfaces/blobs.py b/StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/smithy_python/interfaces/blobs.py new file mode 100644 index 000000000..6d8d88e61 --- /dev/null +++ b/StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/smithy_python/interfaces/blobs.py @@ -0,0 +1,305 @@ +from asyncio import iscoroutinefunction +from io import BytesIO +from typing import ( + AsyncIterable, + AsyncIterator, + Awaitable, + Callable, + Protocol, + Self, + Union, + cast, + runtime_checkable, +) + +# The default chunk size for iterating streams. +_DEFAULT_CHUNK_SIZE = 1024 + + +@runtime_checkable +class ByteStream(Protocol): + """A file-like object with a read method that returns bytes.""" + + def read(self, size: int = -1) -> bytes: + pass + + +@runtime_checkable +class AsyncByteStream(Protocol): + """A file-like object with an async read method.""" + + async def read(self, size: int = -1) -> bytes: + pass + + +# A union of all acceptable streaming blob types. Deserialized payloads will +# always return a ByteStream, or AsyncByteStream if async is enabled. +StreamingBlob = Union[ + ByteStream, + AsyncByteStream, + bytes, + bytearray, + AsyncIterable[bytes], +] + + +# asyncio has a StreamReader class which you might think would be appropriate here, +# but it is unfortunately tied to the asyncio http interfaces. +class AsyncBytesReader: + """A file-like object with an async read method.""" + + # BytesIO *is* a ByteStream, but mypy will nevertheless complain if it isn't here. + _data: ByteStream | AsyncByteStream | AsyncIterable[bytes] | BytesIO | None + _closed = False + + def __init__(self, data: StreamingBlob): + """Initializes self. + + Data is read from the source on an as-needed basis and is not buffered. + + :param data: The source data to read from. + """ + self._remainder = b"" + # pylint: disable-next=isinstance-second-argument-not-valid-type + if isinstance(data, bytes | bytearray): + self._data = BytesIO(data) + else: + self._data = data + + async def read(self, size: int = -1) -> bytes: + """Read a number of bytes from the stream. + + :param size: The maximum number of bytes to read. If less than 0, all bytes + will be read. + """ + if self._closed or not self._data: + raise ValueError("I/O operation on closed file.") + + if isinstance(self._data, ByteStream) and not iscoroutinefunction( + self._data.read + ): + # Python's runtime_checkable can't actually tell the difference between + # sync and async, so we have to check ourselves. + return self._data.read(size) + + if isinstance(self._data, AsyncByteStream): + return await self._data.read(size) + + return await self._read_from_iterable( + cast(AsyncIterable[bytes], self._data), size + ) + + async def _read_from_iterable( + self, iterator: AsyncIterable[bytes], size: int + ) -> bytes: + # This takes the iterator as an arg here just to avoid mypy complaints, since + # we know it's an iterator where this is called. + result = self._remainder + if size < 0: + async for element in iterator: + result += element + self._remainder = b"" + return result + + async for element in iterator: + result += element + if len(result) >= size: + break + + self._remainder = result[size:] + return result[:size] + + def __aiter__(self) -> AsyncIterator[bytes]: + return self.iter_chunks() + + def iter_chunks( + self, chunk_size: int = _DEFAULT_CHUNK_SIZE + ) -> AsyncIterator[bytes]: + """Iterate over the reader in chunks of a given size. + + :param chunk_size: The maximum size of each chunk. If less than 0, the entire + reader will be read into one chunk. + """ + return _AsyncByteStreamIterator(self.read, chunk_size) + + def readable(self) -> bool: + """Returns whether the stream is readable.""" + return True + + def writeable(self) -> bool: + """Returns whether the stream is writeable.""" + return False + + def seekable(self) -> bool: + """Returns whether the stream is seekable.""" + return False + + @property + def closed(self) -> bool: + """Returns whether the stream is closed.""" + return self._closed + + def close(self) -> None: + """Closes the stream, as well as the underlying stream where possible.""" + if (close := getattr(self._data, "close", None)) is not None: + close() + self._data = None + self._closed = True + + +class SeekableAsyncBytesReader: + """A file-like object with async read and seek methods.""" + + def __init__(self, data: StreamingBlob): + """Initializes self. + + Data is read from the source on an as-needed basis and buffered internally so + that it can be rewound safely. + + :param data: The source data to read from. + """ + # pylint: disable-next=isinstance-second-argument-not-valid-type + if isinstance(data, bytes | bytearray): + self._buffer = BytesIO(data) + self._data_source = None + elif isinstance(data, AsyncByteStream) and iscoroutinefunction(data.read): + # Note that we need that iscoroutine check because python won't actually check + # whether or not the read function is async. + self._buffer = BytesIO() + self._data_source = data + else: + self._buffer = BytesIO() + self._data_source = AsyncBytesReader(data) + + async def read(self, size: int = -1) -> bytes: + """Read a number of bytes from the stream. + + :param size: The maximum number of bytes to read. If less than 0, all bytes + will be read. + """ + if self._data_source is None or size == 0: + return self._buffer.read(size) + + start = self._buffer.tell() + current_buffer_size = self._buffer.seek(0, 2) + + if size < 0: + await self._read_into_buffer(size) + elif (target := start + size) > current_buffer_size: + amount_to_read = target - current_buffer_size + await self._read_into_buffer(amount_to_read) + + self._buffer.seek(start, 0) + return self._buffer.read(size) + + async def seek(self, offset: int, whence: int = 0) -> int: + """Moves the cursor to a position relatve to the position indicated by whence. + + Whence can have one of three values: + + * 0 => The offset is relative to the start of the stream. + + * 1 => The offset is relative to the current location of the cursor. + + * 2 => The offset is relative to the end of the stream. + + :param offset: The amount of movement to be done relative to whence. + :param whence: The location the offset is relative to. + :returns: Returns the new position of the cursor. + """ + if self._data_source is None: + return self._buffer.seek(offset, whence) + + if whence >= 2: + # If the seek is relative to the end of the stream, we need to read the + # whole thing in from the source. + self._buffer.seek(0, 2) + self._buffer.write(await self._data_source.read()) + return self._buffer.seek(offset, whence) + + start = self.tell() + target = offset + if whence == 1: + target += start + + current_buffer_size = self._buffer.seek(0, 2) + if current_buffer_size < target: + await self._read_into_buffer(target - current_buffer_size) + + return self._buffer.seek(target, 0) + + async def _read_into_buffer(self, size: int) -> None: + if self._data_source is None: + return + + read_bytes = await self._data_source.read(size) + if len(read_bytes) < size or size < 0: + self._data_source = None + + self._buffer.seek(0, 2) + self._buffer.write(read_bytes) + + def tell(self) -> int: + """Returns the position of the cursor.""" + return self._buffer.tell() + + def __aiter__(self) -> AsyncIterator[bytes]: + return self.iter_chunks() + + def iter_chunks( + self, chunk_size: int = _DEFAULT_CHUNK_SIZE + ) -> AsyncIterator[bytes]: + """Iterate over the reader in chunks of a given size. + + :param chunk_size: The maximum size of each chunk. If less than 0, the entire + reader will be read into one chunk. + """ + return _AsyncByteStreamIterator(self.read, chunk_size) + + def readable(self) -> bool: + """Returns whether the stream is readable.""" + return True + + def writeable(self) -> bool: + """Returns whether the stream is writeable.""" + return False + + def seekable(self) -> bool: + """Returns whether the stream is seekable.""" + return True + + @property + def closed(self) -> bool: + """Returns whether the stream is closed.""" + return self._buffer.closed + + def close(self) -> None: + """Closes the stream, as well as the underlying stream where possible.""" + if callable(close_fn := getattr(self._data_source, "close", None)): + close_fn() # pylint: disable=not-callable + self._data_source = None + self._buffer.close() + + +class _AsyncByteStreamIterator: + """An async bytes iterator that operates over an async read method.""" + + def __init__(self, read: Callable[[int], Awaitable[bytes]], chunk_size: int): + """Initializes self. + + :param read: An async callable that reads a given number of bytes from some + source. + + :param chunk_size: The number of bytes to read in each iteration. + """ + self._read = read + self._chunk_size = chunk_size + + def __aiter__(self) -> Self: + return self + + async def __anext__(self) -> bytes: + data = await self._read(self._chunk_size) + if data: + return data + raise StopAsyncIteration diff --git a/StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/smithy_python/interfaces/http.py b/StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/smithy_python/interfaces/http.py new file mode 100644 index 000000000..370525ccd --- /dev/null +++ b/StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/smithy_python/interfaces/http.py @@ -0,0 +1,112 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). You +# may not use this file except in compliance with the License. A copy of +# the License is located at +# +# http://aws.amazon.com/apache2.0/ +# +# or in the "license" file accompanying this file. This file is +# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF +# ANY KIND, either express or implied. See the License for the specific +# language governing permissions and limitations under the License. +from dataclasses import dataclass +from typing import Protocol, TypeVar + +from . import URI, Fields, Request, Response + +QueryParamsList = list[tuple[str, str]] + + +class HTTPRequest(Request, Protocol): + """HTTP primitive for an Exchange to construct a version agnostic HTTP message. + + :param destination: The URI where the request should be sent to. + :param method: The HTTP method of the request, for example "GET". + :param fields: ``Fields`` object containing HTTP headers and trailers. + :param body: A streamable collection of bytes. + """ + + method: str + fields: Fields + + +class HTTPResponse(Response, Protocol): + """HTTP primitives returned from an Exchange, used to construct a client + response.""" + + @property + def status(self) -> int: + """The 3 digit response status code (1xx, 2xx, 3xx, 4xx, 5xx).""" + ... + + @property + def fields(self) -> Fields: + """``Fields`` object containing HTTP headers and trailers.""" + ... + + @property + def reason(self) -> str | None: + """Optional string provided by the server explaining the status.""" + ... + + +class Endpoint(Protocol): + uri: URI + headers: Fields + + +# EndpointParams are defined in the generated client, so we use a TypeVar here. +# More specific EndpointParams implementations are subtypes of less specific ones. But +# consumers of less specific EndpointParams implementations are subtypes of consumers +# of more specific ones. +EndpointParams = TypeVar("EndpointParams", contravariant=True) + + +class EndpointResolver(Protocol[EndpointParams]): + """Resolves an operation's endpoint based given parameters.""" + + async def resolve_endpoint(self, params: EndpointParams) -> Endpoint: + raise NotImplementedError() + + +@dataclass(kw_only=True) +class HTTPClientConfiguration: + """Client-level HTTP configuration. + + :param force_http_2: Whether to require HTTP/2. + """ + + force_http_2: bool = False + + +@dataclass(kw_only=True) +class HTTPRequestConfiguration: + """Request-level HTTP configuration. + + :param read_timeout: How long, in seconds, the client will attempt to read the + first byte over an established, open connection before timing out. + """ + + read_timeout: float | None = None + + +class HTTPClient(Protocol): + """An asynchronous HTTP client interface.""" + + def __init__(self, *, client_config: HTTPClientConfiguration | None) -> None: + """ + :param client_config: Configuration that applies to all requests made with this + client. + """ + ... + + async def send( + self, *, request: HTTPRequest, request_config: HTTPRequestConfiguration | None + ) -> HTTPResponse: + """Send HTTP request over the wire and return the response. + + :param request: The request including destination URI, fields, payload. + :param request_config: Configuration specific to this request. + """ + ... diff --git a/StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/smithy_python/interfaces/identity.py b/StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/smithy_python/interfaces/identity.py new file mode 100644 index 000000000..3688993b5 --- /dev/null +++ b/StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/smithy_python/interfaces/identity.py @@ -0,0 +1,64 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). You +# may not use this file except in compliance with the License. A copy of +# the License is located at +# +# http://aws.amazon.com/apache2.0/ +# +# or in the "license" file accompanying this file. This file is +# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF +# ANY KIND, either express or implied. See the License for the specific +# language governing permissions and limitations under the License. + +from datetime import datetime +from typing import Protocol, TypedDict, TypeVar + + +class Identity(Protocol): + """An entity available to the client representing who the user is.""" + + # The expiration time of the identity. If time zone is provided, + # it is updated to UTC. The value must always be in UTC. + expiration: datetime | None = None + + @property + def is_expired(self) -> bool: + """Whether the identity is expired.""" + ... + + +IdentityType = TypeVar("IdentityType", bound=Identity) +IdentityType_contra = TypeVar("IdentityType_contra", bound=Identity, contravariant=True) +IdentityType_cov = TypeVar("IdentityType_cov", bound=Identity, covariant=True) + + +class IdentityProperties(TypedDict): + """Properties used to help determine the identity to return.""" + + ... + + +IdentityPropertiesType = TypeVar("IdentityPropertiesType", bound=IdentityProperties) +IdentityPropertiesType_contra = TypeVar( + "IdentityPropertiesType_contra", bound=IdentityProperties, contravariant=True +) + +IdentityConfig_contra = TypeVar("IdentityConfig_contra", contravariant=True) + + +class IdentityResolver(Protocol[IdentityType_cov, IdentityPropertiesType_contra]): + """Used to load a user's `Identity` from a given source. + + Each `Identity` may have one or more resolver implementations. + """ + + async def get_identity( + self, *, identity_properties: IdentityPropertiesType_contra + ) -> IdentityType_cov: + """Load the user's identity from this resolver. + + :param identity_properties: Properties used to help determine the + identity to return. + """ + ... diff --git a/StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/smithy_python/interfaces/interceptor.py b/StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/smithy_python/interfaces/interceptor.py new file mode 100644 index 000000000..bb6f4e483 --- /dev/null +++ b/StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/smithy_python/interfaces/interceptor.py @@ -0,0 +1,606 @@ +from copy import copy, deepcopy +from typing import Any, Generic, TypeVar + +Request = TypeVar("Request") +Response = TypeVar("Response") +TransportRequest = TypeVar("TransportRequest") +TransportResponse = TypeVar("TransportResponse") + + +class InterceptorContext( + Generic[Request, Response, TransportRequest, TransportResponse] +): + def __init__( + self, + *, + request: Request, + response: Response | Exception, + transport_request: TransportRequest, + transport_response: TransportResponse, + ): + """A container for the current data available to an interceptor. + + :param request: The modeled request for the operation being invoked. + :param response: The modeled response for the operation being invoked. This will + only be available once the transport_response has been deserialized or the + attempt/execution has failed. + :param transport_request: The transmittable request for the operation being + invoked. This will only be available once request serialization has + completed. + :param transport_response: The transmitted response for the operation being + invoked. This will only be available once transmission has completed. + """ + self._request = request + self._response = response + self._transport_request = transport_request + self._transport_response = transport_response + self._properties: dict[str, Any] = {} + + @property + def request(self) -> Request: + """Retrieve the modeled request for the operation being invoked.""" + return self._request + + @property + def response(self) -> Response | Exception: + """Retrieve the modeled response for the operation being invoked. + + This will only be available once the transport_response has been deserialized or + the attempt/execution has failed. + """ + return self._response + + # Note that TransportRequest (and TransportResponse below) aren't resolved types, + # but rather TypeVars. This is very important, because in the actual Interceptor + # interface class these are sometimes typed as None rather than, say, HTTPRequest. + # That lets us use the type system to tell people when something will be set and + # when it will not be set without leaking nullability into the cases where the + # property will ALWAYS be set. + @property + def transport_request(self) -> TransportRequest: + """Retrieve the transmittable request for the operation being invoked. + + This will only be available once request serialization has completed. + """ + return self._transport_request + + @property + def transport_response(self) -> TransportResponse: + """Retrieve the transmitted response for the operation being invoked. + + This will only be available once transmission has completed. + """ + return self._transport_response + + @property + def properties(self) -> dict[str, Any]: + """Retrieve the generic property bag. + + These untyped properties will be made available to all other interceptors or + hooks that are called for this execution. + """ + return self._properties + + # The static properties of this class are made 'read-only' like this to discourage + # people from trying to modify the context outside of the specific hooks where that + # is allowed. + def copy( + self, + *, + request: Request | None = None, + response: Response | Exception | None = None, + transport_request: TransportRequest | None = None, + transport_response: TransportResponse | None = None, + ) -> "InterceptorContext[Request, Response, TransportRequest, TransportResponse]": + """Copy the context object, optionally overriding certain properties.""" + if transport_request is None: + transport_request = copy(self._transport_request) + + if transport_response is None: + transport_response = copy(self._transport_response) + + context = InterceptorContext( + request=request if request is not None else self._request, + response=response if response is not None else self._response, + transport_request=transport_request, + transport_response=transport_response, + ) + context._properties = deepcopy(self._properties) + return context + + +class Interceptor(Generic[Request, Response, TransportRequest, TransportResponse]): + """Allows injecting code into the SDK's request execution pipeline. + + Terminology: + + * execution - An execution is one end-to-end invocation against a client. + * attempt - An attempt is an attempt at performing an execution. By default, + executions are retried multiple times based on the client's retry strategy. + * hook - A hook is a single method on the interceptor, allowing injection of code + into a specific part of the SDK's request execution pipeline. Hooks are either + "read" hooks, which make it possible to read in-flight request or response + messages, or "read/write" hooks, which make it possible to modify in-flight + requests or responses. + """ + + def read_before_execution( + self, context: InterceptorContext[Request, None, None, None] + ) -> None: + """A hook called at the start of an execution, before the SDK does anything + else. + + Implementations MUST NOT modify the `request`, `response`, `transport_request`, + or `transport_response` in this hook. + + This will always be called once per execution. The duration between invocation + of this hook and `read_after_execution` is very close to full duration of the + execution. + + The `request` of the context will always be available. Other static properties + will be None. + + Exceptions thrown by this hook will be stored until all interceptors have had + their `read_before_execution` invoked. Other hooks will then be skipped and + execution will jump to `modify_before_completion` with the thrown exception as + the `response`. If multiple `read_before_execution` methods throw exceptions, + the latest will be used and earlier ones will be logged and dropped. + """ + pass + + def modify_before_serialization( + self, context: InterceptorContext[Request, None, None, None] + ) -> Request: + """A hook called before the request is serialized into a transport request. + + This method has the ability to modify and return a new request of the same + type. + + This will ALWAYS be called once per execution, except when a failure occurs + earlier in the request pipeline. + + The `request` of the context will always be available. This `request` may have + been modified by earlier `modify_before_serialization` hooks, and may be + modified further by later hooks. Other static properites will be None. + + If exceptions are thrown by this hook, execution will jump to + `modify_before_completion` with the thrown exception as the `response`. + + The request returned by this hook MUST be the same type of request + message passed into this hook. If not, an exception will immediately occur. + """ + return context.request + + def read_before_serialization( + self, context: InterceptorContext[Request, None, None, None] + ) -> None: + """A hook called before the input message is serialized into a transport + request. + + Implementations MUST NOT modify the `request`, `response`, `transport_request`, + or `transport_response` in this hook. + + This will always be called once per execution, except when a failure occurs + earlier in the request pipeline. The duration between invocation of this hook + and `read_after_serialization` is very close to the amount of time spent + marshalling the request. + + The `request` of the context will always be available. Other static properties + will be None. + + If exceptions are thrown by this hook, execution will jump to + `modify_before_completion` with the thrown exception as the `response`. + """ + pass + + def read_after_serialization( + self, context: InterceptorContext[Request, None, TransportRequest, None] + ) -> None: + """A hook called after the input message is serialized into a transport request. + + Implementations MUST NOT modify the `request`, `response`, `transport_request`, + or `transport_response` in this hook. + + This will always be called once per execution, except when a failure occurs + earlier in the request pipeline. The duration between + `read_before_serialization` and the invocation of this hook is very close to + the amount of time spent serializing the request. + + The `request` and `transport_request` of the context will always be available. + Other static properties will be None. + + If exceptions are thrown by this hook, execution will jump to + `modify_before_completion` with the thrown exception as the `response`. + """ + pass + + def modify_before_retry_loop( + self, context: InterceptorContext[Request, None, TransportRequest, None] + ) -> TransportRequest: + """A hook called before the retry loop is entered. + + This method has the ability to modify and return a new transport request of the + same type. + + This will always be called once per execution, except when a failure occurs + earlier in the request pipeline. + + If exceptions are thrown by this hook, execution will jump to + `modify_before_completion` with the thrown exception as the `response`. + + The transport request returned by this hook MUST be the same type of request + passed into this hook. If not, an exception will immediately occur. + """ + return context.transport_request + + def read_before_attempt( + self, context: InterceptorContext[Request, None, TransportRequest, None] + ) -> None: + """A hook called before each attempt at sending the transport request to the + service. + + Implementations MUST NOT modify the `request`, `response`, `transport_request`, + or `transport_response` in this hook. + + This will always be called once per attempt, except when a failure occurs + earlier in the request pipeline. This method will be called multiple times in + the event of retries. + + The `request` and `transport_request` of the context will always be available. + Other static properties will be None. In the event of retries, the context will + not include changes made in previous attempts (e.g. by request signers or other + interceptors). + + Exceptions thrown by this hook will be stored until all interceptors have had + their `read_before_attempt` invoked. Other hooks will then be skipped and + execution will jump to `modify_before_attempt_completion` with the thrown + exception as the `response` If multiple `read_before_attempt` methods throw + exceptions, the latest will be used and earlier ones will be logged and dropped. + """ + pass + + def modify_before_signing( + self, context: InterceptorContext[Request, None, TransportRequest, None] + ) -> TransportRequest: + """A hook called before the transport request is signed. + + This method has the ability to modify and return a new transport request of the + same type. + + This will always be called once per attempt, except when a failure occurs + earlier in the request pipeline. This method will be called multiple times in + the event of retries. + + The `request` and `transport_request` of the context will always be available. + Other static properties will be None. The `transport_request` may have been + modified by earlier `modify_before_signing` hooks, and may be modified further + by later hooks. In the event of retries, the context will not include changes + made in previous attempts (e.g. by request signers or other interceptors). + + If exceptions are thrown by this hook, execution will jump to + `modify_before_attempt_completion` with the thrown exception as the `response`. + + The transport request returned by this hook MUST be the same type of request + passed into this hook. If not, an exception will immediately occur. + """ + return context.transport_request + + def read_before_signing( + self, context: InterceptorContext[Request, None, TransportRequest, None] + ) -> None: + """A hook called before the transport request is signed. + + Implementations MUST NOT modify the `request`, `response`, `transport_request`, + or `transport_response` in this hook. + + This will always be called once per attempt, except when a failure occurs + earlier in the request pipeline. This method may be called multiple times in + the event of retries. The duration between invocation of this hook and + `read_after_signing` is very close to the amount of time spent signing the + request. + + The `request` and `transport_request` of the context will always be available. + Other static properties will be None. In the event of retries, the context will + not include changes made in previous attempts (e.g. by request signers or other + interceptors). + + If exceptions are thrown by this hook, execution will jump to + `modify_before_attempt_completion` with the thrown exception as the `response`. + """ + pass + + def read_after_signing( + self, context: InterceptorContext[Request, None, TransportRequest, None] + ) -> None: + """A hook called after the transport request is signed. + + Implementations MUST NOT modify the `request`, `response`, `transport_request`, + or `transport_response` in this hook. + + This will always be called once per attempt, except when a failure occurs + earlier in the request pipeline. This method may be called multiple times in + the event of retries. The duration between `read_before_signing` and the + invocation of this hook is very close to the amount of time spent signing the + request. + + The `request` and `transport_request` of the context will always be available. + Other static properties will be None. In the event of retries, the context will + not include changes made in previous attempts (e.g. by request signers or other + interceptors). + + If exceptions are thrown by this hook, execution will jump to + `modify_before_attempt_completion` with the thrown exception as the `response`. + """ + pass + + def modify_before_transmit( + self, context: InterceptorContext[Request, None, TransportRequest, None] + ) -> TransportRequest: + """A hook called before the transport request is sent to the service. + + This method has the ability to modify and return a new transport request of the + same type. + + This will always be called once per attempt, except when a failure occurs + earlier in the request pipeline. This method may be called multiple times in + the event of retries. + + The `request` and `transport_request` of the context will always be available. + Other static properties will be None. The `transport_request` may have been + modified by earlier `modify_before_signing` hooks, and may be modified further + by later hooks. In the event of retries, the context will not include changes + made in previous attempts (e.g. by request signers or other interceptors). + + If exceptions are thrown by this hook, execution will jump to + `modify_before_attempt_completion` with the thrown exception as the `response`. + + The transport request returned by this hook MUST be the same type of request + passed into this hook. If not, an exception will immediately occur. + """ + return context.transport_request + + def read_before_transmit( + self, context: InterceptorContext[Request, None, TransportRequest, None] + ) -> None: + """A hook called before the transport request is sent to the service. + + Implementations MUST NOT modify the `request`, `response`, `transport_request`, + or `transport_response` in this hook. + + This will always be called once per attempt, except when a failure occurs + earlier in the request pipeline. This method may be called multiple times in + the event of retries. The duration between invocation of this hook and + `read_after_transmit` is very close to the amount of time spent communicating + with the service. Depending on the protocol, the duration may not include the + time spent reading the response data. + + The `request` and `transport_request` of the context will always be available. + Other static properties will be None. In the event of retries, the context will + not include changes made in previous attempts (e.g. by request signers or other + interceptors). + + If exceptions are thrown by this hook, execution will jump to + `modify_before_attempt_completion` with the thrown exception as the `response`. + """ + pass + + def read_after_transmit( + self, + context: InterceptorContext[Request, None, TransportRequest, TransportResponse], + ) -> None: + """A hook called after the transport request is sent to the service and a + transport response is received. + + Implementations MUST NOT modify the `request`, `response`, `transport_request`, + or `transport_response` in this hook. + + This will always be called once per attempt, except when a failure occurs + earlier in the request pipeline. This method may be called multiple times in + the event of retries. The duration between `read_before_transmit` and the + invocation of this hook is very close to the amount of time spent communicating + with the service. Depending on the protocol, the duration may not include the + time spent reading the response data. + + The `request`, `transport_request`, and `transport_response` of the context + will always be available. Other static properties will be None. In the event of + retries, the context will not include changes made in previous attempts (e.g. + by request signers or other interceptors). + + If exceptions are thrown by this hook, execution will jump to + `modify_before_attempt_completion` with the thrown exception as the `response`. + """ + pass + + def modify_before_deserialization( + self, + context: InterceptorContext[Request, None, TransportRequest, TransportResponse], + ) -> TransportResponse: + """A hook called before the transport response is deserialized. + + This method has the ability to modify and return a new transport response of the + same type. + + This will always be called once per attempt, except when a failure occurs + earlier in the request pipeline. This method may be called multiple times in + the event of retries. + + The `request`, `transport_request`, and `transport_response` of the context + will always be available. Other static properties will be None. In the event of + retries, the context will not include changes made in previous attempts (e.g. + by request signers or other interceptors). The `transport_response` may have + been modified by earlier `modify_before_deserialization` hooks, and may be + modified further by later hooks. In the event of retries, the context will not + include changes made in previous attempts (e.g. by request signers or other + interceptors). + + If exceptions are thrown by this hook, execution will jump to + `modify_before_attempt_completion` with the thrown exception as the `response`. + + The transport response returned by this hook MUST be the same type of + response passed into this hook. If not, an exception will immediately occur. + """ + return context.transport_response + + def read_before_deserialization( + self, + context: InterceptorContext[Request, None, TransportRequest, TransportResponse], + ) -> None: + """A hook called before the transport response is deserialized. + + Implementations MUST NOT modify the `request`, `response`, `transport_request`, + or `transport_response` in this hook. + + This will always be called once per attempt, except when a failure occurs + earlier in the request pipeline. This method may be called multiple times in + the event of retries. The duration between invocation of this hook and + `read_after_deserialization` is very close to the amount of time spent + deserializing the service response. Depending on the protocol and operation, + the duration may include the time spent downloading the response data. + + The `request`, `transport_request`, and `transport_response` of the context + will always be available. Other static properties will be None. In the event of + retries, the context will not include changes made in previous attempts (e.g. + by request signers or other interceptors). + + If exceptions are thrown by this hook, execution will jump to + `modify_before_attempt_completion` with the thrown exception as the `response`. + """ + pass + + def read_after_deserialization( + self, + context: InterceptorContext[ + Request, Response, TransportRequest, TransportResponse + ], + ) -> None: + """A hook called after the transport response is deserialized. + + Implementations MUST NOT modify the `request`, `response`, `transport_request`, + or `transport_response` in this hook. + + This will always be called once per attempt, except when a failure occurs + earlier in the request pipeline. This method may be called multiple times in + the event of retries. The duration between `read_before_deserialization` + and the invocation of this hook is very close to the amount of time spent + deserializing the service response. Depending on the protocol and operation, + the duration may include the time spent downloading the response data. + + The `request`, `response`, `transport_request`, and `transport_response` of the + context will always be available. In the event of retries, the context will not + include changes made in previous attempts (e.g. by request signers or other + interceptors). + + If exceptions are thrown by this hook, execution will jump to + `modify_before_attempt_completion` with the thrown exception as the `response`. + """ + pass + + def modify_before_attempt_completion( + self, + context: InterceptorContext[ + Request, Response, TransportRequest, TransportResponse | None + ], + ) -> Response | Exception: + """A hook called when an attempt is completed. + + This method has the ability to modify and return a new output message or + exception matching the currently-executing operation. + + This will ALWAYS be called once per attempt, except when a failure occurs + before `read_before_attempt`. This method may be called multiple times in the + event of retries. + + The `request`, `response`, and `transport_request` of the context will always + be available. The `transport_response` will be available if a response was + received by the service for this attempt. In the event of retries, the context + will not include changes made in previous attempts (e.g. by request signers or + other interceptors). + + If exceptions are thrown by this hook, execution will jump to + `read_after_attempt` with the thrown exception as the `response`. + + Any output returned by this hook MUST match the operation being invoked. Any + exception type can be returned, replacing the `response` currently in the + context. + """ + return context.response + + def read_after_attempt( + self, + context: InterceptorContext[ + Request, Response, TransportRequest, TransportResponse | None + ], + ) -> None: + """A hook called when an attempt is completed. + + Implementations MUST NOT modify the `request`, `response`, `transport_request`, + or `transport_response` in this hook. + + This will ALWAYS be called once per attempt, as long as `read_before_attempt` + has been executed. + + The `request`, `response`, and `transport_request` of the context will always + be available. The `transport_response` will be available if a response was + received by the service for this attempt. In the event of retries, the context + will not include changes made in previous attempts (e.g. by request signers or + other interceptors). + + Exceptions thrown by this hook will be stored until all interceptors have had + their `read_after_attempt` invoked. If multiple `read_after_attempt` methods + throw exceptions, the latest will be used and earlier ones will be logged and + dropped. If the retry strategy determines that the execution is retryable, + execution will then jump to `read_before_attempt`. Otherwise, execution will + jump to `modify_before_completion` with the thrown exception as the `response`. + """ + pass + + def modify_before_completion( + self, + context: InterceptorContext[ + Request, Response, TransportRequest | None, TransportResponse | None + ], + ) -> Response | Exception: + """A hook called when an execution is completed. + + This method has the ability to modify and return a new output message or + exception matching the currently-executing operation. + + This will always be called once per execution. + + The `request` and `response` of the context will always be available. The + `transport_request` and `transport_response` will be available if the execution + proceeded far enough for them to be generated. + + If exceptions are thrown by this hook, execution will jump to + `read_after_execution` with the thrown exception as the `response`. + + Any output returned by this hook MUST match the operation being invoked. Any + exception type can be returned, replacing the `response` currently in the context. + """ + return context.response + + def read_after_execution( + self, + context: InterceptorContext[ + Request, Response, TransportRequest | None, TransportResponse | None + ], + ) -> None: + """A hook called when an execution is completed. + + Implementations MUST NOT modify the `request`, `response`, `transport_request`, + or `transport_response` in this hook. + + This will always be called once per execution. The duration between + `read_before_execution` and the invocation of this hook is very close to the + full duration of the execution. + + The `request` and `response` of the context will always be available. The + `transport_request` and `transport_response` will be available if the execution + proceeded far enough for them to be generated. + + Exceptions thrown by this hook will be stored until all interceptors have had + their `read_after_execution` invoked. The exception will then be treated as the + final response. If multiple `read_after_execution` methods throw exceptions, + the latest will be used and earlier ones will be logged and dropped. + """ + pass diff --git a/StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/smithy_python/interfaces/retries.py b/StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/smithy_python/interfaces/retries.py new file mode 100644 index 000000000..160954905 --- /dev/null +++ b/StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/smithy_python/interfaces/retries.py @@ -0,0 +1,132 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). You +# may not use this file except in compliance with the License. A copy of +# the License is located at +# +# http://aws.amazon.com/apache2.0/ +# +# or in the "license" file accompanying this file. This file is +# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF +# ANY KIND, either express or implied. See the License for the specific +# language governing permissions and limitations under the License. + +from dataclasses import dataclass +from enum import Enum +from typing import Protocol + + +class RetryErrorType(Enum): + """Classification of errors based on desired retry behavior.""" + + TRANSIENT = 1 + """A connection level error such as a socket timeout, socket connect error, TLS + negotiation timeout.""" + + THROTTLING = 2 + """The server explicitly told the client to back off, for example with HTTP status + 429 or 503.""" + + SERVER_ERROR = 3 + """A server error that should be retried and does not match the definition of + ``THROTTLING``.""" + + CLIENT_ERROR = 4 + """Doesn't count against any budgets. + + This could be something like a 401 challenge in HTTP. + """ + + +@dataclass(kw_only=True) +class RetryErrorInfo: + """Container for information about a retryable error.""" + + error_type: RetryErrorType + """Classification of error based on desired retry behavior.""" + + retry_after_hint: float | None = None + """Protocol hint for computing the timespan to delay before the next retry. + + This could come from HTTP's 'retry-after' header or similar mechanisms in other + protocols. + """ + + +class RetryBackoffStrategy(Protocol): + """Stateless strategy for computing retry delays based on retry attempt account.""" + + def compute_next_backoff_delay(self, retry_attempt: int) -> float: + """Calculate timespan in seconds to delay before next retry. + + :param retry_attempt: The index of the retry attempt that is about to be made + after the delay. The initial attempt, before any retries, is index ``0``, the + first retry attempt after the initial attempt failed is index ``1``, and so on. + """ + ... + + +@dataclass(kw_only=True) +class RetryToken(Protocol): + """Token issued by a :py:class:`RetryStrategy` for the next attempt.""" + + retry_count: int + """Retry count is the total number of attempts minus the initial attempt.""" + + retry_delay: float + """Delay in seconds to wait before the retry attempt.""" + + +class RetryStrategy(Protocol): + """Issuer of :py:class:`RetryToken`s.""" + + backoff_strategy: RetryBackoffStrategy + """The strategy used by returned tokens to compute delay duration values.""" + + max_attempts: int + """Upper limit on total attempt count (initial attempt plus retries).""" + + def acquire_initial_retry_token( + self, *, token_scope: str | None = None + ) -> RetryToken: + """Called before any retries (for the first attempt at the operation). + + :param token_scope: An arbitrary string accepted by the retry strategy to + separate tokens into scopes. + + :returns: A retry token, to be used for determining the retry delay, refreshing + the token after a failure, and recording success after success. + + :raises SmithyRetryException: If the retry strategy has no available tokens. + """ + ... + + def refresh_retry_token_for_retry( + self, *, token_to_renew: RetryToken, error_info: RetryErrorInfo + ) -> RetryToken: + """Replace an existing retry token from a failed attempt with a new token. + + After a failed operation call, this method is called to exchange a retry token + that was previously obtained by calling :py:func:`acquire_initial_retry_token` + or this method with a new retry token for the next attempt. This method can + either choose to allow another retry and send a new or updated token, or reject + the retry attempt and raise the error as exception. + + :param token_to_renew: The token used for the previous failed attempt. + + :param error_info: If no further retry is allowed, this information is used to + construct the exception. + + :raises SmithyRetryException: If no further retry attempts are allowed. + """ + ... + + def record_success(self, *, token: RetryToken) -> None: + """Return token after successful completion of an operation. + + Upon successful completion of the operation, a user calls this function + to record that the operation was successful. + + :param token: The token used for the previous successful attempt. + """ + ... diff --git a/StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/smithy_python/mediatypes.py b/StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/smithy_python/mediatypes.py new file mode 100644 index 000000000..ecb4eb1bf --- /dev/null +++ b/StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/smithy_python/mediatypes.py @@ -0,0 +1,36 @@ +import json +from typing import Any + + +class JsonString(str): + """A string that contains json data which can be lazily loaded.""" + + _json = None + + def as_json(self) -> Any: + if not self._json: + self._json = json.loads(self) + return self._json + + @staticmethod + def from_json(j: Any) -> "JsonString": + json_string = JsonString(json.dumps(j)) + json_string._json = j + return json_string + + +class JsonBlob(bytes): + """Bytes that contain json data which can be lazily loaded.""" + + _json = None + + def as_json(self) -> Any: + if not self._json: + self._json = json.loads(self.decode(encoding="utf-8")) + return self._json + + @staticmethod + def from_json(j: Any) -> "JsonBlob": + json_string = JsonBlob(json.dumps(j).encode(encoding="utf-8")) + json_string._json = j + return json_string diff --git a/StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/smithy_python/protocolutils.py b/StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/smithy_python/protocolutils.py new file mode 100644 index 000000000..6c26f4263 --- /dev/null +++ b/StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/smithy_python/protocolutils.py @@ -0,0 +1,69 @@ +import json +from typing import NamedTuple + +from .interfaces.http import HTTPResponse +from .types import Document +from .utils import expect_type + +_REST_JSON_CODE_HEADER = "x-amzn-errortype" + +_REST_JSON_CODE_KEYS = {"__type", "code"} + +_REST_JSON_MESSAGE_KEYS = {"message", "errormessage", "error_message"} + + +class RestJsonErrorInfo(NamedTuple): + """Generic error information from a RestJson protocol error.""" + + code: str + """The error code.""" + + message: str + """The generic error message. + + A modeled error may have the error bound somewhere else. This is based off of + checking the most common locations and is intended for use with excpetions that + either didn't model the message or which are unknown. + """ + + json_body: dict[str, Document] | None = None + """The HTTP response body parsed as JSON.""" + + +async def parse_rest_json_error_info( + http_response: HTTPResponse, check_body: bool = True +) -> RestJsonErrorInfo: + """Parses generic RestJson error info from an HTTP response. + + :param http_response: The HTTP response to parse. + :param check_body: Whether to check the body for the code / message. + :returns: The parsed error information. + """ + code: str | None = None + message: str | None = None + json_body: dict[str, Document] | None = None + + for field in http_response.fields: + if field.name.lower() == _REST_JSON_CODE_HEADER: + code = field.values[0] + + if check_body: + if body := await http_response.consume_body(): + json_body = json.loads(body) + + if json_body: + for key, value in json_body.items(): + key_lower = key.lower() + if not code and key_lower in _REST_JSON_CODE_KEYS: + code = expect_type(str, value) + if not message and key_lower in _REST_JSON_MESSAGE_KEYS: + message = expect_type(str, value) + + # Normalize the error code. Some services may try to send a fully-qualified shape + # ID or a URI, but we don't want to include those. + if code: + if "#" in code: + code = code.split("#")[1] + code = code.split(":")[0] + + return RestJsonErrorInfo(code or "Unknown", message or "Unknown", json_body) diff --git a/StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/smithy_python/py.typed b/StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/smithy_python/py.typed new file mode 100644 index 000000000..f5642f79f --- /dev/null +++ b/StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/smithy_python/py.typed @@ -0,0 +1 @@ +Marker diff --git a/StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/smithy_python/types.py b/StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/smithy_python/types.py new file mode 100644 index 000000000..5c317982a --- /dev/null +++ b/StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/smithy_python/types.py @@ -0,0 +1,5 @@ +from typing import Mapping, Sequence, TypeAlias + +Document: TypeAlias = ( + Mapping[str, "Document"] | Sequence["Document"] | str | int | float | bool | None +) diff --git a/StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/smithy_python/utils.py b/StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/smithy_python/utils.py new file mode 100644 index 000000000..b79e0eab5 --- /dev/null +++ b/StandardLibrary/runtimes/python/libs/aws-cryptography-internal-smithy-python/smithy_python/utils.py @@ -0,0 +1,275 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). You +# may not use this file except in compliance with the License. A copy of +# the License is located at +# +# http://aws.amazon.com/apache2.0/ +# +# or in the "license" file accompanying this file. This file is +# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF +# ANY KIND, either express or implied. See the License for the specific +# language governing permissions and limitations under the License. + +import re +from datetime import datetime, timedelta, timezone +from decimal import Decimal +from math import isinf, isnan +from types import UnionType +from typing import Any, TypeVar, overload + +from .exceptions import ExpectationNotMetException + +RFC3339 = "%Y-%m-%dT%H:%M:%SZ" +# Same as RFC3339, but with microsecond precision. +RFC3339_MICRO = "%Y-%m-%dT%H:%M:%S.%fZ" + + +def ensure_utc(value: datetime) -> datetime: + """Ensures that the given datetime is a UTC timezone-aware datetime. + + If the datetime isn't timezone-aware, its timezone is set to UTC. If it is + aware, it's replaced with the equivalent datetime under UTC. + + :param value: A datetime object that may or may not be timezone-aware. + :returns: A UTC timezone-aware equivalent datetime. + """ + if value.tzinfo is None: + return value.replace(tzinfo=timezone.utc) + else: + return value.astimezone(timezone.utc) + + +# Python is way more permissive on value of non-numerical floats than Smithy is, so we +# need to compare potential string values against this set of values that Smithy +# generally permits. +_NON_NUMERICAL_FLOATS = {"NaN", "Infinity", "-Infinity"} + + +def limited_parse_float(value: Any) -> float: + """Asserts a value is a float or a limited set of non-numerical strings and returns + it as a float. + + :param value: An object that is expected to be a float. + :returns: The given value as a float. + :raises SmithyException: If the value is not a float or one of the strings ``NaN``, + ``Infinity``, or ``-Infinity``. + """ + # TODO: add limited bounds checking + if isinstance(value, str) and value in _NON_NUMERICAL_FLOATS: + return float(value) + + return expect_type(float, value) + + +def epoch_seconds_to_datetime(value: int | float) -> datetime: + """Parse numerical epoch timestamps (seconds since 1970) into a datetime in UTC. + + Falls back to using ``timedelta`` when ``fromtimestamp`` raises ``OverflowError``. + From Python's ``fromtimestamp`` documentation: "This may raise OverflowError, if the + timestamp is out of the range of values supported by the platform C localtime() + function, and OSError on localtime() failure. It's common for this to be restricted + to years from 1970 through 2038." This affects 32-bit systems. + """ + try: + return datetime.fromtimestamp(value, tz=timezone.utc) + except OverflowError: + epoch_zero = datetime(1970, 1, 1, 0, 0, 0, tzinfo=timezone.utc) + return epoch_zero + timedelta(seconds=value) + + +_T = TypeVar("_T") + + +@overload +def expect_type(typ: type[_T], value: Any) -> _T: + ... + + +# For some reason, mypy and other type checkers don't treat Union like a full type +# despite it being checkable with isinstance and other methods. This essentially means +# we can't pass back the given type when we're given a union. So instead we have to +# return Any. +@overload +def expect_type(typ: UnionType, value: Any) -> Any: + ... + + +def expect_type(typ: UnionType | type, value: Any) -> Any: + """Asserts a value is of the given type and returns it unchanged. + + This performs both a runtime assertion and type narrowing during type checking + similar to ``typing.cast``. If the runtime assertion is not needed, ``typing.cast`` + should be preferred. + + :param typ: The expected type. + :param value: The value which is expected to be the given type. + :returns: The given value cast as the given type. + :raises SmithyException: If the value does not match the type. + """ + if not isinstance(value, typ): + raise ExpectationNotMetException( + f"Expected {typ}, found {type(value)}: {value}" + ) + return value + + +def split_every(given: str, split_char: str, n: int) -> list[str]: + """Splits a string every nth instance of the given character. + + :param given: The string to split. + :param split_char: The character to split on. + :param n: The number of instances of split_char to see before each split. + :returns: A list of strings. + """ + split = given.split(split_char) + return [split_char.join(split[i : i + n]) for i in range(0, len(split), n)] + + +def strict_parse_bool(given: str) -> bool: + """Strictly parses a boolean from string. + + :param given: A string that is expected to contain either "true" or "false". + :returns: The given string parsed to a boolean. + :raises ExpectationNotMetException: if the given string is neither "true" nor + "false". + """ + match given: + case "true": + return True + case "false": + return False + case _: + raise ExpectationNotMetException( + f"Expected 'true' or 'false', found: {given}" + ) + + +# A regex for Smithy floats. It matches JSON-style numbers. +_FLOAT_REGEX = re.compile( + r""" + ( # Opens the numeric float group. + -? # The integral may start with a negative sign, but not a positive one. + (?:0|[1-9]\d*) # The integral may not have leading 0s unless it is exactly 0. + (?:\.\d+)? # There may be a fraction starting with a period and containing at + # least one number. + (?: # Opens the exponent group. + [eE] # The exponent starts with a case-insensitive e + [+-]? # The exponent may have a positive or negative sign. + \d+ # The exponent must have one or more digits. + )? # Closes the exponent group and makes it optional. + ) # Closes the numeric float group. + |(-?Infinity) # If the float isn't numeric, it may be Infinity or -Infinity + |(NaN) # If the float isn't numeric, it may also be NaN + """, + re.VERBOSE, +) + + +def strict_parse_float(given: str) -> float: + """Strictly parses a float from a string. + + Unlike float(), this forbids the use of "inf" and case-sensitively matches + Infinity and NaN. + + :param given: A string that is expected to contain a float. + :returns: The given string parsed to a float. + :raises ExpectationNotMetException: If the given string isn't a float. + """ + if _FLOAT_REGEX.fullmatch(given): + return float(given) + raise ExpectationNotMetException(f"Expected float, found: {given}") + + +def serialize_float(given: float | Decimal) -> str: + """Serializes a float to a string. + + This ensures non-numeric floats are serialized correctly, and ensures that there is + a fractional part. + + :param given: A float or Decimal to be serialized. + :returns: The string representation of the given float. + """ + if isnan(given): + return "NaN" + if isinf(given): + return "-Infinity" if given < 0 else "Infinity" + + if isinstance(given, Decimal): + given = given.normalize() + + result = str(given) + if result.isnumeric(): + result += ".0" + return result + + +def limited_serialize_float(given: float) -> str | float: + """Serializes non-numeric floats to strings. + + Numeric floats are returned without alteration. + + :param given: A float to be conditionally serialized. + :returns: The given float as a float or string. + """ + if isnan(given): + return "NaN" + if isinf(given): + return "-Infinity" if given < 0 else "Infinity" + + return given + + +def serialize_rfc3339(given: datetime) -> str: + """Serializes a datetime into an RFC3339 string representation. + + If ``microseconds`` is 0, no fractional part is serialized. + + :param given: The datetime to serialize. + :returns: An RFC3339 formatted timestamp. + """ + if given.microsecond != 0: + return given.strftime(RFC3339_MICRO) + else: + return given.strftime(RFC3339) + + +def serialize_epoch_seconds(given: datetime) -> float: + """Serializes a datetime into a string containing the epoch seconds. + + If ``microseconds`` is 0, no fractional part is serialized. + + :param given: The datetime to serialize. + :returns: A string containing the seconds since the UNIX epoch. + """ + result = given.timestamp() + if given.microsecond == 0: + result = int(result) + return result + + +def remove_dot_segments(path: str, remove_consecutive_slashes: bool = False) -> str: + """Removes dot segments from a path per :rfc:`3986#section-5.2.4`. + + Optionally removes consecutive slashes. + + :param path: The path to modify. + :param remove_consecutive_slashes: Whether to remove consecutive slashes. + :returns: The path with dot segments removed. + """ + output = [] + for segment in path.split("/"): + if segment == ".": + continue + elif segment != "..": + output.append(segment) + elif output: + output.pop() + if path.startswith("/") and (not output or output[0]): + output.insert(0, "") + if output and path.endswith(("/.", "/..")): + output.append("") + result = "/".join(output) + if remove_consecutive_slashes: + result = result.replace("//", "/") + return result diff --git a/StandardLibrary/runtimes/python/pyproject.toml b/StandardLibrary/runtimes/python/pyproject.toml new file mode 100644 index 000000000..fa4c9cfb3 --- /dev/null +++ b/StandardLibrary/runtimes/python/pyproject.toml @@ -0,0 +1,43 @@ +[tool.poetry] +name = "aws-cryptography-internal-standard-library" +version = "0.1.0" +description = "" +authors = ["AWS Crypto Tools "] +packages = [ + { include = "smithy_dafny_standard_library", from = "src" }, + # TODO: Depend on PyPi once Smithy-Python publishes their Python package there + { include = "smithy_python", from = "libs/aws-cryptography-internal-smithy-python" }, +] +# Include generated internaldafny files in package distributions, +# even though they are not included in version control +include = [ + "**/internaldafny/generated/*.py", +] + +[tool.poetry.dependencies] +python = "^3.11.0" +pytz = "^2023.3.post1" +# TODO: Longer-term, write something to pull this in from the project's project.properties file +DafnyRuntimePython = "~4.8.0" + +# Package testing + +[tool.poetry.group.test] +optional = true + +[tool.poetry.group.test.dependencies] +pytest = "^7.4.0" + +# Package release + +[tool.poetry.group.release] +optional = true + +[tool.poetry.group.release.dependencies] +poetry = "1.8.3" +twine = "5.1.1" +wheel = "0.38.4" + +[build-system] +requires = ["poetry-core"] +build-backend = "poetry.core.masonry.api" diff --git a/StandardLibrary/runtimes/python/src/smithy_dafny_standard_library/__init__.py b/StandardLibrary/runtimes/python/src/smithy_dafny_standard_library/__init__.py new file mode 100644 index 000000000..b9427e19d --- /dev/null +++ b/StandardLibrary/runtimes/python/src/smithy_dafny_standard_library/__init__.py @@ -0,0 +1,8 @@ +# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 + +# Initialize generated Dafny +from .internaldafny.generated import module_ + +# Initialize externs +from .internaldafny import extern diff --git a/StandardLibrary/runtimes/python/src/smithy_dafny_standard_library/internaldafny/extern/ConcurrentCall.py b/StandardLibrary/runtimes/python/src/smithy_dafny_standard_library/internaldafny/extern/ConcurrentCall.py new file mode 100644 index 000000000..8f00b4942 --- /dev/null +++ b/StandardLibrary/runtimes/python/src/smithy_dafny_standard_library/internaldafny/extern/ConcurrentCall.py @@ -0,0 +1,25 @@ +import smithy_dafny_standard_library.internaldafny.generated.ConcurrentCall + +from threading import Thread + +class default__: + @staticmethod + def ConcurrentCall(callee, serial_iters, concurrent_iters): + thread_list = [] + for i in range(0, concurrent_iters): + local_num = i + thread_list.append( + Thread(target=default__._executor_call, args=(callee, serial_iters, local_num)) + ) + + for i in range(0, concurrent_iters): + thread_list[i].start() + + for i in range(0, concurrent_iters): + thread_list[i].join() + + def _executor_call(callee, serial_iters, local_num): + for j in range(0, serial_iters): + callee.call(j, local_num) + +smithy_dafny_standard_library.internaldafny.generated.ConcurrentCall.default__ = default__ \ No newline at end of file diff --git a/StandardLibrary/runtimes/python/src/smithy_dafny_standard_library/internaldafny/extern/DafnyLibraries.py b/StandardLibrary/runtimes/python/src/smithy_dafny_standard_library/internaldafny/extern/DafnyLibraries.py new file mode 100644 index 000000000..4c2c4f2e5 --- /dev/null +++ b/StandardLibrary/runtimes/python/src/smithy_dafny_standard_library/internaldafny/extern/DafnyLibraries.py @@ -0,0 +1,132 @@ +import _dafny +from pathlib import Path +import threading + +import smithy_dafny_standard_library.internaldafny.generated.DafnyLibraries +from smithy_dafny_standard_library.internaldafny.generated.DafnyLibraries import * +import smithy_dafny_standard_library.internaldafny.generated.Wrappers as Wrappers + +# This is copy-pasted from DafnyStandardLibraries: +# https://github.com/dafny-lang/dafny/blob/f01af4a4e86a038ed4ea9f81464b2c9bca1955e4/Source/DafnyStandardLibraries/src/Std_Concurrent.py + +class Lock: + def ctor__(self): + pass + + def __init__(self) -> None: + self.lock = threading.Lock() + + def Lock__(self): + self.lock.acquire() + + def Unlock(self): + self.lock.release() + + +class MutableMap(smithy_dafny_standard_library.internaldafny.generated.DafnyLibraries.MutableMap): + def ctor__(self): + pass + + def __init__(self) -> None: + self.map = dict() + self.lock = Lock() + + def Keys(self): + self.lock.Lock__() + s = self.map.keys() + self.lock.Unlock() + return _dafny.Set(s) + + def HasKey(self, k): + self.lock.Lock__() + b = k in self.map + self.lock.Unlock() + return b + + def Values(self): + self.lock.Lock__() + s = self.map.values() + self.lock.Unlock() + return _dafny.Set(s) + + def Items(self): + self.lock.Lock__() + s = self.map.items() + self.lock.Unlock() + return _dafny.Set(s) + + def Put(self, k, v): + self.lock.Lock__() + self.map[k] = v + self.lock.Unlock() + + def Get(self, k): + self.lock.Lock__() + try: + v = self.map.get(k) + except KeyError: + self.lock.Unlock() + return Wrappers.Option_None() + self.lock.Unlock() + return Wrappers.Option_Some(v) + + def Remove(self, k): + self.lock.Lock__() + self.map.pop(k, None) + self.lock.Unlock() + + def Size(self): + self.lock.Lock__() + l = len(self.map) + self.lock.Unlock() + return l + + # Added by Crypto Tools. + # Crypto Tools externs refer a `Select` method + # that does not exist on the Dafny implementation. + def Select(self, k): + return self.Get(k).value + +# This is copy-pasted from DafnyStandardLibraries: +# https://github.com/dafny-lang/dafny/blob/f01af4a4e86a038ed4ea9f81464b2c9bca1955e4/Source/DafnyStandardLibraries/src/Std_FileIOInternalExterns.py + +import traceback +import os.path +import pathlib + +class FileIO: + @staticmethod + def INTERNAL_WriteBytesToFile(path, contents): + path_str = path.VerbatimString(False) + contents_bytes = bytes(contents) + + try: + pathlib.Path(path_str).parent.mkdir(parents=True, exist_ok=True) + + with open(path_str, mode="wb") as file: + contents = file.write(contents_bytes) + return (False, _dafny.Seq()) + except: + exc_str = traceback.format_exc() + exc_seq = _dafny.Seq(exc_str) + return (True, exc_seq) + + @staticmethod + def INTERNAL_ReadBytesFromFile(path): + path_str = path.VerbatimString(False) + try: + with open(path_str, mode="rb") as file: + contents = file.read() + contents_seq = _dafny.Seq(contents) + return (False, contents_seq, _dafny.Seq()) + except: + exc_str = traceback.format_exc() + exc_seq = _dafny.Seq(exc_str) + return (True, _dafny.Seq(), exc_seq) + +# Export externs +smithy_dafny_standard_library.internaldafny.generated.DafnyLibraries.FileIO = FileIO +smithy_dafny_standard_library.internaldafny.generated.DafnyLibraries.MutableMap = MutableMap + +import smithy_dafny_standard_library.internaldafny.generated.FileIO +smithy_dafny_standard_library.internaldafny.generated.FileIO.DafnyLibraries = smithy_dafny_standard_library.internaldafny.generated.DafnyLibraries diff --git a/StandardLibrary/runtimes/python/src/smithy_dafny_standard_library/internaldafny/extern/SortedSets.py b/StandardLibrary/runtimes/python/src/smithy_dafny_standard_library/internaldafny/extern/SortedSets.py new file mode 100644 index 000000000..dbf0b4afb --- /dev/null +++ b/StandardLibrary/runtimes/python/src/smithy_dafny_standard_library/internaldafny/extern/SortedSets.py @@ -0,0 +1,48 @@ +from smithy_dafny_standard_library.internaldafny.generated.SortedSets import * +import smithy_dafny_standard_library.internaldafny.generated.SortedSets +import _dafny + +class default__: + + @staticmethod + def SetToSequence(input_set): + return _dafny.Seq(input_set.Elements) + + @staticmethod + def SetToOrderedSequence(input_set, is_less_than): + seq_as_list = list(_dafny.Seq(input_set.Elements).Elements) + comparer = Comparer(is_less_than) + from functools import cmp_to_key + sorted_list = sorted(seq_as_list, key=cmp_to_key(comparer.compare)) + return _dafny.Seq(sorted_list) + + @staticmethod + def SetToOrderedSequence2(input_set, is_less_than): + return default__.SetToOrderedSequence(input_set, is_less_than) + +class Comparer: + is_less_than: Any + + def __init__(self, is_less_than): + self.is_less_than = is_less_than + + def compare(self, x, y): + x_list = list(x.Elements) + y_list = list(y.Elements) + + for i in range(0, min(len(x_list), len(y_list))): + if (self.is_less_than(x_list[i], y_list[i])): + return -1 + if (self.is_less_than(y_list[i], x_list[i])): + return 1 + # Reached the end of one array. Either they are equal, or the + # one which is shorter should be considered "less than" + if len(x_list) < len(y_list): + return -1 + elif len(x_list) == len(y_list): + return 0 + elif len(x_list) > len(y_list): + return 1 + +# Export extern +smithy_dafny_standard_library.internaldafny.generated.SortedSets.default__ = default__ \ No newline at end of file diff --git a/StandardLibrary/runtimes/python/src/smithy_dafny_standard_library/internaldafny/extern/Time.py b/StandardLibrary/runtimes/python/src/smithy_dafny_standard_library/internaldafny/extern/Time.py new file mode 100644 index 000000000..93b7d5327 --- /dev/null +++ b/StandardLibrary/runtimes/python/src/smithy_dafny_standard_library/internaldafny/extern/Time.py @@ -0,0 +1,21 @@ +import datetime +import pytz +import _dafny + +import smithy_dafny_standard_library.internaldafny.generated.Time +import smithy_dafny_standard_library.internaldafny.generated.Wrappers as Wrappers + +class default__: + def CurrentRelativeTime(): + return datetime.datetime.now(tz = pytz.UTC).timestamp() * 1000 + + def GetCurrentTimeStamp(): + try: + d = datetime.datetime.now(tz = pytz.UTC).strftime("%Y-%m-%dT%H:%M:%S.%fZ") + return Wrappers.Result_Success(_dafny.Seq(_dafny.string_of(d))) + except Exception as e: + return Wrappers.Result_Failure(_dafny.string_of("Could not generate a timestamp in ISO8601: " + e)) + + +# Export externs +smithy_dafny_standard_library.internaldafny.generated.Time.default__ = default__ \ No newline at end of file diff --git a/StandardLibrary/runtimes/python/src/smithy_dafny_standard_library/internaldafny/extern/UTF8.py b/StandardLibrary/runtimes/python/src/smithy_dafny_standard_library/internaldafny/extern/UTF8.py new file mode 100644 index 000000000..e0ed1d392 --- /dev/null +++ b/StandardLibrary/runtimes/python/src/smithy_dafny_standard_library/internaldafny/extern/UTF8.py @@ -0,0 +1,133 @@ +""" +Extern UTF8 encode and decode methods. + +Note: +Python represents Unicode-escaped characters based on their presence in the Basic Multilingual Plane (BMP). +The BMP includes characters from U+0000 to U+FFFF (or, 0 <= ord(chr) < 65535; or, 0x0 <= hex(chr) < 0xFFFF). +Note that this is the range of characters that can fit into a single UTF-16 code unit (2 bytes). + +If a Unicode-escaped character is inside the BMP, Python internally represents it +as a single UTF-16-encoded code unit. +ex. +"\u2386" == '⎆' --> ord('⎆') == 9094 --> 9094 < 65535 --> in BMP +Since "\u2386" is in the BMP, Python internally represents it as '⎆': + +``` +>>> s = "\u2386" +>>> s +'⎆' +``` + +However, if a Unicode-escaped character is outside the BMP, Python internally represents it +as a Unicode-escaped character using surrogate pairs. +ex. +"\uD808\uDC00" == '𒀀' --> ord('𒀀') == 73728 --> 73728 > 65535 --> outside BMP +Since "\uD808\uDC00" is outside the BMP, Python internally represents it as "\uD808\uDC00": + +``` +>>> s = "\uD808\uDC00" +>>> s +'\ud808\udc00' +``` + +Dafny expects its strings to be UTF-16 code units. +However, the `.decode()` method with 'surrogatepass' leaves '\ud808\udc00' as '𒀀', +which, if passed directly to Dafny, will be interpreted as a single UTF-32 code unit, +instead of the desired two UTF-16 code units. + +To correct this, the extern implementations +convert between Dafny Seqs of UTF-16 code units (handling multi-byte surrogate pairs) +and Dafny Seqs of UTF-8 bytes. +""" +import _dafny +import struct + +import smithy_dafny_standard_library.internaldafny.generated.UTF8 +from smithy_dafny_standard_library.internaldafny.generated.UTF8 import * + + +# Extend the Dafny-generated class with our extern methods +class default__(smithy_dafny_standard_library.internaldafny.generated.UTF8.default__): + + @staticmethod + def Encode(dafny_utf16_code_units): + try: + return Wrappers.Result_Success(_dafny.Seq( + default__._strict_tostring(dafny_utf16_code_units).encode('utf-8') + )) + # Catch both UnicodeEncodeError and UnicodeDecodeError. + # The `try` block involves both encoding and decoding. + # OverflowError is possibly raised at `_strict_tostring`'s `ord(c).to_bytes` + # if the char `c` is not valid. + except (UnicodeDecodeError, UnicodeEncodeError, OverflowError): + return Wrappers.Result_Failure(_dafny.Seq("Could not encode input to Dafny Bytes.")) + + @staticmethod + def _strict_tostring(dafny_ascii_string): + """ + Converts a Dafny Seq of UTF-16 code units + into a string that can be encoded with Python's built-in `.encode('utf-8')`. + + This encoding-decoding allows subsequent UTF8 encodings + to handle surrogates as expected by Dafny code. + + This is exactly the `_dafny.string_from_utf_16` method from the DafnyRuntime, + except with two changes + 1) + `errors = 'strict'` here, + instead of + `errors = 'replace'` in the `_dafny.string_from_utf_16` function. + `strict` will throw an exception for invalid encodings, allowing us + to detect invalid encodings and raise exceptions, + while `replace` will fail silently. + + 2) + Using big-endian internally instead of little-endian. + :param s: + :return: + """ + return b''\ + .join([c.to_bytes(2, byteorder="big") \ + if isinstance(c, int) \ + else ord(c).to_bytes(2, byteorder="big") \ + for c in dafny_ascii_string])\ + .decode("utf-16-be", errors = 'strict') + + @staticmethod + def Decode(dafny_utf8): + try: + utf8_str = bytes(dafny_utf8).decode('utf-8') + unicode_escaped_utf8_str = default__._reverse_strict_tostring(utf8_str) + return Wrappers.Result_Success(unicode_escaped_utf8_str) + # Catch both UnicodeEncodeError and UnicodeDecodeError. + # The `try` block involves both encoding and decoding. + # ValueError and TypeError are possibly raised at `_reverse_strict_tostring`'s `chr()`. + # struct.error is possibly raised at `struct.unpack`. + except (UnicodeDecodeError, UnicodeEncodeError, ValueError, TypeError, struct.error): + return Wrappers.Result_Failure(_dafny.Seq("Could not decode input from Dafny Bytes.")) + + + @staticmethod + def _reverse_strict_tostring(utf8_str): + """ + Converts a string into a Dafny Seq of unicode-escaped ASCII characters. + This is the inverse of the `_strict_tostring` function in this file. + :param s: + :return: + """ + utf16_bytes = utf8_str.encode("utf-16-be", errors = "strict") + out = [] + # len(b)/2 is an integer by construction of UTF-16 encoding (2 bytes per encoded character) + for i in range(int(len(utf16_bytes)/2)): + # Take two consecutive bytes; + utf_16_bytepair = utf16_bytes[2*i:2*i+2] + # Unpack them into an ordinal representation; + packed_bytes = struct.unpack('>H', utf_16_bytepair) + # Convert into a character representation; + char_representation = chr(packed_bytes[0]) + # Append to returned string + out.append(char_representation) + return _dafny.Seq(out) + +# Export externs +smithy_dafny_standard_library.internaldafny.generated.UTF8.default__ = default__ \ No newline at end of file diff --git a/StandardLibrary/runtimes/python/src/smithy_dafny_standard_library/internaldafny/extern/UUID.py b/StandardLibrary/runtimes/python/src/smithy_dafny_standard_library/internaldafny/extern/UUID.py new file mode 100644 index 000000000..c4fefb2e6 --- /dev/null +++ b/StandardLibrary/runtimes/python/src/smithy_dafny_standard_library/internaldafny/extern/UUID.py @@ -0,0 +1,39 @@ +import _dafny +import uuid + +import smithy_dafny_standard_library.internaldafny.generated.Wrappers as Wrappers +from smithy_dafny_standard_library.internaldafny.generated.UUID import * +import smithy_dafny_standard_library.internaldafny.generated.UUID + +class default__: + @staticmethod + def ToByteArray(dafny_str): + try: + uuid_from_str = uuid.UUID(''.join(dafny_str.Elements)) + return Wrappers.Result_Success(_dafny.Seq(uuid_from_str.bytes)) + except Exception as e: + return Wrappers.Result_Failure(_dafny.string_of( + "Could not convert UUID to byte array: " + str(e) + )) + + @staticmethod + def FromByteArray(dafny_b): + try: + native_bytes = bytes(dafny_b.Elements) + uuid_from_bytes = uuid.UUID(bytes=native_bytes) + return Wrappers.Result_Success(_dafny.Seq(str(uuid_from_bytes))) + except Exception as e: + return Wrappers.Result_Failure(_dafny.string_of( + "Could not convert byte array to UUID: " + str(e) + )) + + @staticmethod + def GenerateUUID(): + try: + generated_uuid = uuid.uuid4() + return Wrappers.Result_Success(_dafny.Seq(str(generated_uuid))) + except Exception as e: + return Wrappers.Result_Failure(_dafny.Seq("Could not generate a UUID: " + str(e))) + +# Export externs +smithy_dafny_standard_library.internaldafny.generated.UUID.default__ = default__ \ No newline at end of file diff --git a/StandardLibrary/runtimes/python/src/smithy_dafny_standard_library/internaldafny/extern/__init__.py b/StandardLibrary/runtimes/python/src/smithy_dafny_standard_library/internaldafny/extern/__init__.py new file mode 100644 index 000000000..bbaeda338 --- /dev/null +++ b/StandardLibrary/runtimes/python/src/smithy_dafny_standard_library/internaldafny/extern/__init__.py @@ -0,0 +1,8 @@ +from . import ( + ConcurrentCall, + DafnyLibraries, + SortedSets, + Time, + UTF8, + UUID, +) \ No newline at end of file diff --git a/StandardLibrary/runtimes/python/src/smithy_dafny_standard_library/internaldafny/generated/dafny_src-py.dtr b/StandardLibrary/runtimes/python/src/smithy_dafny_standard_library/internaldafny/generated/dafny_src-py.dtr new file mode 100644 index 000000000..710d07681 --- /dev/null +++ b/StandardLibrary/runtimes/python/src/smithy_dafny_standard_library/internaldafny/generated/dafny_src-py.dtr @@ -0,0 +1,251 @@ +file_format_version = "1.0" +dafny_version = "4.8.0.0" +[options_by_module.Wrappers] +legacy-module-names = false +python-module-name = "smithy_dafny_standard_library.internaldafny.generated" +[options_by_module.Relations] +legacy-module-names = false +python-module-name = "smithy_dafny_standard_library.internaldafny.generated" +[options_by_module."Seq.MergeSort"] +legacy-module-names = false +python-module-name = "smithy_dafny_standard_library.internaldafny.generated" +[options_by_module.Math] +legacy-module-names = false +python-module-name = "smithy_dafny_standard_library.internaldafny.generated" +[options_by_module.Seq] +legacy-module-names = false +python-module-name = "smithy_dafny_standard_library.internaldafny.generated" +[options_by_module.BoundedInts] +legacy-module-names = false +python-module-name = "smithy_dafny_standard_library.internaldafny.generated" +[options_by_module.AbstractUnicodeStrings] +legacy-module-names = false +python-module-name = "smithy_dafny_standard_library.internaldafny.generated" +[options_by_module.Unicode] +legacy-module-names = false +python-module-name = "smithy_dafny_standard_library.internaldafny.generated" +[options_by_module.Functions] +legacy-module-names = false +python-module-name = "smithy_dafny_standard_library.internaldafny.generated" +[options_by_module.UnicodeEncodingForm] +legacy-module-names = false +python-module-name = "smithy_dafny_standard_library.internaldafny.generated" +[options_by_module.Utf8EncodingForm] +legacy-module-names = false +python-module-name = "smithy_dafny_standard_library.internaldafny.generated" +[options_by_module.Utf16EncodingForm] +legacy-module-names = false +python-module-name = "smithy_dafny_standard_library.internaldafny.generated" +[options_by_module.UnicodeStrings] +legacy-module-names = false +python-module-name = "smithy_dafny_standard_library.internaldafny.generated" +[options_by_module.FileIO] +legacy-module-names = false +python-module-name = "smithy_dafny_standard_library.internaldafny.generated" +[options_by_module.GeneralInternals] +legacy-module-names = false +python-module-name = "smithy_dafny_standard_library.internaldafny.generated" +[options_by_module.MulInternalsNonlinear] +legacy-module-names = false +python-module-name = "smithy_dafny_standard_library.internaldafny.generated" +[options_by_module.MulInternals] +legacy-module-names = false +python-module-name = "smithy_dafny_standard_library.internaldafny.generated" +[options_by_module.Mul] +legacy-module-names = false +python-module-name = "smithy_dafny_standard_library.internaldafny.generated" +[options_by_module.ModInternalsNonlinear] +legacy-module-names = false +python-module-name = "smithy_dafny_standard_library.internaldafny.generated" +[options_by_module.DivInternalsNonlinear] +legacy-module-names = false +python-module-name = "smithy_dafny_standard_library.internaldafny.generated" +[options_by_module.ModInternals] +legacy-module-names = false +python-module-name = "smithy_dafny_standard_library.internaldafny.generated" +[options_by_module.DivInternals] +legacy-module-names = false +python-module-name = "smithy_dafny_standard_library.internaldafny.generated" +[options_by_module.DivMod] +legacy-module-names = false +python-module-name = "smithy_dafny_standard_library.internaldafny.generated" +[options_by_module.Power] +legacy-module-names = false +python-module-name = "smithy_dafny_standard_library.internaldafny.generated" +[options_by_module.Logarithm] +legacy-module-names = false +python-module-name = "smithy_dafny_standard_library.internaldafny.generated" +[options_by_module.StandardLibraryInterop] +legacy-module-names = false +python-module-name = "smithy_dafny_standard_library.internaldafny.generated" +[options_by_module."StandardLibrary.UInt"] +legacy-module-names = false +python-module-name = "smithy_dafny_standard_library.internaldafny.generated" +[options_by_module."StandardLibrary.String"] +legacy-module-names = false +python-module-name = "smithy_dafny_standard_library.internaldafny.generated" +[options_by_module.StandardLibrary] +legacy-module-names = false +python-module-name = "smithy_dafny_standard_library.internaldafny.generated" +[options_by_module.UUID] +legacy-module-names = false +python-module-name = "smithy_dafny_standard_library.internaldafny.generated" +[options_by_module.UTF8] +legacy-module-names = false +python-module-name = "smithy_dafny_standard_library.internaldafny.generated" +[options_by_module.Time] +legacy-module-names = false +python-module-name = "smithy_dafny_standard_library.internaldafny.generated" +[options_by_module.Streams] +legacy-module-names = false +python-module-name = "smithy_dafny_standard_library.internaldafny.generated" +[options_by_module.Sorting] +legacy-module-names = false +python-module-name = "smithy_dafny_standard_library.internaldafny.generated" +[options_by_module.SortedSets] +legacy-module-names = false +python-module-name = "smithy_dafny_standard_library.internaldafny.generated" +[options_by_module.HexStrings] +legacy-module-names = false +python-module-name = "smithy_dafny_standard_library.internaldafny.generated" +[options_by_module.GetOpt] +legacy-module-names = false +python-module-name = "smithy_dafny_standard_library.internaldafny.generated" +[options_by_module.FloatCompare] +legacy-module-names = false +python-module-name = "smithy_dafny_standard_library.internaldafny.generated" +[options_by_module.ConcurrentCall] +legacy-module-names = false +python-module-name = "smithy_dafny_standard_library.internaldafny.generated" +[options_by_module.Base64] +legacy-module-names = false +python-module-name = "smithy_dafny_standard_library.internaldafny.generated" +[options_by_module.Base64Lemmas] +legacy-module-names = false +python-module-name = "smithy_dafny_standard_library.internaldafny.generated" +[options_by_module.Actions] +legacy-module-names = false +python-module-name = "smithy_dafny_standard_library.internaldafny.generated" +[options_by_module.DafnyLibraries] +legacy-module-names = false +python-module-name = "smithy_dafny_standard_library.internaldafny.generated" +[options_by_module."JSON.Utils.Views.Core"] +legacy-module-names = false +python-module-name = "smithy_dafny_standard_library.internaldafny.generated" +[options_by_module."JSON.Utils.Views.Writers"] +legacy-module-names = false +python-module-name = "smithy_dafny_standard_library.internaldafny.generated" +[options_by_module."JSON.Utils.Lexers.Core"] +legacy-module-names = false +python-module-name = "smithy_dafny_standard_library.internaldafny.generated" +[options_by_module."JSON.Utils.Lexers.Strings"] +legacy-module-names = false +python-module-name = "smithy_dafny_standard_library.internaldafny.generated" +[options_by_module."JSON.Utils.Cursors"] +legacy-module-names = false +python-module-name = "smithy_dafny_standard_library.internaldafny.generated" +[options_by_module."JSON.Utils.Parsers"] +legacy-module-names = false +python-module-name = "smithy_dafny_standard_library.internaldafny.generated" +[options_by_module."JSON.Utils.Str.ParametricConversion"] +legacy-module-names = false +python-module-name = "smithy_dafny_standard_library.internaldafny.generated" +[options_by_module."JSON.Utils.Str.ParametricEscaping"] +legacy-module-names = false +python-module-name = "smithy_dafny_standard_library.internaldafny.generated" +[options_by_module."JSON.Utils.Str.CharStrConversion"] +legacy-module-names = false +python-module-name = "smithy_dafny_standard_library.internaldafny.generated" +[options_by_module."JSON.Utils.Str.CharStrEscaping"] +legacy-module-names = false +python-module-name = "smithy_dafny_standard_library.internaldafny.generated" +[options_by_module."JSON.Utils.Str"] +legacy-module-names = false +python-module-name = "smithy_dafny_standard_library.internaldafny.generated" +[options_by_module."JSON.Utils.Seq"] +legacy-module-names = false +python-module-name = "smithy_dafny_standard_library.internaldafny.generated" +[options_by_module."JSON.Utils.Vectors"] +legacy-module-names = false +python-module-name = "smithy_dafny_standard_library.internaldafny.generated" +[options_by_module."JSON.Errors"] +legacy-module-names = false +python-module-name = "smithy_dafny_standard_library.internaldafny.generated" +[options_by_module."JSON.Values"] +legacy-module-names = false +python-module-name = "smithy_dafny_standard_library.internaldafny.generated" +[options_by_module."JSON.Spec"] +legacy-module-names = false +python-module-name = "smithy_dafny_standard_library.internaldafny.generated" +[options_by_module."JSON.Grammar"] +legacy-module-names = false +python-module-name = "smithy_dafny_standard_library.internaldafny.generated" +[options_by_module."JSON.Serializer.ByteStrConversion"] +legacy-module-names = false +python-module-name = "smithy_dafny_standard_library.internaldafny.generated" +[options_by_module."JSON.Serializer"] +legacy-module-names = false +python-module-name = "smithy_dafny_standard_library.internaldafny.generated" +[options_by_module."JSON.Deserializer.Uint16StrConversion"] +legacy-module-names = false +python-module-name = "smithy_dafny_standard_library.internaldafny.generated" +[options_by_module."JSON.Deserializer.ByteStrConversion"] +legacy-module-names = false +python-module-name = "smithy_dafny_standard_library.internaldafny.generated" +[options_by_module."JSON.Deserializer"] +legacy-module-names = false +python-module-name = "smithy_dafny_standard_library.internaldafny.generated" +[options_by_module."JSON.ConcreteSyntax.Spec"] +legacy-module-names = false +python-module-name = "smithy_dafny_standard_library.internaldafny.generated" +[options_by_module."JSON.ConcreteSyntax.SpecProperties"] +legacy-module-names = false +python-module-name = "smithy_dafny_standard_library.internaldafny.generated" +[options_by_module."JSON.ZeroCopy.Serializer"] +legacy-module-names = false +python-module-name = "smithy_dafny_standard_library.internaldafny.generated" +[options_by_module."JSON.ZeroCopy.Deserializer.Core"] +legacy-module-names = false +python-module-name = "smithy_dafny_standard_library.internaldafny.generated" +[options_by_module."JSON.ZeroCopy.Deserializer.SequenceParams"] +legacy-module-names = false +python-module-name = "smithy_dafny_standard_library.internaldafny.generated" +[options_by_module."JSON.ZeroCopy.Deserializer.Sequences"] +legacy-module-names = false +python-module-name = "smithy_dafny_standard_library.internaldafny.generated" +[options_by_module."JSON.ZeroCopy.Deserializer.Strings"] +legacy-module-names = false +python-module-name = "smithy_dafny_standard_library.internaldafny.generated" +[options_by_module."JSON.ZeroCopy.Deserializer.Numbers"] +legacy-module-names = false +python-module-name = "smithy_dafny_standard_library.internaldafny.generated" +[options_by_module."JSON.ZeroCopy.Deserializer.ObjectParams"] +legacy-module-names = false +python-module-name = "smithy_dafny_standard_library.internaldafny.generated" +[options_by_module."JSON.ZeroCopy.Deserializer.Objects"] +legacy-module-names = false +python-module-name = "smithy_dafny_standard_library.internaldafny.generated" +[options_by_module."JSON.ZeroCopy.Deserializer.ArrayParams"] +legacy-module-names = false +python-module-name = "smithy_dafny_standard_library.internaldafny.generated" +[options_by_module."JSON.ZeroCopy.Deserializer.Arrays"] +legacy-module-names = false +python-module-name = "smithy_dafny_standard_library.internaldafny.generated" +[options_by_module."JSON.ZeroCopy.Deserializer.Constants"] +legacy-module-names = false +python-module-name = "smithy_dafny_standard_library.internaldafny.generated" +[options_by_module."JSON.ZeroCopy.Deserializer.Values"] +legacy-module-names = false +python-module-name = "smithy_dafny_standard_library.internaldafny.generated" +[options_by_module."JSON.ZeroCopy.Deserializer.API"] +legacy-module-names = false +python-module-name = "smithy_dafny_standard_library.internaldafny.generated" +[options_by_module."JSON.ZeroCopy.Deserializer"] +legacy-module-names = false +python-module-name = "smithy_dafny_standard_library.internaldafny.generated" +[options_by_module."JSON.ZeroCopy.API"] +legacy-module-names = false +python-module-name = "smithy_dafny_standard_library.internaldafny.generated" +[options_by_module."JSON.API"] +legacy-module-names = false +python-module-name = "smithy_dafny_standard_library.internaldafny.generated" diff --git a/StandardLibrary/runtimes/python/test/internaldafny/__init__.py b/StandardLibrary/runtimes/python/test/internaldafny/__init__.py new file mode 100644 index 000000000..f94fd12a2 --- /dev/null +++ b/StandardLibrary/runtimes/python/test/internaldafny/__init__.py @@ -0,0 +1,2 @@ +# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 diff --git a/StandardLibrary/runtimes/python/test/internaldafny/test_dafny_wrapper.py b/StandardLibrary/runtimes/python/test/internaldafny/test_dafny_wrapper.py new file mode 100644 index 000000000..6622cc3c3 --- /dev/null +++ b/StandardLibrary/runtimes/python/test/internaldafny/test_dafny_wrapper.py @@ -0,0 +1,19 @@ +# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 +""" +Wrapper file for executing Dafny tests from pytest. +This allows us to import modules required by Dafny-generated tests +before executing Dafny-generated tests. +pytest will find and execute the `test_dafny` method below, +which will execute the `internaldafny_test_executor.py` file in the `dafny` directory. +""" + +import sys + +internaldafny_dir = '/'.join(__file__.split("/")[:-1]) + +sys.path.append(internaldafny_dir + "/extern") +sys.path.append(internaldafny_dir + "/generated") + +def test_dafny(): + from .generated import __main__ \ No newline at end of file diff --git a/StandardLibrary/runtimes/python/tox.ini b/StandardLibrary/runtimes/python/tox.ini new file mode 100644 index 000000000..5e6bbcb9d --- /dev/null +++ b/StandardLibrary/runtimes/python/tox.ini @@ -0,0 +1,86 @@ +[tox] +isolated_build = True +envlist = + py{311,312}-{dafnytests} + +[testenv:base-command] +commands = poetry run pytest -l {posargs} + +[testenv] +skip_install = True +allowlist_externals = poetry +passenv = AWS_* +commands_pre = + poetry lock + poetry install --with test +commands = + dafnytests: {[testenv:base-command]commands} test/internaldafny -s -v + +# Release tooling +[testenv:build] +basepython = python3 +skip_install = True +allowlist_externals = poetry +commands = + poetry install --no-root --with release + poetry build + +[testenv:release-base] +basepython = python3 +skip_install = True +allowlist_externals = poetry +comands_pre = + poetry install --no-root --with release +passenv = + # Intentionally omit TWINE_REPOSITORY_URL from the passenv list, + # as this overrides other ways of setting the repository and could + # unexpectedly result in releasing to the wrong repo + {[testenv]passenv} \ + TWINE_USERNAME \ + TWINE_PASSWORD +commands = + {[testenv:build]commands} + +[testenv:release-private] +basepython = python3 +skip_install = True +allowlist_externals = poetry +comands_pre = + poetry install --no-root --with release +passenv = + {[testenv:release-base]passenv} \ + TWINE_REPOSITORY_URL +setenv = + # Explicitly set the URL as the env variable value, which will cause us to + # throw an error if the variable is not set. Otherwise, omission of the + # env variable could cause us to unintentionally upload to the wrong repo + TWINE_REPOSITORY_URL = {env:TWINE_REPOSITORY_URL} +commands = + {[testenv:release-base]commands} + # Omitting an explicit repository will cause twine to use the repository + # specified in the environment variable + poetry run twine upload --skip-existing {toxinidir}/dist/* + +[testenv:test-release] +basepython = python3 +skip_install = True +allowlist_externals = poetry +comands_pre = + poetry install --no-root --with release +passenv = + {[testenv:release-base]passenv} +commands = + {[testenv:release-base]commands} + poetry run twine upload --skip-existing --repository testpypi {toxinidir}/dist/* + +[testenv:release] +basepython = python3 +skip_install = True +allowlist_externals = poetry +comands_pre = + poetry install --no-root --with release +passenv = + {[testenv:release-base]passenv} +commands = + {[testenv:release-base]commands} + poetry run twine upload --skip-existing --repository pypi {toxinidir}/dist/* diff --git a/TestVectorsAwsCryptographicMaterialProviders/Makefile b/TestVectorsAwsCryptographicMaterialProviders/Makefile index 20b4910ee..39d75a260 100644 --- a/TestVectorsAwsCryptographicMaterialProviders/Makefile +++ b/TestVectorsAwsCryptographicMaterialProviders/Makefile @@ -3,6 +3,8 @@ CORES=2 +ENABLE_EXTERN_PROCESSING=1 + include ../SharedMakefileV2.mk PROJECT_SERVICES := \ @@ -56,6 +58,53 @@ SERVICE_DEPS_KeyVectors := \ AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore \ AwsCryptographicMaterialProviders/dafny/AwsCryptographicMaterialProviders \ +# Constants for languages that drop extern names (Python, Go) + +TYPES_FILE_PATH=dafny/KeyVectors/Model/AwsCryptographyMaterialProvidersTestVectorKeysTypes.dfy +TYPES_FILE_WITH_EXTERN_STRING="module {:extern \"software.amazon.cryptography.materialproviderstestvectorkeys.internaldafny.types\" } AwsCryptographyMaterialProvidersTestVectorKeysTypes" +TYPES_FILE_WITHOUT_EXTERN_STRING="module AwsCryptographyMaterialProvidersTestVectorKeysTypes" + +INDEX_FILE_PATH=dafny/KeyVectors/src/Index.dfy +INDEX_FILE_WITH_EXTERN_STRING="module {:extern \"software.amazon.cryptography.materialproviderstestvectorkeys.internaldafny\"} KeyVectors refines AbstractAwsCryptographyMaterialProvidersTestVectorKeysService {" +INDEX_FILE_WITHOUT_EXTERN_STRING="module KeyVectors refines AbstractAwsCryptographyMaterialProvidersTestVectorKeysService {" + +WRAPPED_INDEX_FILE_PATH=dafny/TestVectorsAwsCryptographicMaterialProviders/src/LibraryIndex.dfy +WRAPPED_INDEX_FILE_WITH_EXTERN_STRING="module {:extern \"software.amazon.cryptography.materialproviders.internaldafny.wrapped\" } WrappedMaterialProviders refines WrappedAbstractAwsCryptographyMaterialProvidersService" +WRAPPED_INDEX_FILE_WITHOUT_EXTERN_STRING="module WrappedMaterialProviders refines WrappedAbstractAwsCryptographyMaterialProvidersService" + +# Python + +# smithy.api namespace is a workaround for having a wrapped localService shim in a different Python package, +# as the aws_cryptography_materialproviders namespace is spread across this package (shim only) +# and the aws_cryptographic_material_providers package (all other files). +# This prevents Polymorph from generating invalid references to files in this package, which is incomplete. +# This is a workaround, but is OK because +# 1) this is only for wrapped localService shims, which are only for testing +# 2) this is a test package +PYTHON_DEPENDENCY_MODULE_NAMES := \ + --dependency-library-name=aws.cryptography.primitives=aws_cryptography_primitives \ + --dependency-library-name=com.amazonaws.kms=aws_cryptography_internal_kms \ + --dependency-library-name=com.amazonaws.dynamodb=aws_cryptography_internal_dynamodb \ + --dependency-library-name=aws.cryptography.materialProviders=aws_cryptographic_materialproviders \ + --dependency-library-name=aws.cryptography.keyStore=aws_cryptographic_materialproviders \ + --dependency-library-name=smithy.api=aws_cryptographic_materialproviders + +PYTHON_MODULE_NAME=aws_cryptography_materialproviders_test_vectors + +TRANSLATION_RECORD_PYTHON := \ + --translation-record ../StandardLibrary/runtimes/python/src/smithy_dafny_standard_library/internaldafny/generated/dafny_src-py.dtr \ + --translation-record ../ComAmazonawsKms/runtimes/python/src/aws_cryptography_internal_kms/internaldafny/generated/dafny_src-py.dtr \ + --translation-record ../ComAmazonawsDynamodb/runtimes/python/src/aws_cryptography_internal_dynamodb/internaldafny/generated/dafny_src-py.dtr \ + --translation-record ../AwsCryptographyPrimitives/runtimes/python/src/aws_cryptography_primitives/internaldafny/generated/dafny_src-py.dtr \ + --translation-record ../AwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptographic_materialproviders/internaldafny/generated/dafny_src-py.dtr + +# Python + +# Override default test_python to run tox environment for Dafny tests +test_python: + rm -rf runtimes/python/.tox + python3 -m tox -c runtimes/python -e dafnytests --verbose + # Commands to generate and test test vectors test_generate_vectors_java: gradle -p runtimes/java run --args="encrypt-manifest --encrypt-manifest-output ." @@ -68,6 +117,11 @@ test_generate_vectors_net: dotnet run --project runtimes/net --framework $(FRAMEWORK) encrypt-manifest --encrypt-manifest-output runtimes/net cp dafny/TestVectorsAwsCryptographicMaterialProviders/test/keys.json runtimes/net +test_generate_vectors_python: + rm -rf runtimes/python/.tox + python3 -m tox -c runtimes/python --verbose -e cli -- encrypt-manifest --encrypt-manifest-output runtimes/python + cp dafny/TestVectorsAwsCryptographicMaterialProviders/test/keys.json runtimes/python + test_encrypt_vectors_java: gradle -p runtimes/java run --args="encrypt --manifest-path . --decrypt-manifest-path ." @@ -77,6 +131,10 @@ test_encrypt_vectors_net: dotnet build runtimes/net dotnet run --project runtimes/net --framework $(FRAMEWORK) encrypt --manifest-path runtimes/net --decrypt-manifest-path runtimes/net +test_encrypt_vectors_python: + rm -rf runtimes/python/.tox + python3 -m tox -c runtimes/python --verbose -e cli -- encrypt --manifest-path runtimes/python --decrypt-manifest-path runtimes/python + test_decrypt_encrypt_vectors_java: gradle -p runtimes/java run --args="decrypt --manifest-path ." @@ -85,3 +143,7 @@ test_decrypt_encrypt_vectors_net: dotnet restore runtimes/net dotnet build runtimes/net dotnet run --project runtimes/net --framework $(FRAMEWORK) decrypt --manifest-path runtimes/net + +test_decrypt_encrypt_vectors_python: + rm -rf runtimes/python/.tox + python3 -m tox -c runtimes/python --verbose -e cli -- decrypt --manifest-path runtimes/python diff --git a/TestVectorsAwsCryptographicMaterialProviders/runtimes/python/.gitignore b/TestVectorsAwsCryptographicMaterialProviders/runtimes/python/.gitignore new file mode 100644 index 000000000..9cb72dcab --- /dev/null +++ b/TestVectorsAwsCryptographicMaterialProviders/runtimes/python/.gitignore @@ -0,0 +1,16 @@ +# Python build artifacts +__pycache__ +**/__pycache__ +*.pyc +src/**.egg-info/ +build +poetry.lock +**/poetry.lock +dist + +# Dafny-generated Python +**/internaldafny/generated/*.py + +# Python test artifacts +.tox +.pytest_cache diff --git a/TestVectorsAwsCryptographicMaterialProviders/runtimes/python/pyproject.toml b/TestVectorsAwsCryptographicMaterialProviders/runtimes/python/pyproject.toml new file mode 100644 index 000000000..5ac008516 --- /dev/null +++ b/TestVectorsAwsCryptographicMaterialProviders/runtimes/python/pyproject.toml @@ -0,0 +1,23 @@ +[tool.poetry] +name = "aws-cryptography-internal-mpl-testvectors" +version = "0.1.0" +description = "" +authors = ["AWS Crypto Tools "] +packages = [ + { include = "aws_cryptography_materialproviders_test_vectors", from = "src" } +] +# Include generated internaldafny files in package distributions, +# even though they are not included in version control +include = ["**/internaldafny/generated/*.py"] + +[tool.poetry.dependencies] +python = "^3.11.0" +boto3 = "^1.28.38" +aws-cryptographic-materialproviders = { path = "../../../AwsCryptographicMaterialProviders/runtimes/python", develop = false} + +[tool.poetry.group.test.dependencies] +pytest = "^7.4.0" + +[build-system] +requires = ["poetry-core"] +build-backend = "poetry.core.masonry.api" diff --git a/TestVectorsAwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptography_materialproviders_test_vectors/__init__.py b/TestVectorsAwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptography_materialproviders_test_vectors/__init__.py new file mode 100644 index 000000000..b9427e19d --- /dev/null +++ b/TestVectorsAwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptography_materialproviders_test_vectors/__init__.py @@ -0,0 +1,8 @@ +# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 + +# Initialize generated Dafny +from .internaldafny.generated import module_ + +# Initialize externs +from .internaldafny import extern diff --git a/TestVectorsAwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptography_materialproviders_test_vectors/internaldafny/extern/__init__.py b/TestVectorsAwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptography_materialproviders_test_vectors/internaldafny/extern/__init__.py new file mode 100644 index 000000000..be1ce5e80 --- /dev/null +++ b/TestVectorsAwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptography_materialproviders_test_vectors/internaldafny/extern/__init__.py @@ -0,0 +1,3 @@ +from . import ( + wrapped_mpl, +) \ No newline at end of file diff --git a/TestVectorsAwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptography_materialproviders_test_vectors/internaldafny/extern/wrapped_mpl.py b/TestVectorsAwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptography_materialproviders_test_vectors/internaldafny/extern/wrapped_mpl.py new file mode 100644 index 000000000..4e7b7112b --- /dev/null +++ b/TestVectorsAwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptography_materialproviders_test_vectors/internaldafny/extern/wrapped_mpl.py @@ -0,0 +1,18 @@ +import aws_cryptography_materialproviders_test_vectors.internaldafny.generated.WrappedMaterialProviders as WrappedMaterialProviders +import smithy_dafny_standard_library.internaldafny.generated.Wrappers as Wrappers +import aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.client +import aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.config +import aws_cryptographic_materialproviders.internaldafny.generated.MaterialProviders as MaterialProviders +import aws_cryptography_materialproviders_test_vectors.smithygenerated.aws_cryptography_materialproviders.shim as shim + +class default__(WrappedMaterialProviders.default__): + + @staticmethod + def WrappedMaterialProviders(config): + smithy_client = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.client.AwsCryptographicMaterialProviders( + dafny_client=MaterialProviders.default__.MaterialProviders(config).value + ) + wrapped_client = shim.MaterialProvidersShim(smithy_client) + return Wrappers.Result_Success(wrapped_client) + +WrappedMaterialProviders.default__ = default__ \ No newline at end of file diff --git a/TestVectorsAwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptography_materialproviders_test_vectors/internaldafny/generated/dafny_src-py.dtr b/TestVectorsAwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptography_materialproviders_test_vectors/internaldafny/generated/dafny_src-py.dtr new file mode 100644 index 000000000..b59cf4040 --- /dev/null +++ b/TestVectorsAwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptography_materialproviders_test_vectors/internaldafny/generated/dafny_src-py.dtr @@ -0,0 +1,104 @@ +file_format_version = "1.0" +dafny_version = "4.8.0.0" +[options_by_module.MplManifestOptions] +legacy-module-names = false +python-module-name = "aws_cryptography_materialproviders_test_vectors.internaldafny.generated" +[options_by_module.AllAlgorithmSuites] +legacy-module-names = false +python-module-name = "aws_cryptography_materialproviders_test_vectors.internaldafny.generated" +[options_by_module.WrappedAbstractAwsCryptographyMaterialProvidersService] +legacy-module-names = false +python-module-name = "aws_cryptography_materialproviders_test_vectors.internaldafny.generated" +[options_by_module.WrappedMaterialProviders] +legacy-module-names = false +python-module-name = "aws_cryptography_materialproviders_test_vectors.internaldafny.generated" +[options_by_module.AwsCryptographyMaterialProvidersTestVectorKeysTypes] +legacy-module-names = false +python-module-name = "aws_cryptography_materialproviders_test_vectors.internaldafny.generated" +[options_by_module.AbstractAwsCryptographyMaterialProvidersTestVectorKeysOperations] +legacy-module-names = false +python-module-name = "aws_cryptography_materialproviders_test_vectors.internaldafny.generated" +[options_by_module.AbstractAwsCryptographyMaterialProvidersTestVectorKeysService] +legacy-module-names = false +python-module-name = "aws_cryptography_materialproviders_test_vectors.internaldafny.generated" +[options_by_module.JSONHelpers] +legacy-module-names = false +python-module-name = "aws_cryptography_materialproviders_test_vectors.internaldafny.generated" +[options_by_module.KeyDescription] +legacy-module-names = false +python-module-name = "aws_cryptography_materialproviders_test_vectors.internaldafny.generated" +[options_by_module.KeyMaterial] +legacy-module-names = false +python-module-name = "aws_cryptography_materialproviders_test_vectors.internaldafny.generated" +[options_by_module.CreateStaticKeyrings] +legacy-module-names = false +python-module-name = "aws_cryptography_materialproviders_test_vectors.internaldafny.generated" +[options_by_module.CreateStaticKeyStores] +legacy-module-names = false +python-module-name = "aws_cryptography_materialproviders_test_vectors.internaldafny.generated" +[options_by_module.KeyringFromKeyDescription] +legacy-module-names = false +python-module-name = "aws_cryptography_materialproviders_test_vectors.internaldafny.generated" +[options_by_module.CmmFromKeyDescription] +legacy-module-names = false +python-module-name = "aws_cryptography_materialproviders_test_vectors.internaldafny.generated" +[options_by_module.KeysVectorOperations] +legacy-module-names = false +python-module-name = "aws_cryptography_materialproviders_test_vectors.internaldafny.generated" +[options_by_module.KeyVectors] +legacy-module-names = false +python-module-name = "aws_cryptography_materialproviders_test_vectors.internaldafny.generated" +[options_by_module.TestVectors] +legacy-module-names = false +python-module-name = "aws_cryptography_materialproviders_test_vectors.internaldafny.generated" +[options_by_module.AllHierarchy] +legacy-module-names = false +python-module-name = "aws_cryptography_materialproviders_test_vectors.internaldafny.generated" +[options_by_module.AllKms] +legacy-module-names = false +python-module-name = "aws_cryptography_materialproviders_test_vectors.internaldafny.generated" +[options_by_module.AllKmsMrkAware] +legacy-module-names = false +python-module-name = "aws_cryptography_materialproviders_test_vectors.internaldafny.generated" +[options_by_module.AllKmsMrkAwareDiscovery] +legacy-module-names = false +python-module-name = "aws_cryptography_materialproviders_test_vectors.internaldafny.generated" +[options_by_module.AllKmsRsa] +legacy-module-names = false +python-module-name = "aws_cryptography_materialproviders_test_vectors.internaldafny.generated" +[options_by_module.AllKmsEcdh] +legacy-module-names = false +python-module-name = "aws_cryptography_materialproviders_test_vectors.internaldafny.generated" +[options_by_module.AllRawAES] +legacy-module-names = false +python-module-name = "aws_cryptography_materialproviders_test_vectors.internaldafny.generated" +[options_by_module.AllRawRSA] +legacy-module-names = false +python-module-name = "aws_cryptography_materialproviders_test_vectors.internaldafny.generated" +[options_by_module.AllRawECDH] +legacy-module-names = false +python-module-name = "aws_cryptography_materialproviders_test_vectors.internaldafny.generated" +[options_by_module.AllDefaultCmm] +legacy-module-names = false +python-module-name = "aws_cryptography_materialproviders_test_vectors.internaldafny.generated" +[options_by_module.AllRequiredEncryptionContextCmm] +legacy-module-names = false +python-module-name = "aws_cryptography_materialproviders_test_vectors.internaldafny.generated" +[options_by_module.AllMulti] +legacy-module-names = false +python-module-name = "aws_cryptography_materialproviders_test_vectors.internaldafny.generated" +[options_by_module.WriteJsonManifests] +legacy-module-names = false +python-module-name = "aws_cryptography_materialproviders_test_vectors.internaldafny.generated" +[options_by_module.CompleteVectors] +legacy-module-names = false +python-module-name = "aws_cryptography_materialproviders_test_vectors.internaldafny.generated" +[options_by_module.ParseJsonManifests] +legacy-module-names = false +python-module-name = "aws_cryptography_materialproviders_test_vectors.internaldafny.generated" +[options_by_module.TestManifests] +legacy-module-names = false +python-module-name = "aws_cryptography_materialproviders_test_vectors.internaldafny.generated" +[options_by_module.WrappedMaterialProvidersMain] +legacy-module-names = false +python-module-name = "aws_cryptography_materialproviders_test_vectors.internaldafny.generated" diff --git a/TestVectorsAwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptography_materialproviders_test_vectors/smithygenerated/aws_cryptography_materialproviders/__init__.py b/TestVectorsAwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptography_materialproviders_test_vectors/smithygenerated/aws_cryptography_materialproviders/__init__.py new file mode 100644 index 000000000..09be6133b --- /dev/null +++ b/TestVectorsAwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptography_materialproviders_test_vectors/smithygenerated/aws_cryptography_materialproviders/__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/TestVectorsAwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptography_materialproviders_test_vectors/smithygenerated/aws_cryptography_materialproviders/shim.py b/TestVectorsAwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptography_materialproviders_test_vectors/smithygenerated/aws_cryptography_materialproviders/shim.py new file mode 100644 index 000000000..721d05732 --- /dev/null +++ b/TestVectorsAwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptography_materialproviders_test_vectors/smithygenerated/aws_cryptography_materialproviders/shim.py @@ -0,0 +1,560 @@ +# 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_materialproviders.internaldafny.generated.AwsCryptographyMaterialProvidersTypes import ( + AlgorithmSuiteInfo_AlgorithmSuiteInfo as DafnyAlgorithmSuiteInfo, + CreateAwsKmsDiscoveryKeyringInput_CreateAwsKmsDiscoveryKeyringInput as DafnyCreateAwsKmsDiscoveryKeyringInput, + CreateAwsKmsDiscoveryMultiKeyringInput_CreateAwsKmsDiscoveryMultiKeyringInput as DafnyCreateAwsKmsDiscoveryMultiKeyringInput, + CreateAwsKmsEcdhKeyringInput_CreateAwsKmsEcdhKeyringInput as DafnyCreateAwsKmsEcdhKeyringInput, + CreateAwsKmsHierarchicalKeyringInput_CreateAwsKmsHierarchicalKeyringInput as DafnyCreateAwsKmsHierarchicalKeyringInput, + CreateAwsKmsKeyringInput_CreateAwsKmsKeyringInput as DafnyCreateAwsKmsKeyringInput, + CreateAwsKmsMrkDiscoveryKeyringInput_CreateAwsKmsMrkDiscoveryKeyringInput as DafnyCreateAwsKmsMrkDiscoveryKeyringInput, + CreateAwsKmsMrkDiscoveryMultiKeyringInput_CreateAwsKmsMrkDiscoveryMultiKeyringInput as DafnyCreateAwsKmsMrkDiscoveryMultiKeyringInput, + CreateAwsKmsMrkKeyringInput_CreateAwsKmsMrkKeyringInput as DafnyCreateAwsKmsMrkKeyringInput, + CreateAwsKmsMrkMultiKeyringInput_CreateAwsKmsMrkMultiKeyringInput as DafnyCreateAwsKmsMrkMultiKeyringInput, + CreateAwsKmsMultiKeyringInput_CreateAwsKmsMultiKeyringInput as DafnyCreateAwsKmsMultiKeyringInput, + CreateAwsKmsRsaKeyringInput_CreateAwsKmsRsaKeyringInput as DafnyCreateAwsKmsRsaKeyringInput, + CreateCryptographicMaterialsCacheInput_CreateCryptographicMaterialsCacheInput as DafnyCreateCryptographicMaterialsCacheInput, + CreateDefaultClientSupplierInput_CreateDefaultClientSupplierInput as DafnyCreateDefaultClientSupplierInput, + CreateDefaultCryptographicMaterialsManagerInput_CreateDefaultCryptographicMaterialsManagerInput as DafnyCreateDefaultCryptographicMaterialsManagerInput, + CreateMultiKeyringInput_CreateMultiKeyringInput as DafnyCreateMultiKeyringInput, + CreateRawAesKeyringInput_CreateRawAesKeyringInput as DafnyCreateRawAesKeyringInput, + CreateRawEcdhKeyringInput_CreateRawEcdhKeyringInput as DafnyCreateRawEcdhKeyringInput, + CreateRawRsaKeyringInput_CreateRawRsaKeyringInput as DafnyCreateRawRsaKeyringInput, + CreateRequiredEncryptionContextCMMInput_CreateRequiredEncryptionContextCMMInput as DafnyCreateRequiredEncryptionContextCMMInput, + DecryptionMaterials_DecryptionMaterials as DafnyDecryptionMaterials, + EncryptionMaterials_EncryptionMaterials as DafnyEncryptionMaterials, + InitializeDecryptionMaterialsInput_InitializeDecryptionMaterialsInput as DafnyInitializeDecryptionMaterialsInput, + InitializeEncryptionMaterialsInput_InitializeEncryptionMaterialsInput as DafnyInitializeEncryptionMaterialsInput, + ValidDecryptionMaterialsTransitionInput_ValidDecryptionMaterialsTransitionInput as DafnyValidDecryptionMaterialsTransitionInput, + ValidEncryptionMaterialsTransitionInput_ValidEncryptionMaterialsTransitionInput as DafnyValidEncryptionMaterialsTransitionInput, + ValidateCommitmentPolicyOnDecryptInput_ValidateCommitmentPolicyOnDecryptInput as DafnyValidateCommitmentPolicyOnDecryptInput, + ValidateCommitmentPolicyOnEncryptInput_ValidateCommitmentPolicyOnEncryptInput as DafnyValidateCommitmentPolicyOnEncryptInput, +) +import aws_cryptographic_materialproviders.internaldafny.generated.module_ +import aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy +import aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.errors +from aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.errors import ( + CollectionOfErrors, + OpaqueError, + ServiceError, + _smithy_error_to_dafny_error, +) +import aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models +import aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny +from typing import Any + + +import smithy_dafny_standard_library.internaldafny.generated.Wrappers as Wrappers +import aws_cryptographic_materialproviders.internaldafny.generated.AwsCryptographyMaterialProvidersTypes +import aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.client as client_impl + + +class MaterialProvidersShim( + aws_cryptographic_materialproviders.internaldafny.generated.AwsCryptographyMaterialProvidersTypes.IAwsCryptographicMaterialProvidersClient +): + def __init__(self, _impl: client_impl): + self._impl = _impl + + def CreateAwsKmsKeyring(self, input): + try: + smithy_client_request: ( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.CreateAwsKmsKeyringInput + ) = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_CreateAwsKmsKeyringInput( + input + ) + smithy_client_response = self._impl.create_aws_kms_keyring( + smithy_client_request + ) + return Wrappers.Result_Success( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_CreateKeyringOutput( + smithy_client_response + ) + ) + except Exception as e: + return Wrappers.Result_Failure(_smithy_error_to_dafny_error(e)) + + def CreateAwsKmsDiscoveryKeyring(self, input): + try: + smithy_client_request: ( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.CreateAwsKmsDiscoveryKeyringInput + ) = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_CreateAwsKmsDiscoveryKeyringInput( + input + ) + smithy_client_response = self._impl.create_aws_kms_discovery_keyring( + smithy_client_request + ) + return Wrappers.Result_Success( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_CreateKeyringOutput( + smithy_client_response + ) + ) + except Exception as e: + return Wrappers.Result_Failure(_smithy_error_to_dafny_error(e)) + + def CreateAwsKmsMultiKeyring(self, input): + try: + smithy_client_request: ( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.CreateAwsKmsMultiKeyringInput + ) = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_CreateAwsKmsMultiKeyringInput( + input + ) + smithy_client_response = self._impl.create_aws_kms_multi_keyring( + smithy_client_request + ) + return Wrappers.Result_Success( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_CreateKeyringOutput( + smithy_client_response + ) + ) + except Exception as e: + return Wrappers.Result_Failure(_smithy_error_to_dafny_error(e)) + + def CreateAwsKmsDiscoveryMultiKeyring(self, input): + try: + smithy_client_request: ( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.CreateAwsKmsDiscoveryMultiKeyringInput + ) = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_CreateAwsKmsDiscoveryMultiKeyringInput( + input + ) + smithy_client_response = self._impl.create_aws_kms_discovery_multi_keyring( + smithy_client_request + ) + return Wrappers.Result_Success( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_CreateKeyringOutput( + smithy_client_response + ) + ) + except Exception as e: + return Wrappers.Result_Failure(_smithy_error_to_dafny_error(e)) + + def CreateAwsKmsMrkKeyring(self, input): + try: + smithy_client_request: ( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.CreateAwsKmsMrkKeyringInput + ) = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_CreateAwsKmsMrkKeyringInput( + input + ) + smithy_client_response = self._impl.create_aws_kms_mrk_keyring( + smithy_client_request + ) + return Wrappers.Result_Success( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_CreateKeyringOutput( + smithy_client_response + ) + ) + except Exception as e: + return Wrappers.Result_Failure(_smithy_error_to_dafny_error(e)) + + def CreateAwsKmsMrkMultiKeyring(self, input): + try: + smithy_client_request: ( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.CreateAwsKmsMrkMultiKeyringInput + ) = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_CreateAwsKmsMrkMultiKeyringInput( + input + ) + smithy_client_response = self._impl.create_aws_kms_mrk_multi_keyring( + smithy_client_request + ) + return Wrappers.Result_Success( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_CreateKeyringOutput( + smithy_client_response + ) + ) + except Exception as e: + return Wrappers.Result_Failure(_smithy_error_to_dafny_error(e)) + + def CreateAwsKmsMrkDiscoveryKeyring(self, input): + try: + smithy_client_request: ( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.CreateAwsKmsMrkDiscoveryKeyringInput + ) = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_CreateAwsKmsMrkDiscoveryKeyringInput( + input + ) + smithy_client_response = self._impl.create_aws_kms_mrk_discovery_keyring( + smithy_client_request + ) + return Wrappers.Result_Success( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_CreateKeyringOutput( + smithy_client_response + ) + ) + except Exception as e: + return Wrappers.Result_Failure(_smithy_error_to_dafny_error(e)) + + def CreateAwsKmsMrkDiscoveryMultiKeyring(self, input): + try: + smithy_client_request: ( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.CreateAwsKmsMrkDiscoveryMultiKeyringInput + ) = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_CreateAwsKmsMrkDiscoveryMultiKeyringInput( + input + ) + smithy_client_response = ( + self._impl.create_aws_kms_mrk_discovery_multi_keyring( + smithy_client_request + ) + ) + return Wrappers.Result_Success( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_CreateKeyringOutput( + smithy_client_response + ) + ) + except Exception as e: + return Wrappers.Result_Failure(_smithy_error_to_dafny_error(e)) + + def CreateAwsKmsHierarchicalKeyring(self, input): + try: + smithy_client_request: ( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.CreateAwsKmsHierarchicalKeyringInput + ) = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_CreateAwsKmsHierarchicalKeyringInput( + input + ) + smithy_client_response = self._impl.create_aws_kms_hierarchical_keyring( + smithy_client_request + ) + return Wrappers.Result_Success( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_CreateKeyringOutput( + smithy_client_response + ) + ) + except Exception as e: + return Wrappers.Result_Failure(_smithy_error_to_dafny_error(e)) + + def CreateAwsKmsRsaKeyring(self, input): + try: + smithy_client_request: ( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.CreateAwsKmsRsaKeyringInput + ) = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_CreateAwsKmsRsaKeyringInput( + input + ) + smithy_client_response = self._impl.create_aws_kms_rsa_keyring( + smithy_client_request + ) + return Wrappers.Result_Success( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_CreateKeyringOutput( + smithy_client_response + ) + ) + except Exception as e: + return Wrappers.Result_Failure(_smithy_error_to_dafny_error(e)) + + def CreateAwsKmsEcdhKeyring(self, input): + try: + smithy_client_request: ( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.CreateAwsKmsEcdhKeyringInput + ) = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_CreateAwsKmsEcdhKeyringInput( + input + ) + smithy_client_response = self._impl.create_aws_kms_ecdh_keyring( + smithy_client_request + ) + return Wrappers.Result_Success( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_CreateKeyringOutput( + smithy_client_response + ) + ) + except Exception as e: + return Wrappers.Result_Failure(_smithy_error_to_dafny_error(e)) + + def CreateMultiKeyring(self, input): + try: + smithy_client_request: ( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.CreateMultiKeyringInput + ) = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_CreateMultiKeyringInput( + input + ) + smithy_client_response = self._impl.create_multi_keyring( + smithy_client_request + ) + return Wrappers.Result_Success( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_CreateKeyringOutput( + smithy_client_response + ) + ) + except Exception as e: + return Wrappers.Result_Failure(_smithy_error_to_dafny_error(e)) + + def CreateRawAesKeyring(self, input): + try: + smithy_client_request: ( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.CreateRawAesKeyringInput + ) = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_CreateRawAesKeyringInput( + input + ) + smithy_client_response = self._impl.create_raw_aes_keyring( + smithy_client_request + ) + return Wrappers.Result_Success( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_CreateKeyringOutput( + smithy_client_response + ) + ) + except Exception as e: + return Wrappers.Result_Failure(_smithy_error_to_dafny_error(e)) + + def CreateRawRsaKeyring(self, input): + try: + smithy_client_request: ( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.CreateRawRsaKeyringInput + ) = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_CreateRawRsaKeyringInput( + input + ) + smithy_client_response = self._impl.create_raw_rsa_keyring( + smithy_client_request + ) + return Wrappers.Result_Success( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_CreateKeyringOutput( + smithy_client_response + ) + ) + except Exception as e: + return Wrappers.Result_Failure(_smithy_error_to_dafny_error(e)) + + def CreateRawEcdhKeyring(self, input): + try: + smithy_client_request: ( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.CreateRawEcdhKeyringInput + ) = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_CreateRawEcdhKeyringInput( + input + ) + smithy_client_response = self._impl.create_raw_ecdh_keyring( + smithy_client_request + ) + return Wrappers.Result_Success( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_CreateKeyringOutput( + smithy_client_response + ) + ) + except Exception as e: + return Wrappers.Result_Failure(_smithy_error_to_dafny_error(e)) + + def CreateDefaultCryptographicMaterialsManager(self, input): + try: + smithy_client_request: ( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.CreateDefaultCryptographicMaterialsManagerInput + ) = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_CreateDefaultCryptographicMaterialsManagerInput( + input + ) + smithy_client_response = ( + self._impl.create_default_cryptographic_materials_manager( + smithy_client_request + ) + ) + return Wrappers.Result_Success( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_CreateCryptographicMaterialsManagerOutput( + smithy_client_response + ) + ) + except Exception as e: + return Wrappers.Result_Failure(_smithy_error_to_dafny_error(e)) + + def CreateRequiredEncryptionContextCMM(self, input): + try: + smithy_client_request: ( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.CreateRequiredEncryptionContextCMMInput + ) = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_CreateRequiredEncryptionContextCMMInput( + input + ) + smithy_client_response = self._impl.create_required_encryption_context_cmm( + smithy_client_request + ) + return Wrappers.Result_Success( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_CreateRequiredEncryptionContextCMMOutput( + smithy_client_response + ) + ) + except Exception as e: + return Wrappers.Result_Failure(_smithy_error_to_dafny_error(e)) + + def CreateCryptographicMaterialsCache(self, input): + try: + smithy_client_request: ( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.CreateCryptographicMaterialsCacheInput + ) = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_CreateCryptographicMaterialsCacheInput( + input + ) + smithy_client_response = self._impl.create_cryptographic_materials_cache( + smithy_client_request + ) + return Wrappers.Result_Success( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_CreateCryptographicMaterialsCacheOutput( + smithy_client_response + ) + ) + except Exception as e: + return Wrappers.Result_Failure(_smithy_error_to_dafny_error(e)) + + def CreateDefaultClientSupplier(self, input): + try: + smithy_client_request: ( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.CreateDefaultClientSupplierInput + ) = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_CreateDefaultClientSupplierInput( + input + ) + smithy_client_response = self._impl.create_default_client_supplier( + smithy_client_request + ) + return Wrappers.Result_Success( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_CreateDefaultClientSupplierOutput( + smithy_client_response + ) + ) + except Exception as e: + return Wrappers.Result_Failure(_smithy_error_to_dafny_error(e)) + + def InitializeEncryptionMaterials(self, input): + try: + smithy_client_request: ( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.InitializeEncryptionMaterialsInput + ) = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_InitializeEncryptionMaterialsInput( + input + ) + smithy_client_response = self._impl.initialize_encryption_materials( + smithy_client_request + ) + return Wrappers.Result_Success( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_EncryptionMaterials( + smithy_client_response + ) + ) + except Exception as e: + return Wrappers.Result_Failure(_smithy_error_to_dafny_error(e)) + + def InitializeDecryptionMaterials(self, input): + try: + smithy_client_request: ( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.InitializeDecryptionMaterialsInput + ) = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_InitializeDecryptionMaterialsInput( + input + ) + smithy_client_response = self._impl.initialize_decryption_materials( + smithy_client_request + ) + return Wrappers.Result_Success( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_DecryptionMaterials( + smithy_client_response + ) + ) + except Exception as e: + return Wrappers.Result_Failure(_smithy_error_to_dafny_error(e)) + + def ValidEncryptionMaterialsTransition(self, input): + try: + smithy_client_request: ( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.ValidEncryptionMaterialsTransitionInput + ) = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_ValidEncryptionMaterialsTransitionInput( + input + ) + smithy_client_response = self._impl.valid_encryption_materials_transition( + smithy_client_request + ) + return Wrappers.Result_Success(None) + except Exception as e: + return Wrappers.Result_Failure(_smithy_error_to_dafny_error(e)) + + def ValidDecryptionMaterialsTransition(self, input): + try: + smithy_client_request: ( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.ValidDecryptionMaterialsTransitionInput + ) = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_ValidDecryptionMaterialsTransitionInput( + input + ) + smithy_client_response = self._impl.valid_decryption_materials_transition( + smithy_client_request + ) + return Wrappers.Result_Success(None) + except Exception as e: + return Wrappers.Result_Failure(_smithy_error_to_dafny_error(e)) + + def EncryptionMaterialsHasPlaintextDataKey(self, input): + try: + smithy_client_request: ( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.EncryptionMaterials + ) = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_EncryptionMaterials( + input + ) + smithy_client_response = ( + self._impl.encryption_materials_has_plaintext_data_key( + smithy_client_request + ) + ) + return Wrappers.Result_Success(None) + except Exception as e: + return Wrappers.Result_Failure(_smithy_error_to_dafny_error(e)) + + def DecryptionMaterialsWithPlaintextDataKey(self, input): + try: + smithy_client_request: ( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.DecryptionMaterials + ) = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_DecryptionMaterials( + input + ) + smithy_client_response = ( + self._impl.decryption_materials_with_plaintext_data_key( + smithy_client_request + ) + ) + return Wrappers.Result_Success(None) + except Exception as e: + return Wrappers.Result_Failure(_smithy_error_to_dafny_error(e)) + + def GetAlgorithmSuiteInfo(self, input): + try: + smithy_client_request: ( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.GetAlgorithmSuiteInfoInput + ) = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_GetAlgorithmSuiteInfoInput( + input + ) + smithy_client_response = self._impl.get_algorithm_suite_info( + smithy_client_request + ) + return Wrappers.Result_Success( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_AlgorithmSuiteInfo( + smithy_client_response + ) + ) + except Exception as e: + return Wrappers.Result_Failure(_smithy_error_to_dafny_error(e)) + + def ValidAlgorithmSuiteInfo(self, input): + try: + smithy_client_request: ( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.AlgorithmSuiteInfo + ) = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_AlgorithmSuiteInfo( + input + ) + smithy_client_response = self._impl.valid_algorithm_suite_info( + smithy_client_request + ) + return Wrappers.Result_Success(None) + except Exception as e: + return Wrappers.Result_Failure(_smithy_error_to_dafny_error(e)) + + def ValidateCommitmentPolicyOnEncrypt(self, input): + try: + smithy_client_request: ( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.ValidateCommitmentPolicyOnEncryptInput + ) = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_ValidateCommitmentPolicyOnEncryptInput( + input + ) + smithy_client_response = self._impl.validate_commitment_policy_on_encrypt( + smithy_client_request + ) + return Wrappers.Result_Success(None) + except Exception as e: + return Wrappers.Result_Failure(_smithy_error_to_dafny_error(e)) + + def ValidateCommitmentPolicyOnDecrypt(self, input): + try: + smithy_client_request: ( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models.ValidateCommitmentPolicyOnDecryptInput + ) = aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_ValidateCommitmentPolicyOnDecryptInput( + input + ) + smithy_client_response = self._impl.validate_commitment_policy_on_decrypt( + smithy_client_request + ) + return Wrappers.Result_Success(None) + except Exception as e: + return Wrappers.Result_Failure(_smithy_error_to_dafny_error(e)) diff --git a/TestVectorsAwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptography_materialproviders_test_vectors/smithygenerated/aws_cryptography_materialproviderstestvectorkeys/__init__.py b/TestVectorsAwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptography_materialproviders_test_vectors/smithygenerated/aws_cryptography_materialproviderstestvectorkeys/__init__.py new file mode 100644 index 000000000..09be6133b --- /dev/null +++ b/TestVectorsAwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptography_materialproviders_test_vectors/smithygenerated/aws_cryptography_materialproviderstestvectorkeys/__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/TestVectorsAwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptography_materialproviders_test_vectors/smithygenerated/aws_cryptography_materialproviderstestvectorkeys/aws_sdk_to_dafny.py b/TestVectorsAwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptography_materialproviders_test_vectors/smithygenerated/aws_cryptography_materialproviderstestvectorkeys/aws_sdk_to_dafny.py new file mode 100644 index 000000000..c7e077cb5 --- /dev/null +++ b/TestVectorsAwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptography_materialproviders_test_vectors/smithygenerated/aws_cryptography_materialproviderstestvectorkeys/aws_sdk_to_dafny.py @@ -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. + +from aws_cryptography_internal_kms.internaldafny.generated.ComAmazonawsKmsTypes import ( + EncryptionAlgorithmSpec_RSAES__OAEP__SHA__1, + EncryptionAlgorithmSpec_RSAES__OAEP__SHA__256, + EncryptionAlgorithmSpec_SYMMETRIC__DEFAULT, +) +import aws_cryptography_internal_kms.internaldafny.generated.module_ + + +def com_amazonaws_kms_EncryptionAlgorithmSpec(native_input): + # Convert EncryptionAlgorithmSpec + if native_input == "SYMMETRIC_DEFAULT": + return EncryptionAlgorithmSpec_SYMMETRIC__DEFAULT() + elif native_input == "RSAES_OAEP_SHA_1": + return EncryptionAlgorithmSpec_RSAES__OAEP__SHA__1() + elif native_input == "RSAES_OAEP_SHA_256": + return EncryptionAlgorithmSpec_RSAES__OAEP__SHA__256() + else: + raise ValueError("No recognized enum value in enum type: " + native_input) diff --git a/TestVectorsAwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptography_materialproviders_test_vectors/smithygenerated/aws_cryptography_materialproviderstestvectorkeys/client.py b/TestVectorsAwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptography_materialproviders_test_vectors/smithygenerated/aws_cryptography_materialproviderstestvectorkeys/client.py new file mode 100644 index 000000000..b52b3665b --- /dev/null +++ b/TestVectorsAwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptography_materialproviders_test_vectors/smithygenerated/aws_cryptography_materialproviderstestvectorkeys/client.py @@ -0,0 +1,414 @@ +# 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_materialproviders.smithygenerated.aws_cryptography_materialproviders.references +from aws_cryptography_materialproviders_test_vectors.internaldafny.generated.AwsCryptographyMaterialProvidersTestVectorKeysTypes import ( + IKeyVectorsClient, +) +from typing import Callable, TypeVar, cast + +from .config import Config, KeyVectorsConfig +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_create_test_vector_keyring, + _deserialize_create_wrapped_test_vector_cmm, + _deserialize_create_wrapped_test_vector_keyring, + _deserialize_get_key_description, + _deserialize_serialize_key_description, +) +from .errors import ServiceError +from .models import ( + GetKeyDescriptionInput, + GetKeyDescriptionOutput, + SerializeKeyDescriptionInput, + SerializeKeyDescriptionOutput, + TestVectorCmmInput, + TestVectorKeyringInput, +) +from .serialize import ( + _serialize_create_test_vector_keyring, + _serialize_create_wrapped_test_vector_cmm, + _serialize_create_wrapped_test_vector_keyring, + _serialize_get_key_description, + _serialize_serialize_key_description, +) + + +Input = TypeVar("Input") +Output = TypeVar("Output") + + +class KeyVectors: + """Client for KeyVectors. + + :param config: Configuration for the client. + """ + + def __init__( + self, + config: KeyVectorsConfig | None = None, + dafny_client: IKeyVectorsClient | 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_test_vector_keyring( + self, input: TestVectorKeyringInput + ) -> "aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.references.Keyring": + """Invokes the CreateTestVectorKeyring operation. + + :param input: The operation's input. + """ + return self._execute_operation( + input=input, + plugins=[], + serialize=_serialize_create_test_vector_keyring, + deserialize=_deserialize_create_test_vector_keyring, + config=self._config, + operation_name="CreateTestVectorKeyring", + ) + + def create_wrapped_test_vector_keyring( + self, input: TestVectorKeyringInput + ) -> "aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.references.Keyring": + """Invokes the CreateWrappedTestVectorKeyring operation. + + :param input: The operation's input. + """ + return self._execute_operation( + input=input, + plugins=[], + serialize=_serialize_create_wrapped_test_vector_keyring, + deserialize=_deserialize_create_wrapped_test_vector_keyring, + config=self._config, + operation_name="CreateWrappedTestVectorKeyring", + ) + + def create_wrapped_test_vector_cmm( + self, input: TestVectorCmmInput + ) -> "aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.references.CryptographicMaterialsManager": + """Invokes the CreateWrappedTestVectorCmm operation. + + :param input: The operation's input. + """ + return self._execute_operation( + input=input, + plugins=[], + serialize=_serialize_create_wrapped_test_vector_cmm, + deserialize=_deserialize_create_wrapped_test_vector_cmm, + config=self._config, + operation_name="CreateWrappedTestVectorCmm", + ) + + def get_key_description( + self, input: GetKeyDescriptionInput + ) -> GetKeyDescriptionOutput: + """Invokes the GetKeyDescription operation. + + :param input: The operation's input. + """ + return self._execute_operation( + input=input, + plugins=[], + serialize=_serialize_get_key_description, + deserialize=_deserialize_get_key_description, + config=self._config, + operation_name="GetKeyDescription", + ) + + def serialize_key_description( + self, input: SerializeKeyDescriptionInput + ) -> SerializeKeyDescriptionOutput: + """Invokes the SerializeKeyDescription operation. + + :param input: The operation's input. + """ + return self._execute_operation( + input=input, + plugins=[], + serialize=_serialize_serialize_key_description, + deserialize=_deserialize_serialize_key_description, + config=self._config, + operation_name="SerializeKeyDescription", + ) + + 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/TestVectorsAwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptography_materialproviders_test_vectors/smithygenerated/aws_cryptography_materialproviderstestvectorkeys/config.py b/TestVectorsAwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptography_materialproviders_test_vectors/smithygenerated/aws_cryptography_materialproviderstestvectorkeys/config.py new file mode 100644 index 000000000..f6103cfb3 --- /dev/null +++ b/TestVectorsAwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptography_materialproviders_test_vectors/smithygenerated/aws_cryptography_materialproviderstestvectorkeys/config.py @@ -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. + +from aws_cryptography_materialproviders_test_vectors.internaldafny.generated.AwsCryptographyMaterialProvidersTestVectorKeysTypes import ( + KeyVectorsConfig_KeyVectorsConfig as DafnyKeyVectorsConfig, +) +import aws_cryptography_materialproviders_test_vectors.internaldafny.generated.module_ +import aws_cryptography_materialproviders_test_vectors.smithygenerated.aws_cryptography_materialproviderstestvectorkeys.dafny_to_smithy +import aws_cryptography_materialproviders_test_vectors.smithygenerated.aws_cryptography_materialproviderstestvectorkeys.smithy_to_dafny +from dataclasses import dataclass +from typing import Any, Callable, TypeAlias + +from .dafnyImplInterface import DafnyImplInterface +from smithy_python._private.retries import SimpleRetryStrategy +from smithy_python.interfaces.retries import RetryStrategy + + +_ServiceInterceptor = Any + + +@dataclass(init=False) +class Config: + """Configuration for KeyVectors.""" + + 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 KeyVectorsConfig(Config): + """Smithy-modelled localService Config shape for this localService.""" + + key_manifest_path: str + + def __init__( + self, + key_manifest_path: str, + ): + """Constructor for KeyVectorsConfig.""" + super().__init__() + self.key_manifest_path = key_manifest_path + + +def dafny_config_to_smithy_config(dafny_config) -> KeyVectorsConfig: + """Converts the provided Dafny shape for this localService's config into + the corresponding Smithy-modelled shape.""" + return aws_cryptography_materialproviders_test_vectors.smithygenerated.aws_cryptography_materialproviderstestvectorkeys.dafny_to_smithy.aws_cryptography_materialproviderstestvectorkeys_KeyVectorsConfig( + dafny_config + ) + + +def smithy_config_to_dafny_config(smithy_config) -> DafnyKeyVectorsConfig: + """Converts the provided Smithy-modelled shape for this localService's + config into the corresponding Dafny shape.""" + return aws_cryptography_materialproviders_test_vectors.smithygenerated.aws_cryptography_materialproviderstestvectorkeys.smithy_to_dafny.aws_cryptography_materialproviderstestvectorkeys_KeyVectorsConfig( + smithy_config + ) diff --git a/TestVectorsAwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptography_materialproviders_test_vectors/smithygenerated/aws_cryptography_materialproviderstestvectorkeys/dafnyImplInterface.py b/TestVectorsAwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptography_materialproviders_test_vectors/smithygenerated/aws_cryptography_materialproviderstestvectorkeys/dafnyImplInterface.py new file mode 100644 index 000000000..afbc226f0 --- /dev/null +++ b/TestVectorsAwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptography_materialproviders_test_vectors/smithygenerated/aws_cryptography_materialproviderstestvectorkeys/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_cryptography_materialproviders_test_vectors.internaldafny.generated.KeyVectors import ( + KeyVectorsClient, +) +from .dafny_protocol import DafnyRequest + + +class DafnyImplInterface: + impl: KeyVectorsClient | 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 = { + "CreateTestVectorKeyring": self.impl.CreateTestVectorKeyring, + "CreateWrappedTestVectorKeyring": self.impl.CreateWrappedTestVectorKeyring, + "CreateWrappedTestVectorCmm": self.impl.CreateWrappedTestVectorCmm, + "GetKeyDescription": self.impl.GetKeyDescription, + "SerializeKeyDescription": self.impl.SerializeKeyDescription, + } + + # 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/TestVectorsAwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptography_materialproviders_test_vectors/smithygenerated/aws_cryptography_materialproviderstestvectorkeys/dafny_protocol.py b/TestVectorsAwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptography_materialproviders_test_vectors/smithygenerated/aws_cryptography_materialproviderstestvectorkeys/dafny_protocol.py new file mode 100644 index 000000000..036d42a86 --- /dev/null +++ b/TestVectorsAwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptography_materialproviders_test_vectors/smithygenerated/aws_cryptography_materialproviderstestvectorkeys/dafny_protocol.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_cryptography_materialproviders_test_vectors.internaldafny.generated.AwsCryptographyMaterialProvidersTestVectorKeysTypes import ( + GetKeyDescriptionInput_GetKeyDescriptionInput as DafnyGetKeyDescriptionInput, + SerializeKeyDescriptionInput_SerializeKeyDescriptionInput as DafnySerializeKeyDescriptionInput, + TestVectorCmmInput_TestVectorCmmInput as DafnyTestVectorCmmInput, + TestVectorKeyringInput_TestVectorKeyringInput as DafnyTestVectorKeyringInput, +) +import aws_cryptography_materialproviders_test_vectors.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[ + DafnyGetKeyDescriptionInput, + DafnySerializeKeyDescriptionInput, + DafnyTestVectorKeyringInput, + DafnyTestVectorCmmInput, + ] + + 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/TestVectorsAwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptography_materialproviders_test_vectors/smithygenerated/aws_cryptography_materialproviderstestvectorkeys/dafny_to_aws_sdk.py b/TestVectorsAwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptography_materialproviders_test_vectors/smithygenerated/aws_cryptography_materialproviderstestvectorkeys/dafny_to_aws_sdk.py new file mode 100644 index 000000000..4bdc4dd35 --- /dev/null +++ b/TestVectorsAwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptography_materialproviders_test_vectors/smithygenerated/aws_cryptography_materialproviderstestvectorkeys/dafny_to_aws_sdk.py @@ -0,0 +1,25 @@ +# 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_cryptography_internal_kms.internaldafny.generated.ComAmazonawsKmsTypes import ( + EncryptionAlgorithmSpec_RSAES__OAEP__SHA__1, + EncryptionAlgorithmSpec_RSAES__OAEP__SHA__256, + EncryptionAlgorithmSpec_SYMMETRIC__DEFAULT, +) +import aws_cryptography_internal_kms.internaldafny.generated.module_ + + +def com_amazonaws_kms_EncryptionAlgorithmSpec(dafny_input): + # Convert EncryptionAlgorithmSpec + if isinstance(dafny_input, EncryptionAlgorithmSpec_SYMMETRIC__DEFAULT): + return "SYMMETRIC_DEFAULT" + + elif isinstance(dafny_input, EncryptionAlgorithmSpec_RSAES__OAEP__SHA__1): + return "RSAES_OAEP_SHA_1" + + elif isinstance(dafny_input, EncryptionAlgorithmSpec_RSAES__OAEP__SHA__256): + return "RSAES_OAEP_SHA_256" + + else: + raise ValueError("No recognized enum value in enum type: " + dafny_input) diff --git a/TestVectorsAwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptography_materialproviders_test_vectors/smithygenerated/aws_cryptography_materialproviderstestvectorkeys/dafny_to_smithy.py b/TestVectorsAwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptography_materialproviders_test_vectors/smithygenerated/aws_cryptography_materialproviderstestvectorkeys/dafny_to_smithy.py new file mode 100644 index 000000000..f56156022 --- /dev/null +++ b/TestVectorsAwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptography_materialproviders_test_vectors/smithygenerated/aws_cryptography_materialproviderstestvectorkeys/dafny_to_smithy.py @@ -0,0 +1,363 @@ +# 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_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy +import aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk +from aws_cryptography_materialproviders_test_vectors.internaldafny.generated.AwsCryptographyMaterialProvidersTestVectorKeysTypes import ( + CmmOperation_DECRYPT, + CmmOperation_ENCRYPT, + KeyDescription_AES, + KeyDescription_ECDH, + KeyDescription_Hierarchy, + KeyDescription_Kms, + KeyDescription_KmsECDH, + KeyDescription_KmsMrk, + KeyDescription_KmsMrkDiscovery, + KeyDescription_KmsRsa, + KeyDescription_Multi, + KeyDescription_RSA, + KeyDescription_RequiredEncryptionContext, + KeyDescription_Static, +) +import aws_cryptography_materialproviders_test_vectors.internaldafny.generated.module_ +import aws_cryptography_materialproviders_test_vectors.smithygenerated.aws_cryptography_materialproviderstestvectorkeys.dafny_to_smithy +import aws_cryptography_materialproviders_test_vectors.smithygenerated.aws_cryptography_materialproviderstestvectorkeys.models + + +def aws_cryptography_materialproviderstestvectorkeys_KeyDescription(dafny_input): + # Convert KeyDescription + if isinstance(dafny_input, KeyDescription_Kms): + KeyDescription_union_value = aws_cryptography_materialproviders_test_vectors.smithygenerated.aws_cryptography_materialproviderstestvectorkeys.models.KeyDescriptionKms( + aws_cryptography_materialproviders_test_vectors.smithygenerated.aws_cryptography_materialproviderstestvectorkeys.dafny_to_smithy.aws_cryptography_materialproviderstestvectorkeys_KMSInfo( + dafny_input.Kms + ) + ) + elif isinstance(dafny_input, KeyDescription_KmsMrk): + KeyDescription_union_value = aws_cryptography_materialproviders_test_vectors.smithygenerated.aws_cryptography_materialproviderstestvectorkeys.models.KeyDescriptionKmsMrk( + aws_cryptography_materialproviders_test_vectors.smithygenerated.aws_cryptography_materialproviderstestvectorkeys.dafny_to_smithy.aws_cryptography_materialproviderstestvectorkeys_KmsMrkAware( + dafny_input.KmsMrk + ) + ) + elif isinstance(dafny_input, KeyDescription_KmsMrkDiscovery): + KeyDescription_union_value = aws_cryptography_materialproviders_test_vectors.smithygenerated.aws_cryptography_materialproviderstestvectorkeys.models.KeyDescriptionKmsMrkDiscovery( + aws_cryptography_materialproviders_test_vectors.smithygenerated.aws_cryptography_materialproviderstestvectorkeys.dafny_to_smithy.aws_cryptography_materialproviderstestvectorkeys_KmsMrkAwareDiscovery( + dafny_input.KmsMrkDiscovery + ) + ) + elif isinstance(dafny_input, KeyDescription_RSA): + KeyDescription_union_value = aws_cryptography_materialproviders_test_vectors.smithygenerated.aws_cryptography_materialproviderstestvectorkeys.models.KeyDescriptionRSA( + aws_cryptography_materialproviders_test_vectors.smithygenerated.aws_cryptography_materialproviderstestvectorkeys.dafny_to_smithy.aws_cryptography_materialproviderstestvectorkeys_RawRSA( + dafny_input.RSA + ) + ) + elif isinstance(dafny_input, KeyDescription_AES): + KeyDescription_union_value = aws_cryptography_materialproviders_test_vectors.smithygenerated.aws_cryptography_materialproviderstestvectorkeys.models.KeyDescriptionAES( + aws_cryptography_materialproviders_test_vectors.smithygenerated.aws_cryptography_materialproviderstestvectorkeys.dafny_to_smithy.aws_cryptography_materialproviderstestvectorkeys_RawAES( + dafny_input.AES + ) + ) + elif isinstance(dafny_input, KeyDescription_ECDH): + KeyDescription_union_value = aws_cryptography_materialproviders_test_vectors.smithygenerated.aws_cryptography_materialproviderstestvectorkeys.models.KeyDescriptionECDH( + aws_cryptography_materialproviders_test_vectors.smithygenerated.aws_cryptography_materialproviderstestvectorkeys.dafny_to_smithy.aws_cryptography_materialproviderstestvectorkeys_RawEcdh( + dafny_input.ECDH + ) + ) + elif isinstance(dafny_input, KeyDescription_Static): + KeyDescription_union_value = aws_cryptography_materialproviders_test_vectors.smithygenerated.aws_cryptography_materialproviderstestvectorkeys.models.KeyDescriptionStatic( + aws_cryptography_materialproviders_test_vectors.smithygenerated.aws_cryptography_materialproviderstestvectorkeys.dafny_to_smithy.aws_cryptography_materialproviderstestvectorkeys_StaticKeyring( + dafny_input.Static + ) + ) + elif isinstance(dafny_input, KeyDescription_KmsRsa): + KeyDescription_union_value = aws_cryptography_materialproviders_test_vectors.smithygenerated.aws_cryptography_materialproviderstestvectorkeys.models.KeyDescriptionKmsRsa( + aws_cryptography_materialproviders_test_vectors.smithygenerated.aws_cryptography_materialproviderstestvectorkeys.dafny_to_smithy.aws_cryptography_materialproviderstestvectorkeys_KmsRsaKeyring( + dafny_input.KmsRsa + ) + ) + elif isinstance(dafny_input, KeyDescription_KmsECDH): + KeyDescription_union_value = aws_cryptography_materialproviders_test_vectors.smithygenerated.aws_cryptography_materialproviderstestvectorkeys.models.KeyDescriptionKmsECDH( + aws_cryptography_materialproviders_test_vectors.smithygenerated.aws_cryptography_materialproviderstestvectorkeys.dafny_to_smithy.aws_cryptography_materialproviderstestvectorkeys_KmsEcdhKeyring( + dafny_input.KmsECDH + ) + ) + elif isinstance(dafny_input, KeyDescription_Hierarchy): + KeyDescription_union_value = aws_cryptography_materialproviders_test_vectors.smithygenerated.aws_cryptography_materialproviderstestvectorkeys.models.KeyDescriptionHierarchy( + aws_cryptography_materialproviders_test_vectors.smithygenerated.aws_cryptography_materialproviderstestvectorkeys.dafny_to_smithy.aws_cryptography_materialproviderstestvectorkeys_HierarchyKeyring( + dafny_input.Hierarchy + ) + ) + elif isinstance(dafny_input, KeyDescription_Multi): + KeyDescription_union_value = aws_cryptography_materialproviders_test_vectors.smithygenerated.aws_cryptography_materialproviderstestvectorkeys.models.KeyDescriptionMulti( + aws_cryptography_materialproviders_test_vectors.smithygenerated.aws_cryptography_materialproviderstestvectorkeys.dafny_to_smithy.aws_cryptography_materialproviderstestvectorkeys_MultiKeyring( + dafny_input.Multi + ) + ) + elif isinstance(dafny_input, KeyDescription_RequiredEncryptionContext): + KeyDescription_union_value = aws_cryptography_materialproviders_test_vectors.smithygenerated.aws_cryptography_materialproviderstestvectorkeys.models.KeyDescriptionRequiredEncryptionContext( + aws_cryptography_materialproviders_test_vectors.smithygenerated.aws_cryptography_materialproviderstestvectorkeys.dafny_to_smithy.aws_cryptography_materialproviderstestvectorkeys_RequiredEncryptionContextCMM( + dafny_input.RequiredEncryptionContext + ) + ) + else: + raise ValueError("No recognized union value in union type: " + str(dafny_input)) + + return KeyDescription_union_value + + +def aws_cryptography_materialproviderstestvectorkeys_KMSInfo(dafny_input): + return aws_cryptography_materialproviders_test_vectors.smithygenerated.aws_cryptography_materialproviderstestvectorkeys.models.KMSInfo( + key_id=b"".join(ord(c).to_bytes(2, "big") for c in dafny_input.keyId).decode( + "utf-16-be" + ), + ) + + +def aws_cryptography_materialproviderstestvectorkeys_KmsMrkAware(dafny_input): + return aws_cryptography_materialproviders_test_vectors.smithygenerated.aws_cryptography_materialproviderstestvectorkeys.models.KmsMrkAware( + key_id=b"".join(ord(c).to_bytes(2, "big") for c in dafny_input.keyId).decode( + "utf-16-be" + ), + ) + + +def aws_cryptography_materialproviderstestvectorkeys_KmsMrkAwareDiscovery(dafny_input): + return aws_cryptography_materialproviders_test_vectors.smithygenerated.aws_cryptography_materialproviderstestvectorkeys.models.KmsMrkAwareDiscovery( + key_id=b"".join(ord(c).to_bytes(2, "big") for c in dafny_input.keyId).decode( + "utf-16-be" + ), + default_mrk_region=b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.defaultMrkRegion + ).decode("utf-16-be"), + aws_kms_discovery_filter=( + ( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_DiscoveryFilter( + dafny_input.awsKmsDiscoveryFilter.value + ) + ) + if (dafny_input.awsKmsDiscoveryFilter.is_Some) + else None + ), + ) + + +def aws_cryptography_materialproviderstestvectorkeys_RawRSA(dafny_input): + return aws_cryptography_materialproviders_test_vectors.smithygenerated.aws_cryptography_materialproviderstestvectorkeys.models.RawRSA( + key_id=b"".join(ord(c).to_bytes(2, "big") for c in dafny_input.keyId).decode( + "utf-16-be" + ), + provider_id=b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.providerId + ).decode("utf-16-be"), + padding=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_PaddingScheme( + dafny_input.padding + ), + ) + + +def aws_cryptography_materialproviderstestvectorkeys_RawAES(dafny_input): + return aws_cryptography_materialproviders_test_vectors.smithygenerated.aws_cryptography_materialproviderstestvectorkeys.models.RawAES( + key_id=b"".join(ord(c).to_bytes(2, "big") for c in dafny_input.keyId).decode( + "utf-16-be" + ), + provider_id=b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.providerId + ).decode("utf-16-be"), + ) + + +def aws_cryptography_materialproviderstestvectorkeys_RawEcdh(dafny_input): + return aws_cryptography_materialproviders_test_vectors.smithygenerated.aws_cryptography_materialproviderstestvectorkeys.models.RawEcdh( + sender_key_id=b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.senderKeyId + ).decode("utf-16-be"), + recipient_key_id=b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.recipientKeyId + ).decode("utf-16-be"), + sender_public_key=b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.senderPublicKey + ).decode("utf-16-be"), + recipient_public_key=b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.recipientPublicKey + ).decode("utf-16-be"), + provider_id=b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.providerId + ).decode("utf-16-be"), + curve_spec=b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.curveSpec + ).decode("utf-16-be"), + key_agreement_scheme=b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.keyAgreementScheme + ).decode("utf-16-be"), + ) + + +def aws_cryptography_materialproviderstestvectorkeys_StaticKeyring(dafny_input): + return aws_cryptography_materialproviders_test_vectors.smithygenerated.aws_cryptography_materialproviderstestvectorkeys.models.StaticKeyring( + key_id=b"".join(ord(c).to_bytes(2, "big") for c in dafny_input.keyId).decode( + "utf-16-be" + ), + ) + + +def aws_cryptography_materialproviderstestvectorkeys_KmsRsaKeyring(dafny_input): + return aws_cryptography_materialproviders_test_vectors.smithygenerated.aws_cryptography_materialproviderstestvectorkeys.models.KmsRsaKeyring( + key_id=b"".join(ord(c).to_bytes(2, "big") for c in dafny_input.keyId).decode( + "utf-16-be" + ), + encryption_algorithm=aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.dafny_to_aws_sdk.com_amazonaws_kms_EncryptionAlgorithmSpec( + dafny_input.encryptionAlgorithm + ), + ) + + +def aws_cryptography_materialproviderstestvectorkeys_KmsEcdhKeyring(dafny_input): + return aws_cryptography_materialproviders_test_vectors.smithygenerated.aws_cryptography_materialproviderstestvectorkeys.models.KmsEcdhKeyring( + sender_key_id=b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.senderKeyId + ).decode("utf-16-be"), + recipient_key_id=b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.recipientKeyId + ).decode("utf-16-be"), + sender_public_key=b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.senderPublicKey + ).decode("utf-16-be"), + recipient_public_key=b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.recipientPublicKey + ).decode("utf-16-be"), + curve_spec=b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.curveSpec + ).decode("utf-16-be"), + key_agreement_scheme=b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.keyAgreementScheme + ).decode("utf-16-be"), + ) + + +def aws_cryptography_materialproviderstestvectorkeys_HierarchyKeyring(dafny_input): + return aws_cryptography_materialproviders_test_vectors.smithygenerated.aws_cryptography_materialproviderstestvectorkeys.models.HierarchyKeyring( + key_id=b"".join(ord(c).to_bytes(2, "big") for c in dafny_input.keyId).decode( + "utf-16-be" + ), + ) + + +def aws_cryptography_materialproviderstestvectorkeys_MultiKeyring(dafny_input): + return aws_cryptography_materialproviders_test_vectors.smithygenerated.aws_cryptography_materialproviderstestvectorkeys.models.MultiKeyring( + generator=( + ( + aws_cryptography_materialproviders_test_vectors.smithygenerated.aws_cryptography_materialproviderstestvectorkeys.dafny_to_smithy.aws_cryptography_materialproviderstestvectorkeys_KeyDescription( + dafny_input.generator.value + ) + ) + if (dafny_input.generator.is_Some) + else None + ), + child_keyrings=[ + aws_cryptography_materialproviders_test_vectors.smithygenerated.aws_cryptography_materialproviderstestvectorkeys.dafny_to_smithy.aws_cryptography_materialproviderstestvectorkeys_KeyDescription( + list_element + ) + for list_element in dafny_input.childKeyrings + ], + ) + + +def aws_cryptography_materialproviderstestvectorkeys_RequiredEncryptionContextCMM( + dafny_input, +): + return aws_cryptography_materialproviders_test_vectors.smithygenerated.aws_cryptography_materialproviderstestvectorkeys.models.RequiredEncryptionContextCMM( + underlying=aws_cryptography_materialproviders_test_vectors.smithygenerated.aws_cryptography_materialproviderstestvectorkeys.dafny_to_smithy.aws_cryptography_materialproviderstestvectorkeys_KeyDescription( + dafny_input.underlying + ), + required_encryption_context_keys=[ + bytes(list_element.Elements).decode("utf-8") + for list_element in dafny_input.requiredEncryptionContextKeys + ], + ) + + +def aws_cryptography_materialproviderstestvectorkeys_TestVectorKeyringInput( + dafny_input, +): + return aws_cryptography_materialproviders_test_vectors.smithygenerated.aws_cryptography_materialproviderstestvectorkeys.models.TestVectorKeyringInput( + key_description=aws_cryptography_materialproviders_test_vectors.smithygenerated.aws_cryptography_materialproviderstestvectorkeys.dafny_to_smithy.aws_cryptography_materialproviderstestvectorkeys_KeyDescription( + dafny_input.keyDescription + ), + ) + + +def aws_cryptography_materialproviderstestvectorkeys_CmmOperation(dafny_input): + if isinstance(dafny_input, CmmOperation_ENCRYPT): + return "ENCRYPT" + + elif isinstance(dafny_input, CmmOperation_DECRYPT): + return "DECRYPT" + + else: + raise ValueError(f"No recognized enum value in enum type: {dafny_input=}") + + +def aws_cryptography_materialproviderstestvectorkeys_TestVectorCmmInput(dafny_input): + return aws_cryptography_materialproviders_test_vectors.smithygenerated.aws_cryptography_materialproviderstestvectorkeys.models.TestVectorCmmInput( + key_description=aws_cryptography_materialproviders_test_vectors.smithygenerated.aws_cryptography_materialproviderstestvectorkeys.dafny_to_smithy.aws_cryptography_materialproviderstestvectorkeys_KeyDescription( + dafny_input.keyDescription + ), + for_operation=aws_cryptography_materialproviders_test_vectors.smithygenerated.aws_cryptography_materialproviderstestvectorkeys.dafny_to_smithy.aws_cryptography_materialproviderstestvectorkeys_CmmOperation( + dafny_input.forOperation + ), + ) + + +def aws_cryptography_materialproviderstestvectorkeys_GetKeyDescriptionInput( + dafny_input, +): + return aws_cryptography_materialproviders_test_vectors.smithygenerated.aws_cryptography_materialproviderstestvectorkeys.models.GetKeyDescriptionInput( + json=bytes(dafny_input.json), + ) + + +def aws_cryptography_materialproviderstestvectorkeys_SerializeKeyDescriptionInput( + dafny_input, +): + return aws_cryptography_materialproviders_test_vectors.smithygenerated.aws_cryptography_materialproviderstestvectorkeys.models.SerializeKeyDescriptionInput( + key_description=aws_cryptography_materialproviders_test_vectors.smithygenerated.aws_cryptography_materialproviderstestvectorkeys.dafny_to_smithy.aws_cryptography_materialproviderstestvectorkeys_KeyDescription( + dafny_input.keyDescription + ), + ) + + +def aws_cryptography_materialproviderstestvectorkeys_CreateWrappedTestVectorCmmOutput( + dafny_input, +): + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_CryptographicMaterialsManagerReference( + dafny_input + ) + + +def aws_cryptography_materialproviderstestvectorkeys_GetKeyDescriptionOutput( + dafny_input, +): + return aws_cryptography_materialproviders_test_vectors.smithygenerated.aws_cryptography_materialproviderstestvectorkeys.models.GetKeyDescriptionOutput( + key_description=aws_cryptography_materialproviders_test_vectors.smithygenerated.aws_cryptography_materialproviderstestvectorkeys.dafny_to_smithy.aws_cryptography_materialproviderstestvectorkeys_KeyDescription( + dafny_input.keyDescription + ), + ) + + +def aws_cryptography_materialproviderstestvectorkeys_SerializeKeyDescriptionOutput( + dafny_input, +): + return aws_cryptography_materialproviders_test_vectors.smithygenerated.aws_cryptography_materialproviderstestvectorkeys.models.SerializeKeyDescriptionOutput( + json=bytes(dafny_input.json), + ) + + +def aws_cryptography_materialproviderstestvectorkeys_KeyVectorsConfig(dafny_input): + # Deferred import of .config to avoid circular dependency + import aws_cryptography_materialproviders_test_vectors.smithygenerated.aws_cryptography_materialproviderstestvectorkeys.config + + return aws_cryptography_materialproviders_test_vectors.smithygenerated.aws_cryptography_materialproviderstestvectorkeys.config.KeyVectorsConfig( + key_manifest_path=b"".join( + ord(c).to_bytes(2, "big") for c in dafny_input.keyManifestPath + ).decode("utf-16-be"), + ) diff --git a/TestVectorsAwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptography_materialproviders_test_vectors/smithygenerated/aws_cryptography_materialproviderstestvectorkeys/deserialize.py b/TestVectorsAwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptography_materialproviders_test_vectors/smithygenerated/aws_cryptography_materialproviderstestvectorkeys/deserialize.py new file mode 100644 index 000000000..ae2d7d8db --- /dev/null +++ b/TestVectorsAwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptography_materialproviders_test_vectors/smithygenerated/aws_cryptography_materialproviderstestvectorkeys/deserialize.py @@ -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. + +import _dafny +import aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy +from aws_cryptography_materialproviders_test_vectors.internaldafny.generated.AwsCryptographyMaterialProvidersTestVectorKeysTypes import ( + Error, + Error_KeyVectorException, + GetKeyDescriptionOutput_GetKeyDescriptionOutput as DafnyGetKeyDescriptionOutput, + SerializeKeyDescriptionOutput_SerializeKeyDescriptionOutput as DafnySerializeKeyDescriptionOutput, +) +import aws_cryptography_materialproviders_test_vectors.internaldafny.generated.module_ +import aws_cryptography_materialproviders_test_vectors.smithygenerated.aws_cryptography_materialproviderstestvectorkeys.dafny_to_smithy +from typing import Any + +from .dafny_protocol import DafnyResponse +from .errors import CollectionOfErrors, KeyVectorException, OpaqueError, ServiceError + +from .config import Config + + +def _deserialize_create_test_vector_keyring(input: DafnyResponse, config: Config): + + if input.IsFailure(): + return _deserialize_error(input.error) + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_CreateKeyringOutput( + input.value + ) + + +def _deserialize_create_wrapped_test_vector_keyring( + input: DafnyResponse, config: Config +): + + if input.IsFailure(): + return _deserialize_error(input.error) + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.dafny_to_smithy.aws_cryptography_materialproviders_CreateKeyringOutput( + input.value + ) + + +def _deserialize_create_wrapped_test_vector_cmm(input: DafnyResponse, config: Config): + + if input.IsFailure(): + return _deserialize_error(input.error) + return aws_cryptography_materialproviders_test_vectors.smithygenerated.aws_cryptography_materialproviderstestvectorkeys.dafny_to_smithy.aws_cryptography_materialproviderstestvectorkeys_CreateWrappedTestVectorCmmOutput( + input.value + ) + + +def _deserialize_get_key_description(input: DafnyResponse, config: Config): + + if input.IsFailure(): + return _deserialize_error(input.error) + return aws_cryptography_materialproviders_test_vectors.smithygenerated.aws_cryptography_materialproviderstestvectorkeys.dafny_to_smithy.aws_cryptography_materialproviderstestvectorkeys_GetKeyDescriptionOutput( + input.value + ) + + +def _deserialize_serialize_key_description(input: DafnyResponse, config: Config): + + if input.IsFailure(): + return _deserialize_error(input.error) + return aws_cryptography_materialproviders_test_vectors.smithygenerated.aws_cryptography_materialproviderstestvectorkeys.dafny_to_smithy.aws_cryptography_materialproviderstestvectorkeys_SerializeKeyDescriptionOutput( + input.value + ) + + +def _deserialize_error(error: Error) -> ServiceError: + if error.is_Opaque: + return OpaqueError(obj=error.obj) + 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_KeyVectorException: + return KeyVectorException(message=_dafny.string_of(error.message)) + else: + return OpaqueError(obj=error) diff --git a/TestVectorsAwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptography_materialproviders_test_vectors/smithygenerated/aws_cryptography_materialproviderstestvectorkeys/errors.py b/TestVectorsAwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptography_materialproviders_test_vectors/smithygenerated/aws_cryptography_materialproviderstestvectorkeys/errors.py new file mode 100644 index 000000000..283ad1174 --- /dev/null +++ b/TestVectorsAwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptography_materialproviders_test_vectors/smithygenerated/aws_cryptography_materialproviderstestvectorkeys/errors.py @@ -0,0 +1,170 @@ +# 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_cryptography_materialproviders_test_vectors.internaldafny.generated +import aws_cryptography_materialproviders_test_vectors.internaldafny.generated.AwsCryptographyMaterialProvidersTestVectorKeysTypes +import aws_cryptography_materialproviders_test_vectors.smithygenerated.aws_cryptography_materialproviderstestvectorkeys.errors +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 KeyVectorException(ApiError[Literal["KeyVectorException"]]): + code: Literal["KeyVectorException"] = "KeyVectorException" + message: str + + +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) + + +def _smithy_error_to_dafny_error(e: ServiceError): + """Converts the provided native Smithy-modeled error into the corresponding + Dafny error.""" + if isinstance( + e, + aws_cryptography_materialproviders_test_vectors.smithygenerated.aws_cryptography_materialproviderstestvectorkeys.errors.KeyVectorException, + ): + return aws_cryptography_materialproviders_test_vectors.internaldafny.generated.AwsCryptographyMaterialProvidersTestVectorKeysTypes.Error_KeyVectorException( + message=_dafny.Seq(e.message) + ) + + if isinstance(e, CollectionOfErrors): + return aws_cryptography_materialproviders_test_vectors.internaldafny.generated.AwsCryptographyMaterialProvidersTestVectorKeysTypes.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_cryptography_materialproviders_test_vectors.internaldafny.generated.AwsCryptographyMaterialProvidersTestVectorKeysTypes.Error_Opaque( + obj=e.obj + ) + + else: + return aws_cryptography_materialproviders_test_vectors.internaldafny.generated.AwsCryptographyMaterialProvidersTestVectorKeysTypes.Error_Opaque( + obj=e + ) diff --git a/TestVectorsAwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptography_materialproviders_test_vectors/smithygenerated/aws_cryptography_materialproviderstestvectorkeys/models.py b/TestVectorsAwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptography_materialproviders_test_vectors/smithygenerated/aws_cryptography_materialproviderstestvectorkeys/models.py new file mode 100644 index 000000000..7d3851eb3 --- /dev/null +++ b/TestVectorsAwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptography_materialproviders_test_vectors/smithygenerated/aws_cryptography_materialproviderstestvectorkeys/models.py @@ -0,0 +1,1330 @@ +# 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_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.models import ( + DiscoveryFilter, +) + + +class CmmOperation: + ENCRYPT = "ENCRYPT" + + DECRYPT = "DECRYPT" + + # This set contains every possible value known at the time this was generated. New + # values may be added in the future. + values = frozenset({"ENCRYPT", "DECRYPT"}) + + +class RawAES: + key_id: str + provider_id: str + + def __init__( + self, + *, + key_id: str, + provider_id: str, + ): + self.key_id = key_id + self.provider_id = provider_id + + def as_dict(self) -> Dict[str, Any]: + """Converts the RawAES to a dictionary.""" + return { + "key_id": self.key_id, + "provider_id": self.provider_id, + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "RawAES": + """Creates a RawAES from a dictionary.""" + kwargs: Dict[str, Any] = { + "key_id": d["key_id"], + "provider_id": d["provider_id"], + } + + return RawAES(**kwargs) + + def __repr__(self) -> str: + result = "RawAES(" + if self.key_id is not None: + result += f"key_id={repr(self.key_id)}, " + + if self.provider_id is not None: + result += f"provider_id={repr(self.provider_id)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, RawAES): + return False + attributes: list[str] = [ + "key_id", + "provider_id", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class RawEcdh: + sender_key_id: str + recipient_key_id: str + sender_public_key: str + recipient_public_key: str + provider_id: str + curve_spec: str + key_agreement_scheme: str + + def __init__( + self, + *, + sender_key_id: str, + recipient_key_id: str, + sender_public_key: str, + recipient_public_key: str, + provider_id: str, + curve_spec: str, + key_agreement_scheme: str, + ): + self.sender_key_id = sender_key_id + self.recipient_key_id = recipient_key_id + self.sender_public_key = sender_public_key + self.recipient_public_key = recipient_public_key + self.provider_id = provider_id + self.curve_spec = curve_spec + self.key_agreement_scheme = key_agreement_scheme + + def as_dict(self) -> Dict[str, Any]: + """Converts the RawEcdh to a dictionary.""" + return { + "sender_key_id": self.sender_key_id, + "recipient_key_id": self.recipient_key_id, + "sender_public_key": self.sender_public_key, + "recipient_public_key": self.recipient_public_key, + "provider_id": self.provider_id, + "curve_spec": self.curve_spec, + "key_agreement_scheme": self.key_agreement_scheme, + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "RawEcdh": + """Creates a RawEcdh from a dictionary.""" + kwargs: Dict[str, Any] = { + "sender_key_id": d["sender_key_id"], + "recipient_key_id": d["recipient_key_id"], + "sender_public_key": d["sender_public_key"], + "recipient_public_key": d["recipient_public_key"], + "provider_id": d["provider_id"], + "curve_spec": d["curve_spec"], + "key_agreement_scheme": d["key_agreement_scheme"], + } + + return RawEcdh(**kwargs) + + def __repr__(self) -> str: + result = "RawEcdh(" + if self.sender_key_id is not None: + result += f"sender_key_id={repr(self.sender_key_id)}, " + + if self.recipient_key_id is not None: + result += f"recipient_key_id={repr(self.recipient_key_id)}, " + + if self.sender_public_key is not None: + result += f"sender_public_key={repr(self.sender_public_key)}, " + + if self.recipient_public_key is not None: + result += f"recipient_public_key={repr(self.recipient_public_key)}, " + + if self.provider_id is not None: + result += f"provider_id={repr(self.provider_id)}, " + + if self.curve_spec is not None: + result += f"curve_spec={repr(self.curve_spec)}, " + + if self.key_agreement_scheme is not None: + result += f"key_agreement_scheme={repr(self.key_agreement_scheme)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, RawEcdh): + return False + attributes: list[str] = [ + "sender_key_id", + "recipient_key_id", + "sender_public_key", + "recipient_public_key", + "provider_id", + "curve_spec", + "key_agreement_scheme", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class HierarchyKeyring: + key_id: str + + def __init__( + self, + *, + key_id: str, + ): + self.key_id = key_id + + def as_dict(self) -> Dict[str, Any]: + """Converts the HierarchyKeyring to a dictionary.""" + return { + "key_id": self.key_id, + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "HierarchyKeyring": + """Creates a HierarchyKeyring from a dictionary.""" + kwargs: Dict[str, Any] = { + "key_id": d["key_id"], + } + + return HierarchyKeyring(**kwargs) + + def __repr__(self) -> str: + result = "HierarchyKeyring(" + if self.key_id is not None: + result += f"key_id={repr(self.key_id)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, HierarchyKeyring): + return False + attributes: list[str] = [ + "key_id", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class KMSInfo: + key_id: str + + def __init__( + self, + *, + key_id: str, + ): + self.key_id = key_id + + def as_dict(self) -> Dict[str, Any]: + """Converts the KMSInfo to a dictionary.""" + return { + "key_id": self.key_id, + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "KMSInfo": + """Creates a KMSInfo from a dictionary.""" + kwargs: Dict[str, Any] = { + "key_id": d["key_id"], + } + + return KMSInfo(**kwargs) + + def __repr__(self) -> str: + result = "KMSInfo(" + if self.key_id is not None: + result += f"key_id={repr(self.key_id)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, KMSInfo): + return False + attributes: list[str] = [ + "key_id", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class KmsEcdhKeyring: + sender_key_id: str + recipient_key_id: str + sender_public_key: str + recipient_public_key: str + curve_spec: str + key_agreement_scheme: str + + def __init__( + self, + *, + sender_key_id: str, + recipient_key_id: str, + sender_public_key: str, + recipient_public_key: str, + curve_spec: str, + key_agreement_scheme: str, + ): + self.sender_key_id = sender_key_id + self.recipient_key_id = recipient_key_id + self.sender_public_key = sender_public_key + self.recipient_public_key = recipient_public_key + self.curve_spec = curve_spec + self.key_agreement_scheme = key_agreement_scheme + + def as_dict(self) -> Dict[str, Any]: + """Converts the KmsEcdhKeyring to a dictionary.""" + return { + "sender_key_id": self.sender_key_id, + "recipient_key_id": self.recipient_key_id, + "sender_public_key": self.sender_public_key, + "recipient_public_key": self.recipient_public_key, + "curve_spec": self.curve_spec, + "key_agreement_scheme": self.key_agreement_scheme, + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "KmsEcdhKeyring": + """Creates a KmsEcdhKeyring from a dictionary.""" + kwargs: Dict[str, Any] = { + "sender_key_id": d["sender_key_id"], + "recipient_key_id": d["recipient_key_id"], + "sender_public_key": d["sender_public_key"], + "recipient_public_key": d["recipient_public_key"], + "curve_spec": d["curve_spec"], + "key_agreement_scheme": d["key_agreement_scheme"], + } + + return KmsEcdhKeyring(**kwargs) + + def __repr__(self) -> str: + result = "KmsEcdhKeyring(" + if self.sender_key_id is not None: + result += f"sender_key_id={repr(self.sender_key_id)}, " + + if self.recipient_key_id is not None: + result += f"recipient_key_id={repr(self.recipient_key_id)}, " + + if self.sender_public_key is not None: + result += f"sender_public_key={repr(self.sender_public_key)}, " + + if self.recipient_public_key is not None: + result += f"recipient_public_key={repr(self.recipient_public_key)}, " + + if self.curve_spec is not None: + result += f"curve_spec={repr(self.curve_spec)}, " + + if self.key_agreement_scheme is not None: + result += f"key_agreement_scheme={repr(self.key_agreement_scheme)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, KmsEcdhKeyring): + return False + attributes: list[str] = [ + "sender_key_id", + "recipient_key_id", + "sender_public_key", + "recipient_public_key", + "curve_spec", + "key_agreement_scheme", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class KmsMrkAware: + key_id: str + + def __init__( + self, + *, + key_id: str, + ): + self.key_id = key_id + + def as_dict(self) -> Dict[str, Any]: + """Converts the KmsMrkAware to a dictionary.""" + return { + "key_id": self.key_id, + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "KmsMrkAware": + """Creates a KmsMrkAware from a dictionary.""" + kwargs: Dict[str, Any] = { + "key_id": d["key_id"], + } + + return KmsMrkAware(**kwargs) + + def __repr__(self) -> str: + result = "KmsMrkAware(" + if self.key_id is not None: + result += f"key_id={repr(self.key_id)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, KmsMrkAware): + return False + attributes: list[str] = [ + "key_id", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class KmsMrkAwareDiscovery: + key_id: str + default_mrk_region: str + aws_kms_discovery_filter: Optional[DiscoveryFilter] + + def __init__( + self, + *, + key_id: str, + default_mrk_region: str, + aws_kms_discovery_filter: Optional[DiscoveryFilter] = None, + ): + """ + :param aws_kms_discovery_filter: A filter which defines what AWS partition and + AWS accounts a KMS Key may be in for a Keyring to be allowed to attempt to + decrypt it. + """ + self.key_id = key_id + self.default_mrk_region = default_mrk_region + self.aws_kms_discovery_filter = aws_kms_discovery_filter + + def as_dict(self) -> Dict[str, Any]: + """Converts the KmsMrkAwareDiscovery to a dictionary.""" + d: Dict[str, Any] = { + "key_id": self.key_id, + "default_mrk_region": self.default_mrk_region, + } + + if self.aws_kms_discovery_filter is not None: + d["aws_kms_discovery_filter"] = self.aws_kms_discovery_filter.as_dict() + + return d + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "KmsMrkAwareDiscovery": + """Creates a KmsMrkAwareDiscovery from a dictionary.""" + kwargs: Dict[str, Any] = { + "key_id": d["key_id"], + "default_mrk_region": d["default_mrk_region"], + } + + if "aws_kms_discovery_filter" in d: + kwargs["aws_kms_discovery_filter"] = DiscoveryFilter.from_dict( + d["aws_kms_discovery_filter"] + ) + + return KmsMrkAwareDiscovery(**kwargs) + + def __repr__(self) -> str: + result = "KmsMrkAwareDiscovery(" + if self.key_id is not None: + result += f"key_id={repr(self.key_id)}, " + + if self.default_mrk_region is not None: + result += f"default_mrk_region={repr(self.default_mrk_region)}, " + + if self.aws_kms_discovery_filter is not None: + result += f"aws_kms_discovery_filter={repr(self.aws_kms_discovery_filter)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, KmsMrkAwareDiscovery): + return False + attributes: list[str] = [ + "key_id", + "default_mrk_region", + "aws_kms_discovery_filter", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class KmsRsaKeyring: + key_id: str + encryption_algorithm: str + + def __init__( + self, + *, + key_id: str, + encryption_algorithm: str, + ): + self.key_id = key_id + self.encryption_algorithm = encryption_algorithm + + def as_dict(self) -> Dict[str, Any]: + """Converts the KmsRsaKeyring to a dictionary.""" + return { + "key_id": self.key_id, + "encryption_algorithm": self.encryption_algorithm, + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "KmsRsaKeyring": + """Creates a KmsRsaKeyring from a dictionary.""" + kwargs: Dict[str, Any] = { + "key_id": d["key_id"], + "encryption_algorithm": d["encryption_algorithm"], + } + + return KmsRsaKeyring(**kwargs) + + def __repr__(self) -> str: + result = "KmsRsaKeyring(" + if self.key_id is not None: + result += f"key_id={repr(self.key_id)}, " + + if self.encryption_algorithm is not None: + result += f"encryption_algorithm={repr(self.encryption_algorithm)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, KmsRsaKeyring): + return False + attributes: list[str] = [ + "key_id", + "encryption_algorithm", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class RawRSA: + key_id: str + provider_id: str + padding: str + + def __init__( + self, + *, + key_id: str, + provider_id: str, + padding: str, + ): + self.key_id = key_id + self.provider_id = provider_id + self.padding = padding + + def as_dict(self) -> Dict[str, Any]: + """Converts the RawRSA to a dictionary.""" + return { + "key_id": self.key_id, + "provider_id": self.provider_id, + "padding": self.padding, + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "RawRSA": + """Creates a RawRSA from a dictionary.""" + kwargs: Dict[str, Any] = { + "key_id": d["key_id"], + "provider_id": d["provider_id"], + "padding": d["padding"], + } + + return RawRSA(**kwargs) + + def __repr__(self) -> str: + result = "RawRSA(" + if self.key_id is not None: + result += f"key_id={repr(self.key_id)}, " + + if self.provider_id is not None: + result += f"provider_id={repr(self.provider_id)}, " + + if self.padding is not None: + result += f"padding={repr(self.padding)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, RawRSA): + return False + attributes: list[str] = [ + "key_id", + "provider_id", + "padding", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class StaticKeyring: + key_id: str + + def __init__( + self, + *, + key_id: str, + ): + self.key_id = key_id + + def as_dict(self) -> Dict[str, Any]: + """Converts the StaticKeyring to a dictionary.""" + return { + "key_id": self.key_id, + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "StaticKeyring": + """Creates a StaticKeyring from a dictionary.""" + kwargs: Dict[str, Any] = { + "key_id": d["key_id"], + } + + return StaticKeyring(**kwargs) + + def __repr__(self) -> str: + result = "StaticKeyring(" + if self.key_id is not None: + result += f"key_id={repr(self.key_id)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, StaticKeyring): + return False + attributes: list[str] = [ + "key_id", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class GetKeyDescriptionInput: + json: bytes | bytearray + + def __init__( + self, + *, + json: bytes | bytearray, + ): + self.json = json + + def as_dict(self) -> Dict[str, Any]: + """Converts the GetKeyDescriptionInput to a dictionary.""" + return { + "json": self.json, + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "GetKeyDescriptionInput": + """Creates a GetKeyDescriptionInput from a dictionary.""" + kwargs: Dict[str, Any] = { + "json": d["json"], + } + + return GetKeyDescriptionInput(**kwargs) + + def __repr__(self) -> str: + result = "GetKeyDescriptionInput(" + if self.json is not None: + result += f"json={repr(self.json)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, GetKeyDescriptionInput): + return False + attributes: list[str] = [ + "json", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class SerializeKeyDescriptionOutput: + json: bytes | bytearray + + def __init__( + self, + *, + json: bytes | bytearray, + ): + self.json = json + + def as_dict(self) -> Dict[str, Any]: + """Converts the SerializeKeyDescriptionOutput to a dictionary.""" + return { + "json": self.json, + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "SerializeKeyDescriptionOutput": + """Creates a SerializeKeyDescriptionOutput from a dictionary.""" + kwargs: Dict[str, Any] = { + "json": d["json"], + } + + return SerializeKeyDescriptionOutput(**kwargs) + + def __repr__(self) -> str: + result = "SerializeKeyDescriptionOutput(" + if self.json is not None: + result += f"json={repr(self.json)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, SerializeKeyDescriptionOutput): + return False + attributes: list[str] = [ + "json", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class KeyDescriptionKms: + def __init__(self, value: KMSInfo): + self.value = value + + def as_dict(self) -> Dict[str, Any]: + return {"Kms": self.value.as_dict()} + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "KeyDescriptionKms": + if len(d) != 1: + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + + return KeyDescriptionKms(KMSInfo.from_dict(d["Kms"])) + + def __repr__(self) -> str: + return f"KeyDescriptionKms(value=repr(self.value))" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, KeyDescriptionKms): + return False + return self.value == other.value + + +class KeyDescriptionKmsMrk: + def __init__(self, value: KmsMrkAware): + self.value = value + + def as_dict(self) -> Dict[str, Any]: + return {"KmsMrk": self.value.as_dict()} + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "KeyDescriptionKmsMrk": + if len(d) != 1: + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + + return KeyDescriptionKmsMrk(KmsMrkAware.from_dict(d["KmsMrk"])) + + def __repr__(self) -> str: + return f"KeyDescriptionKmsMrk(value=repr(self.value))" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, KeyDescriptionKmsMrk): + return False + return self.value == other.value + + +class KeyDescriptionKmsMrkDiscovery: + def __init__(self, value: KmsMrkAwareDiscovery): + self.value = value + + def as_dict(self) -> Dict[str, Any]: + return {"KmsMrkDiscovery": self.value.as_dict()} + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "KeyDescriptionKmsMrkDiscovery": + if len(d) != 1: + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + + return KeyDescriptionKmsMrkDiscovery( + KmsMrkAwareDiscovery.from_dict(d["KmsMrkDiscovery"]) + ) + + def __repr__(self) -> str: + return f"KeyDescriptionKmsMrkDiscovery(value=repr(self.value))" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, KeyDescriptionKmsMrkDiscovery): + return False + return self.value == other.value + + +class KeyDescriptionRSA: + def __init__(self, value: RawRSA): + self.value = value + + def as_dict(self) -> Dict[str, Any]: + return {"RSA": self.value.as_dict()} + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "KeyDescriptionRSA": + if len(d) != 1: + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + + return KeyDescriptionRSA(RawRSA.from_dict(d["RSA"])) + + def __repr__(self) -> str: + return f"KeyDescriptionRSA(value=repr(self.value))" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, KeyDescriptionRSA): + return False + return self.value == other.value + + +class KeyDescriptionAES: + def __init__(self, value: RawAES): + self.value = value + + def as_dict(self) -> Dict[str, Any]: + return {"AES": self.value.as_dict()} + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "KeyDescriptionAES": + if len(d) != 1: + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + + return KeyDescriptionAES(RawAES.from_dict(d["AES"])) + + def __repr__(self) -> str: + return f"KeyDescriptionAES(value=repr(self.value))" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, KeyDescriptionAES): + return False + return self.value == other.value + + +class KeyDescriptionECDH: + def __init__(self, value: RawEcdh): + self.value = value + + def as_dict(self) -> Dict[str, Any]: + return {"ECDH": self.value.as_dict()} + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "KeyDescriptionECDH": + if len(d) != 1: + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + + return KeyDescriptionECDH(RawEcdh.from_dict(d["ECDH"])) + + def __repr__(self) -> str: + return f"KeyDescriptionECDH(value=repr(self.value))" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, KeyDescriptionECDH): + return False + return self.value == other.value + + +class KeyDescriptionStatic: + def __init__(self, value: StaticKeyring): + self.value = value + + def as_dict(self) -> Dict[str, Any]: + return {"Static": self.value.as_dict()} + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "KeyDescriptionStatic": + if len(d) != 1: + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + + return KeyDescriptionStatic(StaticKeyring.from_dict(d["Static"])) + + def __repr__(self) -> str: + return f"KeyDescriptionStatic(value=repr(self.value))" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, KeyDescriptionStatic): + return False + return self.value == other.value + + +class KeyDescriptionKmsRsa: + def __init__(self, value: KmsRsaKeyring): + self.value = value + + def as_dict(self) -> Dict[str, Any]: + return {"KmsRsa": self.value.as_dict()} + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "KeyDescriptionKmsRsa": + if len(d) != 1: + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + + return KeyDescriptionKmsRsa(KmsRsaKeyring.from_dict(d["KmsRsa"])) + + def __repr__(self) -> str: + return f"KeyDescriptionKmsRsa(value=repr(self.value))" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, KeyDescriptionKmsRsa): + return False + return self.value == other.value + + +class KeyDescriptionKmsECDH: + def __init__(self, value: KmsEcdhKeyring): + self.value = value + + def as_dict(self) -> Dict[str, Any]: + return {"KmsECDH": self.value.as_dict()} + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "KeyDescriptionKmsECDH": + if len(d) != 1: + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + + return KeyDescriptionKmsECDH(KmsEcdhKeyring.from_dict(d["KmsECDH"])) + + def __repr__(self) -> str: + return f"KeyDescriptionKmsECDH(value=repr(self.value))" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, KeyDescriptionKmsECDH): + return False + return self.value == other.value + + +class KeyDescriptionHierarchy: + def __init__(self, value: HierarchyKeyring): + self.value = value + + def as_dict(self) -> Dict[str, Any]: + return {"Hierarchy": self.value.as_dict()} + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "KeyDescriptionHierarchy": + if len(d) != 1: + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + + return KeyDescriptionHierarchy(HierarchyKeyring.from_dict(d["Hierarchy"])) + + def __repr__(self) -> str: + return f"KeyDescriptionHierarchy(value=repr(self.value))" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, KeyDescriptionHierarchy): + return False + return self.value == other.value + + +class KeyDescriptionMulti: + def __init__(self, value: "MultiKeyring"): + self.value = value + + def as_dict(self) -> Dict[str, Any]: + return {"Multi": self.value.as_dict()} + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "KeyDescriptionMulti": + if len(d) != 1: + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + + return KeyDescriptionMulti(MultiKeyring.from_dict(d["Multi"])) + + def __repr__(self) -> str: + return f"KeyDescriptionMulti(value=repr(self.value))" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, KeyDescriptionMulti): + return False + return self.value == other.value + + +class KeyDescriptionRequiredEncryptionContext: + def __init__(self, value: "RequiredEncryptionContextCMM"): + self.value = value + + def as_dict(self) -> Dict[str, Any]: + return {"RequiredEncryptionContext": self.value.as_dict()} + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "KeyDescriptionRequiredEncryptionContext": + if len(d) != 1: + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + + return KeyDescriptionRequiredEncryptionContext( + RequiredEncryptionContextCMM.from_dict(d["RequiredEncryptionContext"]) + ) + + def __repr__(self) -> str: + return f"KeyDescriptionRequiredEncryptionContext(value=repr(self.value))" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, KeyDescriptionRequiredEncryptionContext): + return False + return self.value == other.value + + +class KeyDescriptionUnknown: + """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]) -> "KeyDescriptionUnknown": + if len(d) != 1: + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + return KeyDescriptionUnknown(d["SDK_UNKNOWN_MEMBER"]["name"]) + + def __repr__(self) -> str: + return f"KeyDescriptionUnknown(tag={self.tag})" + + +KeyDescription = Union[ + KeyDescriptionKms, + KeyDescriptionKmsMrk, + KeyDescriptionKmsMrkDiscovery, + KeyDescriptionRSA, + KeyDescriptionAES, + KeyDescriptionECDH, + KeyDescriptionStatic, + KeyDescriptionKmsRsa, + KeyDescriptionKmsECDH, + KeyDescriptionHierarchy, + KeyDescriptionMulti, + KeyDescriptionRequiredEncryptionContext, + KeyDescriptionUnknown, +] + + +def _key_description_from_dict(d: Dict[str, Any]) -> KeyDescription: + if "Kms" in d: + return KeyDescriptionKms.from_dict(d) + + if "KmsMrk" in d: + return KeyDescriptionKmsMrk.from_dict(d) + + if "KmsMrkDiscovery" in d: + return KeyDescriptionKmsMrkDiscovery.from_dict(d) + + if "RSA" in d: + return KeyDescriptionRSA.from_dict(d) + + if "AES" in d: + return KeyDescriptionAES.from_dict(d) + + if "ECDH" in d: + return KeyDescriptionECDH.from_dict(d) + + if "Static" in d: + return KeyDescriptionStatic.from_dict(d) + + if "KmsRsa" in d: + return KeyDescriptionKmsRsa.from_dict(d) + + if "KmsECDH" in d: + return KeyDescriptionKmsECDH.from_dict(d) + + if "Hierarchy" in d: + return KeyDescriptionHierarchy.from_dict(d) + + if "Multi" in d: + return KeyDescriptionMulti.from_dict(d) + + if "RequiredEncryptionContext" in d: + return KeyDescriptionRequiredEncryptionContext.from_dict(d) + + raise TypeError(f"Unions may have exactly 1 value, but found {len(d)}") + + +class RequiredEncryptionContextCMM: + underlying: "KeyDescription" + required_encryption_context_keys: list[str] + + def __init__( + self, + *, + underlying: "KeyDescription", + required_encryption_context_keys: list[str], + ): + self.underlying = underlying + self.required_encryption_context_keys = required_encryption_context_keys + + def as_dict(self) -> Dict[str, Any]: + """Converts the RequiredEncryptionContextCMM to a dictionary.""" + return { + "underlying": self.underlying.as_dict(), + "required_encryption_context_keys": self.required_encryption_context_keys, + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "RequiredEncryptionContextCMM": + """Creates a RequiredEncryptionContextCMM from a dictionary.""" + kwargs: Dict[str, Any] = { + "underlying": _key_description_from_dict(d["underlying"]), + "required_encryption_context_keys": d["required_encryption_context_keys"], + } + + return RequiredEncryptionContextCMM(**kwargs) + + def __repr__(self) -> str: + result = "RequiredEncryptionContextCMM(" + if self.underlying is not None: + result += f"underlying={repr(self.underlying)}, " + + if self.required_encryption_context_keys is not None: + result += f"required_encryption_context_keys={repr(self.required_encryption_context_keys)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, RequiredEncryptionContextCMM): + return False + attributes: list[str] = [ + "underlying", + "required_encryption_context_keys", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class GetKeyDescriptionOutput: + key_description: "KeyDescription" + + def __init__( + self, + *, + key_description: "KeyDescription", + ): + self.key_description = key_description + + def as_dict(self) -> Dict[str, Any]: + """Converts the GetKeyDescriptionOutput to a dictionary.""" + return { + "key_description": self.key_description.as_dict(), + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "GetKeyDescriptionOutput": + """Creates a GetKeyDescriptionOutput from a dictionary.""" + kwargs: Dict[str, Any] = { + "key_description": _key_description_from_dict(d["key_description"]), + } + + return GetKeyDescriptionOutput(**kwargs) + + def __repr__(self) -> str: + result = "GetKeyDescriptionOutput(" + if self.key_description is not None: + result += f"key_description={repr(self.key_description)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, GetKeyDescriptionOutput): + return False + attributes: list[str] = [ + "key_description", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class SerializeKeyDescriptionInput: + key_description: "KeyDescription" + + def __init__( + self, + *, + key_description: "KeyDescription", + ): + self.key_description = key_description + + def as_dict(self) -> Dict[str, Any]: + """Converts the SerializeKeyDescriptionInput to a dictionary.""" + return { + "key_description": self.key_description.as_dict(), + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "SerializeKeyDescriptionInput": + """Creates a SerializeKeyDescriptionInput from a dictionary.""" + kwargs: Dict[str, Any] = { + "key_description": _key_description_from_dict(d["key_description"]), + } + + return SerializeKeyDescriptionInput(**kwargs) + + def __repr__(self) -> str: + result = "SerializeKeyDescriptionInput(" + if self.key_description is not None: + result += f"key_description={repr(self.key_description)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, SerializeKeyDescriptionInput): + return False + attributes: list[str] = [ + "key_description", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class TestVectorCmmInput: + key_description: "KeyDescription" + for_operation: str + + def __init__( + self, + *, + key_description: "KeyDescription", + for_operation: str, + ): + self.key_description = key_description + self.for_operation = for_operation + + def as_dict(self) -> Dict[str, Any]: + """Converts the TestVectorCmmInput to a dictionary.""" + return { + "key_description": self.key_description.as_dict(), + "for_operation": self.for_operation, + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "TestVectorCmmInput": + """Creates a TestVectorCmmInput from a dictionary.""" + kwargs: Dict[str, Any] = { + "key_description": _key_description_from_dict(d["key_description"]), + "for_operation": d["for_operation"], + } + + return TestVectorCmmInput(**kwargs) + + def __repr__(self) -> str: + result = "TestVectorCmmInput(" + if self.key_description is not None: + result += f"key_description={repr(self.key_description)}, " + + if self.for_operation is not None: + result += f"for_operation={repr(self.for_operation)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, TestVectorCmmInput): + return False + attributes: list[str] = [ + "key_description", + "for_operation", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class TestVectorKeyringInput: + key_description: "KeyDescription" + + def __init__( + self, + *, + key_description: "KeyDescription", + ): + self.key_description = key_description + + def as_dict(self) -> Dict[str, Any]: + """Converts the TestVectorKeyringInput to a dictionary.""" + return { + "key_description": self.key_description.as_dict(), + } + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "TestVectorKeyringInput": + """Creates a TestVectorKeyringInput from a dictionary.""" + kwargs: Dict[str, Any] = { + "key_description": _key_description_from_dict(d["key_description"]), + } + + return TestVectorKeyringInput(**kwargs) + + def __repr__(self) -> str: + result = "TestVectorKeyringInput(" + if self.key_description is not None: + result += f"key_description={repr(self.key_description)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, TestVectorKeyringInput): + return False + attributes: list[str] = [ + "key_description", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +class MultiKeyring: + generator: Optional["KeyDescription"] + child_keyrings: "list[KeyDescription]" + + def __init__( + self, + *, + child_keyrings: "list[KeyDescription]", + generator: Optional["KeyDescription"] = None, + ): + self.child_keyrings = child_keyrings + self.generator = generator + + def as_dict(self) -> Dict[str, Any]: + """Converts the MultiKeyring to a dictionary.""" + d: Dict[str, Any] = { + "child_keyrings": _key_description_list_as_dict(self.child_keyrings), + } + + if self.generator is not None: + d["generator"] = self.generator.as_dict() + + return d + + @staticmethod + def from_dict(d: Dict[str, Any]) -> "MultiKeyring": + """Creates a MultiKeyring from a dictionary.""" + kwargs: Dict[str, Any] = { + "child_keyrings": _key_description_list_from_dict(d["child_keyrings"]), + } + + if "generator" in d: + kwargs["generator"] = (_key_description_from_dict(d["generator"]),) + + return MultiKeyring(**kwargs) + + def __repr__(self) -> str: + result = "MultiKeyring(" + if self.generator is not None: + result += f"generator={repr(self.generator)}, " + + if self.child_keyrings is not None: + result += f"child_keyrings={repr(self.child_keyrings)}" + + return result + ")" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, MultiKeyring): + return False + attributes: list[str] = [ + "generator", + "child_keyrings", + ] + return all(getattr(self, a) == getattr(other, a) for a in attributes) + + +def _key_description_list_as_dict(given: list[KeyDescription]) -> List[Any]: + return [v.as_dict() for v in given] + + +def _key_description_list_from_dict(given: List[Any]) -> list[KeyDescription]: + return [KeyDescription.from_dict(v) for v in given] + + +class Unit: + pass diff --git a/TestVectorsAwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptography_materialproviders_test_vectors/smithygenerated/aws_cryptography_materialproviderstestvectorkeys/plugin.py b/TestVectorsAwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptography_materialproviders_test_vectors/smithygenerated/aws_cryptography_materialproviderstestvectorkeys/plugin.py new file mode 100644 index 000000000..5e5c15b4d --- /dev/null +++ b/TestVectorsAwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptography_materialproviders_test_vectors/smithygenerated/aws_cryptography_materialproviderstestvectorkeys/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, KeyVectorsConfig +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, KeyVectorsConfig): + from aws_cryptography_materialproviders_test_vectors.internaldafny.generated.KeyVectors import ( + default__, + ) + + config.dafnyImplInterface.impl = default__.KeyVectors( + 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/TestVectorsAwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptography_materialproviders_test_vectors/smithygenerated/aws_cryptography_materialproviderstestvectorkeys/serialize.py b/TestVectorsAwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptography_materialproviders_test_vectors/smithygenerated/aws_cryptography_materialproviderstestvectorkeys/serialize.py new file mode 100644 index 000000000..9efdef9ad --- /dev/null +++ b/TestVectorsAwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptography_materialproviders_test_vectors/smithygenerated/aws_cryptography_materialproviderstestvectorkeys/serialize.py @@ -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. + +import aws_cryptography_materialproviders_test_vectors.smithygenerated.aws_cryptography_materialproviderstestvectorkeys.smithy_to_dafny + +from .dafny_protocol import DafnyRequest + +from .config import Config + + +def _serialize_create_test_vector_keyring(input, config: Config) -> DafnyRequest: + return DafnyRequest( + operation_name="CreateTestVectorKeyring", + dafny_operation_input=aws_cryptography_materialproviders_test_vectors.smithygenerated.aws_cryptography_materialproviderstestvectorkeys.smithy_to_dafny.aws_cryptography_materialproviderstestvectorkeys_TestVectorKeyringInput( + input + ), + ) + + +def _serialize_create_wrapped_test_vector_keyring( + input, config: Config +) -> DafnyRequest: + return DafnyRequest( + operation_name="CreateWrappedTestVectorKeyring", + dafny_operation_input=aws_cryptography_materialproviders_test_vectors.smithygenerated.aws_cryptography_materialproviderstestvectorkeys.smithy_to_dafny.aws_cryptography_materialproviderstestvectorkeys_TestVectorKeyringInput( + input + ), + ) + + +def _serialize_create_wrapped_test_vector_cmm(input, config: Config) -> DafnyRequest: + return DafnyRequest( + operation_name="CreateWrappedTestVectorCmm", + dafny_operation_input=aws_cryptography_materialproviders_test_vectors.smithygenerated.aws_cryptography_materialproviderstestvectorkeys.smithy_to_dafny.aws_cryptography_materialproviderstestvectorkeys_TestVectorCmmInput( + input + ), + ) + + +def _serialize_get_key_description(input, config: Config) -> DafnyRequest: + return DafnyRequest( + operation_name="GetKeyDescription", + dafny_operation_input=aws_cryptography_materialproviders_test_vectors.smithygenerated.aws_cryptography_materialproviderstestvectorkeys.smithy_to_dafny.aws_cryptography_materialproviderstestvectorkeys_GetKeyDescriptionInput( + input + ), + ) + + +def _serialize_serialize_key_description(input, config: Config) -> DafnyRequest: + return DafnyRequest( + operation_name="SerializeKeyDescription", + dafny_operation_input=aws_cryptography_materialproviders_test_vectors.smithygenerated.aws_cryptography_materialproviderstestvectorkeys.smithy_to_dafny.aws_cryptography_materialproviderstestvectorkeys_SerializeKeyDescriptionInput( + input + ), + ) diff --git a/TestVectorsAwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptography_materialproviders_test_vectors/smithygenerated/aws_cryptography_materialproviderstestvectorkeys/smithy_to_dafny.py b/TestVectorsAwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptography_materialproviders_test_vectors/smithygenerated/aws_cryptography_materialproviderstestvectorkeys/smithy_to_dafny.py new file mode 100644 index 000000000..0267c658a --- /dev/null +++ b/TestVectorsAwsCryptographicMaterialProviders/runtimes/python/src/aws_cryptography_materialproviders_test_vectors/smithygenerated/aws_cryptography_materialproviderstestvectorkeys/smithy_to_dafny.py @@ -0,0 +1,608 @@ +# 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 Seq +import aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny +import aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny +from aws_cryptography_materialproviders_test_vectors.internaldafny.generated.AwsCryptographyMaterialProvidersTestVectorKeysTypes import ( + CmmOperation_DECRYPT, + CmmOperation_ENCRYPT, + GetKeyDescriptionInput_GetKeyDescriptionInput as DafnyGetKeyDescriptionInput, + GetKeyDescriptionOutput_GetKeyDescriptionOutput as DafnyGetKeyDescriptionOutput, + HierarchyKeyring_HierarchyKeyring as DafnyHierarchyKeyring, + KMSInfo_KMSInfo as DafnyKMSInfo, + KeyDescription_AES, + KeyDescription_ECDH, + KeyDescription_Hierarchy, + KeyDescription_Kms, + KeyDescription_KmsECDH, + KeyDescription_KmsMrk, + KeyDescription_KmsMrkDiscovery, + KeyDescription_KmsRsa, + KeyDescription_Multi, + KeyDescription_RSA, + KeyDescription_RequiredEncryptionContext, + KeyDescription_Static, + KeyVectorsConfig_KeyVectorsConfig as DafnyKeyVectorsConfig, + KmsEcdhKeyring_KmsEcdhKeyring as DafnyKmsEcdhKeyring, + KmsMrkAwareDiscovery_KmsMrkAwareDiscovery as DafnyKmsMrkAwareDiscovery, + KmsMrkAware_KmsMrkAware as DafnyKmsMrkAware, + KmsRsaKeyring_KmsRsaKeyring as DafnyKmsRsaKeyring, + MultiKeyring_MultiKeyring as DafnyMultiKeyring, + RawAES_RawAES as DafnyRawAES, + RawEcdh_RawEcdh as DafnyRawEcdh, + RawRSA_RawRSA as DafnyRawRSA, + RequiredEncryptionContextCMM_RequiredEncryptionContextCMM as DafnyRequiredEncryptionContextCMM, + SerializeKeyDescriptionInput_SerializeKeyDescriptionInput as DafnySerializeKeyDescriptionInput, + SerializeKeyDescriptionOutput_SerializeKeyDescriptionOutput as DafnySerializeKeyDescriptionOutput, + StaticKeyring_StaticKeyring as DafnyStaticKeyring, + TestVectorCmmInput_TestVectorCmmInput as DafnyTestVectorCmmInput, + TestVectorKeyringInput_TestVectorKeyringInput as DafnyTestVectorKeyringInput, +) +import aws_cryptography_materialproviders_test_vectors.internaldafny.generated.module_ +import aws_cryptography_materialproviders_test_vectors.smithygenerated.aws_cryptography_materialproviderstestvectorkeys.models +import aws_cryptography_materialproviders_test_vectors.smithygenerated.aws_cryptography_materialproviderstestvectorkeys.smithy_to_dafny +from smithy_dafny_standard_library.internaldafny.generated.Wrappers import ( + Option_None, + Option_Some, +) + + +def aws_cryptography_materialproviderstestvectorkeys_TestVectorKeyringInput( + native_input, +): + return DafnyTestVectorKeyringInput( + keyDescription=aws_cryptography_materialproviders_test_vectors.smithygenerated.aws_cryptography_materialproviderstestvectorkeys.smithy_to_dafny.aws_cryptography_materialproviderstestvectorkeys_KeyDescription( + native_input.key_description + ), + ) + + +def aws_cryptography_materialproviderstestvectorkeys_KeyDescription(native_input): + if isinstance( + native_input, + aws_cryptography_materialproviders_test_vectors.smithygenerated.aws_cryptography_materialproviderstestvectorkeys.models.KeyDescriptionKms, + ): + KeyDescription_union_value = KeyDescription_Kms( + aws_cryptography_materialproviders_test_vectors.smithygenerated.aws_cryptography_materialproviderstestvectorkeys.smithy_to_dafny.aws_cryptography_materialproviderstestvectorkeys_KMSInfo( + native_input.value + ) + ) + elif isinstance( + native_input, + aws_cryptography_materialproviders_test_vectors.smithygenerated.aws_cryptography_materialproviderstestvectorkeys.models.KeyDescriptionKmsMrk, + ): + KeyDescription_union_value = KeyDescription_KmsMrk( + aws_cryptography_materialproviders_test_vectors.smithygenerated.aws_cryptography_materialproviderstestvectorkeys.smithy_to_dafny.aws_cryptography_materialproviderstestvectorkeys_KmsMrkAware( + native_input.value + ) + ) + elif isinstance( + native_input, + aws_cryptography_materialproviders_test_vectors.smithygenerated.aws_cryptography_materialproviderstestvectorkeys.models.KeyDescriptionKmsMrkDiscovery, + ): + KeyDescription_union_value = KeyDescription_KmsMrkDiscovery( + aws_cryptography_materialproviders_test_vectors.smithygenerated.aws_cryptography_materialproviderstestvectorkeys.smithy_to_dafny.aws_cryptography_materialproviderstestvectorkeys_KmsMrkAwareDiscovery( + native_input.value + ) + ) + elif isinstance( + native_input, + aws_cryptography_materialproviders_test_vectors.smithygenerated.aws_cryptography_materialproviderstestvectorkeys.models.KeyDescriptionRSA, + ): + KeyDescription_union_value = KeyDescription_RSA( + aws_cryptography_materialproviders_test_vectors.smithygenerated.aws_cryptography_materialproviderstestvectorkeys.smithy_to_dafny.aws_cryptography_materialproviderstestvectorkeys_RawRSA( + native_input.value + ) + ) + elif isinstance( + native_input, + aws_cryptography_materialproviders_test_vectors.smithygenerated.aws_cryptography_materialproviderstestvectorkeys.models.KeyDescriptionAES, + ): + KeyDescription_union_value = KeyDescription_AES( + aws_cryptography_materialproviders_test_vectors.smithygenerated.aws_cryptography_materialproviderstestvectorkeys.smithy_to_dafny.aws_cryptography_materialproviderstestvectorkeys_RawAES( + native_input.value + ) + ) + elif isinstance( + native_input, + aws_cryptography_materialproviders_test_vectors.smithygenerated.aws_cryptography_materialproviderstestvectorkeys.models.KeyDescriptionECDH, + ): + KeyDescription_union_value = KeyDescription_ECDH( + aws_cryptography_materialproviders_test_vectors.smithygenerated.aws_cryptography_materialproviderstestvectorkeys.smithy_to_dafny.aws_cryptography_materialproviderstestvectorkeys_RawEcdh( + native_input.value + ) + ) + elif isinstance( + native_input, + aws_cryptography_materialproviders_test_vectors.smithygenerated.aws_cryptography_materialproviderstestvectorkeys.models.KeyDescriptionStatic, + ): + KeyDescription_union_value = KeyDescription_Static( + aws_cryptography_materialproviders_test_vectors.smithygenerated.aws_cryptography_materialproviderstestvectorkeys.smithy_to_dafny.aws_cryptography_materialproviderstestvectorkeys_StaticKeyring( + native_input.value + ) + ) + elif isinstance( + native_input, + aws_cryptography_materialproviders_test_vectors.smithygenerated.aws_cryptography_materialproviderstestvectorkeys.models.KeyDescriptionKmsRsa, + ): + KeyDescription_union_value = KeyDescription_KmsRsa( + aws_cryptography_materialproviders_test_vectors.smithygenerated.aws_cryptography_materialproviderstestvectorkeys.smithy_to_dafny.aws_cryptography_materialproviderstestvectorkeys_KmsRsaKeyring( + native_input.value + ) + ) + elif isinstance( + native_input, + aws_cryptography_materialproviders_test_vectors.smithygenerated.aws_cryptography_materialproviderstestvectorkeys.models.KeyDescriptionKmsECDH, + ): + KeyDescription_union_value = KeyDescription_KmsECDH( + aws_cryptography_materialproviders_test_vectors.smithygenerated.aws_cryptography_materialproviderstestvectorkeys.smithy_to_dafny.aws_cryptography_materialproviderstestvectorkeys_KmsEcdhKeyring( + native_input.value + ) + ) + elif isinstance( + native_input, + aws_cryptography_materialproviders_test_vectors.smithygenerated.aws_cryptography_materialproviderstestvectorkeys.models.KeyDescriptionHierarchy, + ): + KeyDescription_union_value = KeyDescription_Hierarchy( + aws_cryptography_materialproviders_test_vectors.smithygenerated.aws_cryptography_materialproviderstestvectorkeys.smithy_to_dafny.aws_cryptography_materialproviderstestvectorkeys_HierarchyKeyring( + native_input.value + ) + ) + elif isinstance( + native_input, + aws_cryptography_materialproviders_test_vectors.smithygenerated.aws_cryptography_materialproviderstestvectorkeys.models.KeyDescriptionMulti, + ): + KeyDescription_union_value = KeyDescription_Multi( + aws_cryptography_materialproviders_test_vectors.smithygenerated.aws_cryptography_materialproviderstestvectorkeys.smithy_to_dafny.aws_cryptography_materialproviderstestvectorkeys_MultiKeyring( + native_input.value + ) + ) + elif isinstance( + native_input, + aws_cryptography_materialproviders_test_vectors.smithygenerated.aws_cryptography_materialproviderstestvectorkeys.models.KeyDescriptionRequiredEncryptionContext, + ): + KeyDescription_union_value = KeyDescription_RequiredEncryptionContext( + aws_cryptography_materialproviders_test_vectors.smithygenerated.aws_cryptography_materialproviderstestvectorkeys.smithy_to_dafny.aws_cryptography_materialproviderstestvectorkeys_RequiredEncryptionContextCMM( + native_input.value + ) + ) + else: + raise ValueError( + "No recognized union value in union type: " + str(native_input) + ) + + return KeyDescription_union_value + + +def aws_cryptography_materialproviderstestvectorkeys_KMSInfo(native_input): + return DafnyKMSInfo( + keyId=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input.key_id.encode("utf-16-be"))] * 2 + ) + ] + ) + ), + ) + + +def aws_cryptography_materialproviderstestvectorkeys_KmsMrkAware(native_input): + return DafnyKmsMrkAware( + keyId=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input.key_id.encode("utf-16-be"))] * 2 + ) + ] + ) + ), + ) + + +def aws_cryptography_materialproviderstestvectorkeys_KmsMrkAwareDiscovery(native_input): + return DafnyKmsMrkAwareDiscovery( + keyId=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input.key_id.encode("utf-16-be"))] * 2 + ) + ] + ) + ), + defaultMrkRegion=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input.default_mrk_region.encode("utf-16-be"))] * 2 + ) + ] + ) + ), + awsKmsDiscoveryFilter=( + ( + Option_Some( + aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_DiscoveryFilter( + native_input.aws_kms_discovery_filter + ) + ) + ) + if (native_input.aws_kms_discovery_filter is not None) + else (Option_None()) + ), + ) + + +def aws_cryptography_materialproviderstestvectorkeys_RawRSA(native_input): + return DafnyRawRSA( + keyId=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input.key_id.encode("utf-16-be"))] * 2 + ) + ] + ) + ), + providerId=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input.provider_id.encode("utf-16-be"))] * 2 + ) + ] + ) + ), + padding=aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_PaddingScheme( + native_input.padding + ), + ) + + +def aws_cryptography_materialproviderstestvectorkeys_RawAES(native_input): + return DafnyRawAES( + keyId=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input.key_id.encode("utf-16-be"))] * 2 + ) + ] + ) + ), + providerId=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input.provider_id.encode("utf-16-be"))] * 2 + ) + ] + ) + ), + ) + + +def aws_cryptography_materialproviderstestvectorkeys_RawEcdh(native_input): + return DafnyRawEcdh( + senderKeyId=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input.sender_key_id.encode("utf-16-be"))] * 2 + ) + ] + ) + ), + recipientKeyId=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input.recipient_key_id.encode("utf-16-be"))] * 2 + ) + ] + ) + ), + senderPublicKey=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input.sender_public_key.encode("utf-16-be"))] * 2 + ) + ] + ) + ), + recipientPublicKey=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input.recipient_public_key.encode("utf-16-be"))] + * 2 + ) + ] + ) + ), + providerId=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input.provider_id.encode("utf-16-be"))] * 2 + ) + ] + ) + ), + curveSpec=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input.curve_spec.encode("utf-16-be"))] * 2 + ) + ] + ) + ), + keyAgreementScheme=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input.key_agreement_scheme.encode("utf-16-be"))] + * 2 + ) + ] + ) + ), + ) + + +def aws_cryptography_materialproviderstestvectorkeys_StaticKeyring(native_input): + return DafnyStaticKeyring( + keyId=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input.key_id.encode("utf-16-be"))] * 2 + ) + ] + ) + ), + ) + + +def aws_cryptography_materialproviderstestvectorkeys_KmsRsaKeyring(native_input): + return DafnyKmsRsaKeyring( + keyId=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input.key_id.encode("utf-16-be"))] * 2 + ) + ] + ) + ), + encryptionAlgorithm=aws_cryptography_internal_kms.smithygenerated.com_amazonaws_kms.aws_sdk_to_dafny.com_amazonaws_kms_EncryptionAlgorithmSpec( + native_input.encryption_algorithm + ), + ) + + +def aws_cryptography_materialproviderstestvectorkeys_KmsEcdhKeyring(native_input): + return DafnyKmsEcdhKeyring( + senderKeyId=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input.sender_key_id.encode("utf-16-be"))] * 2 + ) + ] + ) + ), + recipientKeyId=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input.recipient_key_id.encode("utf-16-be"))] * 2 + ) + ] + ) + ), + senderPublicKey=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input.sender_public_key.encode("utf-16-be"))] * 2 + ) + ] + ) + ), + recipientPublicKey=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input.recipient_public_key.encode("utf-16-be"))] + * 2 + ) + ] + ) + ), + curveSpec=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input.curve_spec.encode("utf-16-be"))] * 2 + ) + ] + ) + ), + keyAgreementScheme=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input.key_agreement_scheme.encode("utf-16-be"))] + * 2 + ) + ] + ) + ), + ) + + +def aws_cryptography_materialproviderstestvectorkeys_HierarchyKeyring(native_input): + return DafnyHierarchyKeyring( + keyId=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input.key_id.encode("utf-16-be"))] * 2 + ) + ] + ) + ), + ) + + +def aws_cryptography_materialproviderstestvectorkeys_MultiKeyring(native_input): + return DafnyMultiKeyring( + generator=( + ( + Option_Some( + aws_cryptography_materialproviders_test_vectors.smithygenerated.aws_cryptography_materialproviderstestvectorkeys.smithy_to_dafny.aws_cryptography_materialproviderstestvectorkeys_KeyDescription( + native_input.generator + ) + ) + ) + if (native_input.generator is not None) + else (Option_None()) + ), + childKeyrings=Seq( + [ + aws_cryptography_materialproviders_test_vectors.smithygenerated.aws_cryptography_materialproviderstestvectorkeys.smithy_to_dafny.aws_cryptography_materialproviderstestvectorkeys_KeyDescription( + list_element + ) + for list_element in native_input.child_keyrings + ] + ), + ) + + +def aws_cryptography_materialproviderstestvectorkeys_RequiredEncryptionContextCMM( + native_input, +): + return DafnyRequiredEncryptionContextCMM( + underlying=aws_cryptography_materialproviders_test_vectors.smithygenerated.aws_cryptography_materialproviderstestvectorkeys.smithy_to_dafny.aws_cryptography_materialproviderstestvectorkeys_KeyDescription( + native_input.underlying + ), + requiredEncryptionContextKeys=Seq( + [ + Seq(list_element.encode("utf-8")) + for list_element in native_input.required_encryption_context_keys + ] + ), + ) + + +def aws_cryptography_materialproviderstestvectorkeys_TestVectorCmmInput(native_input): + return DafnyTestVectorCmmInput( + keyDescription=aws_cryptography_materialproviders_test_vectors.smithygenerated.aws_cryptography_materialproviderstestvectorkeys.smithy_to_dafny.aws_cryptography_materialproviderstestvectorkeys_KeyDescription( + native_input.key_description + ), + forOperation=aws_cryptography_materialproviders_test_vectors.smithygenerated.aws_cryptography_materialproviderstestvectorkeys.smithy_to_dafny.aws_cryptography_materialproviderstestvectorkeys_CmmOperation( + native_input.for_operation + ), + ) + + +def aws_cryptography_materialproviderstestvectorkeys_CmmOperation(native_input): + if native_input == "ENCRYPT": + return CmmOperation_ENCRYPT() + + elif native_input == "DECRYPT": + return CmmOperation_DECRYPT() + + else: + raise ValueError(f"No recognized enum value in enum type: {native_input=}") + + +def aws_cryptography_materialproviderstestvectorkeys_GetKeyDescriptionInput( + native_input, +): + return DafnyGetKeyDescriptionInput( + json=Seq(native_input.json), + ) + + +def aws_cryptography_materialproviderstestvectorkeys_SerializeKeyDescriptionInput( + native_input, +): + return DafnySerializeKeyDescriptionInput( + keyDescription=aws_cryptography_materialproviders_test_vectors.smithygenerated.aws_cryptography_materialproviderstestvectorkeys.smithy_to_dafny.aws_cryptography_materialproviderstestvectorkeys_KeyDescription( + native_input.key_description + ), + ) + + +def aws_cryptography_materialproviderstestvectorkeys_CreateWrappedTestVectorCmmOutput( + native_input, +): + return aws_cryptographic_materialproviders.smithygenerated.aws_cryptography_materialproviders.smithy_to_dafny.aws_cryptography_materialproviders_CryptographicMaterialsManagerReference( + native_input + ) + + +def aws_cryptography_materialproviderstestvectorkeys_GetKeyDescriptionOutput( + native_input, +): + return DafnyGetKeyDescriptionOutput( + keyDescription=aws_cryptography_materialproviders_test_vectors.smithygenerated.aws_cryptography_materialproviderstestvectorkeys.smithy_to_dafny.aws_cryptography_materialproviderstestvectorkeys_KeyDescription( + native_input.key_description + ), + ) + + +def aws_cryptography_materialproviderstestvectorkeys_SerializeKeyDescriptionOutput( + native_input, +): + return DafnySerializeKeyDescriptionOutput( + json=Seq(native_input.json), + ) + + +def aws_cryptography_materialproviderstestvectorkeys_KeyVectorsConfig(native_input): + return DafnyKeyVectorsConfig( + keyManifestPath=Seq( + "".join( + [ + chr(int.from_bytes(pair, "big")) + for pair in zip( + *[iter(native_input.key_manifest_path.encode("utf-16-be"))] * 2 + ) + ] + ) + ), + ) diff --git a/TestVectorsAwsCryptographicMaterialProviders/runtimes/python/test/__init__.py b/TestVectorsAwsCryptographicMaterialProviders/runtimes/python/test/__init__.py new file mode 100644 index 000000000..f94fd12a2 --- /dev/null +++ b/TestVectorsAwsCryptographicMaterialProviders/runtimes/python/test/__init__.py @@ -0,0 +1,2 @@ +# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 diff --git a/TestVectorsAwsCryptographicMaterialProviders/runtimes/python/test/internaldafny/__init__.py b/TestVectorsAwsCryptographicMaterialProviders/runtimes/python/test/internaldafny/__init__.py new file mode 100644 index 000000000..f94fd12a2 --- /dev/null +++ b/TestVectorsAwsCryptographicMaterialProviders/runtimes/python/test/internaldafny/__init__.py @@ -0,0 +1,2 @@ +# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 diff --git a/TestVectorsAwsCryptographicMaterialProviders/runtimes/python/test/internaldafny/extern/GetTestDirectoryExtern.py b/TestVectorsAwsCryptographicMaterialProviders/runtimes/python/test/internaldafny/extern/GetTestDirectoryExtern.py new file mode 100644 index 000000000..9887426a1 --- /dev/null +++ b/TestVectorsAwsCryptographicMaterialProviders/runtimes/python/test/internaldafny/extern/GetTestDirectoryExtern.py @@ -0,0 +1,8 @@ +import TestWrappedMaterialProvidersMain +import os +import _dafny + +def GetTestVectorExecutionDirectory(): + return _dafny.Seq(os.getcwd() + "/../../") + +TestWrappedMaterialProvidersMain.default__.GetTestVectorExecutionDirectory = GetTestVectorExecutionDirectory \ No newline at end of file diff --git a/TestVectorsAwsCryptographicMaterialProviders/runtimes/python/test/internaldafny/extern/__init__.py b/TestVectorsAwsCryptographicMaterialProviders/runtimes/python/test/internaldafny/extern/__init__.py new file mode 100644 index 000000000..af51022be --- /dev/null +++ b/TestVectorsAwsCryptographicMaterialProviders/runtimes/python/test/internaldafny/extern/__init__.py @@ -0,0 +1,3 @@ +from . import ( + GetTestDirectoryExtern, +) \ No newline at end of file diff --git a/TestVectorsAwsCryptographicMaterialProviders/runtimes/python/test/internaldafny/test_dafny_wrapper.py b/TestVectorsAwsCryptographicMaterialProviders/runtimes/python/test/internaldafny/test_dafny_wrapper.py new file mode 100644 index 000000000..c59be6d1e --- /dev/null +++ b/TestVectorsAwsCryptographicMaterialProviders/runtimes/python/test/internaldafny/test_dafny_wrapper.py @@ -0,0 +1,21 @@ +# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 +""" +Wrapper file for executing Dafny tests from pytest. +This allows us to import modules required by Dafny-generated tests +before executing Dafny-generated tests. +pytest will find and execute the `test_dafny` method below, +which will execute the `internaldafny_test_executor.py` file in the `dafny` directory. +""" + +import sys + +internaldafny_dir = '/'.join(__file__.split("/")[:-1]) + +sys.path.append(internaldafny_dir + "/extern") +sys.path.append(internaldafny_dir + "/generated") + +from . import extern + +def test_dafny(): + from .generated import __main__ \ No newline at end of file diff --git a/TestVectorsAwsCryptographicMaterialProviders/runtimes/python/tox.ini b/TestVectorsAwsCryptographicMaterialProviders/runtimes/python/tox.ini new file mode 100644 index 000000000..b3761f5c7 --- /dev/null +++ b/TestVectorsAwsCryptographicMaterialProviders/runtimes/python/tox.ini @@ -0,0 +1,28 @@ +[tox] +isolated_build = True +envlist = + py{311,312}-{dafnytests,cli} + +[testenv:dafnytests] +skip_install = true +allowlist_externals = poetry +passenv = AWS_* +setenv = VIRTUALENV_DOWNLOAD=0 + PIP_DISABLE_PIP_VERSION_CHECK=1 +commands_pre = + poetry lock + poetry install --with test +commands = + poetry run pytest -s -v test/ + +[testenv:cli] +skip_install = true +allowlist_externals = poetry +passenv = AWS_* +setenv = VIRTUALENV_DOWNLOAD=0 + PIP_DISABLE_PIP_VERSION_CHECK=1 +commands_pre = + poetry lock + poetry install --with test +commands = + poetry run python src/aws_cryptography_materialproviders_test_vectors/internaldafny/generated {posargs} \ No newline at end of file diff --git a/cfn/python/MPL-Python.yml b/cfn/python/MPL-Python.yml new file mode 100644 index 000000000..8cc83074b --- /dev/null +++ b/cfn/python/MPL-Python.yml @@ -0,0 +1,405 @@ +# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0AWSTemplateFormatVersion: "2010-09-09" +AWSTemplateFormatVersion: 2010-09-09 +Description: >- + Template to build a CodeBuild Project, assumes that GitHub credentials are + already set up. +Parameters: + ProjectName: + Type: String + Description: The name of the CodeBuild Project + Default: AWS-MPL-Python + ProjectDescription: + Type: String + Description: The description for the CodeBuild Project + Default: CFN stack for managing CodeBuild projects for the AWS Material Providers Library Python + SourceLocation: + Type: String + Description: The https GitHub URL for the project + Default: "https://github.com/aws/aws-cryptographic-material-providers-library.git" + NumberOfBuildsInBatch: + Type: Number + MaxValue: 100 + MinValue: 1 + Default: 16 + Description: The number of builds you expect to run in a batch +Metadata: + "AWS::CloudFormation::Interface": + ParameterGroups: + - Label: + default: Crypto Tools CodeBuild Project Template + Parameters: + - ProjectName + - ProjectDescription + - SourceLocation + +Resources: + CodeBuildProjectTestRelease: + Type: "AWS::CodeBuild::Project" + Properties: + Name: !Sub "${ProjectName}-test-release" + Description: !Sub "CodeBuild project for ${ProjectName} to release to test PyPi." + Source: + Location: !Ref SourceLocation + BuildSpec: codebuild/release-python/test-release.yml + ## https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codebuild-project-source.html#cfn-codebuild-project-source-gitclonedepth + ## If this value is 0, greater than 25, or not provided then the full history is downloaded with each build project. + GitCloneDepth: 0 + GitSubmodulesConfig: + FetchSubmodules: true + InsecureSsl: false + ReportBuildStatus: false + Type: GITHUB + Artifacts: + Type: NO_ARTIFACTS + Cache: + Type: NO_CACHE + Environment: + ComputeType: BUILD_GENERAL1_LARGE + Image: "aws/codebuild/standard:7.0" + ImagePullCredentialsType: CODEBUILD + PrivilegedMode: false + Type: LINUX_CONTAINER + ServiceRole: !GetAtt CodeBuildTestReleaseServiceRole.Arn + TimeoutInMinutes: 60 + QueuedTimeoutInMinutes: 480 + EncryptionKey: !Sub "arn:aws:kms:${AWS::Region}:${AWS::AccountId}:alias/aws/s3" + BadgeEnabled: false + BuildBatchConfig: + ServiceRole: !GetAtt CodeBuildTestReleaseServiceRole.Arn + Restrictions: + MaximumBuildsAllowed: !Ref NumberOfBuildsInBatch + ComputeTypesAllowed: + - BUILD_GENERAL1_SMALL + - BUILD_GENERAL1_MEDIUM + - BUILD_GENERAL1_LARGE + TimeoutInMins: 480 + LogsConfig: + CloudWatchLogs: + Status: ENABLED + S3Logs: + Status: DISABLED + EncryptionDisabled: false + + # CodeBuildProjectProdRelease: + # Type: "AWS::CodeBuild::Project" + # Properties: + # Name: !Sub "${ProjectName}-prod-release" + # Description: !Sub "CodeBuild project for ${ProjectName} to release to prod PyPi." + # Source: + # Location: !Ref SourceLocation + # BuildSpec: codebuild/release-python/prod-release.yml + # ## https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codebuild-project-source.html#cfn-codebuild-project-source-gitclonedepth + # ## If this value is 0, greater than 25, or not provided then the full history is downloaded with each build project. + # GitCloneDepth: 0 + # GitSubmodulesConfig: + # FetchSubmodules: true + # InsecureSsl: false + # ReportBuildStatus: false + # Type: GITHUB + # Artifacts: + # Type: NO_ARTIFACTS + # Cache: + # Type: NO_CACHE + # Environment: + # ComputeType: BUILD_GENERAL1_LARGE + # Image: "aws/codebuild/standard:7.0" + # ImagePullCredentialsType: CODEBUILD + # PrivilegedMode: false + # Type: LINUX_CONTAINER + # ServiceRole: !GetAtt CodeBuildProdReleaseServiceRole.Arn + # TimeoutInMinutes: 60 + # QueuedTimeoutInMinutes: 480 + # EncryptionKey: !Sub "arn:aws:kms:${AWS::Region}:${AWS::AccountId}:alias/aws/s3" + # BadgeEnabled: false + # BuildBatchConfig: + # ServiceRole: !GetAtt CodeBuildProdReleaseServiceRole.Arn + # Restrictions: + # MaximumBuildsAllowed: !Ref NumberOfBuildsInBatch + # ComputeTypesAllowed: + # - BUILD_GENERAL1_SMALL + # - BUILD_GENERAL1_MEDIUM + # - BUILD_GENERAL1_LARGE + # TimeoutInMins: 480 + # LogsConfig: + # CloudWatchLogs: + # Status: ENABLED + # S3Logs: + # Status: DISABLED + # EncryptionDisabled: false + + CodeBuildTestReleaseServiceRole: + Type: "AWS::IAM::Role" + Properties: + Path: /service-role/ + RoleName: !Sub "codebuild-${ProjectName}-test-service-role" + AssumeRolePolicyDocument: >- + {"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":{"Service":"codebuild.amazonaws.com"},"Action":"sts:AssumeRole"}]} + MaxSessionDuration: 3600 + ManagedPolicyArns: + - !Ref CryptoToolsKMS + - !Ref CodeBuildTestReleaseBatchPolicy + - !Ref CodeBuildTestReleaseBasePolicy + - !Ref SecretsManagerTestReleasePolicy + - !Ref CodeBuildCISTSAllow + + # CodeBuildProdReleaseServiceRole: + # Type: "AWS::IAM::Role" + # Properties: + # Path: /service-role/ + # RoleName: !Sub "codebuild-${ProjectName}-prod-service-role" + # AssumeRolePolicyDocument: >- + # {"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":{"Service":"codebuild.amazonaws.com"},"Action":"sts:AssumeRole"}]} + # MaxSessionDuration: 3600 + # ManagedPolicyArns: + # - !Ref CryptoToolsKMS + # - !Ref CodeBuildProdReleaseBatchPolicy + # - !Ref CodeBuildProdReleaseBasePolicy + # - !Ref SecretsManagerProdReleasePolicy + # - !Ref CodeBuildCISTSAllow + # # - "arn:aws:iam::aws:policy/AWSCodeArtifactReadOnlyAccess" + # # - "arn:aws:iam::aws:policy/AWSCodeArtifactAdminAccess" + + CodeBuildTestReleaseBatchPolicy: + Type: "AWS::IAM::ManagedPolicy" + Properties: + ManagedPolicyName: !Sub >- + CodeBuildTestBuildBatchPolicy-${ProjectName}-${AWS::Region}-codebuild-${ProjectName}-test-service-role + Path: /service-role/ + PolicyDocument: !Sub | + { + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Allow", + "Resource": [ + "arn:aws:codebuild:${AWS::Region}:${AWS::AccountId}:project/${ProjectName}", + "arn:aws:codebuild:${AWS::Region}:${AWS::AccountId}:project/${ProjectName}-test-release" + ], + "Action": [ + "codebuild:StartBuild", + "codebuild:StopBuild", + "codebuild:RetryBuild" + ] + } + ] + } + + # CodeBuildProdReleaseBatchPolicy: + # Type: "AWS::IAM::ManagedPolicy" + # Properties: + # ManagedPolicyName: !Sub >- + # CodeBuildBuildBatchPolicy-${ProjectName}-${AWS::Region}-codebuild-${ProjectName}-prod-service-role + # Path: /service-role/ + # PolicyDocument: !Sub | + # { + # "Version": "2012-10-17", + # "Statement": [ + # { + # "Effect": "Allow", + # "Resource": [ + # "arn:aws:codebuild:${AWS::Region}:${AWS::AccountId}:project/${ProjectName}", + # "arn:aws:codebuild:${AWS::Region}:${AWS::AccountId}:project/${ProjectName}-prod-release" + # ], + # "Action": [ + # "codebuild:StartBuild", + # "codebuild:StopBuild", + # "codebuild:RetryBuild" + # ] + # } + # ] + # } + + CodeBuildTestReleaseBasePolicy: + Type: "AWS::IAM::ManagedPolicy" + Properties: + ManagedPolicyName: !Sub "CodeBuildTestBasePolicy-${ProjectName}-${AWS::Region}" + Path: /service-role/ + PolicyDocument: !Sub | + { + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Allow", + "Resource": [ + "arn:aws:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/codebuild/${ProjectName}", + "arn:aws:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/codebuild/${ProjectName}:*", + "arn:aws:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/codebuild/${ProjectName}-test-release", + "arn:aws:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/codebuild/${ProjectName}-test-release:*" + ], + "Action": [ + "logs:CreateLogGroup", + "logs:CreateLogStream", + "logs:PutLogEvents", + "logs:GetLogEvents" + ] + }, + { + "Effect": "Allow", + "Resource": [ + "arn:aws:s3:::codepipeline-${AWS::Region}-*" + ], + "Action": [ + "s3:PutObject", + "s3:GetObject", + "s3:GetObjectVersion", + "s3:GetBucketAcl", + "s3:GetBucketLocation" + ] + }, + { + "Effect": "Allow", + "Action": [ + "codebuild:CreateReportGroup", + "codebuild:CreateReport", + "codebuild:UpdateReport", + "codebuild:BatchPutTestCases", + "codebuild:BatchPutCodeCoverages" + ], + "Resource": [ + "arn:aws:codebuild:${AWS::Region}:${AWS::AccountId}:report-group/${ProjectName}-*" + ] + } + ] + } + + # CodeBuildProdReleaseBasePolicy: + # Type: "AWS::IAM::ManagedPolicy" + # Properties: + # ManagedPolicyName: !Sub "CodeBuildProdBasePolicy-${ProjectName}-${AWS::Region}" + # Path: /service-role/ + # PolicyDocument: !Sub | + # { + # "Version": "2012-10-17", + # "Statement": [ + # { + # "Effect": "Allow", + # "Resource": [ + # "arn:aws:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/codebuild/${ProjectName}", + # "arn:aws:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/codebuild/${ProjectName}:*", + # "arn:aws:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/codebuild/${ProjectName}-prod-release", + # "arn:aws:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/codebuild/${ProjectName}-prod-release:*" + # ], + # "Action": [ + # "logs:CreateLogGroup", + # "logs:CreateLogStream", + # "logs:PutLogEvents", + # "logs:GetLogEvents" + # ] + # }, + # { + # "Effect": "Allow", + # "Resource": [ + # "arn:aws:s3:::codepipeline-${AWS::Region}-*" + # ], + # "Action": [ + # "s3:PutObject", + # "s3:GetObject", + # "s3:GetObjectVersion", + # "s3:GetBucketAcl", + # "s3:GetBucketLocation" + # ] + # }, + # { + # "Effect": "Allow", + # "Action": [ + # "codebuild:CreateReportGroup", + # "codebuild:CreateReport", + # "codebuild:UpdateReport", + # "codebuild:BatchPutTestCases", + # "codebuild:BatchPutCodeCoverages" + # ], + # "Resource": [ + # "arn:aws:codebuild:${AWS::Region}:${AWS::AccountId}:report-group/${ProjectName}-*" + # ] + # } + # ] + # } + + SecretsManagerTestReleasePolicy: + Type: "AWS::IAM::ManagedPolicy" + Properties: + ManagedPolicyName: !Sub "CryptoTools-SecretsManagerTest-${ProjectName}-release" + Path: /service-role/ + PolicyDocument: !Sub | + { + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Allow", + "Resource": [ + "arn:aws:secretsmanager:us-west-2:587316601012:secret:TestPyPiCryptoTools-SxeLBh", + "arn:aws:secretsmanager:us-west-2:587316601012:secret:TestPyPiAPIToken-uERFjs" + ], + "Action": "secretsmanager:GetSecretValue" + } + ] + } + + # SecretsManagerProdReleasePolicy: + # Type: "AWS::IAM::ManagedPolicy" + # Properties: + # ManagedPolicyName: !Sub "CryptoTools-SecretsManagerProd-${ProjectName}-release" + # Path: /service-role/ + # PolicyDocument: !Sub | + # { + # "Version": "2012-10-17", + # "Statement": [ + # { + # "Effect": "Allow", + # "Resource": [ + # "arn:aws:secretsmanager:us-west-2:587316601012:secret:PyPiAdmin-ZWyd1T" + # ], + # "Action": "secretsmanager:GetSecretValue" + # } + # ] + # } + + # There exist public AWS KMS CMKs that are used for testing + # Take care with these CMKs they are **ONLY** for testing!!! + CryptoToolsKMS: + Type: "AWS::IAM::ManagedPolicy" + Properties: + ManagedPolicyName: !Sub "CrypotToolsKMSPolicy-${ProjectName}-${AWS::Region}-codebuild-${ProjectName}-service-role" + Path: /service-role/ + PolicyDocument: !Sub | + { + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Allow", + "Resource": [ + "arn:aws:kms:*:658956600833:key/*", + "arn:aws:kms:*:658956600833:alias/*", + "arn:aws:kms:*:370957321024:key/*", + "arn:aws:kms:*:370957321024:alias/*" + ], + "Action": [ + "kms:Encrypt", + "kms:Decrypt", + "kms:ReEncrypt*", + "kms:Generate*", + "kms:GetPublicKey", + "kms:DescribeKey" + ] + } + ] + } + + CodeBuildCISTSAllow: + Type: "AWS::IAM::ManagedPolicy" + Properties: + ManagedPolicyName: !Sub >- + CodeBuildCISTSAllow-${ProjectName} + Path: /service-role/ + PolicyDocument: !Sub | + { + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Allow", + "Action": "sts:AssumeRole", + "Resource": "arn:aws:iam::370957321024:role/GitHub-CI-MPL-Dafny-Role-us-west-2" + } + ] + } diff --git a/model/traits.smithy b/model/traits.smithy index c657671bb..7c1262530 100644 --- a/model/traits.smithy +++ b/model/traits.smithy @@ -22,6 +22,10 @@ list ServiceList { // A trait for explicitly modeling the configuration options that should be // available in the generated methods for creating clients. @trait(selector: "service") +// @protocolDefinition trait is used by Smithy code generators +// (Smithy-Python, Smithy-Rust, Smithy-Go) +// to identify shapes that define protocols used by services. +@protocolDefinition structure localService { @required sdkId: String, diff --git a/smithy-dafny b/smithy-dafny index 98939e130..82c765afc 160000 --- a/smithy-dafny +++ b/smithy-dafny @@ -1 +1 @@ -Subproject commit 98939e130695095386059967509a19299dfac320 +Subproject commit 82c765afc2b304b5af1d4ffecb19212b4033c1b2