swarmauri_keyprovider_aws_kms 0.3.0.dev4__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [2025] [Jacob Stewart @ Swarmauri]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,44 @@
1
+ Metadata-Version: 2.3
2
+ Name: swarmauri_keyprovider_aws_kms
3
+ Version: 0.3.0.dev4
4
+ Summary: AWS KMS KeyProvider for Swarmauri
5
+ License: Apache-2.0
6
+ Author: Swarmauri
7
+ Author-email: opensource@swarmauri.com
8
+ Requires-Python: >=3.10,<3.13
9
+ Classifier: License :: OSI Approved :: Apache Software License
10
+ Classifier: Programming Language :: Python :: 3.10
11
+ Classifier: Programming Language :: Python :: 3.11
12
+ Classifier: Programming Language :: Python :: 3.12
13
+ Provides-Extra: docs
14
+ Provides-Extra: perf
15
+ Requires-Dist: boto3 (>=1.28.0)
16
+ Requires-Dist: cryptography
17
+ Requires-Dist: mkdocs ; extra == "docs"
18
+ Requires-Dist: pytest-benchmark (>=4.0.0) ; extra == "perf"
19
+ Requires-Dist: swarmauri_base
20
+ Requires-Dist: swarmauri_core
21
+ Requires-Dist: swarmauri_standard
22
+ Description-Content-Type: text/markdown
23
+
24
+ # Swarmauri AWS KMS Key Provider
25
+
26
+ Community plugin providing an AWS KMS backed `KeyProvider` for Swarmauri.
27
+
28
+ ## Features
29
+ - Manage RSA and AES keys via AWS KMS
30
+ - Publish JWKs following [RFC 7517](https://datatracker.ietf.org/doc/html/rfc7517)
31
+ - Generate cryptographically secure random bytes
32
+
33
+ ## Installation
34
+ ```bash
35
+ pip install swarmauri_keyprovider_aws_kms
36
+ ```
37
+
38
+ ## Usage
39
+ ```python
40
+ from swarmauri_keyprovider_aws_kms import AwsKmsKeyProvider
41
+
42
+ provider = AwsKmsKeyProvider(region="us-east-1")
43
+ ```
44
+
@@ -0,0 +1,20 @@
1
+ # Swarmauri AWS KMS Key Provider
2
+
3
+ Community plugin providing an AWS KMS backed `KeyProvider` for Swarmauri.
4
+
5
+ ## Features
6
+ - Manage RSA and AES keys via AWS KMS
7
+ - Publish JWKs following [RFC 7517](https://datatracker.ietf.org/doc/html/rfc7517)
8
+ - Generate cryptographically secure random bytes
9
+
10
+ ## Installation
11
+ ```bash
12
+ pip install swarmauri_keyprovider_aws_kms
13
+ ```
14
+
15
+ ## Usage
16
+ ```python
17
+ from swarmauri_keyprovider_aws_kms import AwsKmsKeyProvider
18
+
19
+ provider = AwsKmsKeyProvider(region="us-east-1")
20
+ ```
@@ -0,0 +1,72 @@
1
+ [project]
2
+ name = "swarmauri_keyprovider_aws_kms"
3
+ version = "0.3.0.dev4"
4
+ description = "AWS KMS KeyProvider for Swarmauri"
5
+ license = "Apache-2.0"
6
+ readme = "README.md"
7
+ repository = "http://github.com/swarmauri/swarmauri-sdk"
8
+ requires-python = ">=3.10,<3.13"
9
+ classifiers = [
10
+ "License :: OSI Approved :: Apache Software License",
11
+ "Programming Language :: Python :: 3.10",
12
+ "Programming Language :: Python :: 3.11",
13
+ "Programming Language :: Python :: 3.12",
14
+ ]
15
+ authors = [{ name = "Swarmauri", email = "opensource@swarmauri.com" }]
16
+ dependencies = [
17
+ "boto3>=1.28.0",
18
+ "swarmauri_core",
19
+ "swarmauri_base",
20
+ "swarmauri_standard",
21
+ "cryptography",
22
+ ]
23
+
24
+ [project.optional-dependencies]
25
+ docs = ["mkdocs"]
26
+ perf = ["pytest-benchmark>=4.0.0"]
27
+
28
+ [tool.uv.sources]
29
+ swarmauri_core = { workspace = true }
30
+ swarmauri_base = { workspace = true }
31
+ swarmauri_standard = { workspace = true }
32
+
33
+ [tool.pytest.ini_options]
34
+ norecursedirs = ["combined", "scripts"]
35
+ markers = [
36
+ "test: standard test",
37
+ "unit: Unit tests",
38
+ "i9n: Integration tests",
39
+ "r8n: Regression tests",
40
+ "timeout: mark test to timeout after X seconds",
41
+ "xpass: Expected passes",
42
+ "xfail: Expected failures",
43
+ "acceptance: Acceptance tests",
44
+ "perf: Performance tests that measure execution time and resource usage",
45
+ ]
46
+ timeout = 300
47
+ log_cli = true
48
+ log_cli_level = "INFO"
49
+ log_cli_format = "%(asctime)s [%(levelname)s] %(message)s"
50
+ log_cli_date_format = "%Y-%m-%d %H:%M:%S"
51
+ asyncio_default_fixture_loop_scope = "function"
52
+
53
+ [project.entry-points.'swarmauri.key_providers']
54
+ AwsKmsKeyProvider = "swarmauri_keyprovider_aws_kms.AwsKmsKeyProvider:AwsKmsKeyProvider"
55
+
56
+ [build-system]
57
+ requires = ["poetry-core>=1.0.0"]
58
+ build-backend = "poetry.core.masonry.api"
59
+
60
+ [dependency-groups]
61
+ dev = [
62
+ "pytest>=8.0",
63
+ "pytest-asyncio>=0.24.0",
64
+ "pytest-xdist>=3.6.1",
65
+ "pytest-json-report>=1.5.0",
66
+ "python-dotenv",
67
+ "requests>=2.32.3",
68
+ "flake8>=7.0",
69
+ "pytest-timeout>=2.3.1",
70
+ "ruff>=0.9.9",
71
+ "pytest-benchmark>=4.0.0",
72
+ ]
@@ -0,0 +1,435 @@
1
+ from __future__ import annotations
2
+
3
+ import base64
4
+ import hashlib
5
+ import os
6
+ from dataclasses import dataclass
7
+ from typing import Dict, Iterable, Mapping, Optional, Tuple, Literal
8
+
9
+ try:
10
+ import boto3
11
+ from botocore.exceptions import ClientError
12
+ except Exception as e: # pragma: no cover
13
+ raise ImportError(
14
+ "AwsKmsKeyProvider requires 'boto3'. Install with: pip install boto3"
15
+ ) from e
16
+
17
+ from cryptography.hazmat.primitives import serialization
18
+ from cryptography.hazmat.primitives.asymmetric import rsa, ec
19
+
20
+ from swarmauri_base.keys.KeyProviderBase import KeyProviderBase
21
+ from swarmauri_core.keys.types import KeySpec, KeyAlg, KeyClass, ExportPolicy, KeyUse
22
+ from swarmauri_core.crypto.types import KeyRef
23
+
24
+
25
+ def _b64u(b: bytes) -> str:
26
+ return base64.urlsafe_b64encode(b).rstrip(b"=").decode("ascii")
27
+
28
+
29
+ @dataclass(frozen=True)
30
+ class _KmsSpec:
31
+ KeySpec: str
32
+ KeyUsage: str
33
+
34
+
35
+ class AwsKmsKeyProvider(KeyProviderBase):
36
+ """
37
+ AWS KMS-backed KeyProvider.
38
+
39
+ - Creates new KMS CMKs per (kid, version); maintains stable alias:
40
+ alias/<alias_prefix>/<kid> -> latest version
41
+ alias/<alias_prefix>/<kid>/v<ver> -> specific version
42
+ - Rotation = create new KMS key (same alg/usage), bump /vN alias, repoint "latest".
43
+ - get_key(include_secret=...) never returns private material (KMS non-exportable).
44
+ - get_public_jwk() parses GetPublicKey DER to RFC 7517 JWK.
45
+ - jwks() publishes latest per 'kid' (resolved via stable alias) with kid.version.
46
+
47
+ IAM needed (minimum):
48
+ kms:CreateKey, kms:CreateAlias, kms:UpdateAlias, kms:ListAliases,
49
+ kms:DescribeKey, kms:ListResourceTags, kms:GetPublicKey, kms:ScheduleKeyDeletion
50
+ """
51
+
52
+ type: Literal["AwsKmsKeyProvider"] = "AwsKmsKeyProvider"
53
+
54
+ def __init__(
55
+ self,
56
+ *,
57
+ region: str,
58
+ alias_prefix: str = "swarmauri",
59
+ key_policy: Optional[dict] = None,
60
+ ):
61
+ """
62
+ region: AWS region name (e.g., "us-east-1")
63
+ alias_prefix: alias namespace (no 'alias/' prefix here). Final aliases look like:
64
+ 'alias/<alias_prefix>/<kid>' and 'alias/<alias_prefix>/<kid>/v<ver>'
65
+ key_policy: optional explicit key policy JSON; if None, KMS uses account default.
66
+ """
67
+ super().__init__()
68
+ self._region = region
69
+ self._alias_prefix = alias_prefix.strip("/")
70
+
71
+ self._kms = boto3.client("kms", region_name=region)
72
+ self._key_policy = key_policy
73
+
74
+ def supports(self) -> Mapping[str, Iterable[str]]:
75
+ return {
76
+ "class": ("sym", "asym"),
77
+ "algs": (
78
+ KeyAlg.AES256_GCM,
79
+ KeyAlg.RSA_OAEP_SHA256,
80
+ KeyAlg.RSA_PSS_SHA256,
81
+ KeyAlg.ECDSA_P256_SHA256,
82
+ ),
83
+ "features": ("create", "rotate", "jwks", "non_exportable"),
84
+ }
85
+
86
+ def _gen_kid(self) -> str:
87
+ return hashlib.sha256(os.urandom(16)).hexdigest()[:16]
88
+
89
+ def _alias_latest(self, kid: str) -> str:
90
+ return f"alias/{self._alias_prefix}/{kid}"
91
+
92
+ def _alias_version(self, kid: str, version: int) -> str:
93
+ return f"alias/{self._alias_prefix}/{kid}/v{version}"
94
+
95
+ def _create_or_update_alias(self, alias_name: str, target_key_id: str) -> None:
96
+ try:
97
+ self._kms.create_alias(AliasName=alias_name, TargetKeyId=target_key_id)
98
+ except ClientError as e:
99
+ if e.response.get("Error", {}).get("Code") == "AlreadyExistsException":
100
+ self._kms.update_alias(AliasName=alias_name, TargetKeyId=target_key_id)
101
+ else:
102
+ raise
103
+
104
+ def _kms_spec_for_alg(self, spec: KeySpec) -> _KmsSpec:
105
+ if spec.klass == KeyClass.symmetric:
106
+ if spec.alg != KeyAlg.AES256_GCM:
107
+ raise ValueError(f"Unsupported symmetric alg for AWS KMS: {spec.alg}")
108
+ return _KmsSpec(KeySpec="SYMMETRIC_DEFAULT", KeyUsage="ENCRYPT_DECRYPT")
109
+
110
+ if spec.alg == KeyAlg.RSA_OAEP_SHA256:
111
+ bits = spec.size_bits or 3072
112
+ if bits not in (2048, 3072, 4096):
113
+ raise ValueError("AWS KMS RSA supports 2048/3072/4096 bit sizes")
114
+ return _KmsSpec(KeySpec=f"RSA_{bits}", KeyUsage="ENCRYPT_DECRYPT")
115
+
116
+ if spec.alg == KeyAlg.RSA_PSS_SHA256:
117
+ bits = spec.size_bits or 3072
118
+ if bits not in (2048, 3072, 4096):
119
+ raise ValueError("AWS KMS RSA supports 2048/3072/4096 bit sizes")
120
+ return _KmsSpec(KeySpec=f"RSA_{bits}", KeyUsage="SIGN_VERIFY")
121
+
122
+ if spec.alg == KeyAlg.ECDSA_P256_SHA256:
123
+ return _KmsSpec(KeySpec="ECC_NIST_P256", KeyUsage="SIGN_VERIFY")
124
+
125
+ raise ValueError(f"Unsupported alg for AWS KMS: {spec.alg}")
126
+
127
+ def _get_tags(self, key_id: str) -> Dict[str, str]:
128
+ out: Dict[str, str] = {}
129
+ paginator = self._kms.get_paginator("list_resource_tags")
130
+ for page in paginator.paginate(KeyId=key_id):
131
+ for t in page.get("Tags", []):
132
+ out[t["TagKey"]] = t["TagValue"]
133
+ return out
134
+
135
+ def _public_jwk_from_der(self, der: bytes, jwk_kid: str) -> dict:
136
+ pk = serialization.load_der_public_key(der)
137
+ if isinstance(pk, rsa.RSAPublicKey):
138
+ nums = pk.public_numbers()
139
+ n = nums.n.to_bytes((nums.n.bit_length() + 7) // 8, "big")
140
+ e = nums.e.to_bytes((nums.e.bit_length() + 7) // 8, "big")
141
+ return {"kty": "RSA", "n": _b64u(n), "e": _b64u(e), "kid": jwk_kid}
142
+ if isinstance(pk, ec.EllipticCurvePublicKey):
143
+ curve = pk.curve
144
+ if isinstance(curve, ec.SECP256R1):
145
+ nums = pk.public_numbers()
146
+ x = nums.x.to_bytes(32, "big")
147
+ y = nums.y.to_bytes(32, "big")
148
+ return {
149
+ "kty": "EC",
150
+ "crv": "P-256",
151
+ "x": _b64u(x),
152
+ "y": _b64u(y),
153
+ "kid": jwk_kid,
154
+ }
155
+ raise ValueError("Unsupported public key type returned by KMS")
156
+
157
+ def _keyref_from_key_id(
158
+ self,
159
+ kid: str,
160
+ version: int,
161
+ key_id: str,
162
+ *,
163
+ tags: Optional[Dict[str, str]] = None,
164
+ ) -> KeyRef:
165
+ public: Optional[bytes] = None
166
+ try:
167
+ resp = self._kms.get_public_key(KeyId=key_id)
168
+ der = resp.get("PublicKey")
169
+ if der:
170
+ public = serialization.load_der_public_key(der).public_bytes(
171
+ serialization.Encoding.PEM,
172
+ serialization.PublicFormat.SubjectPublicKeyInfo,
173
+ )
174
+ except ClientError as e:
175
+ code = e.response.get("Error", {}).get("Code")
176
+ if code not in (
177
+ "UnsupportedOperationException",
178
+ "NotFoundException",
179
+ "InvalidArnException",
180
+ "IncorrectKeySpecException",
181
+ ):
182
+ raise
183
+
184
+ uses: Tuple[KeyUse, ...] = (KeyUse.encrypt, KeyUse.decrypt)
185
+ try:
186
+ md = self._kms.describe_key(KeyId=key_id)["KeyMetadata"]
187
+ if md.get("KeyUsage") == "SIGN_VERIFY":
188
+ uses = (KeyUse.sign, KeyUse.verify)
189
+ elif md.get("KeyUsage") == "ENCRYPT_DECRYPT":
190
+ uses = (KeyUse.encrypt, KeyUse.decrypt)
191
+ except Exception:
192
+ pass
193
+
194
+ tag_map = dict(tags or {})
195
+ return KeyRef(
196
+ kid=kid,
197
+ version=version,
198
+ type="OPAQUE",
199
+ uses=uses,
200
+ export_policy=ExportPolicy.never_export_secret,
201
+ public=public,
202
+ material=None,
203
+ tags={
204
+ "alg": tag_map.get("saur:alg"),
205
+ "kms:key_id": key_id,
206
+ "kms:region": self._region,
207
+ "label": tag_map.get("saur:label"),
208
+ },
209
+ fingerprint=self._fingerprint(public=public, kid=kid),
210
+ )
211
+
212
+ async def create_key(self, spec: KeySpec) -> KeyRef:
213
+ kid = self._gen_kid()
214
+ version = 1
215
+ kms_spec = self._kms_spec_for_alg(spec)
216
+
217
+ kwargs = {
218
+ "KeyUsage": kms_spec.KeyUsage,
219
+ "KeySpec": kms_spec.KeySpec,
220
+ "Tags": [
221
+ {"TagKey": "saur:kid", "TagValue": kid},
222
+ {"TagKey": "saur:version", "TagValue": str(version)},
223
+ {"TagKey": "saur:alg", "TagValue": spec.alg.value},
224
+ ],
225
+ }
226
+ if spec.label:
227
+ kwargs["Tags"].append({"TagKey": "saur:label", "TagValue": spec.label})
228
+ if self._key_policy:
229
+ kwargs["Policy"] = self._key_policy
230
+
231
+ resp = self._kms.create_key(**kwargs)
232
+ key_id = resp["KeyMetadata"]["KeyId"]
233
+
234
+ self._create_or_update_alias(self._alias_version(kid, version), key_id)
235
+ self._create_or_update_alias(self._alias_latest(kid), key_id)
236
+
237
+ tags = {t["TagKey"]: t["TagValue"] for t in kwargs["Tags"]}
238
+ return self._keyref_from_key_id(kid, version, key_id, tags=tags)
239
+
240
+ async def import_key(
241
+ self, spec: KeySpec, material: bytes, *, public: Optional[bytes] = None
242
+ ) -> KeyRef:
243
+ raise NotImplementedError(
244
+ "AWS KMS does not support importing private keys via this provider; use create_key()."
245
+ )
246
+
247
+ async def rotate_key(
248
+ self, kid: str, *, spec_overrides: Optional[dict] = None
249
+ ) -> KeyRef:
250
+ latest_alias = self._alias_latest(kid)
251
+ try:
252
+ alias_desc = self._find_alias(latest_alias)
253
+ except KeyError:
254
+ raise KeyError(f"Unknown kid: {kid}")
255
+
256
+ current_key_id = alias_desc["TargetKeyId"]
257
+ current_tags = self._get_tags(current_key_id)
258
+ current_alg = current_tags.get("saur:alg")
259
+ if not current_alg:
260
+ raise RuntimeError("Missing 'saur:alg' tag on current KMS key")
261
+
262
+ alg = KeyAlg(current_alg)
263
+ size_bits = (spec_overrides or {}).get("size_bits")
264
+ label = (spec_overrides or {}).get("label", current_tags.get("saur:label"))
265
+ uses = ()
266
+ new_spec = KeySpec(
267
+ klass=(
268
+ KeyClass.symmetric if alg == KeyAlg.AES256_GCM else KeyClass.asymmetric
269
+ ),
270
+ alg=alg,
271
+ size_bits=size_bits,
272
+ label=label,
273
+ export_policy=ExportPolicy.never_export_secret,
274
+ uses=uses,
275
+ tags=None,
276
+ )
277
+
278
+ try:
279
+ versions = await self.list_versions(kid)
280
+ next_version = (max(versions) + 1) if versions else 2
281
+ except Exception:
282
+ v = int(current_tags.get("saur:version", "1"))
283
+ next_version = v + 1
284
+
285
+ kms_spec = self._kms_spec_for_alg(new_spec)
286
+ kwargs = {
287
+ "KeyUsage": kms_spec.KeyUsage,
288
+ "KeySpec": kms_spec.KeySpec,
289
+ "Tags": [
290
+ {"TagKey": "saur:kid", "TagValue": kid},
291
+ {"TagKey": "saur:version", "TagValue": str(next_version)},
292
+ {"TagKey": "saur:alg", "TagValue": alg.value},
293
+ ],
294
+ }
295
+ if label:
296
+ kwargs["Tags"].append({"TagKey": "saur:label", "TagValue": label})
297
+ if self._key_policy:
298
+ kwargs["Policy"] = self._key_policy
299
+
300
+ resp = self._kms.create_key(**kwargs)
301
+ new_key_id = resp["KeyMetadata"]["KeyId"]
302
+
303
+ self._create_or_update_alias(self._alias_version(kid, next_version), new_key_id)
304
+ self._create_or_update_alias(self._alias_latest(kid), new_key_id)
305
+
306
+ return self._keyref_from_key_id(
307
+ kid,
308
+ next_version,
309
+ new_key_id,
310
+ tags={t["TagKey"]: t["TagValue"] for t in kwargs["Tags"]},
311
+ )
312
+
313
+ async def destroy_key(self, kid: str, version: Optional[int] = None) -> bool:
314
+ try:
315
+ if version is None:
316
+ for ver in await self.list_versions(kid):
317
+ alias_name = self._alias_version(kid, ver)
318
+ alias_desc = self._find_alias(alias_name)
319
+ self._kms.schedule_key_deletion(
320
+ KeyId=alias_desc["TargetKeyId"], PendingWindowInDays=7
321
+ )
322
+ return True
323
+ else:
324
+ alias_name = self._alias_version(kid, version)
325
+ alias_desc = self._find_alias(alias_name)
326
+ self._kms.schedule_key_deletion(
327
+ KeyId=alias_desc["TargetKeyId"], PendingWindowInDays=7
328
+ )
329
+ return True
330
+ except Exception:
331
+ return False
332
+
333
+ async def get_key(
334
+ self, kid: str, version: Optional[int] = None, *, include_secret: bool = False
335
+ ) -> KeyRef:
336
+ alias_name = (
337
+ self._alias_version(kid, version) if version else self._alias_latest(kid)
338
+ )
339
+ alias_desc = self._find_alias(alias_name)
340
+ key_id = alias_desc["TargetKeyId"]
341
+
342
+ tags = self._get_tags(key_id)
343
+ ver = int(tags.get("saur:version") or (version or 1))
344
+ return self._keyref_from_key_id(kid, ver, key_id, tags=tags)
345
+
346
+ async def list_versions(self, kid: str) -> Tuple[int, ...]:
347
+ prefix = f"alias/{self._alias_prefix}/{kid}/v"
348
+ out: list[int] = []
349
+ paginator = self._kms.get_paginator("list_aliases")
350
+ for page in paginator.paginate():
351
+ for a in page.get("Aliases", []):
352
+ name = a.get("AliasName")
353
+ if not name or not name.startswith(prefix):
354
+ continue
355
+ tail = name[len(prefix) :]
356
+ if tail.isdigit():
357
+ out.append(int(tail))
358
+ if not out:
359
+ try:
360
+ self._find_alias(self._alias_latest(kid))
361
+ out = [1]
362
+ except KeyError:
363
+ pass
364
+ out.sort()
365
+ return tuple(out)
366
+
367
+ async def get_public_jwk(self, kid: str, version: Optional[int] = None) -> dict:
368
+ alias_name = (
369
+ self._alias_version(kid, version) if version else self._alias_latest(kid)
370
+ )
371
+ alias_desc = self._find_alias(alias_name)
372
+ key_id = alias_desc["TargetKeyId"]
373
+
374
+ tags = self._get_tags(key_id)
375
+ ver = int(tags.get("saur:version") or (version or 1))
376
+ jwk_kid = f"{kid}.{ver}"
377
+
378
+ try:
379
+ pk = self._kms.get_public_key(KeyId=key_id).get("PublicKey")
380
+ if not pk:
381
+ return {"kty": "oct", "alg": "A256GCM", "kid": jwk_kid}
382
+ return self._public_jwk_from_der(pk, jwk_kid)
383
+ except ClientError as e:
384
+ code = e.response.get("Error", {}).get("Code")
385
+ if code in ("UnsupportedOperationException", "IncorrectKeySpecException"):
386
+ return {"kty": "oct", "alg": "A256GCM", "kid": jwk_kid}
387
+ raise
388
+
389
+ async def jwks(self, *, prefix_kids: Optional[str] = None) -> dict:
390
+ keys = []
391
+ base_prefix = f"alias/{self._alias_prefix}/"
392
+ paginator = self._kms.get_paginator("list_aliases")
393
+ seen_latest: set[str] = set()
394
+ for page in paginator.paginate():
395
+ for a in page.get("Aliases", []):
396
+ name = a.get("AliasName") or ""
397
+ if not name.startswith(base_prefix):
398
+ continue
399
+ tail = name[len(base_prefix) :]
400
+ if "/v" in tail:
401
+ continue
402
+ kid = tail
403
+ if prefix_kids and not kid.startswith(prefix_kids):
404
+ continue
405
+ if kid in seen_latest:
406
+ continue
407
+ seen_latest.add(kid)
408
+ try:
409
+ key_id = a["TargetKeyId"]
410
+ tags = self._get_tags(key_id)
411
+ ver = int(tags.get("saur:version", "1"))
412
+ jwk = await self.get_public_jwk(kid, ver)
413
+ keys.append(jwk)
414
+ except Exception:
415
+ continue
416
+ return {"keys": keys}
417
+
418
+ async def random_bytes(self, n: int) -> bytes:
419
+ return os.urandom(n)
420
+
421
+ async def hkdf(self, ikm: bytes, *, salt: bytes, info: bytes, length: int) -> bytes:
422
+ from cryptography.hazmat.primitives.kdf.hkdf import HKDF
423
+ from cryptography.hazmat.primitives import hashes
424
+
425
+ return HKDF(
426
+ algorithm=hashes.SHA256(), length=length, salt=salt, info=info
427
+ ).derive(ikm)
428
+
429
+ def _find_alias(self, alias_name: str) -> dict:
430
+ paginator = self._kms.get_paginator("list_aliases")
431
+ for page in paginator.paginate():
432
+ for a in page.get("Aliases", []):
433
+ if a.get("AliasName") == alias_name and "TargetKeyId" in a:
434
+ return a
435
+ raise KeyError(f"Alias not found or no target: {alias_name}")
@@ -0,0 +1,3 @@
1
+ from .AwsKmsKeyProvider import AwsKmsKeyProvider, _b64u
2
+
3
+ __all__ = ["AwsKmsKeyProvider", "_b64u"]