teef 0.1.1__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.
- teef/__init__.py +84 -0
- teef/__main__.py +5 -0
- teef/catalog.py +128 -0
- teef/cli.py +466 -0
- teef/context.py +49 -0
- teef/errors.py +13 -0
- teef/findings.py +17 -0
- teef/jose.py +199 -0
- teef/keys.py +141 -0
- teef/models.py +387 -0
- teef/package.py +272 -0
- teef/parsing.py +73 -0
- teef/py.typed +0 -0
- teef/reader.py +171 -0
- teef/recipient.py +510 -0
- teef/report.py +229 -0
- teef/rules.py +297 -0
- teef/schema.py +42 -0
- teef/schemas/tprm-evidence-exchange-0.1.0.schema.json +425 -0
- teef/serialize.py +38 -0
- teef/sources.py +303 -0
- teef/templates/report.css +93 -0
- teef/templates/report.html.j2 +276 -0
- teef-0.1.1.dist-info/METADATA +299 -0
- teef-0.1.1.dist-info/RECORD +28 -0
- teef-0.1.1.dist-info/WHEEL +4 -0
- teef-0.1.1.dist-info/entry_points.txt +2 -0
- teef-0.1.1.dist-info/licenses/LICENSE +202 -0
teef/context.py
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
"""What a recipient knows from outside the package."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass, field
|
|
4
|
+
from datetime import date
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
from joserfc.jwk import KeySet, RSAKey
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
@dataclass(frozen=True)
|
|
11
|
+
class Limits:
|
|
12
|
+
"""Archive limits the recipient applies before extracting attachments (TEEF-ARC-07)."""
|
|
13
|
+
|
|
14
|
+
max_archive_bytes: int = 100 * 1024**2
|
|
15
|
+
"""Size of the ZIP file, or of a bare manifest."""
|
|
16
|
+
max_entries: int = 1000
|
|
17
|
+
"""Number of archive entries, or of files in a folder."""
|
|
18
|
+
max_expanded_bytes: int = 200 * 1024**2
|
|
19
|
+
"""Total uncompressed size of all entries."""
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
DEFAULT_LIMITS = Limits()
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@dataclass(frozen=True)
|
|
26
|
+
class Context:
|
|
27
|
+
"""Recipient context for reading a package.
|
|
28
|
+
|
|
29
|
+
``previous_packages`` are the parsed manifests of packages already received, used for
|
|
30
|
+
package ID reuse (TEEF-ID-02) and ``supersedes`` checks (TEEF-REF-08). ``intake_date``
|
|
31
|
+
is the date the package is taken in for review (TEEF-DATE-05). ``known_questionnaires``
|
|
32
|
+
holds ``(id, version)`` pairs; when it is ``None``, TEEF-ANS-12 is not applied.
|
|
33
|
+
"""
|
|
34
|
+
|
|
35
|
+
previous_packages: tuple[dict[str, Any], ...] = ()
|
|
36
|
+
intake_date: date | None = None
|
|
37
|
+
known_questionnaires: frozenset[tuple[str, str]] | None = None
|
|
38
|
+
limits: Limits = field(default=DEFAULT_LIMITS)
|
|
39
|
+
trusted_keys: KeySet | None = None
|
|
40
|
+
"""Public keys whose signatures are trusted (used when verifying signatures)."""
|
|
41
|
+
decryption_key: RSAKey | None = None
|
|
42
|
+
"""The recipient's private key, for decrypting an encrypted package."""
|
|
43
|
+
require_signature: bool = False
|
|
44
|
+
"""Report an unsigned package as an error."""
|
|
45
|
+
|
|
46
|
+
def __post_init__(self) -> None:
|
|
47
|
+
object.__setattr__(self, "previous_packages", tuple(self.previous_packages))
|
|
48
|
+
if self.known_questionnaires is not None:
|
|
49
|
+
object.__setattr__(self, "known_questionnaires", frozenset(self.known_questionnaires))
|
teef/errors.py
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
"""Exceptions raised by teef."""
|
|
2
|
+
|
|
3
|
+
from .findings import Finding
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class PackageValidationError(Exception):
|
|
7
|
+
"""A package breaks one or more TEEF rules and cannot be written."""
|
|
8
|
+
|
|
9
|
+
def __init__(self, findings: list[Finding]) -> None:
|
|
10
|
+
self.findings = findings
|
|
11
|
+
errors = [f for f in findings if f.severity == "error"]
|
|
12
|
+
lines = [f"{f.rule_id} at {f.location or '/'}: {f.message}" for f in errors]
|
|
13
|
+
super().__init__("package is not valid:\n" + "\n".join(lines))
|
teef/findings.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
"""Findings reported by package checks."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
from typing import Literal
|
|
5
|
+
|
|
6
|
+
Severity = Literal["error", "warning"]
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
@dataclass(frozen=True)
|
|
10
|
+
class Finding:
|
|
11
|
+
"""One rule violation or reviewer notice, identified by its TEEF rule ID."""
|
|
12
|
+
|
|
13
|
+
rule_id: str
|
|
14
|
+
severity: Severity
|
|
15
|
+
message: str
|
|
16
|
+
location: str | None = None
|
|
17
|
+
"""JSON pointer into the manifest, such as ``/evidence/0/kind``."""
|
teef/jose.py
ADDED
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
"""Thin JOSE wrappers for TEEF. All cryptography is done by joserfc."""
|
|
2
|
+
|
|
3
|
+
import base64
|
|
4
|
+
import binascii
|
|
5
|
+
import json
|
|
6
|
+
import re
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from typing import Any, Literal
|
|
9
|
+
|
|
10
|
+
from joserfc import jwe, jws
|
|
11
|
+
from joserfc.errors import JoseError
|
|
12
|
+
from joserfc.jwk import KeySet, RSAKey
|
|
13
|
+
|
|
14
|
+
from .findings import Finding
|
|
15
|
+
|
|
16
|
+
JWS_HEADER_ALG = "PS256"
|
|
17
|
+
JWE_ALG = "RSA-OAEP-256"
|
|
18
|
+
JWE_ENC = "A256GCM"
|
|
19
|
+
JWE_CTY = "application/zip"
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _kid(key: RSAKey) -> str:
|
|
23
|
+
kid = key.kid
|
|
24
|
+
if not kid:
|
|
25
|
+
raise ValueError("the key has no kid; set one when loading or generating the key")
|
|
26
|
+
return str(kid)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def sign_manifest(manifest: bytes, key: RSAKey) -> bytes:
|
|
30
|
+
"""Return the detached compact JWS (PS256) over ``manifest`` as ASCII bytes."""
|
|
31
|
+
if not key.is_private:
|
|
32
|
+
raise ValueError("signing needs a private key; the key given has no private part")
|
|
33
|
+
header = {"alg": JWS_HEADER_ALG, "kid": _kid(key)}
|
|
34
|
+
compact = jws.serialize_compact(header, manifest, key, algorithms=[JWS_HEADER_ALG])
|
|
35
|
+
return jws.detach_content(compact).encode("ascii")
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def encrypt_package(zip_bytes: bytes, key: RSAKey) -> bytes:
|
|
39
|
+
"""Return ``zip_bytes`` as a compact JWE for ``key`` (RSA-OAEP-256, A256GCM), ASCII bytes."""
|
|
40
|
+
header = {"alg": JWE_ALG, "enc": JWE_ENC, "cty": JWE_CTY, "kid": _kid(key)}
|
|
41
|
+
token = jwe.encrypt_compact(header, zip_bytes, key, algorithms=[JWE_ALG, JWE_ENC])
|
|
42
|
+
return token.encode("ascii")
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
_SEGMENT = re.compile(rb"[A-Za-z0-9_-]*")
|
|
46
|
+
_WHITESPACE = b" \t\r\n"
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def strip_jwe(data: bytes) -> bytes:
|
|
50
|
+
"""Drop trailing ASCII whitespace from an outer JWE (a file may end with a newline)."""
|
|
51
|
+
return data.rstrip(_WHITESPACE)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def jwe_header(data: bytes) -> dict[str, Any] | None:
|
|
55
|
+
"""Return the unverified protected header of a compact JWE, or None if it is not one."""
|
|
56
|
+
if not data.isascii():
|
|
57
|
+
return None
|
|
58
|
+
segments = data.split(b".")
|
|
59
|
+
if len(segments) != 5 or not all(_SEGMENT.fullmatch(s) for s in segments):
|
|
60
|
+
return None
|
|
61
|
+
head = segments[0]
|
|
62
|
+
try:
|
|
63
|
+
decoded = base64.urlsafe_b64decode(head + b"=" * (-len(head) % 4))
|
|
64
|
+
header = json.loads(decoded)
|
|
65
|
+
except (binascii.Error, ValueError):
|
|
66
|
+
return None
|
|
67
|
+
if not isinstance(header, dict) or "enc" not in header:
|
|
68
|
+
return None
|
|
69
|
+
return header
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def looks_like_jwe(data: bytes) -> bool:
|
|
73
|
+
"""True when ``data`` has the shape of a compact JWE (five segments, JSON header with enc)."""
|
|
74
|
+
return jwe_header(data) is not None
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def jwe_header_problem(header: dict[str, Any]) -> str | None:
|
|
78
|
+
"""Name the first problem in the JWE protected header, or None when it is acceptable."""
|
|
79
|
+
for name, required in (("alg", JWE_ALG), ("enc", JWE_ENC), ("cty", JWE_CTY)):
|
|
80
|
+
if header.get(name) != required:
|
|
81
|
+
return f"JWE header {name!r} must be {required!r}"
|
|
82
|
+
kid = header.get("kid")
|
|
83
|
+
if not isinstance(kid, str) or not kid:
|
|
84
|
+
return "JWE header 'kid' is missing"
|
|
85
|
+
if "zip" in header:
|
|
86
|
+
return "JWE header 'zip' (compression) is not allowed"
|
|
87
|
+
if "crit" in header:
|
|
88
|
+
return "JWE header 'crit' is not allowed"
|
|
89
|
+
return None
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def decrypt_failure(header: dict[str, Any], key: RSAKey, error: Exception) -> str:
|
|
93
|
+
"""The text for a failed decryption, naming the key the JWE is for when it is another."""
|
|
94
|
+
message = f"cannot decrypt with key {key.kid}: {type(error).__name__}"
|
|
95
|
+
header_kid = header.get("kid")
|
|
96
|
+
if isinstance(header_kid, str) and header_kid != key.kid:
|
|
97
|
+
message += f"; the package is encrypted for kid {header_kid}"
|
|
98
|
+
return message
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def decrypt_package(data: bytes, key: RSAKey) -> bytes:
|
|
102
|
+
"""Decrypt a compact JWE with ``key``. Raises joserfc's JoseError on failure."""
|
|
103
|
+
token = jwe.decrypt_compact(data, key, algorithms=[JWE_ALG, JWE_ENC])
|
|
104
|
+
plaintext = token.plaintext
|
|
105
|
+
if plaintext is None:
|
|
106
|
+
raise ValueError("the JWE has no plaintext")
|
|
107
|
+
return plaintext
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
@dataclass(frozen=True)
|
|
111
|
+
class SignatureInfo:
|
|
112
|
+
"""What a package's ``manifest.jws`` says, and whether teef verified it."""
|
|
113
|
+
|
|
114
|
+
kid: str | None
|
|
115
|
+
"""The signing key ID from the protected header, when it could be read."""
|
|
116
|
+
status: Literal["verified", "invalid", "not verified"]
|
|
117
|
+
"""``not verified`` means the recipient gave no trusted keys."""
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def _b64_json(segment: bytes) -> Any:
|
|
121
|
+
try:
|
|
122
|
+
return json.loads(base64.urlsafe_b64decode(segment + b"=" * (-len(segment) % 4)))
|
|
123
|
+
except (binascii.Error, ValueError):
|
|
124
|
+
return None
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def jws_header(value: bytes) -> dict[str, Any] | None:
|
|
128
|
+
"""Return the unverified protected header of a compact JWS, or None if it is not one."""
|
|
129
|
+
if not value.isascii():
|
|
130
|
+
return None
|
|
131
|
+
segments = value.split(b".")
|
|
132
|
+
if len(segments) != 3 or not all(_SEGMENT.fullmatch(s) for s in segments):
|
|
133
|
+
return None
|
|
134
|
+
header = _b64_json(segments[0])
|
|
135
|
+
return header if isinstance(header, dict) else None
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def _header_kid(header: dict[str, Any] | None) -> str | None:
|
|
139
|
+
kid = header.get("kid") if header is not None else None
|
|
140
|
+
return kid if isinstance(kid, str) and kid else None
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def signature_kid(value: bytes) -> str | None:
|
|
144
|
+
"""The ``kid`` from a compact JWS protected header, or None when it cannot be read."""
|
|
145
|
+
return _header_kid(jws_header(value))
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def _invalid(kid: str | None, rule_id: str, message: str) -> tuple[SignatureInfo, list[Finding]]:
|
|
149
|
+
return SignatureInfo(kid, "invalid"), [Finding(rule_id, "error", message, None)]
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def check_signature(
|
|
153
|
+
jws_bytes: bytes, manifest_bytes: bytes, trusted: KeySet
|
|
154
|
+
) -> tuple[SignatureInfo, list[Finding]]:
|
|
155
|
+
"""Verify ``manifest.jws`` over the exact manifest bytes against the trusted keys.
|
|
156
|
+
|
|
157
|
+
Checks run in order and the first failure decides: the detached form (TEEF-SIG-06),
|
|
158
|
+
the header values (TEEF-SIG-07), the key lookup by ``kid`` (TEEF-SIG-08), then the
|
|
159
|
+
signature itself, checked by joserfc (TEEF-SIG-12).
|
|
160
|
+
"""
|
|
161
|
+
if any(byte in _WHITESPACE for byte in jws_bytes):
|
|
162
|
+
kid = signature_kid(jws_bytes.strip(_WHITESPACE))
|
|
163
|
+
return _invalid(
|
|
164
|
+
kid, "TEEF-SIG-06", "manifest.jws has trailing whitespace; a compact JWS has none"
|
|
165
|
+
)
|
|
166
|
+
header = jws_header(jws_bytes)
|
|
167
|
+
kid = _header_kid(header)
|
|
168
|
+
if header is None:
|
|
169
|
+
return _invalid(None, "TEEF-SIG-06", "manifest.jws is not a compact JWS")
|
|
170
|
+
if jws_bytes.split(b".")[1]:
|
|
171
|
+
return _invalid(kid, "TEEF-SIG-06", "manifest.jws carries its payload; it must be detached")
|
|
172
|
+
if "b64" in header:
|
|
173
|
+
return _invalid(
|
|
174
|
+
kid, "TEEF-SIG-06", "manifest.jws must use standard Base64url payload encoding (b64)"
|
|
175
|
+
)
|
|
176
|
+
alg = header.get("alg")
|
|
177
|
+
if alg != JWS_HEADER_ALG:
|
|
178
|
+
return _invalid(
|
|
179
|
+
kid, "TEEF-SIG-07", f"manifest.jws uses alg {alg!r}; it must be {JWS_HEADER_ALG}"
|
|
180
|
+
)
|
|
181
|
+
if kid is None:
|
|
182
|
+
return _invalid(None, "TEEF-SIG-07", "manifest.jws has no kid in its protected header")
|
|
183
|
+
matches = [key for key in trusted.keys if key.kid == kid]
|
|
184
|
+
if not matches:
|
|
185
|
+
return _invalid(
|
|
186
|
+
kid, "TEEF-SIG-08", f"signing key {kid} is not among the trusted publisher keys"
|
|
187
|
+
)
|
|
188
|
+
key = matches[0]
|
|
189
|
+
if key.get("use") == "enc":
|
|
190
|
+
return _invalid(
|
|
191
|
+
kid, "TEEF-SIG-08", f"trusted key {kid} is an encryption key, not a signing key"
|
|
192
|
+
)
|
|
193
|
+
try:
|
|
194
|
+
jws.deserialize_compact(jws_bytes, key, algorithms=[JWS_HEADER_ALG], payload=manifest_bytes)
|
|
195
|
+
except (JoseError, ValueError):
|
|
196
|
+
return _invalid(
|
|
197
|
+
kid, "TEEF-SIG-12", f"the signature by key {kid} does not verify over manifest.json"
|
|
198
|
+
)
|
|
199
|
+
return SignatureInfo(kid, "verified"), []
|
teef/keys.py
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
"""Load RSA keys for TEEF signing and encryption.
|
|
2
|
+
|
|
3
|
+
All cryptography is done by joserfc; this module only reads files, applies the
|
|
4
|
+
TEEF key rules (RSA only, at least 2048 bits, a kid on every key) and turns
|
|
5
|
+
failures into KeyFileError. Messages never contain key material or passwords.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
import os
|
|
12
|
+
import warnings
|
|
13
|
+
from typing import Any, cast
|
|
14
|
+
|
|
15
|
+
from joserfc.errors import SecurityWarning
|
|
16
|
+
from joserfc.jwk import KeySet, RSAKey
|
|
17
|
+
from joserfc.util import urlsafe_b64decode
|
|
18
|
+
|
|
19
|
+
MIN_RSA_BITS = 2048
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class KeyFileError(ValueError):
|
|
23
|
+
"""A key file could not be used. The message names the file and the problem."""
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _fail(path: str | os.PathLike[str], problem: str) -> KeyFileError:
|
|
27
|
+
return KeyFileError(f"Key file {os.fspath(path)}: {problem}")
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _read(path: str | os.PathLike[str]) -> bytes:
|
|
31
|
+
try:
|
|
32
|
+
with open(path, "rb") as fh:
|
|
33
|
+
return fh.read()
|
|
34
|
+
except OSError as exc:
|
|
35
|
+
raise _fail(path, f"cannot be read ({exc.strerror or type(exc).__name__}).") from None
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _check(path: str | os.PathLike[str], key: RSAKey) -> RSAKey:
|
|
39
|
+
n = key.as_dict(private=False).get("n")
|
|
40
|
+
if not isinstance(n, str):
|
|
41
|
+
raise _fail(path, "is not an RSA key; only RSA keys are supported.")
|
|
42
|
+
bits = int.from_bytes(urlsafe_b64decode(n.encode("ascii")), "big").bit_length()
|
|
43
|
+
if bits < MIN_RSA_BITS:
|
|
44
|
+
raise _fail(
|
|
45
|
+
path,
|
|
46
|
+
f"RSA key is {bits} bits; at least {MIN_RSA_BITS} bits are required.",
|
|
47
|
+
)
|
|
48
|
+
return key
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _import(
|
|
52
|
+
path: str | os.PathLike[str],
|
|
53
|
+
data: bytes | dict[str, Any],
|
|
54
|
+
kid: str | None,
|
|
55
|
+
password: bytes | None = None,
|
|
56
|
+
) -> RSAKey:
|
|
57
|
+
try:
|
|
58
|
+
# Too-small keys are rejected by _check right after, so the warning is only noise.
|
|
59
|
+
with warnings.catch_warnings():
|
|
60
|
+
warnings.simplefilter("ignore", SecurityWarning)
|
|
61
|
+
return RSAKey.import_key(
|
|
62
|
+
data, parameters={"kid": kid} if kid is not None else None, password=password
|
|
63
|
+
)
|
|
64
|
+
except TypeError:
|
|
65
|
+
raise _fail(path, "is encrypted but no password was given.") from None
|
|
66
|
+
except Exception as exc:
|
|
67
|
+
if "password" in str(exc).lower():
|
|
68
|
+
raise _fail(path, "could not be decrypted; the password is wrong.") from None
|
|
69
|
+
raise _fail(
|
|
70
|
+
path,
|
|
71
|
+
"is not a valid RSA key (expected a PEM or JWK file holding an RSA key).",
|
|
72
|
+
) from None
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def load_private_key(
|
|
76
|
+
path: str | os.PathLike[str], *, kid: str, password: bytes | None = None
|
|
77
|
+
) -> RSAKey:
|
|
78
|
+
"""Load a private RSA key from a PEM file (optionally encrypted) and give it ``kid``."""
|
|
79
|
+
key = _import(path, _read(path), kid, password)
|
|
80
|
+
if not key.is_private:
|
|
81
|
+
raise _fail(path, "does not hold a private key.")
|
|
82
|
+
return _check(path, key)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _load_jwk_dict(path: str | os.PathLike[str], data: bytes) -> dict[str, Any] | None:
|
|
86
|
+
stripped = data.lstrip()
|
|
87
|
+
if not stripped.startswith(b"{"):
|
|
88
|
+
return None
|
|
89
|
+
try:
|
|
90
|
+
obj = json.loads(stripped)
|
|
91
|
+
except ValueError:
|
|
92
|
+
raise _fail(path, "is not valid JSON.") from None
|
|
93
|
+
if not isinstance(obj, dict):
|
|
94
|
+
raise _fail(path, "is not a JWK object.")
|
|
95
|
+
return obj
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def load_public_key(path: str | os.PathLike[str], *, kid: str | None = None) -> RSAKey:
|
|
99
|
+
"""Load a public RSA key from PEM (``kid`` required) or JWK JSON (its own ``kid``)."""
|
|
100
|
+
data = _read(path)
|
|
101
|
+
jwk = _load_jwk_dict(path, data)
|
|
102
|
+
if jwk is None:
|
|
103
|
+
if kid is None:
|
|
104
|
+
raise _fail(path, "is a PEM file, so a kid must be given.")
|
|
105
|
+
return _check(path, _import(path, data, kid))
|
|
106
|
+
own = jwk.get("kid")
|
|
107
|
+
if not isinstance(own, str) or not own:
|
|
108
|
+
raise _fail(path, "JWK has no kid.")
|
|
109
|
+
if kid is not None and kid != own:
|
|
110
|
+
raise _fail(path, f"JWK has kid {own!r}, which does not match the requested kid {kid!r}.")
|
|
111
|
+
return _check(path, _import(path, jwk, None))
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def load_key_set(path: str | os.PathLike[str]) -> KeySet:
|
|
115
|
+
"""Load a JWK Set where every key is RSA, has a kid, and no kid repeats."""
|
|
116
|
+
data = _read(path)
|
|
117
|
+
try:
|
|
118
|
+
obj = json.loads(data)
|
|
119
|
+
except ValueError:
|
|
120
|
+
raise _fail(path, "is not valid JSON.") from None
|
|
121
|
+
entries = obj.get("keys") if isinstance(obj, dict) else None
|
|
122
|
+
if not isinstance(entries, list) or not entries:
|
|
123
|
+
raise _fail(path, "is not a JWK Set (expected a non-empty 'keys' list).")
|
|
124
|
+
seen: set[str] = set()
|
|
125
|
+
keys: list[RSAKey] = []
|
|
126
|
+
for index, entry in enumerate(entries):
|
|
127
|
+
if not isinstance(entry, dict):
|
|
128
|
+
raise _fail(path, f"key {index} is not a JWK object.")
|
|
129
|
+
kid = entry.get("kid")
|
|
130
|
+
if not isinstance(kid, str) or not kid:
|
|
131
|
+
raise _fail(path, f"key {index} has no kid.")
|
|
132
|
+
if kid in seen:
|
|
133
|
+
raise _fail(path, f"kid {kid!r} appears more than once.")
|
|
134
|
+
seen.add(kid)
|
|
135
|
+
keys.append(_check(path, _import(path, entry, None)))
|
|
136
|
+
return KeySet(cast("list[Any]", keys)) # list is invariant; every entry is an RSAKey
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def thumbprint(key: RSAKey) -> str:
|
|
140
|
+
"""RFC 7638 thumbprint of ``key`` (base64url SHA-256), computed by joserfc."""
|
|
141
|
+
return key.thumbprint()
|