swarmauri_keyprovider_file 0.2.0.dev2__py3-none-any.whl

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,567 @@
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.keys.KeyProviderBase import KeyProviderBase
18
+ from swarmauri_core.keys.types import KeySpec, KeyAlg, KeyClass, ExportPolicy, KeyUse
19
+ from swarmauri_core.crypto.types import KeyRef
20
+
21
+
22
+ def _b64u(b: bytes) -> str:
23
+ return base64.urlsafe_b64encode(b).rstrip(b"=").decode("ascii")
24
+
25
+
26
+ def _hash_hex(b: bytes, nbytes: int = 16) -> str:
27
+ h = hashes.Hash(hashes.SHA256())
28
+ h.update(b)
29
+ return h.finalize().hex()[: 2 * nbytes]
30
+
31
+
32
+ def _serialize_keypair(priv, spec: KeySpec) -> tuple[bytes, Optional[bytes]]:
33
+ """Serialize private and public key material according to ``spec``."""
34
+
35
+ encoding = (
36
+ serialization.Encoding[spec.encoding]
37
+ if spec.encoding
38
+ else serialization.Encoding.PEM
39
+ )
40
+ public_format = (
41
+ serialization.PublicFormat[spec.public_format]
42
+ if spec.public_format
43
+ else serialization.PublicFormat.SubjectPublicKeyInfo
44
+ )
45
+ public = priv.public_key().public_bytes(encoding=encoding, format=public_format)
46
+
47
+ material: Optional[bytes] = None
48
+ if spec.export_policy != ExportPolicy.PUBLIC_ONLY:
49
+ private_format = (
50
+ serialization.PrivateFormat[spec.private_format]
51
+ if spec.private_format
52
+ else serialization.PrivateFormat.PKCS8
53
+ )
54
+ if spec.encryption and spec.encryption != "NoEncryption":
55
+ raise ValueError(f"Unsupported encryption: {spec.encryption}")
56
+ material = priv.private_bytes(
57
+ encoding,
58
+ private_format,
59
+ serialization.NoEncryption(),
60
+ )
61
+
62
+ return public, material
63
+
64
+
65
+ def _ensure_dir(p: Path) -> None:
66
+ p.mkdir(parents=True, exist_ok=True)
67
+
68
+
69
+ def _now() -> int:
70
+ return int(time.time())
71
+
72
+
73
+ class FileKeyProvider(KeyProviderBase):
74
+ """File-backed key provider."""
75
+
76
+ type: Literal["FileKeyProvider"] = "FileKeyProvider"
77
+
78
+ def __init__(self, root_dir: str | Path) -> None:
79
+ super().__init__()
80
+ self.root = Path(root_dir)
81
+ _ensure_dir(self.root)
82
+ _ensure_dir(self.root / "keys")
83
+ object.__setattr__(self, "_lock", threading.RLock())
84
+
85
+ def supports(self) -> Mapping[str, Iterable[str]]:
86
+ return {
87
+ "class": ("sym", "asym"),
88
+ "algs": (
89
+ KeyAlg.AES256_GCM,
90
+ KeyAlg.ED25519,
91
+ KeyAlg.X25519,
92
+ KeyAlg.RSA_OAEP_SHA256,
93
+ KeyAlg.RSA_PSS_SHA256,
94
+ KeyAlg.ECDSA_P256_SHA256,
95
+ ),
96
+ "features": (
97
+ "create",
98
+ "rotate",
99
+ "import",
100
+ "jwks",
101
+ "hkdf",
102
+ "random",
103
+ "persist",
104
+ ),
105
+ }
106
+
107
+ def _key_dir(self, kid: str) -> Path:
108
+ return self.root / "keys" / kid
109
+
110
+ def _ver_dir(self, kid: str, version: int) -> Path:
111
+ return self._key_dir(kid) / f"v{version}"
112
+
113
+ def _meta_path(self, kid: str) -> Path:
114
+ return self._key_dir(kid) / "meta.json"
115
+
116
+ def _write_meta(
117
+ self,
118
+ kid: str,
119
+ *,
120
+ klass: KeyClass,
121
+ alg: KeyAlg,
122
+ uses: Tuple[KeyUse, ...],
123
+ export_policy: ExportPolicy,
124
+ label: Optional[str],
125
+ tags: Optional[Dict[str, object]],
126
+ ) -> None:
127
+ p = self._meta_path(kid)
128
+ meta = {
129
+ "kid": kid,
130
+ "klass": klass.value,
131
+ "alg": alg.value,
132
+ "uses": [u.value for u in uses],
133
+ "export_policy": export_policy.value,
134
+ "label": label,
135
+ "tags": tags or {},
136
+ "created_at": _now(),
137
+ }
138
+ _ensure_dir(p.parent)
139
+ p.write_text(json.dumps(meta, indent=2))
140
+
141
+ def _read_meta(self, kid: str) -> dict:
142
+ p = self._meta_path(kid)
143
+ if not p.exists():
144
+ raise KeyError(f"unknown kid: {kid}")
145
+ return json.loads(p.read_text())
146
+
147
+ def _latest_version(self, kid: str) -> int:
148
+ kd = self._key_dir(kid)
149
+ if not kd.exists():
150
+ raise KeyError(f"unknown kid: {kid}")
151
+ max_v = 0
152
+ for entry in kd.iterdir():
153
+ if entry.is_dir() and entry.name.startswith("v"):
154
+ try:
155
+ v = int(entry.name[1:])
156
+ if v > max_v:
157
+ max_v = v
158
+ except Exception:
159
+ continue
160
+ if max_v == 0:
161
+ raise KeyError(f"no versions for kid: {kid}")
162
+ return max_v
163
+
164
+ async def create_key(self, spec: KeySpec) -> KeyRef:
165
+ with self._lock:
166
+ kid = _hash_hex(os.urandom(16))
167
+ version = 1
168
+ vdir = self._ver_dir(kid, version)
169
+ _ensure_dir(vdir)
170
+
171
+ public: Optional[bytes] = None
172
+ material: Optional[bytes] = None
173
+
174
+ if spec.klass == KeyClass.symmetric:
175
+ if spec.alg != KeyAlg.AES256_GCM:
176
+ raise ValueError(f"Unsupported symmetric alg: {spec.alg}")
177
+ raw = secrets.token_bytes(32)
178
+ if spec.export_policy != ExportPolicy.PUBLIC_ONLY:
179
+ material = raw
180
+ (vdir / "private.pem").write_text(
181
+ json.dumps({"kty": "oct", "k": _b64u(raw)})
182
+ )
183
+ (vdir / "public.jwk").write_text(
184
+ json.dumps({"kty": "oct", "alg": "A256GCM"})
185
+ )
186
+ else:
187
+ if spec.alg == KeyAlg.ED25519:
188
+ sk = ed25519.Ed25519PrivateKey.generate()
189
+ elif spec.alg == KeyAlg.X25519:
190
+ sk = x25519.X25519PrivateKey.generate()
191
+ elif spec.alg in (KeyAlg.RSA_OAEP_SHA256, KeyAlg.RSA_PSS_SHA256):
192
+ bits = spec.size_bits or 3072
193
+ sk = rsa.generate_private_key(public_exponent=65537, key_size=bits)
194
+ elif spec.alg == KeyAlg.ECDSA_P256_SHA256:
195
+ sk = ec.generate_private_key(ec.SECP256R1())
196
+ else:
197
+ raise ValueError(f"Unsupported asymmetric alg: {spec.alg}")
198
+
199
+ public, material = _serialize_keypair(sk, spec)
200
+ (vdir / "public.pem").write_bytes(public)
201
+ if material is not None:
202
+ (vdir / "private.pem").write_bytes(material)
203
+
204
+ self._write_meta(
205
+ kid,
206
+ klass=spec.klass,
207
+ alg=spec.alg,
208
+ uses=spec.uses,
209
+ export_policy=spec.export_policy,
210
+ label=spec.label,
211
+ tags=spec.tags,
212
+ )
213
+
214
+ return KeyRef(
215
+ kid=kid,
216
+ version=version,
217
+ type="OPAQUE",
218
+ uses=spec.uses,
219
+ export_policy=spec.export_policy,
220
+ public=public,
221
+ material=material,
222
+ tags={"label": spec.label, "alg": spec.alg.value, **(spec.tags or {})},
223
+ fingerprint=self._fingerprint(
224
+ public=public, material=material, kid=kid
225
+ ),
226
+ )
227
+
228
+ async def import_key(
229
+ self, spec: KeySpec, material: bytes, *, public: Optional[bytes] = None
230
+ ) -> KeyRef:
231
+ with self._lock:
232
+ kid = _hash_hex(material if material else os.urandom(16))
233
+ version = 1
234
+ vdir = self._ver_dir(kid, version)
235
+ _ensure_dir(vdir)
236
+
237
+ if spec.klass == KeyClass.symmetric:
238
+ if spec.export_policy == ExportPolicy.PUBLIC_ONLY:
239
+ (vdir / "private.pem").write_text(
240
+ json.dumps({"kty": "oct", "k": None})
241
+ )
242
+ mat_out = None
243
+ else:
244
+ (vdir / "private.pem").write_text(
245
+ json.dumps({"kty": "oct", "k": _b64u(material)})
246
+ )
247
+ mat_out = material
248
+ (vdir / "public.jwk").write_text(
249
+ json.dumps({"kty": "oct", "alg": "A256GCM"})
250
+ )
251
+ pub_out = None
252
+ else:
253
+ if public:
254
+ (vdir / "public.pem").write_bytes(public)
255
+ pub_out = public
256
+ else:
257
+ try:
258
+ sk = serialization.load_pem_private_key(material, password=None)
259
+ pub_out = sk.public_key().public_bytes(
260
+ serialization.Encoding.PEM,
261
+ serialization.PublicFormat.SubjectPublicKeyInfo,
262
+ )
263
+ (vdir / "public.pem").write_bytes(pub_out)
264
+ except Exception:
265
+ pub_out = None
266
+ if spec.export_policy != ExportPolicy.PUBLIC_ONLY:
267
+ (vdir / "private.pem").write_bytes(material)
268
+ mat_out = material
269
+ else:
270
+ mat_out = None
271
+
272
+ self._write_meta(
273
+ kid,
274
+ klass=spec.klass,
275
+ alg=spec.alg,
276
+ uses=spec.uses,
277
+ export_policy=spec.export_policy,
278
+ label=spec.label,
279
+ tags=spec.tags,
280
+ )
281
+
282
+ return KeyRef(
283
+ kid=kid,
284
+ version=version,
285
+ type="OPAQUE",
286
+ uses=spec.uses,
287
+ export_policy=spec.export_policy,
288
+ public=pub_out,
289
+ material=mat_out,
290
+ tags={
291
+ "label": spec.label,
292
+ "alg": spec.alg.value,
293
+ "imported": True,
294
+ **(spec.tags or {}),
295
+ },
296
+ fingerprint=self._fingerprint(
297
+ public=pub_out, material=mat_out, kid=kid
298
+ ),
299
+ )
300
+
301
+ async def rotate_key(
302
+ self, kid: str, *, spec_overrides: Optional[dict] = None
303
+ ) -> KeyRef:
304
+ with self._lock:
305
+ meta = self._read_meta(kid)
306
+ latest = self._latest_version(kid)
307
+ next_v = latest + 1
308
+ klass = KeyClass(meta["klass"])
309
+ alg = KeyAlg(meta["alg"])
310
+ uses = tuple(KeyUse(u) for u in meta["uses"])
311
+ export_policy = ExportPolicy(meta["export_policy"])
312
+ label = meta.get("label")
313
+ tags = meta.get("tags") or {}
314
+
315
+ vdir = self._ver_dir(kid, next_v)
316
+ _ensure_dir(vdir)
317
+
318
+ ov = spec_overrides or {}
319
+ material: Optional[bytes] = None
320
+ public: Optional[bytes] = None
321
+
322
+ if klass == KeyClass.symmetric:
323
+ raw = secrets.token_bytes(32)
324
+ if export_policy != ExportPolicy.PUBLIC_ONLY:
325
+ material = raw
326
+ (vdir / "private.pem").write_text(
327
+ json.dumps({"kty": "oct", "k": _b64u(raw)})
328
+ )
329
+ (vdir / "public.jwk").write_text(
330
+ json.dumps({"kty": "oct", "alg": "A256GCM"})
331
+ )
332
+ else:
333
+ if alg == KeyAlg.ED25519:
334
+ sk = ed25519.Ed25519PrivateKey.generate()
335
+ elif alg == KeyAlg.X25519:
336
+ sk = x25519.X25519PrivateKey.generate()
337
+ elif alg in (KeyAlg.RSA_OAEP_SHA256, KeyAlg.RSA_PSS_SHA256):
338
+ bits = int(ov.get("size_bits") or 3072)
339
+ sk = rsa.generate_private_key(public_exponent=65537, key_size=bits)
340
+ elif alg == KeyAlg.ECDSA_P256_SHA256:
341
+ sk = ec.generate_private_key(ec.SECP256R1())
342
+ else:
343
+ raise ValueError(f"Unsupported alg during rotate: {alg}")
344
+
345
+ tmp_spec = KeySpec(
346
+ klass=klass,
347
+ alg=alg,
348
+ uses=uses,
349
+ export_policy=export_policy,
350
+ )
351
+ public, material = _serialize_keypair(sk, tmp_spec)
352
+ (vdir / "public.pem").write_bytes(public)
353
+ if material is not None:
354
+ (vdir / "private.pem").write_bytes(material)
355
+
356
+ if ov:
357
+ new_meta = dict(meta)
358
+ if "label" in ov:
359
+ new_meta["label"] = ov["label"]
360
+ label = ov["label"]
361
+ if "tags" in ov and isinstance(ov["tags"], dict):
362
+ tags.update(ov["tags"])
363
+ new_meta["tags"] = tags
364
+ self._meta_path(kid).write_text(json.dumps(new_meta, indent=2))
365
+
366
+ return KeyRef(
367
+ kid=kid,
368
+ version=next_v,
369
+ type="OPAQUE",
370
+ uses=uses,
371
+ export_policy=export_policy,
372
+ public=public,
373
+ material=material,
374
+ tags={"label": label, "alg": alg.value, **tags},
375
+ fingerprint=self._fingerprint(
376
+ public=public, material=material, kid=kid
377
+ ),
378
+ )
379
+
380
+ async def destroy_key(self, kid: str, version: Optional[int] = None) -> bool:
381
+ with self._lock:
382
+ kdir = self._key_dir(kid)
383
+ if not kdir.exists():
384
+ return False
385
+ if version is None:
386
+ shutil.rmtree(kdir, ignore_errors=True)
387
+ return True
388
+ vdir = self._ver_dir(kid, version)
389
+ if vdir.exists():
390
+ shutil.rmtree(vdir, ignore_errors=True)
391
+ try:
392
+ _ = self._latest_version(kid)
393
+ except Exception:
394
+ if self._meta_path(kid).exists():
395
+ self._meta_path(kid).unlink(missing_ok=True)
396
+ if kdir.exists():
397
+ try:
398
+ kdir.rmdir()
399
+ except Exception:
400
+ pass
401
+ return True
402
+
403
+ async def get_key(
404
+ self, kid: str, version: Optional[int] = None, *, include_secret: bool = False
405
+ ) -> KeyRef:
406
+ with self._lock:
407
+ meta = self._read_meta(kid)
408
+ v = version or self._latest_version(kid)
409
+ vdir = self._ver_dir(kid, v)
410
+ if not vdir.exists():
411
+ raise KeyError(f"unknown version: {kid}.v{v}")
412
+
413
+ export_policy = ExportPolicy(meta["export_policy"])
414
+ alg = KeyAlg(meta["alg"])
415
+ uses = tuple(KeyUse(u) for u in meta["uses"])
416
+
417
+ public: Optional[bytes] = None
418
+ material: Optional[bytes] = None
419
+
420
+ pem_pub = vdir / "public.pem"
421
+ if pem_pub.exists():
422
+ public = pem_pub.read_bytes()
423
+ else:
424
+ jwk_pub = vdir / "public.jwk"
425
+ if jwk_pub.exists():
426
+ public = jwk_pub.read_bytes()
427
+
428
+ if include_secret and export_policy != ExportPolicy.PUBLIC_ONLY:
429
+ pem_priv = vdir / "private.pem"
430
+ if pem_priv.exists():
431
+ try:
432
+ obj = json.loads(pem_priv.read_text())
433
+ if obj.get("kty") == "oct" and obj.get("k"):
434
+ material = base64.urlsafe_b64decode(obj["k"] + "==")
435
+ else:
436
+ material = pem_priv.read_bytes()
437
+ except json.JSONDecodeError:
438
+ material = pem_priv.read_bytes()
439
+
440
+ return KeyRef(
441
+ kid=kid,
442
+ version=v,
443
+ type="OPAQUE",
444
+ uses=uses,
445
+ export_policy=export_policy,
446
+ public=public,
447
+ material=material,
448
+ tags={
449
+ "label": meta.get("label"),
450
+ "alg": alg.value,
451
+ **(meta.get("tags") or {}),
452
+ },
453
+ fingerprint=self._fingerprint(
454
+ public=public, material=material, kid=kid
455
+ ),
456
+ )
457
+
458
+ async def list_versions(self, kid: str) -> Tuple[int, ...]:
459
+ with self._lock:
460
+ kd = self._key_dir(kid)
461
+ if not kd.exists():
462
+ raise KeyError(f"unknown kid: {kid}")
463
+ vs: list[int] = []
464
+ for entry in kd.iterdir():
465
+ if entry.is_dir() and entry.name.startswith("v"):
466
+ try:
467
+ vs.append(int(entry.name[1:]))
468
+ except Exception:
469
+ pass
470
+ if not vs:
471
+ raise KeyError(f"no versions for kid: {kid}")
472
+ vs.sort()
473
+ return tuple(vs)
474
+
475
+ async def get_public_jwk(self, kid: str, version: Optional[int] = None) -> dict:
476
+ ref = await self.get_key(kid, version, include_secret=False)
477
+ alg = KeyAlg(ref.tags["alg"])
478
+
479
+ if alg == KeyAlg.AES256_GCM:
480
+ return {
481
+ "kty": "oct",
482
+ "alg": "A256GCM",
483
+ "kid": f"{ref.kid}.{ref.version}",
484
+ }
485
+
486
+ if ref.public is None:
487
+ vdir = self._ver_dir(ref.kid, ref.version)
488
+ pem_pub = vdir / "public.pem"
489
+ if not pem_pub.exists():
490
+ raise RuntimeError("Public material unavailable for asymmetric key")
491
+ pub_bytes = pem_pub.read_bytes()
492
+ else:
493
+ pub_bytes = ref.public
494
+
495
+ pk = serialization.load_pem_public_key(pub_bytes)
496
+
497
+ if alg == KeyAlg.ED25519:
498
+ raw = pk.public_bytes(
499
+ serialization.Encoding.Raw, serialization.PublicFormat.Raw
500
+ )
501
+ return {
502
+ "kty": "OKP",
503
+ "crv": "Ed25519",
504
+ "x": _b64u(raw),
505
+ "kid": f"{ref.kid}.{ref.version}",
506
+ }
507
+
508
+ if alg == KeyAlg.X25519:
509
+ raw = pk.public_bytes(
510
+ serialization.Encoding.Raw, serialization.PublicFormat.Raw
511
+ )
512
+ return {
513
+ "kty": "OKP",
514
+ "crv": "X25519",
515
+ "x": _b64u(raw),
516
+ "kid": f"{ref.kid}.{ref.version}",
517
+ }
518
+
519
+ if alg in (KeyAlg.RSA_OAEP_SHA256, KeyAlg.RSA_PSS_SHA256):
520
+ nums = pk.public_numbers()
521
+ n = nums.n.to_bytes((nums.n.bit_length() + 7) // 8, "big")
522
+ e = nums.e.to_bytes((nums.e.bit_length() + 7) // 8, "big")
523
+ return {
524
+ "kty": "RSA",
525
+ "n": _b64u(n),
526
+ "e": _b64u(e),
527
+ "kid": f"{ref.kid}.{ref.version}",
528
+ }
529
+
530
+ if alg == KeyAlg.ECDSA_P256_SHA256:
531
+ nums = pk.public_numbers()
532
+ x = nums.x.to_bytes(32, "big")
533
+ y = nums.y.to_bytes(32, "big")
534
+ return {
535
+ "kty": "EC",
536
+ "crv": "P-256",
537
+ "x": _b64u(x),
538
+ "y": _b64u(y),
539
+ "kid": f"{ref.kid}.{ref.version}",
540
+ }
541
+
542
+ raise ValueError(f"Unsupported alg for JWK export: {alg}")
543
+
544
+ async def jwks(self, *, prefix_kids: Optional[str] = None) -> dict:
545
+ with self._lock:
546
+ out = []
547
+ kroot = self.root / "keys"
548
+ for kid_dir in kroot.iterdir():
549
+ if not kid_dir.is_dir():
550
+ continue
551
+ kid = kid_dir.name
552
+ if prefix_kids and not kid.startswith(prefix_kids):
553
+ continue
554
+ try:
555
+ latest = self._latest_version(kid)
556
+ out.append(await self.get_public_jwk(kid, latest))
557
+ except Exception:
558
+ continue
559
+ return {"keys": out}
560
+
561
+ async def random_bytes(self, n: int) -> bytes:
562
+ return secrets.token_bytes(n)
563
+
564
+ async def hkdf(self, ikm: bytes, *, salt: bytes, info: bytes, length: int) -> bytes:
565
+ return HKDF(
566
+ algorithm=hashes.SHA256(), length=length, salt=salt, info=info
567
+ ).derive(ikm)
@@ -0,0 +1,5 @@
1
+ """File-backed key provider."""
2
+
3
+ from .FileKeyProvider import FileKeyProvider
4
+
5
+ __all__ = ["FileKeyProvider"]
@@ -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.keys.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.keys.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()))
@@ -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,77 @@
1
+ Metadata-Version: 2.3
2
+ Name: swarmauri_keyprovider_file
3
+ Version: 0.2.0.dev2
4
+ Summary: File-backed 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: Natural Language :: English
11
+ Classifier: Programming Language :: Python :: 3.10
12
+ Classifier: Programming Language :: Python :: 3.11
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Classifier: Programming Language :: Python :: 3.13
15
+ Classifier: Development Status :: 3 - Alpha
16
+ Classifier: Topic :: Security :: Cryptography
17
+ Classifier: Intended Audience :: Developers
18
+ Provides-Extra: cbor
19
+ Provides-Extra: jwks
20
+ Requires-Dist: cbor2 ; extra == "cbor"
21
+ Requires-Dist: cryptography
22
+ Requires-Dist: jwcrypto ; extra == "jwks"
23
+ Requires-Dist: swarmauri_base
24
+ Requires-Dist: swarmauri_core
25
+ Description-Content-Type: text/markdown
26
+
27
+ ![Swamauri Logo](https://res.cloudinary.com/dbjmpekvl/image/upload/v1730099724/Swarmauri-logo-lockup-2048x757_hww01w.png)
28
+
29
+ # Swarmauri File Key Provider
30
+
31
+ A file-backed key provider implementing the `KeyProviderBase` interface.
32
+ It manages symmetric and asymmetric keys on disk and exports public material via JWK/JWKS.
33
+
34
+ ## Installation
35
+
36
+ ```bash
37
+ pip install swarmauri_keyprovider_file
38
+ ```
39
+
40
+ ## Usage
41
+
42
+ ```python
43
+ import asyncio
44
+ from tempfile import TemporaryDirectory
45
+
46
+ from swarmauri_keyprovider_file import FileKeyProvider
47
+ from swarmauri_core.keys.types import (
48
+ ExportPolicy,
49
+ KeyAlg,
50
+ KeyClass,
51
+ KeySpec,
52
+ )
53
+ from swarmauri_core.crypto.types import KeyUse
54
+
55
+
56
+ async def run_example() -> str:
57
+ with TemporaryDirectory() as tmp:
58
+ provider = FileKeyProvider(tmp)
59
+ spec = KeySpec(
60
+ klass=KeyClass.symmetric,
61
+ alg=KeyAlg.AES256_GCM,
62
+ uses=(KeyUse.ENCRYPT,),
63
+ export_policy=ExportPolicy.SECRET_WHEN_ALLOWED,
64
+ )
65
+ created = await provider.create_key(spec)
66
+ provider2 = FileKeyProvider(tmp)
67
+ loaded = await provider2.get_key(created.kid, include_secret=True)
68
+ print(f"Loaded key: {loaded.kid}")
69
+
70
+
71
+ asyncio.run(run_example())
72
+ ```
73
+
74
+ ## Entry Point
75
+
76
+ The provider registers under the `swarmauri.key_providers` entry point as `FileKeyProvider`.
77
+
@@ -0,0 +1,10 @@
1
+ swarmauri_keyprovider_file/FileKeyProvider.py,sha256=FplMzaprq2F7g7YTPihlW6u8B3p83t1whiKFtBFHXGE,20236
2
+ swarmauri_keyprovider_file/__init__.py,sha256=kI8RSEku6hc-0yYXS76rdaDb_tBsJA024nuUXsyRaVE,109
3
+ swarmauri_keyprovider_file/examples/README.md,sha256=J7x4YnEewZGyX7Q5Q67NRkUKlzPlN57L9Jj6iK_APZI,1065
4
+ swarmauri_keyprovider_file/examples/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
+ swarmauri_keyprovider_file/examples/basic_usage.py,sha256=OUegKAyH4oK4IX4OanDHkB4C3fNlYLm5UPa4Z0B76WU,947
6
+ swarmauri_keyprovider_file-0.2.0.dev2.dist-info/LICENSE,sha256=djUXOlCxLVszShEpZXshZ7v33G-2qIC_j9KXpWKZSzQ,11359
7
+ swarmauri_keyprovider_file-0.2.0.dev2.dist-info/METADATA,sha256=aqcoOCriUWPRv4tv5xdcURw-oy1x47TdRFLA9gd1bws,2256
8
+ swarmauri_keyprovider_file-0.2.0.dev2.dist-info/WHEEL,sha256=b4K_helf-jlQoXBBETfwnf4B04YC67LOev0jo4fX5m8,88
9
+ swarmauri_keyprovider_file-0.2.0.dev2.dist-info/entry_points.txt,sha256=yqFMI_Tg6n-vyIrSs_29mHkihtLIiBOINAJN5vllE6s,198
10
+ swarmauri_keyprovider_file-0.2.0.dev2.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: poetry-core 2.1.3
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,6 @@
1
+ [peagen.plugins.key_providers]
2
+ file=swarmauri_keyprovider_file.FileKeyProvider:FileKeyProvider
3
+
4
+ [swarmauri.key_providers]
5
+ FileKeyProvider=swarmauri_keyprovider_file.FileKeyProvider:FileKeyProvider
6
+