swarmauri_keyprovider_file 0.2.0__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_file-0.2.0/LICENSE +201 -0
- swarmauri_keyprovider_file-0.2.0/PKG-INFO +130 -0
- swarmauri_keyprovider_file-0.2.0/README.md +99 -0
- swarmauri_keyprovider_file-0.2.0/pyproject.toml +82 -0
- swarmauri_keyprovider_file-0.2.0/swarmauri_keyprovider_file/FileKeyProvider.py +573 -0
- swarmauri_keyprovider_file-0.2.0/swarmauri_keyprovider_file/__init__.py +5 -0
- swarmauri_keyprovider_file-0.2.0/swarmauri_keyprovider_file/examples/README.md +38 -0
- swarmauri_keyprovider_file-0.2.0/swarmauri_keyprovider_file/examples/__init__.py +0 -0
- swarmauri_keyprovider_file-0.2.0/swarmauri_keyprovider_file/examples/basic_usage.py +32 -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,130 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: swarmauri_keyprovider_file
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: File-backed key provider for Swarmauri
|
|
5
|
+
License-Expression: Apache-2.0
|
|
6
|
+
License-File: LICENSE
|
|
7
|
+
Keywords: swarmauri,sdk,standards,keyprovider,file,key-management
|
|
8
|
+
Author: Jacob Stewart
|
|
9
|
+
Author-email: jacob@swarmauri.com
|
|
10
|
+
Requires-Python: >=3.10,<3.13
|
|
11
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
12
|
+
Classifier: Natural Language :: English
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
17
|
+
Classifier: Development Status :: 3 - Alpha
|
|
18
|
+
Classifier: Topic :: Security :: Cryptography
|
|
19
|
+
Classifier: Intended Audience :: Developers
|
|
20
|
+
Classifier: Programming Language :: Python
|
|
21
|
+
Classifier: Programming Language :: Python :: 3
|
|
22
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
23
|
+
Provides-Extra: cbor
|
|
24
|
+
Provides-Extra: jwks
|
|
25
|
+
Requires-Dist: cbor2 ; extra == "cbor"
|
|
26
|
+
Requires-Dist: cryptography
|
|
27
|
+
Requires-Dist: jwcrypto ; extra == "jwks"
|
|
28
|
+
Requires-Dist: swarmauri_base
|
|
29
|
+
Requires-Dist: swarmauri_core
|
|
30
|
+
Description-Content-Type: text/markdown
|
|
31
|
+
|
|
32
|
+

|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
<p align="center">
|
|
36
|
+
<a href="https://pypi.org/project/swarmauri_keyprovider_file/">
|
|
37
|
+
<img src="https://img.shields.io/pypi/dm/swarmauri_keyprovider_file" alt="PyPI - Downloads"/></a>
|
|
38
|
+
<a href="https://hits.sh/github.com/swarmauri/swarmauri-sdk/tree/master/pkgs/standards/swarmauri_keyprovider_file/">
|
|
39
|
+
<img alt="Hits" src="https://hits.sh/github.com/swarmauri/swarmauri-sdk/tree/master/pkgs/standards/swarmauri_keyprovider_file.svg"/></a>
|
|
40
|
+
<a href="https://pypi.org/project/swarmauri_keyprovider_file/">
|
|
41
|
+
<img src="https://img.shields.io/pypi/pyversions/swarmauri_keyprovider_file" alt="PyPI - Python Version"/></a>
|
|
42
|
+
<a href="https://pypi.org/project/swarmauri_keyprovider_file/">
|
|
43
|
+
<img src="https://img.shields.io/pypi/l/swarmauri_keyprovider_file" alt="PyPI - License"/></a>
|
|
44
|
+
<a href="https://pypi.org/project/swarmauri_keyprovider_file/">
|
|
45
|
+
<img src="https://img.shields.io/pypi/v/swarmauri_keyprovider_file?label=swarmauri_keyprovider_file&color=green" alt="PyPI - swarmauri_keyprovider_file"/></a>
|
|
46
|
+
</p>
|
|
47
|
+
|
|
48
|
+
---
|
|
49
|
+
|
|
50
|
+
# Swarmauri File Key Provider
|
|
51
|
+
|
|
52
|
+
`FileKeyProvider` is a file-backed implementation of the `KeyProviderBase`
|
|
53
|
+
interface. It persists each key beneath a `keys/<kid>/v<version>/` directory,
|
|
54
|
+
captures metadata in `meta.json`, and exports public material in PEM or JWK
|
|
55
|
+
form. The provider supports the same lifecycle semantics as the in-memory
|
|
56
|
+
providers, but every operation is durable on disk.
|
|
57
|
+
|
|
58
|
+
## Highlights
|
|
59
|
+
|
|
60
|
+
- Generate symmetric AES-256-GCM keys and asymmetric Ed25519, X25519, RSA
|
|
61
|
+
(OAEP/PSS), or ECDSA (P-256) key material.
|
|
62
|
+
- Import existing keys while preserving private material when allowed by the
|
|
63
|
+
selected `ExportPolicy`.
|
|
64
|
+
- Rotate versions in-place, destroy versions or entire keys, and list
|
|
65
|
+
historical versions stored on disk.
|
|
66
|
+
- Publish public material as individual JWKs or aggregate JWKS documents and
|
|
67
|
+
expose HKDF and random byte helpers.
|
|
68
|
+
|
|
69
|
+
## Installation
|
|
70
|
+
|
|
71
|
+
Choose the tool that matches your workflow:
|
|
72
|
+
|
|
73
|
+
```bash
|
|
74
|
+
# pip
|
|
75
|
+
pip install swarmauri_keyprovider_file
|
|
76
|
+
|
|
77
|
+
# Poetry
|
|
78
|
+
poetry add swarmauri_keyprovider_file
|
|
79
|
+
|
|
80
|
+
# uv
|
|
81
|
+
uv add swarmauri_keyprovider_file
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
## Usage
|
|
85
|
+
|
|
86
|
+
```python
|
|
87
|
+
import asyncio
|
|
88
|
+
from tempfile import TemporaryDirectory
|
|
89
|
+
|
|
90
|
+
from swarmauri_keyprovider_file import FileKeyProvider
|
|
91
|
+
from swarmauri_core.key_providers.types import (
|
|
92
|
+
ExportPolicy,
|
|
93
|
+
KeyAlg,
|
|
94
|
+
KeyClass,
|
|
95
|
+
KeySpec,
|
|
96
|
+
)
|
|
97
|
+
from swarmauri_core.crypto.types import KeyUse
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
async def run_example() -> str:
|
|
101
|
+
with TemporaryDirectory() as tmp:
|
|
102
|
+
provider = FileKeyProvider(tmp)
|
|
103
|
+
spec = KeySpec(
|
|
104
|
+
klass=KeyClass.symmetric,
|
|
105
|
+
alg=KeyAlg.AES256_GCM,
|
|
106
|
+
uses=(KeyUse.ENCRYPT,),
|
|
107
|
+
export_policy=ExportPolicy.SECRET_WHEN_ALLOWED,
|
|
108
|
+
)
|
|
109
|
+
created = await provider.create_key(spec)
|
|
110
|
+
provider2 = FileKeyProvider(tmp)
|
|
111
|
+
loaded = await provider2.get_key(created.kid, include_secret=True)
|
|
112
|
+
print(f"Loaded key: {loaded.kid}")
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
asyncio.run(run_example())
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
`FileKeyProvider` is asynchronous—every lifecycle method returns a
|
|
119
|
+
`KeyRef`. Use `include_secret=True` when retrieving keys that allow private
|
|
120
|
+
material export so symmetric key bytes are loaded from disk.
|
|
121
|
+
|
|
122
|
+
## Entry Point
|
|
123
|
+
|
|
124
|
+
The provider registers under the `swarmauri.key_providers` entry point as `FileKeyProvider`.
|
|
125
|
+
|
|
126
|
+
## Want to help?
|
|
127
|
+
|
|
128
|
+
If you want to contribute to swarmauri-sdk, read up on our
|
|
129
|
+
[guidelines for contributing](https://github.com/swarmauri/swarmauri-sdk/blob/master/CONTRIBUTING.md)
|
|
130
|
+
that will help you get started.
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+

|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
<p align="center">
|
|
5
|
+
<a href="https://pypi.org/project/swarmauri_keyprovider_file/">
|
|
6
|
+
<img src="https://img.shields.io/pypi/dm/swarmauri_keyprovider_file" alt="PyPI - Downloads"/></a>
|
|
7
|
+
<a href="https://hits.sh/github.com/swarmauri/swarmauri-sdk/tree/master/pkgs/standards/swarmauri_keyprovider_file/">
|
|
8
|
+
<img alt="Hits" src="https://hits.sh/github.com/swarmauri/swarmauri-sdk/tree/master/pkgs/standards/swarmauri_keyprovider_file.svg"/></a>
|
|
9
|
+
<a href="https://pypi.org/project/swarmauri_keyprovider_file/">
|
|
10
|
+
<img src="https://img.shields.io/pypi/pyversions/swarmauri_keyprovider_file" alt="PyPI - Python Version"/></a>
|
|
11
|
+
<a href="https://pypi.org/project/swarmauri_keyprovider_file/">
|
|
12
|
+
<img src="https://img.shields.io/pypi/l/swarmauri_keyprovider_file" alt="PyPI - License"/></a>
|
|
13
|
+
<a href="https://pypi.org/project/swarmauri_keyprovider_file/">
|
|
14
|
+
<img src="https://img.shields.io/pypi/v/swarmauri_keyprovider_file?label=swarmauri_keyprovider_file&color=green" alt="PyPI - swarmauri_keyprovider_file"/></a>
|
|
15
|
+
</p>
|
|
16
|
+
|
|
17
|
+
---
|
|
18
|
+
|
|
19
|
+
# Swarmauri File Key Provider
|
|
20
|
+
|
|
21
|
+
`FileKeyProvider` is a file-backed implementation of the `KeyProviderBase`
|
|
22
|
+
interface. It persists each key beneath a `keys/<kid>/v<version>/` directory,
|
|
23
|
+
captures metadata in `meta.json`, and exports public material in PEM or JWK
|
|
24
|
+
form. The provider supports the same lifecycle semantics as the in-memory
|
|
25
|
+
providers, but every operation is durable on disk.
|
|
26
|
+
|
|
27
|
+
## Highlights
|
|
28
|
+
|
|
29
|
+
- Generate symmetric AES-256-GCM keys and asymmetric Ed25519, X25519, RSA
|
|
30
|
+
(OAEP/PSS), or ECDSA (P-256) key material.
|
|
31
|
+
- Import existing keys while preserving private material when allowed by the
|
|
32
|
+
selected `ExportPolicy`.
|
|
33
|
+
- Rotate versions in-place, destroy versions or entire keys, and list
|
|
34
|
+
historical versions stored on disk.
|
|
35
|
+
- Publish public material as individual JWKs or aggregate JWKS documents and
|
|
36
|
+
expose HKDF and random byte helpers.
|
|
37
|
+
|
|
38
|
+
## Installation
|
|
39
|
+
|
|
40
|
+
Choose the tool that matches your workflow:
|
|
41
|
+
|
|
42
|
+
```bash
|
|
43
|
+
# pip
|
|
44
|
+
pip install swarmauri_keyprovider_file
|
|
45
|
+
|
|
46
|
+
# Poetry
|
|
47
|
+
poetry add swarmauri_keyprovider_file
|
|
48
|
+
|
|
49
|
+
# uv
|
|
50
|
+
uv add swarmauri_keyprovider_file
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
## Usage
|
|
54
|
+
|
|
55
|
+
```python
|
|
56
|
+
import asyncio
|
|
57
|
+
from tempfile import TemporaryDirectory
|
|
58
|
+
|
|
59
|
+
from swarmauri_keyprovider_file import FileKeyProvider
|
|
60
|
+
from swarmauri_core.key_providers.types import (
|
|
61
|
+
ExportPolicy,
|
|
62
|
+
KeyAlg,
|
|
63
|
+
KeyClass,
|
|
64
|
+
KeySpec,
|
|
65
|
+
)
|
|
66
|
+
from swarmauri_core.crypto.types import KeyUse
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
async def run_example() -> str:
|
|
70
|
+
with TemporaryDirectory() as tmp:
|
|
71
|
+
provider = FileKeyProvider(tmp)
|
|
72
|
+
spec = KeySpec(
|
|
73
|
+
klass=KeyClass.symmetric,
|
|
74
|
+
alg=KeyAlg.AES256_GCM,
|
|
75
|
+
uses=(KeyUse.ENCRYPT,),
|
|
76
|
+
export_policy=ExportPolicy.SECRET_WHEN_ALLOWED,
|
|
77
|
+
)
|
|
78
|
+
created = await provider.create_key(spec)
|
|
79
|
+
provider2 = FileKeyProvider(tmp)
|
|
80
|
+
loaded = await provider2.get_key(created.kid, include_secret=True)
|
|
81
|
+
print(f"Loaded key: {loaded.kid}")
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
asyncio.run(run_example())
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
`FileKeyProvider` is asynchronous—every lifecycle method returns a
|
|
88
|
+
`KeyRef`. Use `include_secret=True` when retrieving keys that allow private
|
|
89
|
+
material export so symmetric key bytes are loaded from disk.
|
|
90
|
+
|
|
91
|
+
## Entry Point
|
|
92
|
+
|
|
93
|
+
The provider registers under the `swarmauri.key_providers` entry point as `FileKeyProvider`.
|
|
94
|
+
|
|
95
|
+
## Want to help?
|
|
96
|
+
|
|
97
|
+
If you want to contribute to swarmauri-sdk, read up on our
|
|
98
|
+
[guidelines for contributing](https://github.com/swarmauri/swarmauri-sdk/blob/master/CONTRIBUTING.md)
|
|
99
|
+
that will help you get started.
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "swarmauri_keyprovider_file"
|
|
3
|
+
version = "0.2.0"
|
|
4
|
+
description = "File-backed key provider for Swarmauri"
|
|
5
|
+
license = "Apache-2.0"
|
|
6
|
+
readme = "README.md"
|
|
7
|
+
requires-python = ">=3.10,<3.13"
|
|
8
|
+
authors = [{ name = "Jacob Stewart", email = "jacob@swarmauri.com" }]
|
|
9
|
+
classifiers = [
|
|
10
|
+
"License :: OSI Approved :: Apache Software License",
|
|
11
|
+
"Natural Language :: English",
|
|
12
|
+
"Programming Language :: Python :: 3.10",
|
|
13
|
+
"Programming Language :: Python :: 3.11",
|
|
14
|
+
"Programming Language :: Python :: 3.12",
|
|
15
|
+
"Programming Language :: Python :: 3.13",
|
|
16
|
+
"Development Status :: 3 - Alpha",
|
|
17
|
+
"Topic :: Security :: Cryptography",
|
|
18
|
+
"Intended Audience :: Developers",
|
|
19
|
+
"Programming Language :: Python",
|
|
20
|
+
"Programming Language :: Python :: 3",
|
|
21
|
+
"Programming Language :: Python :: 3 :: Only",
|
|
22
|
+
]
|
|
23
|
+
dependencies = [
|
|
24
|
+
"swarmauri_core",
|
|
25
|
+
"swarmauri_base",
|
|
26
|
+
"cryptography",
|
|
27
|
+
]
|
|
28
|
+
keywords = [
|
|
29
|
+
'swarmauri',
|
|
30
|
+
'sdk',
|
|
31
|
+
'standards',
|
|
32
|
+
'keyprovider',
|
|
33
|
+
'file',
|
|
34
|
+
'key-management',
|
|
35
|
+
]
|
|
36
|
+
|
|
37
|
+
[project.optional-dependencies]
|
|
38
|
+
cbor = ["cbor2"]
|
|
39
|
+
jwks = ["jwcrypto"]
|
|
40
|
+
|
|
41
|
+
[tool.uv.sources]
|
|
42
|
+
swarmauri_core = { workspace = true }
|
|
43
|
+
swarmauri_base = { workspace = true }
|
|
44
|
+
|
|
45
|
+
[tool.pytest.ini_options]
|
|
46
|
+
norecursedirs = ["combined", "scripts"]
|
|
47
|
+
markers = [
|
|
48
|
+
"test: standard test",
|
|
49
|
+
"unit: Unit tests",
|
|
50
|
+
"i9n: Integration tests",
|
|
51
|
+
"r8n: Regression tests",
|
|
52
|
+
"acceptance: Acceptance tests",
|
|
53
|
+
"perf: Performance tests",
|
|
54
|
+
"example: Documentation-backed examples",
|
|
55
|
+
]
|
|
56
|
+
timeout = 300
|
|
57
|
+
log_cli = true
|
|
58
|
+
log_cli_level = "INFO"
|
|
59
|
+
log_cli_format = "%(asctime)s [%(levelname)s] %(message)s"
|
|
60
|
+
log_cli_date_format = "%Y-%m-%d %H:%M:%S"
|
|
61
|
+
asyncio_default_fixture_loop_scope = "function"
|
|
62
|
+
|
|
63
|
+
[dependency-groups]
|
|
64
|
+
dev = [
|
|
65
|
+
"pytest>=8.0",
|
|
66
|
+
"pytest-asyncio>=0.24.0",
|
|
67
|
+
"pytest-xdist>=3.6.1",
|
|
68
|
+
"pytest-json-report>=1.5.0",
|
|
69
|
+
"pytest-timeout>=2.3.1",
|
|
70
|
+
"pytest-benchmark>=4.0.0",
|
|
71
|
+
"ruff>=0.9.9",
|
|
72
|
+
]
|
|
73
|
+
|
|
74
|
+
[build-system]
|
|
75
|
+
requires = ["poetry-core>=1.0.0"]
|
|
76
|
+
build-backend = "poetry.core.masonry.api"
|
|
77
|
+
|
|
78
|
+
[project.entry-points.'swarmauri.key_providers']
|
|
79
|
+
FileKeyProvider = "swarmauri_keyprovider_file.FileKeyProvider:FileKeyProvider"
|
|
80
|
+
|
|
81
|
+
[project.entry-points."peagen.plugins.key_providers"]
|
|
82
|
+
file = "swarmauri_keyprovider_file.FileKeyProvider:FileKeyProvider"
|
|
@@ -0,0 +1,573 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import base64
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
import secrets
|
|
7
|
+
import shutil
|
|
8
|
+
import threading
|
|
9
|
+
import time
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import Dict, Iterable, Mapping, Optional, Tuple, Literal
|
|
12
|
+
|
|
13
|
+
from cryptography.hazmat.primitives import hashes, serialization
|
|
14
|
+
from cryptography.hazmat.primitives.asymmetric import ed25519, rsa, ec, x25519
|
|
15
|
+
from cryptography.hazmat.primitives.kdf.hkdf import HKDF
|
|
16
|
+
|
|
17
|
+
from swarmauri_base.key_providers.KeyProviderBase import KeyProviderBase
|
|
18
|
+
from swarmauri_core.key_providers.types import (
|
|
19
|
+
KeySpec,
|
|
20
|
+
KeyAlg,
|
|
21
|
+
KeyClass,
|
|
22
|
+
ExportPolicy,
|
|
23
|
+
KeyUse,
|
|
24
|
+
)
|
|
25
|
+
from swarmauri_core.crypto.types import KeyRef
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _b64u(b: bytes) -> str:
|
|
29
|
+
return base64.urlsafe_b64encode(b).rstrip(b"=").decode("ascii")
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _hash_hex(b: bytes, nbytes: int = 16) -> str:
|
|
33
|
+
h = hashes.Hash(hashes.SHA256())
|
|
34
|
+
h.update(b)
|
|
35
|
+
return h.finalize().hex()[: 2 * nbytes]
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _serialize_keypair(priv, spec: KeySpec) -> tuple[bytes, Optional[bytes]]:
|
|
39
|
+
"""Serialize private and public key material according to ``spec``."""
|
|
40
|
+
|
|
41
|
+
encoding = (
|
|
42
|
+
serialization.Encoding[spec.encoding]
|
|
43
|
+
if spec.encoding
|
|
44
|
+
else serialization.Encoding.PEM
|
|
45
|
+
)
|
|
46
|
+
public_format = (
|
|
47
|
+
serialization.PublicFormat[spec.public_format]
|
|
48
|
+
if spec.public_format
|
|
49
|
+
else serialization.PublicFormat.SubjectPublicKeyInfo
|
|
50
|
+
)
|
|
51
|
+
public = priv.public_key().public_bytes(encoding=encoding, format=public_format)
|
|
52
|
+
|
|
53
|
+
material: Optional[bytes] = None
|
|
54
|
+
if spec.export_policy != ExportPolicy.PUBLIC_ONLY:
|
|
55
|
+
private_format = (
|
|
56
|
+
serialization.PrivateFormat[spec.private_format]
|
|
57
|
+
if spec.private_format
|
|
58
|
+
else serialization.PrivateFormat.PKCS8
|
|
59
|
+
)
|
|
60
|
+
if spec.encryption and spec.encryption != "NoEncryption":
|
|
61
|
+
raise ValueError(f"Unsupported encryption: {spec.encryption}")
|
|
62
|
+
material = priv.private_bytes(
|
|
63
|
+
encoding,
|
|
64
|
+
private_format,
|
|
65
|
+
serialization.NoEncryption(),
|
|
66
|
+
)
|
|
67
|
+
|
|
68
|
+
return public, material
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _ensure_dir(p: Path) -> None:
|
|
72
|
+
p.mkdir(parents=True, exist_ok=True)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _now() -> int:
|
|
76
|
+
return int(time.time())
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
class FileKeyProvider(KeyProviderBase):
|
|
80
|
+
"""File-backed key provider."""
|
|
81
|
+
|
|
82
|
+
type: Literal["FileKeyProvider"] = "FileKeyProvider"
|
|
83
|
+
|
|
84
|
+
def __init__(self, root_dir: str | Path) -> None:
|
|
85
|
+
super().__init__()
|
|
86
|
+
self.root = Path(root_dir)
|
|
87
|
+
_ensure_dir(self.root)
|
|
88
|
+
_ensure_dir(self.root / "keys")
|
|
89
|
+
object.__setattr__(self, "_lock", threading.RLock())
|
|
90
|
+
|
|
91
|
+
def supports(self) -> Mapping[str, Iterable[str]]:
|
|
92
|
+
return {
|
|
93
|
+
"class": ("sym", "asym"),
|
|
94
|
+
"algs": (
|
|
95
|
+
KeyAlg.AES256_GCM,
|
|
96
|
+
KeyAlg.ED25519,
|
|
97
|
+
KeyAlg.X25519,
|
|
98
|
+
KeyAlg.RSA_OAEP_SHA256,
|
|
99
|
+
KeyAlg.RSA_PSS_SHA256,
|
|
100
|
+
KeyAlg.ECDSA_P256_SHA256,
|
|
101
|
+
),
|
|
102
|
+
"features": (
|
|
103
|
+
"create",
|
|
104
|
+
"rotate",
|
|
105
|
+
"import",
|
|
106
|
+
"jwks",
|
|
107
|
+
"hkdf",
|
|
108
|
+
"random",
|
|
109
|
+
"persist",
|
|
110
|
+
),
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
def _key_dir(self, kid: str) -> Path:
|
|
114
|
+
return self.root / "keys" / kid
|
|
115
|
+
|
|
116
|
+
def _ver_dir(self, kid: str, version: int) -> Path:
|
|
117
|
+
return self._key_dir(kid) / f"v{version}"
|
|
118
|
+
|
|
119
|
+
def _meta_path(self, kid: str) -> Path:
|
|
120
|
+
return self._key_dir(kid) / "meta.json"
|
|
121
|
+
|
|
122
|
+
def _write_meta(
|
|
123
|
+
self,
|
|
124
|
+
kid: str,
|
|
125
|
+
*,
|
|
126
|
+
klass: KeyClass,
|
|
127
|
+
alg: KeyAlg,
|
|
128
|
+
uses: Tuple[KeyUse, ...],
|
|
129
|
+
export_policy: ExportPolicy,
|
|
130
|
+
label: Optional[str],
|
|
131
|
+
tags: Optional[Dict[str, object]],
|
|
132
|
+
) -> None:
|
|
133
|
+
p = self._meta_path(kid)
|
|
134
|
+
meta = {
|
|
135
|
+
"kid": kid,
|
|
136
|
+
"klass": klass.value,
|
|
137
|
+
"alg": alg.value,
|
|
138
|
+
"uses": [u.value for u in uses],
|
|
139
|
+
"export_policy": export_policy.value,
|
|
140
|
+
"label": label,
|
|
141
|
+
"tags": tags or {},
|
|
142
|
+
"created_at": _now(),
|
|
143
|
+
}
|
|
144
|
+
_ensure_dir(p.parent)
|
|
145
|
+
p.write_text(json.dumps(meta, indent=2))
|
|
146
|
+
|
|
147
|
+
def _read_meta(self, kid: str) -> dict:
|
|
148
|
+
p = self._meta_path(kid)
|
|
149
|
+
if not p.exists():
|
|
150
|
+
raise KeyError(f"unknown kid: {kid}")
|
|
151
|
+
return json.loads(p.read_text())
|
|
152
|
+
|
|
153
|
+
def _latest_version(self, kid: str) -> int:
|
|
154
|
+
kd = self._key_dir(kid)
|
|
155
|
+
if not kd.exists():
|
|
156
|
+
raise KeyError(f"unknown kid: {kid}")
|
|
157
|
+
max_v = 0
|
|
158
|
+
for entry in kd.iterdir():
|
|
159
|
+
if entry.is_dir() and entry.name.startswith("v"):
|
|
160
|
+
try:
|
|
161
|
+
v = int(entry.name[1:])
|
|
162
|
+
if v > max_v:
|
|
163
|
+
max_v = v
|
|
164
|
+
except Exception:
|
|
165
|
+
continue
|
|
166
|
+
if max_v == 0:
|
|
167
|
+
raise KeyError(f"no versions for kid: {kid}")
|
|
168
|
+
return max_v
|
|
169
|
+
|
|
170
|
+
async def create_key(self, spec: KeySpec) -> KeyRef:
|
|
171
|
+
with self._lock:
|
|
172
|
+
kid = _hash_hex(os.urandom(16))
|
|
173
|
+
version = 1
|
|
174
|
+
vdir = self._ver_dir(kid, version)
|
|
175
|
+
_ensure_dir(vdir)
|
|
176
|
+
|
|
177
|
+
public: Optional[bytes] = None
|
|
178
|
+
material: Optional[bytes] = None
|
|
179
|
+
|
|
180
|
+
if spec.klass == KeyClass.symmetric:
|
|
181
|
+
if spec.alg != KeyAlg.AES256_GCM:
|
|
182
|
+
raise ValueError(f"Unsupported symmetric alg: {spec.alg}")
|
|
183
|
+
raw = secrets.token_bytes(32)
|
|
184
|
+
if spec.export_policy != ExportPolicy.PUBLIC_ONLY:
|
|
185
|
+
material = raw
|
|
186
|
+
(vdir / "private.pem").write_text(
|
|
187
|
+
json.dumps({"kty": "oct", "k": _b64u(raw)})
|
|
188
|
+
)
|
|
189
|
+
(vdir / "public.jwk").write_text(
|
|
190
|
+
json.dumps({"kty": "oct", "alg": "A256GCM"})
|
|
191
|
+
)
|
|
192
|
+
else:
|
|
193
|
+
if spec.alg == KeyAlg.ED25519:
|
|
194
|
+
sk = ed25519.Ed25519PrivateKey.generate()
|
|
195
|
+
elif spec.alg == KeyAlg.X25519:
|
|
196
|
+
sk = x25519.X25519PrivateKey.generate()
|
|
197
|
+
elif spec.alg in (KeyAlg.RSA_OAEP_SHA256, KeyAlg.RSA_PSS_SHA256):
|
|
198
|
+
bits = spec.size_bits or 3072
|
|
199
|
+
sk = rsa.generate_private_key(public_exponent=65537, key_size=bits)
|
|
200
|
+
elif spec.alg == KeyAlg.ECDSA_P256_SHA256:
|
|
201
|
+
sk = ec.generate_private_key(ec.SECP256R1())
|
|
202
|
+
else:
|
|
203
|
+
raise ValueError(f"Unsupported asymmetric alg: {spec.alg}")
|
|
204
|
+
|
|
205
|
+
public, material = _serialize_keypair(sk, spec)
|
|
206
|
+
(vdir / "public.pem").write_bytes(public)
|
|
207
|
+
if material is not None:
|
|
208
|
+
(vdir / "private.pem").write_bytes(material)
|
|
209
|
+
|
|
210
|
+
self._write_meta(
|
|
211
|
+
kid,
|
|
212
|
+
klass=spec.klass,
|
|
213
|
+
alg=spec.alg,
|
|
214
|
+
uses=spec.uses,
|
|
215
|
+
export_policy=spec.export_policy,
|
|
216
|
+
label=spec.label,
|
|
217
|
+
tags=spec.tags,
|
|
218
|
+
)
|
|
219
|
+
|
|
220
|
+
return KeyRef(
|
|
221
|
+
kid=kid,
|
|
222
|
+
version=version,
|
|
223
|
+
type="OPAQUE",
|
|
224
|
+
uses=spec.uses,
|
|
225
|
+
export_policy=spec.export_policy,
|
|
226
|
+
public=public,
|
|
227
|
+
material=material,
|
|
228
|
+
tags={"label": spec.label, "alg": spec.alg.value, **(spec.tags or {})},
|
|
229
|
+
fingerprint=self._fingerprint(
|
|
230
|
+
public=public, material=material, kid=kid
|
|
231
|
+
),
|
|
232
|
+
)
|
|
233
|
+
|
|
234
|
+
async def import_key(
|
|
235
|
+
self, spec: KeySpec, material: bytes, *, public: Optional[bytes] = None
|
|
236
|
+
) -> KeyRef:
|
|
237
|
+
with self._lock:
|
|
238
|
+
kid = _hash_hex(material if material else os.urandom(16))
|
|
239
|
+
version = 1
|
|
240
|
+
vdir = self._ver_dir(kid, version)
|
|
241
|
+
_ensure_dir(vdir)
|
|
242
|
+
|
|
243
|
+
if spec.klass == KeyClass.symmetric:
|
|
244
|
+
if spec.export_policy == ExportPolicy.PUBLIC_ONLY:
|
|
245
|
+
(vdir / "private.pem").write_text(
|
|
246
|
+
json.dumps({"kty": "oct", "k": None})
|
|
247
|
+
)
|
|
248
|
+
mat_out = None
|
|
249
|
+
else:
|
|
250
|
+
(vdir / "private.pem").write_text(
|
|
251
|
+
json.dumps({"kty": "oct", "k": _b64u(material)})
|
|
252
|
+
)
|
|
253
|
+
mat_out = material
|
|
254
|
+
(vdir / "public.jwk").write_text(
|
|
255
|
+
json.dumps({"kty": "oct", "alg": "A256GCM"})
|
|
256
|
+
)
|
|
257
|
+
pub_out = None
|
|
258
|
+
else:
|
|
259
|
+
if public:
|
|
260
|
+
(vdir / "public.pem").write_bytes(public)
|
|
261
|
+
pub_out = public
|
|
262
|
+
else:
|
|
263
|
+
try:
|
|
264
|
+
sk = serialization.load_pem_private_key(material, password=None)
|
|
265
|
+
pub_out = sk.public_key().public_bytes(
|
|
266
|
+
serialization.Encoding.PEM,
|
|
267
|
+
serialization.PublicFormat.SubjectPublicKeyInfo,
|
|
268
|
+
)
|
|
269
|
+
(vdir / "public.pem").write_bytes(pub_out)
|
|
270
|
+
except Exception:
|
|
271
|
+
pub_out = None
|
|
272
|
+
if spec.export_policy != ExportPolicy.PUBLIC_ONLY:
|
|
273
|
+
(vdir / "private.pem").write_bytes(material)
|
|
274
|
+
mat_out = material
|
|
275
|
+
else:
|
|
276
|
+
mat_out = None
|
|
277
|
+
|
|
278
|
+
self._write_meta(
|
|
279
|
+
kid,
|
|
280
|
+
klass=spec.klass,
|
|
281
|
+
alg=spec.alg,
|
|
282
|
+
uses=spec.uses,
|
|
283
|
+
export_policy=spec.export_policy,
|
|
284
|
+
label=spec.label,
|
|
285
|
+
tags=spec.tags,
|
|
286
|
+
)
|
|
287
|
+
|
|
288
|
+
return KeyRef(
|
|
289
|
+
kid=kid,
|
|
290
|
+
version=version,
|
|
291
|
+
type="OPAQUE",
|
|
292
|
+
uses=spec.uses,
|
|
293
|
+
export_policy=spec.export_policy,
|
|
294
|
+
public=pub_out,
|
|
295
|
+
material=mat_out,
|
|
296
|
+
tags={
|
|
297
|
+
"label": spec.label,
|
|
298
|
+
"alg": spec.alg.value,
|
|
299
|
+
"imported": True,
|
|
300
|
+
**(spec.tags or {}),
|
|
301
|
+
},
|
|
302
|
+
fingerprint=self._fingerprint(
|
|
303
|
+
public=pub_out, material=mat_out, kid=kid
|
|
304
|
+
),
|
|
305
|
+
)
|
|
306
|
+
|
|
307
|
+
async def rotate_key(
|
|
308
|
+
self, kid: str, *, spec_overrides: Optional[dict] = None
|
|
309
|
+
) -> KeyRef:
|
|
310
|
+
with self._lock:
|
|
311
|
+
meta = self._read_meta(kid)
|
|
312
|
+
latest = self._latest_version(kid)
|
|
313
|
+
next_v = latest + 1
|
|
314
|
+
klass = KeyClass(meta["klass"])
|
|
315
|
+
alg = KeyAlg(meta["alg"])
|
|
316
|
+
uses = tuple(KeyUse(u) for u in meta["uses"])
|
|
317
|
+
export_policy = ExportPolicy(meta["export_policy"])
|
|
318
|
+
label = meta.get("label")
|
|
319
|
+
tags = meta.get("tags") or {}
|
|
320
|
+
|
|
321
|
+
vdir = self._ver_dir(kid, next_v)
|
|
322
|
+
_ensure_dir(vdir)
|
|
323
|
+
|
|
324
|
+
ov = spec_overrides or {}
|
|
325
|
+
material: Optional[bytes] = None
|
|
326
|
+
public: Optional[bytes] = None
|
|
327
|
+
|
|
328
|
+
if klass == KeyClass.symmetric:
|
|
329
|
+
raw = secrets.token_bytes(32)
|
|
330
|
+
if export_policy != ExportPolicy.PUBLIC_ONLY:
|
|
331
|
+
material = raw
|
|
332
|
+
(vdir / "private.pem").write_text(
|
|
333
|
+
json.dumps({"kty": "oct", "k": _b64u(raw)})
|
|
334
|
+
)
|
|
335
|
+
(vdir / "public.jwk").write_text(
|
|
336
|
+
json.dumps({"kty": "oct", "alg": "A256GCM"})
|
|
337
|
+
)
|
|
338
|
+
else:
|
|
339
|
+
if alg == KeyAlg.ED25519:
|
|
340
|
+
sk = ed25519.Ed25519PrivateKey.generate()
|
|
341
|
+
elif alg == KeyAlg.X25519:
|
|
342
|
+
sk = x25519.X25519PrivateKey.generate()
|
|
343
|
+
elif alg in (KeyAlg.RSA_OAEP_SHA256, KeyAlg.RSA_PSS_SHA256):
|
|
344
|
+
bits = int(ov.get("size_bits") or 3072)
|
|
345
|
+
sk = rsa.generate_private_key(public_exponent=65537, key_size=bits)
|
|
346
|
+
elif alg == KeyAlg.ECDSA_P256_SHA256:
|
|
347
|
+
sk = ec.generate_private_key(ec.SECP256R1())
|
|
348
|
+
else:
|
|
349
|
+
raise ValueError(f"Unsupported alg during rotate: {alg}")
|
|
350
|
+
|
|
351
|
+
tmp_spec = KeySpec(
|
|
352
|
+
klass=klass,
|
|
353
|
+
alg=alg,
|
|
354
|
+
uses=uses,
|
|
355
|
+
export_policy=export_policy,
|
|
356
|
+
)
|
|
357
|
+
public, material = _serialize_keypair(sk, tmp_spec)
|
|
358
|
+
(vdir / "public.pem").write_bytes(public)
|
|
359
|
+
if material is not None:
|
|
360
|
+
(vdir / "private.pem").write_bytes(material)
|
|
361
|
+
|
|
362
|
+
if ov:
|
|
363
|
+
new_meta = dict(meta)
|
|
364
|
+
if "label" in ov:
|
|
365
|
+
new_meta["label"] = ov["label"]
|
|
366
|
+
label = ov["label"]
|
|
367
|
+
if "tags" in ov and isinstance(ov["tags"], dict):
|
|
368
|
+
tags.update(ov["tags"])
|
|
369
|
+
new_meta["tags"] = tags
|
|
370
|
+
self._meta_path(kid).write_text(json.dumps(new_meta, indent=2))
|
|
371
|
+
|
|
372
|
+
return KeyRef(
|
|
373
|
+
kid=kid,
|
|
374
|
+
version=next_v,
|
|
375
|
+
type="OPAQUE",
|
|
376
|
+
uses=uses,
|
|
377
|
+
export_policy=export_policy,
|
|
378
|
+
public=public,
|
|
379
|
+
material=material,
|
|
380
|
+
tags={"label": label, "alg": alg.value, **tags},
|
|
381
|
+
fingerprint=self._fingerprint(
|
|
382
|
+
public=public, material=material, kid=kid
|
|
383
|
+
),
|
|
384
|
+
)
|
|
385
|
+
|
|
386
|
+
async def destroy_key(self, kid: str, version: Optional[int] = None) -> bool:
|
|
387
|
+
with self._lock:
|
|
388
|
+
kdir = self._key_dir(kid)
|
|
389
|
+
if not kdir.exists():
|
|
390
|
+
return False
|
|
391
|
+
if version is None:
|
|
392
|
+
shutil.rmtree(kdir, ignore_errors=True)
|
|
393
|
+
return True
|
|
394
|
+
vdir = self._ver_dir(kid, version)
|
|
395
|
+
if vdir.exists():
|
|
396
|
+
shutil.rmtree(vdir, ignore_errors=True)
|
|
397
|
+
try:
|
|
398
|
+
_ = self._latest_version(kid)
|
|
399
|
+
except Exception:
|
|
400
|
+
if self._meta_path(kid).exists():
|
|
401
|
+
self._meta_path(kid).unlink(missing_ok=True)
|
|
402
|
+
if kdir.exists():
|
|
403
|
+
try:
|
|
404
|
+
kdir.rmdir()
|
|
405
|
+
except Exception:
|
|
406
|
+
pass
|
|
407
|
+
return True
|
|
408
|
+
|
|
409
|
+
async def get_key(
|
|
410
|
+
self, kid: str, version: Optional[int] = None, *, include_secret: bool = False
|
|
411
|
+
) -> KeyRef:
|
|
412
|
+
with self._lock:
|
|
413
|
+
meta = self._read_meta(kid)
|
|
414
|
+
v = version or self._latest_version(kid)
|
|
415
|
+
vdir = self._ver_dir(kid, v)
|
|
416
|
+
if not vdir.exists():
|
|
417
|
+
raise KeyError(f"unknown version: {kid}.v{v}")
|
|
418
|
+
|
|
419
|
+
export_policy = ExportPolicy(meta["export_policy"])
|
|
420
|
+
alg = KeyAlg(meta["alg"])
|
|
421
|
+
uses = tuple(KeyUse(u) for u in meta["uses"])
|
|
422
|
+
|
|
423
|
+
public: Optional[bytes] = None
|
|
424
|
+
material: Optional[bytes] = None
|
|
425
|
+
|
|
426
|
+
pem_pub = vdir / "public.pem"
|
|
427
|
+
if pem_pub.exists():
|
|
428
|
+
public = pem_pub.read_bytes()
|
|
429
|
+
else:
|
|
430
|
+
jwk_pub = vdir / "public.jwk"
|
|
431
|
+
if jwk_pub.exists():
|
|
432
|
+
public = jwk_pub.read_bytes()
|
|
433
|
+
|
|
434
|
+
if include_secret and export_policy != ExportPolicy.PUBLIC_ONLY:
|
|
435
|
+
pem_priv = vdir / "private.pem"
|
|
436
|
+
if pem_priv.exists():
|
|
437
|
+
try:
|
|
438
|
+
obj = json.loads(pem_priv.read_text())
|
|
439
|
+
if obj.get("kty") == "oct" and obj.get("k"):
|
|
440
|
+
material = base64.urlsafe_b64decode(obj["k"] + "==")
|
|
441
|
+
else:
|
|
442
|
+
material = pem_priv.read_bytes()
|
|
443
|
+
except json.JSONDecodeError:
|
|
444
|
+
material = pem_priv.read_bytes()
|
|
445
|
+
|
|
446
|
+
return KeyRef(
|
|
447
|
+
kid=kid,
|
|
448
|
+
version=v,
|
|
449
|
+
type="OPAQUE",
|
|
450
|
+
uses=uses,
|
|
451
|
+
export_policy=export_policy,
|
|
452
|
+
public=public,
|
|
453
|
+
material=material,
|
|
454
|
+
tags={
|
|
455
|
+
"label": meta.get("label"),
|
|
456
|
+
"alg": alg.value,
|
|
457
|
+
**(meta.get("tags") or {}),
|
|
458
|
+
},
|
|
459
|
+
fingerprint=self._fingerprint(
|
|
460
|
+
public=public, material=material, kid=kid
|
|
461
|
+
),
|
|
462
|
+
)
|
|
463
|
+
|
|
464
|
+
async def list_versions(self, kid: str) -> Tuple[int, ...]:
|
|
465
|
+
with self._lock:
|
|
466
|
+
kd = self._key_dir(kid)
|
|
467
|
+
if not kd.exists():
|
|
468
|
+
raise KeyError(f"unknown kid: {kid}")
|
|
469
|
+
vs: list[int] = []
|
|
470
|
+
for entry in kd.iterdir():
|
|
471
|
+
if entry.is_dir() and entry.name.startswith("v"):
|
|
472
|
+
try:
|
|
473
|
+
vs.append(int(entry.name[1:]))
|
|
474
|
+
except Exception:
|
|
475
|
+
pass
|
|
476
|
+
if not vs:
|
|
477
|
+
raise KeyError(f"no versions for kid: {kid}")
|
|
478
|
+
vs.sort()
|
|
479
|
+
return tuple(vs)
|
|
480
|
+
|
|
481
|
+
async def get_public_jwk(self, kid: str, version: Optional[int] = None) -> dict:
|
|
482
|
+
ref = await self.get_key(kid, version, include_secret=False)
|
|
483
|
+
alg = KeyAlg(ref.tags["alg"])
|
|
484
|
+
|
|
485
|
+
if alg == KeyAlg.AES256_GCM:
|
|
486
|
+
return {
|
|
487
|
+
"kty": "oct",
|
|
488
|
+
"alg": "A256GCM",
|
|
489
|
+
"kid": f"{ref.kid}.{ref.version}",
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
if ref.public is None:
|
|
493
|
+
vdir = self._ver_dir(ref.kid, ref.version)
|
|
494
|
+
pem_pub = vdir / "public.pem"
|
|
495
|
+
if not pem_pub.exists():
|
|
496
|
+
raise RuntimeError("Public material unavailable for asymmetric key")
|
|
497
|
+
pub_bytes = pem_pub.read_bytes()
|
|
498
|
+
else:
|
|
499
|
+
pub_bytes = ref.public
|
|
500
|
+
|
|
501
|
+
pk = serialization.load_pem_public_key(pub_bytes)
|
|
502
|
+
|
|
503
|
+
if alg == KeyAlg.ED25519:
|
|
504
|
+
raw = pk.public_bytes(
|
|
505
|
+
serialization.Encoding.Raw, serialization.PublicFormat.Raw
|
|
506
|
+
)
|
|
507
|
+
return {
|
|
508
|
+
"kty": "OKP",
|
|
509
|
+
"crv": "Ed25519",
|
|
510
|
+
"x": _b64u(raw),
|
|
511
|
+
"kid": f"{ref.kid}.{ref.version}",
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
if alg == KeyAlg.X25519:
|
|
515
|
+
raw = pk.public_bytes(
|
|
516
|
+
serialization.Encoding.Raw, serialization.PublicFormat.Raw
|
|
517
|
+
)
|
|
518
|
+
return {
|
|
519
|
+
"kty": "OKP",
|
|
520
|
+
"crv": "X25519",
|
|
521
|
+
"x": _b64u(raw),
|
|
522
|
+
"kid": f"{ref.kid}.{ref.version}",
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
if alg in (KeyAlg.RSA_OAEP_SHA256, KeyAlg.RSA_PSS_SHA256):
|
|
526
|
+
nums = pk.public_numbers()
|
|
527
|
+
n = nums.n.to_bytes((nums.n.bit_length() + 7) // 8, "big")
|
|
528
|
+
e = nums.e.to_bytes((nums.e.bit_length() + 7) // 8, "big")
|
|
529
|
+
return {
|
|
530
|
+
"kty": "RSA",
|
|
531
|
+
"n": _b64u(n),
|
|
532
|
+
"e": _b64u(e),
|
|
533
|
+
"kid": f"{ref.kid}.{ref.version}",
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
if alg == KeyAlg.ECDSA_P256_SHA256:
|
|
537
|
+
nums = pk.public_numbers()
|
|
538
|
+
x = nums.x.to_bytes(32, "big")
|
|
539
|
+
y = nums.y.to_bytes(32, "big")
|
|
540
|
+
return {
|
|
541
|
+
"kty": "EC",
|
|
542
|
+
"crv": "P-256",
|
|
543
|
+
"x": _b64u(x),
|
|
544
|
+
"y": _b64u(y),
|
|
545
|
+
"kid": f"{ref.kid}.{ref.version}",
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
raise ValueError(f"Unsupported alg for JWK export: {alg}")
|
|
549
|
+
|
|
550
|
+
async def jwks(self, *, prefix_kids: Optional[str] = None) -> dict:
|
|
551
|
+
with self._lock:
|
|
552
|
+
out = []
|
|
553
|
+
kroot = self.root / "keys"
|
|
554
|
+
for kid_dir in kroot.iterdir():
|
|
555
|
+
if not kid_dir.is_dir():
|
|
556
|
+
continue
|
|
557
|
+
kid = kid_dir.name
|
|
558
|
+
if prefix_kids and not kid.startswith(prefix_kids):
|
|
559
|
+
continue
|
|
560
|
+
try:
|
|
561
|
+
latest = self._latest_version(kid)
|
|
562
|
+
out.append(await self.get_public_jwk(kid, latest))
|
|
563
|
+
except Exception:
|
|
564
|
+
continue
|
|
565
|
+
return {"keys": out}
|
|
566
|
+
|
|
567
|
+
async def random_bytes(self, n: int) -> bytes:
|
|
568
|
+
return secrets.token_bytes(n)
|
|
569
|
+
|
|
570
|
+
async def hkdf(self, ikm: bytes, *, salt: bytes, info: bytes, length: int) -> bytes:
|
|
571
|
+
return HKDF(
|
|
572
|
+
algorithm=hashes.SHA256(), length=length, salt=salt, info=info
|
|
573
|
+
).derive(ikm)
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
# FileKeyProvider Examples
|
|
2
|
+
|
|
3
|
+
This example shows how to persist a symmetric key using `FileKeyProvider`.
|
|
4
|
+
|
|
5
|
+
```python
|
|
6
|
+
import asyncio
|
|
7
|
+
from tempfile import TemporaryDirectory
|
|
8
|
+
|
|
9
|
+
from swarmauri_keyprovider_file import FileKeyProvider
|
|
10
|
+
from swarmauri_core.key_providers.types import (
|
|
11
|
+
ExportPolicy,
|
|
12
|
+
KeyAlg,
|
|
13
|
+
KeyClass,
|
|
14
|
+
KeySpec,
|
|
15
|
+
)
|
|
16
|
+
from swarmauri_core.crypto.types import KeyUse
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
async def run_example() -> str:
|
|
20
|
+
"""Persist a symmetric key on disk using FileKeyProvider."""
|
|
21
|
+
with TemporaryDirectory() as tmp:
|
|
22
|
+
provider = FileKeyProvider(tmp)
|
|
23
|
+
spec = KeySpec(
|
|
24
|
+
klass=KeyClass.symmetric,
|
|
25
|
+
alg=KeyAlg.AES256_GCM,
|
|
26
|
+
uses=(KeyUse.ENCRYPT,),
|
|
27
|
+
export_policy=ExportPolicy.SECRET_WHEN_ALLOWED,
|
|
28
|
+
)
|
|
29
|
+
created = await provider.create_key(spec)
|
|
30
|
+
provider2 = FileKeyProvider(tmp)
|
|
31
|
+
loaded = await provider2.get_key(created.kid, include_secret=True)
|
|
32
|
+
assert loaded.material == created.material
|
|
33
|
+
return loaded.kid
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
if __name__ == "__main__":
|
|
37
|
+
print(asyncio.run(run_example()))
|
|
38
|
+
```
|
|
File without changes
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
from tempfile import TemporaryDirectory
|
|
3
|
+
|
|
4
|
+
from swarmauri_keyprovider_file import FileKeyProvider
|
|
5
|
+
from swarmauri_core.key_providers.types import (
|
|
6
|
+
ExportPolicy,
|
|
7
|
+
KeyAlg,
|
|
8
|
+
KeyClass,
|
|
9
|
+
KeySpec,
|
|
10
|
+
)
|
|
11
|
+
from swarmauri_core.crypto.types import KeyUse
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
async def run_example() -> str:
|
|
15
|
+
"""Persist a symmetric key on disk using FileKeyProvider."""
|
|
16
|
+
with TemporaryDirectory() as tmp:
|
|
17
|
+
provider = FileKeyProvider(tmp)
|
|
18
|
+
spec = KeySpec(
|
|
19
|
+
klass=KeyClass.symmetric,
|
|
20
|
+
alg=KeyAlg.AES256_GCM,
|
|
21
|
+
uses=(KeyUse.ENCRYPT,),
|
|
22
|
+
export_policy=ExportPolicy.SECRET_WHEN_ALLOWED,
|
|
23
|
+
)
|
|
24
|
+
created = await provider.create_key(spec)
|
|
25
|
+
provider2 = FileKeyProvider(tmp)
|
|
26
|
+
loaded = await provider2.get_key(created.kid, include_secret=True)
|
|
27
|
+
assert loaded.material == created.material
|
|
28
|
+
return loaded.kid
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
if __name__ == "__main__":
|
|
32
|
+
print(asyncio.run(run_example()))
|