flechtctl 0.16.0__tar.gz → 0.17.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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: flechtctl
3
- Version: 0.16.0
3
+ Version: 0.17.0
4
4
  Summary: Keyrings and flenc:/flsig: secret tokens for Flechtwerk, without the framework: a library and a command line tool.
5
5
  Project-URL: Documentation, https://bsure-analytics.github.io/flechtwerk/guides/flechtctl/
6
6
  Project-URL: Homepage, https://github.com/bsure-analytics/flechtwerk
@@ -20,6 +20,7 @@ functions for the shell (`flechtctl --help`).
20
20
  eagerly, every `flechtctl.tokens` name lazily on first access (PEP 562).
21
21
  """
22
22
  import importlib
23
+ from typing import TYPE_CHECKING
23
24
 
24
25
  from .errors import (
25
26
  PlaintextSecretError,
@@ -40,6 +41,36 @@ from .keyring import (
40
41
  keyring_from_jwk,
41
42
  )
42
43
 
44
+ if TYPE_CHECKING:
45
+ # The lazy names, for type checkers and IDEs only: at runtime they resolve
46
+ # through `__getattr__` below, so `import flechtctl` still loads no joserfc.
47
+ from .tokens import (
48
+ PREFIX,
49
+ SCHEME,
50
+ SIGNATURE_PREFIX,
51
+ SIGNATURE_SCHEME,
52
+ canonical_json,
53
+ decrypt,
54
+ decrypt_bytes,
55
+ decrypt_keyring,
56
+ encrypt,
57
+ encrypt_bytes,
58
+ encrypt_keyring,
59
+ generate_ed25519_key,
60
+ generate_oct_key,
61
+ generate_x25519_key,
62
+ is_encrypted,
63
+ is_signed,
64
+ kid_of,
65
+ read_header,
66
+ reencrypt,
67
+ sign,
68
+ sign_bytes,
69
+ signer_of,
70
+ verify,
71
+ verify_bytes,
72
+ )
73
+
43
74
  __all__ = [
44
75
  "Ed25519Key",
45
76
  "KEY_BYTES",
@@ -21,7 +21,9 @@ one, and `flechtctl.tokens.decrypt_keyring` opens it.
21
21
  """
22
22
  import base64
23
23
  import json
24
+ from collections.abc import Mapping, Set
24
25
  from dataclasses import dataclass, field, replace
26
+ from typing import Any
25
27
 
26
28
  __all__ = [
27
29
  "Ed25519Key",
@@ -191,7 +193,7 @@ class Keyring:
191
193
  primary: str,
192
194
  primaries: dict[str, str] | None = None,
193
195
  recipients: dict[str, X25519Key] | None = None,
194
- scopes: dict[str, set[str] | frozenset[str]] | None = None,
196
+ scopes: Mapping[str, Set[str]] | None = None,
195
197
  signers: dict[str, Ed25519Key] | None = None,
196
198
  signing: dict[str, str] | None = None,
197
199
  ) -> "Keyring":
@@ -201,7 +203,8 @@ class Keyring:
201
203
  primary=primary,
202
204
  primaries=dict(primaries or {}),
203
205
  recipients=dict(recipients or {}),
204
- scopes={kid: bound if isinstance(bound, str) else frozenset(bound) for kid, bound in (scopes or {}).items()},
206
+ # `__post_init__` normalizes every bound to a frozenset.
207
+ scopes=dict(scopes or {}), # pyright: ignore[reportArgumentType]
205
208
  signers=dict(signers or {}),
206
209
  signing=dict(signing or {}),
207
210
  )
@@ -240,15 +243,15 @@ class Keyring:
240
243
  scopes: dict[str, frozenset[str]] = {}
241
244
  signers: dict[str, Ed25519Key] = {}
242
245
  for jwk in raw_keys:
243
- kind, kid, material, bound = _parse_jwk(jwk, held=frozenset([*keys, *recipients, *signers]))
246
+ kid, material, bound = _parse_jwk(jwk, held=frozenset([*keys, *recipients, *signers]))
244
247
  if bound is not None:
245
248
  scopes[kid] = bound
246
- if kind == "oct":
247
- keys[kid] = material
248
- elif kind == "X25519":
249
+ if isinstance(material, X25519Key):
249
250
  recipients[kid] = material
250
- else:
251
+ elif isinstance(material, Ed25519Key):
251
252
  signers[kid] = material
253
+ else:
254
+ keys[kid] = material
252
255
  if "primary" not in doc:
253
256
  raise KeyringError("keyring document has no top-level 'primary' member")
254
257
  return cls(
@@ -268,7 +271,7 @@ class Keyring:
268
271
  `Keyring.from_json(k.to_json()) == k` for every valid keyring. The private
269
272
  halves are included — this is the file form, not a shareable one (see `public_jwk`).
270
273
  """
271
- jwks = [
274
+ jwks: list[dict[str, Any]] = [
272
275
  {"k": _encode_key(key), "kid": kid, "kty": "oct"} for kid, key in self.keys.items()
273
276
  ] + [
274
277
  _okp_jwk("X25519", kid, key) for kid, key in self.recipients.items()
@@ -309,13 +312,13 @@ class Keyring:
309
312
  The private half is kept if the JWK carries one, and so are its scopes.
310
313
  A kid already held raises `KeyringError`; the constructor's validation runs.
311
314
  """
312
- kind, kid, material, bound = _parse_jwk(jwk, held=frozenset(self.kids()))
315
+ kid, material, bound = _parse_jwk(jwk, held=frozenset(self.kids()))
313
316
  return replace(
314
317
  self,
315
- keys={**self.keys, kid: material} if kind == "oct" else self.keys,
316
- recipients={**self.recipients, kid: material} if kind == "X25519" else self.recipients,
318
+ keys={**self.keys, kid: material} if isinstance(material, bytes) else self.keys,
319
+ recipients={**self.recipients, kid: material} if isinstance(material, X25519Key) else self.recipients,
317
320
  scopes={**self.scopes, kid: bound} if bound is not None else self.scopes,
318
- signers={**self.signers, kid: material} if kind == "Ed25519" else self.signers,
321
+ signers={**self.signers, kid: material} if isinstance(material, Ed25519Key) else self.signers,
319
322
  )
320
323
 
321
324
  def key_for(self, kid: str) -> bytes:
@@ -398,13 +401,13 @@ def keyring_from_jwk(jwk: dict) -> Keyring:
398
401
 
399
402
  An Ed25519 entry cannot be primary, so the constructor's own validation rejects it.
400
403
  """
401
- kind, kid, material, bound = _parse_jwk(jwk, held=frozenset())
404
+ kid, material, bound = _parse_jwk(jwk, held=frozenset())
402
405
  return Keyring(
403
- keys={kid: material} if kind == "oct" else {},
406
+ keys={kid: material} if isinstance(material, bytes) else {},
404
407
  primary=kid,
405
- recipients={kid: material} if kind == "X25519" else {},
408
+ recipients={kid: material} if isinstance(material, X25519Key) else {},
406
409
  scopes={kid: bound} if bound is not None else {},
407
- signers={kid: material} if kind == "Ed25519" else {},
410
+ signers={kid: material} if isinstance(material, Ed25519Key) else {},
408
411
  )
409
412
 
410
413
 
@@ -418,8 +421,8 @@ def _okp_jwk(crv: str, kid: str, key: X25519Key | Ed25519Key) -> dict:
418
421
 
419
422
  def _parse_jwk(
420
423
  jwk: object, *, held: frozenset[str],
421
- ) -> tuple[str, str, bytes | X25519Key | Ed25519Key, frozenset[str] | None]:
422
- """Parse one JWK into `(kind, kid, material, scopes)`; kind is `oct`, `X25519` or `Ed25519`.
424
+ ) -> tuple[str, bytes | X25519Key | Ed25519Key, frozenset[str] | None]:
425
+ """Parse one JWK into `(kid, material, scopes)`; the material's type is the key's kind.
423
426
 
424
427
  Checks in order: object, `kty`, `kid`, a kid already in `held`, scopes, key
425
428
  material — so a duplicate kid with malformed material still reports the duplicate.
@@ -438,15 +441,15 @@ def _parse_jwk(
438
441
  raise KeyringError(f"duplicate kid {kid!r} in the keyring")
439
442
  bound = _parse_scopes(kid, jwk["flenc_scopes"]) if "flenc_scopes" in jwk else None
440
443
  if kty == "oct":
441
- return "oct", kid, _decode_member(kid, jwk, "k"), bound
444
+ return kid, _decode_member(kid, jwk, "k"), bound
442
445
  crv = jwk.get("crv")
443
446
  if crv not in ("Ed25519", "X25519"):
444
447
  raise KeyringError(f"JWK {kid!r} has unsupported curve {crv!r} — only X25519 and Ed25519 are used")
445
448
  public = _decode_member(kid, jwk, "x")
446
449
  private = _decode_member(kid, jwk, "d") if "d" in jwk else None
447
450
  if crv == "X25519":
448
- return "X25519", kid, X25519Key(public=public, private=private), bound
449
- return "Ed25519", kid, Ed25519Key(public=public, private=private), bound
451
+ return kid, X25519Key(public=public, private=private), bound
452
+ return kid, Ed25519Key(public=public, private=private), bound
450
453
 
451
454
 
452
455
  def _decode_member(kid: str, jwk: dict, member: str) -> bytes:
@@ -32,6 +32,7 @@ import base64
32
32
  import functools
33
33
  import json
34
34
  import secrets
35
+ from typing import Literal
35
36
 
36
37
  from joserfc import jwe, jws
37
38
  from joserfc.jwk import OctKey, OKPKey
@@ -251,6 +252,7 @@ def _okp_private_key(kid: str, crv: str, public: bytes, private: bytes) -> OKPKe
251
252
  `KeyringError`, unwrapped.
252
253
  """
253
254
  key = OKPKey.import_key({"crv": crv, "d": _b64url(private), "kty": "OKP", "x": _b64url(public)})
255
+ assert key.private_key is not None, "imported with its private half"
254
256
  if key.private_key.public_key().public_bytes_raw() != public:
255
257
  raise KeyringError(f"{crv} key {kid!r}: the private key does not match its public key")
256
258
  return key
@@ -359,6 +361,7 @@ def decrypt_bytes(keyring: Keyring, token: str, *, scope: str = "", topic: str |
359
361
  scope=scope, kid=kid, topic=topic, wire_key=wire_key,
360
362
  reason=f"key {kid!r} is bound to scopes {sorted(bound)}; token stamped {stamped!r}",
361
363
  )
364
+ assert obj.plaintext is not None, "a decrypted JWE always carries its plaintext"
362
365
  return obj.plaintext
363
366
 
364
367
 
@@ -476,6 +479,7 @@ def decrypt_keyring(text: str, password: str) -> Keyring:
476
479
  message = "cannot open the password-protected keyring — wrong password or damaged file"
477
480
  try:
478
481
  obj = jwe.decrypt_compact(text.strip(), _password_key(password), registry=_KEYRING_REGISTRY)
482
+ assert obj.plaintext is not None, "a decrypted JWE always carries its plaintext"
479
483
  plaintext = obj.plaintext.decode("utf-8")
480
484
  except Exception as e:
481
485
  raise KeyringError(message) from e
@@ -497,9 +501,11 @@ def generate_oct_key() -> bytes:
497
501
  return secrets.token_bytes(KEY_BYTES)
498
502
 
499
503
 
500
- def _generate_okp(crv: str) -> tuple[bytes, bytes]:
504
+ def _generate_okp(crv: Literal["Ed25519", "X25519"]) -> tuple[bytes, bytes]:
501
505
  jwk = OKPKey.generate_key(crv).as_dict(private=True)
502
- return _decode_key(jwk["x"], "x"), _decode_key(jwk["d"], "d")
506
+ x, d = jwk["x"], jwk["d"]
507
+ assert isinstance(x, str) and isinstance(d, str), "OKP members are base64url strings"
508
+ return _decode_key(x, "x"), _decode_key(d, "d")
503
509
 
504
510
 
505
511
  def generate_x25519_key() -> X25519Key:
File without changes
File without changes
File without changes