swarmauri_keyprovider_gcpkms 0.9.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.
- swarmauri_keyprovider_gcpkms-0.9.0.dev4/LICENSE +201 -0
- swarmauri_keyprovider_gcpkms-0.9.0.dev4/PKG-INFO +63 -0
- swarmauri_keyprovider_gcpkms-0.9.0.dev4/README.md +40 -0
- swarmauri_keyprovider_gcpkms-0.9.0.dev4/pyproject.toml +73 -0
- swarmauri_keyprovider_gcpkms-0.9.0.dev4/swarmauri_keyprovider_gcpkms/GcpKmsKeyProvider.py +567 -0
- swarmauri_keyprovider_gcpkms-0.9.0.dev4/swarmauri_keyprovider_gcpkms/__init__.py +3 -0
|
@@ -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,63 @@
|
|
|
1
|
+
Metadata-Version: 2.3
|
|
2
|
+
Name: swarmauri_keyprovider_gcpkms
|
|
3
|
+
Version: 0.9.0.dev4
|
|
4
|
+
Summary: Google Cloud KMS Key Provider 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: cbor
|
|
14
|
+
Requires-Dist: cbor2 ; extra == "cbor"
|
|
15
|
+
Requires-Dist: cryptography
|
|
16
|
+
Requires-Dist: google-auth
|
|
17
|
+
Requires-Dist: requests
|
|
18
|
+
Requires-Dist: swarmauri_base
|
|
19
|
+
Requires-Dist: swarmauri_core
|
|
20
|
+
Requires-Dist: swarmauri_standard
|
|
21
|
+
Description-Content-Type: text/markdown
|
|
22
|
+
|
|
23
|
+
# Swarmauri GCP KMS Key Provider
|
|
24
|
+
|
|
25
|
+
GCP KMS-backed key provider for the Swarmauri framework. This plugin exposes
|
|
26
|
+
Google Cloud KMS keys through the common `IKeyProvider` interface, enabling
|
|
27
|
+
signing, verification, encryption and random byte generation.
|
|
28
|
+
|
|
29
|
+
## Optional Canonicalization Extras
|
|
30
|
+
|
|
31
|
+
- `cbor` – enables CBOR canonicalization utilities via `cbor2`.
|
|
32
|
+
|
|
33
|
+
## Features
|
|
34
|
+
|
|
35
|
+
- AES encryption and decryption using KMS-managed symmetric keys.
|
|
36
|
+
- RSA and EC signing backed by Cloud KMS.
|
|
37
|
+
- RSA wrapping and unwrapping of data encryption keys.
|
|
38
|
+
- JWKS export for asymmetric public keys.
|
|
39
|
+
|
|
40
|
+
## Installation
|
|
41
|
+
|
|
42
|
+
```bash
|
|
43
|
+
uv add swarmauri_keyprovider_gcpkms
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
Enable CBOR canonicalization support:
|
|
47
|
+
|
|
48
|
+
```bash
|
|
49
|
+
uv add swarmauri_keyprovider_gcpkms[cbor]
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
## Usage
|
|
53
|
+
|
|
54
|
+
```python
|
|
55
|
+
from swarmauri_keyprovider_gcpkms import GcpKmsKeyProvider
|
|
56
|
+
|
|
57
|
+
kp = GcpKmsKeyProvider(
|
|
58
|
+
project_id="my-project",
|
|
59
|
+
location_id="us-east1",
|
|
60
|
+
key_ring_id="my-ring",
|
|
61
|
+
)
|
|
62
|
+
```
|
|
63
|
+
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
# Swarmauri GCP KMS Key Provider
|
|
2
|
+
|
|
3
|
+
GCP KMS-backed key provider for the Swarmauri framework. This plugin exposes
|
|
4
|
+
Google Cloud KMS keys through the common `IKeyProvider` interface, enabling
|
|
5
|
+
signing, verification, encryption and random byte generation.
|
|
6
|
+
|
|
7
|
+
## Optional Canonicalization Extras
|
|
8
|
+
|
|
9
|
+
- `cbor` – enables CBOR canonicalization utilities via `cbor2`.
|
|
10
|
+
|
|
11
|
+
## Features
|
|
12
|
+
|
|
13
|
+
- AES encryption and decryption using KMS-managed symmetric keys.
|
|
14
|
+
- RSA and EC signing backed by Cloud KMS.
|
|
15
|
+
- RSA wrapping and unwrapping of data encryption keys.
|
|
16
|
+
- JWKS export for asymmetric public keys.
|
|
17
|
+
|
|
18
|
+
## Installation
|
|
19
|
+
|
|
20
|
+
```bash
|
|
21
|
+
uv add swarmauri_keyprovider_gcpkms
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
Enable CBOR canonicalization support:
|
|
25
|
+
|
|
26
|
+
```bash
|
|
27
|
+
uv add swarmauri_keyprovider_gcpkms[cbor]
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
## Usage
|
|
31
|
+
|
|
32
|
+
```python
|
|
33
|
+
from swarmauri_keyprovider_gcpkms import GcpKmsKeyProvider
|
|
34
|
+
|
|
35
|
+
kp = GcpKmsKeyProvider(
|
|
36
|
+
project_id="my-project",
|
|
37
|
+
location_id="us-east1",
|
|
38
|
+
key_ring_id="my-ring",
|
|
39
|
+
)
|
|
40
|
+
```
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "swarmauri_keyprovider_gcpkms"
|
|
3
|
+
version = "0.9.0.dev4"
|
|
4
|
+
description = "Google Cloud KMS Key Provider 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
|
+
"google-auth",
|
|
18
|
+
"requests",
|
|
19
|
+
"cryptography",
|
|
20
|
+
"swarmauri_core",
|
|
21
|
+
"swarmauri_base",
|
|
22
|
+
"swarmauri_standard",
|
|
23
|
+
]
|
|
24
|
+
|
|
25
|
+
[project.optional-dependencies]
|
|
26
|
+
cbor = ["cbor2"]
|
|
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
|
+
"functional: Functional tests",
|
|
46
|
+
]
|
|
47
|
+
timeout = 300
|
|
48
|
+
log_cli = true
|
|
49
|
+
log_cli_level = "INFO"
|
|
50
|
+
log_cli_format = "%(asctime)s [%(levelname)s] %(message)s"
|
|
51
|
+
log_cli_date_format = "%Y-%m-%d %H:%M:%S"
|
|
52
|
+
asyncio_default_fixture_loop_scope = "function"
|
|
53
|
+
|
|
54
|
+
[project.entry-points.'swarmauri.key_providers']
|
|
55
|
+
GcpKmsKeyProvider = "swarmauri_keyprovider_gcpkms.GcpKmsKeyProvider:GcpKmsKeyProvider"
|
|
56
|
+
|
|
57
|
+
[build-system]
|
|
58
|
+
requires = ["poetry-core>=1.0.0"]
|
|
59
|
+
build-backend = "poetry.core.masonry.api"
|
|
60
|
+
|
|
61
|
+
[dependency-groups]
|
|
62
|
+
dev = [
|
|
63
|
+
"pytest>=8.0",
|
|
64
|
+
"pytest-asyncio>=0.24.0",
|
|
65
|
+
"pytest-xdist>=3.6.1",
|
|
66
|
+
"pytest-json-report>=1.5.0",
|
|
67
|
+
"python-dotenv",
|
|
68
|
+
"requests>=2.32.3",
|
|
69
|
+
"flake8>=7.0",
|
|
70
|
+
"pytest-timeout>=2.3.1",
|
|
71
|
+
"ruff>=0.9.9",
|
|
72
|
+
"pytest-benchmark>=4.0.0",
|
|
73
|
+
]
|
|
@@ -0,0 +1,567 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import base64
|
|
4
|
+
import json
|
|
5
|
+
import threading
|
|
6
|
+
import time
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from typing import Any, Dict, Iterable, Literal, Mapping, Optional, Tuple
|
|
9
|
+
|
|
10
|
+
import google.auth
|
|
11
|
+
from google.auth.transport.requests import Request as GARequest
|
|
12
|
+
import requests
|
|
13
|
+
|
|
14
|
+
from cryptography.hazmat.primitives import hashes
|
|
15
|
+
from cryptography.hazmat.primitives.asymmetric import ec, padding, rsa
|
|
16
|
+
from cryptography.hazmat.primitives.asymmetric.utils import Prehashed
|
|
17
|
+
from cryptography.hazmat.primitives.serialization import load_pem_public_key
|
|
18
|
+
from cryptography.hazmat.primitives.kdf.hkdf import HKDF
|
|
19
|
+
import secrets
|
|
20
|
+
|
|
21
|
+
from pydantic import PrivateAttr
|
|
22
|
+
|
|
23
|
+
from swarmauri_base.keys.KeyProviderBase import KeyProviderBase
|
|
24
|
+
from swarmauri_core.keys.types import ExportPolicy, KeySpec, KeyUse
|
|
25
|
+
from swarmauri_core.crypto.types import JWAAlg, KeyRef
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
API_ROOT = "https://cloudkms.googleapis.com/v1"
|
|
29
|
+
SCOPE = "https://www.googleapis.com/auth/cloud-platform"
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
# ---------- Helpers ----------
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _b64e(b: bytes) -> str:
|
|
36
|
+
return base64.b64encode(b).decode("ascii")
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _b64d(s: str) -> bytes:
|
|
40
|
+
return base64.b64decode(s.encode("ascii"))
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _now() -> float:
|
|
44
|
+
return time.time()
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _is_rsa_decrypt_purpose(algorithm: str) -> bool:
|
|
48
|
+
return algorithm.startswith("RSA_DECRYPT_")
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _is_rsa_sign_purpose(algorithm: str) -> bool:
|
|
52
|
+
return algorithm.startswith("RSA_SIGN_")
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _is_ec_sign_purpose(algorithm: str) -> bool:
|
|
56
|
+
return algorithm.startswith("EC_SIGN_")
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _hash_from_algo(algorithm: str):
|
|
60
|
+
if algorithm.endswith("SHA256"):
|
|
61
|
+
return hashes.SHA256()
|
|
62
|
+
if algorithm.endswith("SHA384"):
|
|
63
|
+
return hashes.SHA384()
|
|
64
|
+
if algorithm.endswith("SHA512"):
|
|
65
|
+
return hashes.SHA512()
|
|
66
|
+
return hashes.SHA256()
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _ec_curve_from_algo(algorithm: str):
|
|
70
|
+
if "P256" in algorithm:
|
|
71
|
+
return ec.SECP256R1()
|
|
72
|
+
if "P384" in algorithm:
|
|
73
|
+
return ec.SECP384R1()
|
|
74
|
+
if "SECP256K1" in algorithm:
|
|
75
|
+
return ec.SECP256K1()
|
|
76
|
+
return ec.SECP256R1()
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _jwk_from_pem_public_key(pem_bytes: bytes) -> Dict[str, Any]:
|
|
80
|
+
pub = load_pem_public_key(pem_bytes)
|
|
81
|
+
if isinstance(pub, rsa.RSAPublicKey):
|
|
82
|
+
numbers = pub.public_numbers()
|
|
83
|
+
n = numbers.n.to_bytes((numbers.n.bit_length() + 7) // 8, "big")
|
|
84
|
+
e = numbers.e.to_bytes((numbers.e.bit_length() + 7) // 8, "big")
|
|
85
|
+
return {
|
|
86
|
+
"kty": "RSA",
|
|
87
|
+
"n": base64.urlsafe_b64encode(n).rstrip(b"=").decode("ascii"),
|
|
88
|
+
"e": base64.urlsafe_b64encode(e).rstrip(b"=").decode("ascii"),
|
|
89
|
+
}
|
|
90
|
+
if isinstance(pub, ec.EllipticCurvePublicKey):
|
|
91
|
+
numbers = pub.public_numbers()
|
|
92
|
+
x = numbers.x.to_bytes((numbers.curve.key_size + 7) // 8, "big")
|
|
93
|
+
y = numbers.y.to_bytes((numbers.curve.key_size + 7) // 8, "big")
|
|
94
|
+
crv = "P-256"
|
|
95
|
+
if isinstance(numbers.curve, ec.SECP384R1):
|
|
96
|
+
crv = "P-384"
|
|
97
|
+
elif isinstance(numbers.curve, ec.SECP256K1):
|
|
98
|
+
crv = "secp256k1"
|
|
99
|
+
return {
|
|
100
|
+
"kty": "EC",
|
|
101
|
+
"crv": crv,
|
|
102
|
+
"x": base64.urlsafe_b64encode(x).rstrip(b"=").decode("ascii"),
|
|
103
|
+
"y": base64.urlsafe_b64encode(y).rstrip(b"=").decode("ascii"),
|
|
104
|
+
}
|
|
105
|
+
raise ValueError("Unsupported public key type in PEM")
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
@dataclass(frozen=True)
|
|
109
|
+
class _GcpKeyRef(KeyRef):
|
|
110
|
+
"""Read-only reference to a KMS key version."""
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
class GcpKmsKeyProvider(KeyProviderBase):
|
|
114
|
+
type: Literal["GcpKmsKeyProvider"] = "GcpKmsKeyProvider"
|
|
115
|
+
_creds = PrivateAttr()
|
|
116
|
+
_ga_req = PrivateAttr()
|
|
117
|
+
_lock: threading.RLock = PrivateAttr(default_factory=threading.RLock)
|
|
118
|
+
_pub_cache: Dict[str, Tuple[bytes, str]] = PrivateAttr(default_factory=dict)
|
|
119
|
+
_pub_cache_at: Dict[str, float] = PrivateAttr(default_factory=dict)
|
|
120
|
+
_pub_ttl: float = PrivateAttr(default=300.0)
|
|
121
|
+
|
|
122
|
+
def __init__(
|
|
123
|
+
self,
|
|
124
|
+
*,
|
|
125
|
+
project_id: str,
|
|
126
|
+
location_id: str,
|
|
127
|
+
key_ring_id: str,
|
|
128
|
+
http_timeout_s: int = 8,
|
|
129
|
+
user_agent: str = "GcpKmsKeyProvider/1.0",
|
|
130
|
+
) -> None:
|
|
131
|
+
super().__init__()
|
|
132
|
+
self._project = project_id
|
|
133
|
+
self._location = location_id
|
|
134
|
+
self._ring = key_ring_id
|
|
135
|
+
self._timeout = http_timeout_s
|
|
136
|
+
self._ua = user_agent
|
|
137
|
+
|
|
138
|
+
creds, _ = google.auth.default(scopes=[SCOPE])
|
|
139
|
+
self._creds = creds
|
|
140
|
+
self._ga_req = GARequest()
|
|
141
|
+
|
|
142
|
+
def supports(self) -> Mapping[str, Iterable[str]]:
|
|
143
|
+
return {
|
|
144
|
+
"class": ("kms", "asym", "sym"),
|
|
145
|
+
"algs": ("AES", "RSA", "EC"),
|
|
146
|
+
"features": (
|
|
147
|
+
"create",
|
|
148
|
+
"encrypt",
|
|
149
|
+
"decrypt",
|
|
150
|
+
"sign",
|
|
151
|
+
"verify",
|
|
152
|
+
"wrap",
|
|
153
|
+
"unwrap",
|
|
154
|
+
"jwks",
|
|
155
|
+
),
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
async def create_key(self, spec: KeySpec) -> KeyRef:
|
|
159
|
+
purpose = "ENCRYPT_DECRYPT"
|
|
160
|
+
token = self._token()
|
|
161
|
+
url = (
|
|
162
|
+
f"{API_ROOT}/projects/{self._project}/locations/{self._location}/"
|
|
163
|
+
f"keyRings/{self._ring}/cryptoKeys?cryptoKeyId={spec.name}"
|
|
164
|
+
)
|
|
165
|
+
body = {"purpose": purpose}
|
|
166
|
+
r = requests.post(
|
|
167
|
+
url, headers=self._hdr(token), json=body, timeout=self._timeout
|
|
168
|
+
)
|
|
169
|
+
if r.status_code not in (200, 201):
|
|
170
|
+
raise RuntimeError(f"create_key failed: {r.status_code} {r.text}")
|
|
171
|
+
return _GcpKeyRef(
|
|
172
|
+
kid=spec.name,
|
|
173
|
+
version=1,
|
|
174
|
+
type="OPAQUE",
|
|
175
|
+
uses=(KeyUse.encrypt, KeyUse.decrypt),
|
|
176
|
+
export_policy=ExportPolicy.public_only,
|
|
177
|
+
public=None,
|
|
178
|
+
material=None,
|
|
179
|
+
tags={"kms": "gcp"},
|
|
180
|
+
fingerprint=self._fingerprint(kid=spec.name),
|
|
181
|
+
)
|
|
182
|
+
|
|
183
|
+
async def import_key(
|
|
184
|
+
self, spec: KeySpec, material: bytes, *, public: Optional[bytes] = None
|
|
185
|
+
) -> KeyRef:
|
|
186
|
+
raise NotImplementedError(
|
|
187
|
+
"Use Cloud KMS ImportJobs to import external keys (not provided here)"
|
|
188
|
+
)
|
|
189
|
+
|
|
190
|
+
async def rotate_key(
|
|
191
|
+
self, kid: str, *, spec_overrides: Optional[dict] = None
|
|
192
|
+
) -> KeyRef:
|
|
193
|
+
raise NotImplementedError(
|
|
194
|
+
"Configure rotation via Cloud KMS CryptoKey rotation config or create new versions"
|
|
195
|
+
)
|
|
196
|
+
|
|
197
|
+
async def destroy_key(self, kid: str, version: Optional[int] = None) -> bool:
|
|
198
|
+
if version is None:
|
|
199
|
+
raise ValueError("GCP KMS requires a specific version to destroy")
|
|
200
|
+
name = self._version_name(kid, version)
|
|
201
|
+
token = self._token()
|
|
202
|
+
url = f"{API_ROOT}/{name}:destroy"
|
|
203
|
+
r = requests.post(url, headers=self._hdr(token), json={}, timeout=self._timeout)
|
|
204
|
+
if r.status_code != 200:
|
|
205
|
+
raise RuntimeError(f"destroy_key failed: {r.status_code} {r.text}")
|
|
206
|
+
return True
|
|
207
|
+
|
|
208
|
+
async def get_key(
|
|
209
|
+
self, kid: str, version: Optional[int] = None, *, include_secret: bool = False
|
|
210
|
+
) -> KeyRef:
|
|
211
|
+
vname, algo = self._effective_version_and_algo(kid, version)
|
|
212
|
+
public_pem = self._maybe_fetch_public_pem(vname, algo)
|
|
213
|
+
public_bytes = None
|
|
214
|
+
tags: Dict[str, Any] = {"kms": "gcp", "algorithm": algo}
|
|
215
|
+
if public_pem:
|
|
216
|
+
jwk = _jwk_from_pem_public_key(public_pem)
|
|
217
|
+
tags["kty"] = jwk.get("kty")
|
|
218
|
+
public_bytes = json.dumps(
|
|
219
|
+
jwk, separators=(",", ":"), sort_keys=True
|
|
220
|
+
).encode("utf-8")
|
|
221
|
+
|
|
222
|
+
ver_num = int(vname.rsplit("/", 1)[-1])
|
|
223
|
+
if _is_rsa_decrypt_purpose(algo):
|
|
224
|
+
uses = (KeyUse.wrap, KeyUse.unwrap)
|
|
225
|
+
elif _is_rsa_sign_purpose(algo) or _is_ec_sign_purpose(algo):
|
|
226
|
+
uses = (KeyUse.sign, KeyUse.verify)
|
|
227
|
+
else:
|
|
228
|
+
uses = (KeyUse.encrypt, KeyUse.decrypt)
|
|
229
|
+
|
|
230
|
+
return _GcpKeyRef(
|
|
231
|
+
kid=kid,
|
|
232
|
+
version=ver_num,
|
|
233
|
+
type="OPAQUE",
|
|
234
|
+
uses=uses,
|
|
235
|
+
export_policy=ExportPolicy.public_only,
|
|
236
|
+
public=public_bytes,
|
|
237
|
+
material=None,
|
|
238
|
+
tags=tags,
|
|
239
|
+
fingerprint=self._fingerprint(public=public_bytes, kid=kid),
|
|
240
|
+
)
|
|
241
|
+
|
|
242
|
+
async def list_versions(self, kid: str) -> Tuple[int, ...]:
|
|
243
|
+
token = self._token()
|
|
244
|
+
name = self._key_name(kid)
|
|
245
|
+
url = f"{API_ROOT}/{name}/cryptoKeyVersions?pageSize=1000"
|
|
246
|
+
r = requests.get(url, headers=self._hdr(token), timeout=self._timeout)
|
|
247
|
+
if r.status_code != 200:
|
|
248
|
+
raise RuntimeError(f"list_versions failed: {r.status_code} {r.text}")
|
|
249
|
+
obj = r.json()
|
|
250
|
+
vers = []
|
|
251
|
+
for v in obj.get("cryptoKeyVersions", []):
|
|
252
|
+
if v.get("state") == "ENABLED":
|
|
253
|
+
vers.append(int(v["name"].split("/")[-1]))
|
|
254
|
+
return tuple(sorted(vers))
|
|
255
|
+
|
|
256
|
+
async def get_public_jwk(self, kid: str, version: Optional[int] = None) -> dict:
|
|
257
|
+
ref = await self.get_key(kid, version)
|
|
258
|
+
if not ref.public:
|
|
259
|
+
raise RuntimeError("no public key material available")
|
|
260
|
+
return json.loads(ref.public.decode("utf-8"))
|
|
261
|
+
|
|
262
|
+
async def jwks(self, *, prefix_kids: Optional[str] = None) -> dict:
|
|
263
|
+
token = self._token()
|
|
264
|
+
list_url = f"{API_ROOT}/projects/{self._project}/locations/{self._location}/keyRings/{self._ring}/cryptoKeys?pageSize=1000"
|
|
265
|
+
r = requests.get(list_url, headers=self._hdr(token), timeout=self._timeout)
|
|
266
|
+
if r.status_code != 200:
|
|
267
|
+
raise RuntimeError(f"jwks list keys failed: {r.status_code} {r.text}")
|
|
268
|
+
keys_out = []
|
|
269
|
+
for ck in r.json().get("cryptoKeys", []):
|
|
270
|
+
kid = ck["name"].split("/")[-1]
|
|
271
|
+
if prefix_kids and not kid.startswith(prefix_kids):
|
|
272
|
+
continue
|
|
273
|
+
v_url = f"{API_ROOT}/{ck['name']}/cryptoKeyVersions?pageSize=1000"
|
|
274
|
+
rv = requests.get(v_url, headers=self._hdr(token), timeout=self._timeout)
|
|
275
|
+
if rv.status_code != 200:
|
|
276
|
+
continue
|
|
277
|
+
for v in rv.json().get("cryptoKeyVersions", []):
|
|
278
|
+
if v.get("state") != "ENABLED":
|
|
279
|
+
continue
|
|
280
|
+
algo = v.get("algorithm", "")
|
|
281
|
+
if (
|
|
282
|
+
_is_rsa_sign_purpose(algo)
|
|
283
|
+
or _is_ec_sign_purpose(algo)
|
|
284
|
+
or _is_rsa_decrypt_purpose(algo)
|
|
285
|
+
):
|
|
286
|
+
vname = v["name"]
|
|
287
|
+
pem = self._maybe_fetch_public_pem(vname, algo)
|
|
288
|
+
if not pem:
|
|
289
|
+
continue
|
|
290
|
+
jwk = _jwk_from_pem_public_key(pem)
|
|
291
|
+
jwk["kid"] = f"{kid}.{int(vname.split('/')[-1])}"
|
|
292
|
+
if _is_rsa_sign_purpose(algo):
|
|
293
|
+
jwk["alg"] = (
|
|
294
|
+
JWAAlg.PS256.value
|
|
295
|
+
if "PKCS1_PSS" in algo or "PSS" in algo
|
|
296
|
+
else JWAAlg.RS256.value
|
|
297
|
+
)
|
|
298
|
+
elif _is_ec_sign_purpose(algo):
|
|
299
|
+
jwk["alg"] = (
|
|
300
|
+
JWAAlg.ES256.value if "P256" in algo else JWAAlg.ES384.value
|
|
301
|
+
)
|
|
302
|
+
elif _is_rsa_decrypt_purpose(algo):
|
|
303
|
+
jwk["alg"] = JWAAlg.RSA_OAEP_256.value
|
|
304
|
+
keys_out.append(jwk)
|
|
305
|
+
return {"keys": keys_out}
|
|
306
|
+
|
|
307
|
+
async def encrypt(
|
|
308
|
+
self,
|
|
309
|
+
kid: str,
|
|
310
|
+
plaintext: bytes,
|
|
311
|
+
*,
|
|
312
|
+
aad: Optional[bytes] = None,
|
|
313
|
+
version: Optional[int] = None,
|
|
314
|
+
) -> bytes:
|
|
315
|
+
name = self._key_name(kid)
|
|
316
|
+
token = self._token()
|
|
317
|
+
url = f"{API_ROOT}/{name}:encrypt"
|
|
318
|
+
body: Dict[str, Any] = {"plaintext": _b64e(plaintext)}
|
|
319
|
+
if aad:
|
|
320
|
+
body["additionalAuthenticatedData"] = _b64e(aad)
|
|
321
|
+
r = requests.post(
|
|
322
|
+
url, headers=self._hdr(token), json=body, timeout=self._timeout
|
|
323
|
+
)
|
|
324
|
+
if r.status_code != 200:
|
|
325
|
+
raise RuntimeError(f"encrypt failed: {r.status_code} {r.text}")
|
|
326
|
+
return _b64d(r.json()["ciphertext"])
|
|
327
|
+
|
|
328
|
+
async def decrypt(
|
|
329
|
+
self,
|
|
330
|
+
kid: str,
|
|
331
|
+
ciphertext: bytes,
|
|
332
|
+
*,
|
|
333
|
+
aad: Optional[bytes] = None,
|
|
334
|
+
version: Optional[int] = None,
|
|
335
|
+
) -> bytes:
|
|
336
|
+
name = self._key_name(kid)
|
|
337
|
+
token = self._token()
|
|
338
|
+
url = f"{API_ROOT}/{name}:decrypt"
|
|
339
|
+
body: Dict[str, Any] = {"ciphertext": _b64e(ciphertext)}
|
|
340
|
+
if aad:
|
|
341
|
+
body["additionalAuthenticatedData"] = _b64e(aad)
|
|
342
|
+
r = requests.post(
|
|
343
|
+
url, headers=self._hdr(token), json=body, timeout=self._timeout
|
|
344
|
+
)
|
|
345
|
+
if r.status_code != 200:
|
|
346
|
+
raise RuntimeError(f"decrypt failed: {r.status_code} {r.text}")
|
|
347
|
+
return _b64d(r.json()["plaintext"])
|
|
348
|
+
|
|
349
|
+
async def wrap_key(
|
|
350
|
+
self, kid: str, dek: bytes, *, version: Optional[int] = None
|
|
351
|
+
) -> bytes:
|
|
352
|
+
vname, algo = self._effective_version_and_algo(kid, version)
|
|
353
|
+
if not _is_rsa_decrypt_purpose(algo):
|
|
354
|
+
raise ValueError(f"wrap_key requires RSA_DECRYPT_* algorithm, got {algo}")
|
|
355
|
+
pem = self._maybe_fetch_public_pem(vname, algo)
|
|
356
|
+
if not pem:
|
|
357
|
+
raise RuntimeError("No public key available for wrap_key")
|
|
358
|
+
pub = load_pem_public_key(pem)
|
|
359
|
+
if not isinstance(pub, rsa.RSAPublicKey):
|
|
360
|
+
raise ValueError("wrap_key requires RSA public key")
|
|
361
|
+
oaep_hash = _hash_from_algo(algo)
|
|
362
|
+
ct = pub.encrypt(
|
|
363
|
+
dek,
|
|
364
|
+
padding.OAEP(
|
|
365
|
+
mgf=padding.MGF1(algorithm=oaep_hash),
|
|
366
|
+
algorithm=oaep_hash,
|
|
367
|
+
label=None,
|
|
368
|
+
),
|
|
369
|
+
)
|
|
370
|
+
return ct
|
|
371
|
+
|
|
372
|
+
async def unwrap_key(
|
|
373
|
+
self, kid: str, wrapped: bytes, *, version: Optional[int] = None
|
|
374
|
+
) -> bytes:
|
|
375
|
+
vname, algo = self._effective_version_and_algo(kid, version)
|
|
376
|
+
if not _is_rsa_decrypt_purpose(algo):
|
|
377
|
+
raise ValueError(f"unwrap_key requires RSA_DECRYPT_* algorithm, got {algo}")
|
|
378
|
+
token = self._token()
|
|
379
|
+
url = f"{API_ROOT}/{vname}:asymmetricDecrypt"
|
|
380
|
+
body = {"ciphertext": _b64e(wrapped)}
|
|
381
|
+
r = requests.post(
|
|
382
|
+
url, headers=self._hdr(token), json=body, timeout=self._timeout
|
|
383
|
+
)
|
|
384
|
+
if r.status_code != 200:
|
|
385
|
+
raise RuntimeError(f"unwrap_key failed: {r.status_code} {r.text}")
|
|
386
|
+
return _b64d(r.json()["plaintext"])
|
|
387
|
+
|
|
388
|
+
async def sign(
|
|
389
|
+
self,
|
|
390
|
+
kid: str,
|
|
391
|
+
message: bytes,
|
|
392
|
+
*,
|
|
393
|
+
version: Optional[int] = None,
|
|
394
|
+
prehashed: bool = False,
|
|
395
|
+
) -> bytes:
|
|
396
|
+
vname, algo = self._effective_version_and_algo(kid, version)
|
|
397
|
+
if not (_is_rsa_sign_purpose(algo) or _is_ec_sign_purpose(algo)):
|
|
398
|
+
raise ValueError(
|
|
399
|
+
f"sign requires RSA_SIGN_* or EC_SIGN_* algorithm, got {algo}"
|
|
400
|
+
)
|
|
401
|
+
|
|
402
|
+
h = _hash_from_algo(algo)
|
|
403
|
+
if prehashed:
|
|
404
|
+
digest_bytes = message
|
|
405
|
+
else:
|
|
406
|
+
digest = hashes.Hash(h)
|
|
407
|
+
digest.update(message)
|
|
408
|
+
digest_bytes = digest.finalize()
|
|
409
|
+
|
|
410
|
+
token = self._token()
|
|
411
|
+
url = f"{API_ROOT}/{vname}:asymmetricSign"
|
|
412
|
+
body = {"digest": {f"sha{h.digest_size * 8}": _b64e(digest_bytes)}}
|
|
413
|
+
r = requests.post(
|
|
414
|
+
url, headers=self._hdr(token), json=body, timeout=self._timeout
|
|
415
|
+
)
|
|
416
|
+
if r.status_code != 200:
|
|
417
|
+
raise RuntimeError(f"sign failed: {r.status_code} {r.text}")
|
|
418
|
+
return _b64d(r.json()["signature"])
|
|
419
|
+
|
|
420
|
+
async def verify(
|
|
421
|
+
self,
|
|
422
|
+
kid: str,
|
|
423
|
+
message: bytes,
|
|
424
|
+
signature: bytes,
|
|
425
|
+
*,
|
|
426
|
+
version: Optional[int] = None,
|
|
427
|
+
prehashed: bool = False,
|
|
428
|
+
) -> bool:
|
|
429
|
+
vname, algo = self._effective_version_and_algo(kid, version)
|
|
430
|
+
pem = self._maybe_fetch_public_pem(vname, algo)
|
|
431
|
+
if not pem:
|
|
432
|
+
raise RuntimeError("No public key available for verify")
|
|
433
|
+
pub = load_pem_public_key(pem)
|
|
434
|
+
|
|
435
|
+
h = _hash_from_algo(algo)
|
|
436
|
+
if prehashed:
|
|
437
|
+
digest_bytes = message
|
|
438
|
+
else:
|
|
439
|
+
digest_calc = hashes.Hash(h)
|
|
440
|
+
digest_calc.update(message)
|
|
441
|
+
digest_bytes = digest_calc.finalize()
|
|
442
|
+
|
|
443
|
+
try:
|
|
444
|
+
if isinstance(pub, rsa.RSAPublicKey):
|
|
445
|
+
if "PKCS1" in algo and "PSS" not in algo:
|
|
446
|
+
pub.verify(
|
|
447
|
+
signature,
|
|
448
|
+
digest_bytes,
|
|
449
|
+
padding.PKCS1v15(),
|
|
450
|
+
Prehashed(h),
|
|
451
|
+
)
|
|
452
|
+
else:
|
|
453
|
+
pub.verify(
|
|
454
|
+
signature,
|
|
455
|
+
digest_bytes,
|
|
456
|
+
padding.PSS(
|
|
457
|
+
mgf=padding.MGF1(h),
|
|
458
|
+
salt_length=padding.PSS.MAX_LENGTH,
|
|
459
|
+
),
|
|
460
|
+
Prehashed(h),
|
|
461
|
+
)
|
|
462
|
+
return True
|
|
463
|
+
if isinstance(pub, ec.EllipticCurvePublicKey):
|
|
464
|
+
pub.verify(signature, digest_bytes, ec.ECDSA(Prehashed(h)))
|
|
465
|
+
return True
|
|
466
|
+
except Exception:
|
|
467
|
+
return False
|
|
468
|
+
return False
|
|
469
|
+
|
|
470
|
+
async def random_bytes(self, n: int) -> bytes:
|
|
471
|
+
return secrets.token_bytes(n)
|
|
472
|
+
|
|
473
|
+
async def hkdf(self, ikm: bytes, *, salt: bytes, info: bytes, length: int) -> bytes:
|
|
474
|
+
return HKDF(
|
|
475
|
+
algorithm=hashes.SHA256(), length=length, salt=salt, info=info
|
|
476
|
+
).derive(ikm)
|
|
477
|
+
|
|
478
|
+
def _token(self) -> str:
|
|
479
|
+
with self._lock:
|
|
480
|
+
if not self._creds.valid:
|
|
481
|
+
self._creds.refresh(self._ga_req)
|
|
482
|
+
return self._creds.token # type: ignore[return-value]
|
|
483
|
+
|
|
484
|
+
def _hdr(self, token: str) -> Dict[str, str]:
|
|
485
|
+
return {
|
|
486
|
+
"Authorization": f"Bearer {token}",
|
|
487
|
+
"Content-Type": "application/json",
|
|
488
|
+
"Accept": "application/json",
|
|
489
|
+
"User-Agent": self._ua,
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
def _key_name(self, kid: str) -> str:
|
|
493
|
+
return f"projects/{self._project}/locations/{self._location}/keyRings/{self._ring}/cryptoKeys/{kid}"
|
|
494
|
+
|
|
495
|
+
def _version_name(self, kid: str, version: int) -> str:
|
|
496
|
+
return f"{self._key_name(kid)}/cryptoKeyVersions/{int(version)}"
|
|
497
|
+
|
|
498
|
+
def _effective_version_and_algo(
|
|
499
|
+
self, kid: str, version: Optional[int]
|
|
500
|
+
) -> Tuple[str, str]:
|
|
501
|
+
token = self._token()
|
|
502
|
+
if version is None:
|
|
503
|
+
ck_url = f"{API_ROOT}/{self._key_name(kid)}"
|
|
504
|
+
r = requests.get(ck_url, headers=self._hdr(token), timeout=self._timeout)
|
|
505
|
+
if r.status_code != 200:
|
|
506
|
+
raise RuntimeError(f"get CryptoKey failed: {r.status_code} {r.text}")
|
|
507
|
+
obj = r.json()
|
|
508
|
+
primary = obj.get("primary", {}).get("name")
|
|
509
|
+
if primary:
|
|
510
|
+
vname = primary
|
|
511
|
+
else:
|
|
512
|
+
lv_url = (
|
|
513
|
+
f"{API_ROOT}/{self._key_name(kid)}/cryptoKeyVersions?pageSize=1000"
|
|
514
|
+
)
|
|
515
|
+
rv = requests.get(
|
|
516
|
+
lv_url, headers=self._hdr(token), timeout=self._timeout
|
|
517
|
+
)
|
|
518
|
+
if rv.status_code != 200:
|
|
519
|
+
raise RuntimeError(
|
|
520
|
+
f"list versions failed: {rv.status_code} {rv.text}"
|
|
521
|
+
)
|
|
522
|
+
enabled = [
|
|
523
|
+
(
|
|
524
|
+
int(v["name"].split("/")[-1]),
|
|
525
|
+
v["name"],
|
|
526
|
+
v.get("algorithm", ""),
|
|
527
|
+
)
|
|
528
|
+
for v in rv.json().get("cryptoKeyVersions", [])
|
|
529
|
+
if v.get("state") == "ENABLED"
|
|
530
|
+
]
|
|
531
|
+
if not enabled:
|
|
532
|
+
raise RuntimeError("no ENABLED versions available")
|
|
533
|
+
enabled.sort(key=lambda t: t[0], reverse=True)
|
|
534
|
+
vname = enabled[0][1]
|
|
535
|
+
else:
|
|
536
|
+
vname = self._version_name(kid, version)
|
|
537
|
+
|
|
538
|
+
v_url = f"{API_ROOT}/{vname}"
|
|
539
|
+
rv = requests.get(v_url, headers=self._hdr(token), timeout=self._timeout)
|
|
540
|
+
if rv.status_code != 200:
|
|
541
|
+
raise RuntimeError(f"get version failed: {rv.status_code} {rv.text}")
|
|
542
|
+
algo = rv.json().get("algorithm", "")
|
|
543
|
+
return vname, algo
|
|
544
|
+
|
|
545
|
+
def _maybe_fetch_public_pem(
|
|
546
|
+
self, version_name: str, algorithm: str
|
|
547
|
+
) -> Optional[bytes]:
|
|
548
|
+
if not (
|
|
549
|
+
_is_rsa_sign_purpose(algorithm)
|
|
550
|
+
or _is_ec_sign_purpose(algorithm)
|
|
551
|
+
or _is_rsa_decrypt_purpose(algorithm)
|
|
552
|
+
):
|
|
553
|
+
return None
|
|
554
|
+
with self._lock:
|
|
555
|
+
ts = self._pub_cache_at.get(version_name, 0.0)
|
|
556
|
+
if version_name in self._pub_cache and (_now() - ts) < self._pub_ttl:
|
|
557
|
+
return self._pub_cache[version_name][0]
|
|
558
|
+
token = self._token()
|
|
559
|
+
url = f"{API_ROOT}/{version_name}/publicKey"
|
|
560
|
+
r = requests.get(url, headers=self._hdr(token), timeout=self._timeout)
|
|
561
|
+
if r.status_code != 200:
|
|
562
|
+
raise RuntimeError(f"getPublicKey failed: {r.status_code} {r.text}")
|
|
563
|
+
pem = r.json().get("pem", "").encode("utf-8")
|
|
564
|
+
with self._lock:
|
|
565
|
+
self._pub_cache[version_name] = (pem, algorithm)
|
|
566
|
+
self._pub_cache_at[version_name] = _now()
|
|
567
|
+
return pem
|